[
  {
    "path": ".api-reports/api-report-cache.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache as ApolloCache_2 } from '@apollo/client';\nimport type { AsStoreObject } from '@apollo/client/utilities';\nimport { canonicalStringify } from '@apollo/client/utilities';\nimport type { DataValue } from '@apollo/client';\nimport type { DeepPartial } from '@apollo/client/utilities';\nimport type { DocumentNode } from 'graphql';\nimport type { DocumentNode as DocumentNode_2 } from '@apollo/client';\nimport type { ExtensionsWithStreamInfo } from '@apollo/client/utilities/internal';\nimport type { FieldNode } from 'graphql';\nimport type { FragmentDefinitionNode } from 'graphql';\nimport type { FragmentMap } from '@apollo/client/utilities/internal';\nimport type { FragmentMapFunction } from '@apollo/client/utilities/internal';\nimport type { FragmentType } from '@apollo/client/masking';\nimport { getApolloCacheMemoryInternals } from '@apollo/client/utilities/internal';\nimport type { GetDataState } from '@apollo/client';\nimport { getInMemoryCacheMemoryInternals } from '@apollo/client/utilities/internal';\nimport type { Incremental } from '@apollo/client/incremental';\nimport type { InlineFragmentNode } from 'graphql';\nimport type { IsAny } from '@apollo/client/utilities/internal';\nimport { isReference } from '@apollo/client/utilities';\nimport type { NoInfer as NoInfer_2 } from '@apollo/client/utilities/internal';\nimport { Observable } from 'rxjs';\nimport type { OperationVariables } from '@apollo/client';\nimport type { Prettify } from '@apollo/client/utilities/internal';\nimport { Reference } from '@apollo/client/utilities';\nimport type { SelectionSetNode } from 'graphql';\nimport type { StoreObject } from '@apollo/client/utilities';\nimport type { StoreValue } from '@apollo/client/utilities';\nimport { Trie } from '@wry/trie';\nimport type { TypedDocumentNode } from '@apollo/client';\nimport type { Unmasked } from '@apollo/client/masking';\n\n// Warning: (ae-forgotten-export) The symbol \"StoreObjectValueMaybeReference\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype AllFieldsModifier<Entity extends Record<string, any>> = Modifier<Entity[keyof Entity] extends infer Value ? StoreObjectValueMaybeReference<Exclude<Value, undefined>> : never>;\n\n// @public (undocumented)\nexport namespace ApolloCache {\n    export type FromOptionValue<TData> = StoreObject | Reference | FragmentType<NoInfer_2<TData>> | string;\n    // (undocumented)\n    export interface ObservableFragment<TData = unknown> extends Observable<ApolloCache.WatchFragmentResult<TData>> {\n        getCurrentResult: () => ApolloCache.WatchFragmentResult<TData>;\n    }\n    export interface WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        from: ApolloCache.FromOptionValue<TData> | Array<ApolloCache.FromOptionValue<TData> | null> | null;\n        optimistic?: boolean;\n        variables?: TVariables;\n    }\n    export type WatchFragmentResult<TData = unknown> = true extends IsAny<TData> ? ({\n        complete: true;\n        missing?: never;\n    } & GetDataState<any, \"complete\">) | ({\n        complete: false;\n        missing?: MissingTree;\n    } & GetDataState<any, \"partial\">) : TData extends null | null[] ? Prettify<{\n        complete: true;\n        missing?: never;\n    } & GetDataState<TData, \"complete\">> : Prettify<{\n        complete: true;\n        missing?: never;\n    } & GetDataState<TData, \"complete\">> | {\n        complete: false;\n        missing?: MissingTree;\n        data: TData extends Array<infer TItem> ? Array<DataValue.Partial<TItem> | null> : DataValue.Partial<TData>;\n        dataState: \"partial\";\n    };\n}\n\n// @public (undocumented)\nexport abstract class ApolloCache {\n    // (undocumented)\n    readonly assumeImmutableResults: boolean;\n    batch<U>(options: Cache_2.BatchOptions<this, U>): U;\n    abstract diff<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: Cache_2.DiffOptions<TData, TVariables>): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    abstract evict(options: Cache_2.EvictOptions): boolean;\n    abstract extract(optimistic?: boolean): unknown;\n    // (undocumented)\n    abstract fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string): boolean;\n    // (undocumented)\n    gc(): string[];\n    // @internal @deprecated\n    getMemoryInternals?: typeof getApolloCacheMemoryInternals;\n    // (undocumented)\n    identify(object: StoreObject | Reference): string | undefined;\n    // (undocumented)\n    lookupFragment(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    modify<Entity extends Record<string, any> = Record<string, any>>(options: Cache_2.ModifyOptions<Entity>): boolean;\n    protected onAfterBroadcast: (cb: () => void) => void;\n    // (undocumented)\n    abstract performTransaction(transaction: Transaction, optimisticId?: string | null): void;\n    // (undocumented)\n    abstract read<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: Cache_2.ReadOptions<TData, TVariables>): Unmasked<TData> | null;\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ fragment, variables, fragmentName, id, from, optimistic, returnPartialData, }: Cache_2.ReadFragmentOptions<TData, TVariables>): Unmasked<TData> | null;\n    // (undocumented)\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.ReadFragmentOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ query, variables, id, optimistic, returnPartialData, }: Cache_2.ReadQueryOptions<TData, TVariables>): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.ReadQueryOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    // (undocumented)\n    recordOptimisticTransaction(transaction: Transaction, optimisticId: string): void;\n    // (undocumented)\n    abstract removeOptimistic(id: string): void;\n    // (undocumented)\n    abstract reset(options?: Cache_2.ResetOptions): Promise<void>;\n    resolvesClientField?(typename: string, fieldName: string): boolean;\n    abstract restore(serializedState: unknown): this;\n    // (undocumented)\n    transformDocument(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    transformForLink(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    updateFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.UpdateFragmentOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void): Unmasked<TData> | null;\n    // (undocumented)\n    updateQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.UpdateQueryOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void): Unmasked<TData> | null;\n    // (undocumented)\n    abstract watch<TData = unknown, TVariables extends OperationVariables = OperationVariables>(watch: Cache_2.WatchOptions<TData, TVariables>): () => void;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData>>;\n    }): ApolloCache.ObservableFragment<Array<Unmasked<TData>>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<null>;\n    }): ApolloCache.ObservableFragment<Array<null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }): ApolloCache.ObservableFragment<Array<Unmasked<TData> | null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: null;\n    }): ApolloCache.ObservableFragment<null>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: ApolloCache.FromOptionValue<TData>;\n    }): ApolloCache.ObservableFragment<Unmasked<TData>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables>): ApolloCache.ObservableFragment<Unmasked<TData> | null>;\n    // (undocumented)\n    abstract write<TData = unknown, TVariables extends OperationVariables = OperationVariables>(write: Cache_2.WriteOptions<TData, TVariables>): Reference | undefined;\n    writeFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ data, fragment, fragmentName, variables, overwrite, id, from, broadcast, }: Cache_2.WriteFragmentOptions<TData, TVariables>): Reference | undefined;\n    writeQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ data, query, variables, overwrite, id, broadcast, }: Cache_2.WriteQueryOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public (undocumented)\nexport type ApolloReducerConfig = {\n    dataIdFromObject?: KeyFieldsFunction;\n};\n\n// @public (undocumented)\ntype BroadcastOptions = Pick<Cache_2.BatchOptions<InMemoryCache>, \"optimistic\" | \"onWatchUpdated\">;\n\n// @public (undocumented)\nnamespace Cache_2 {\n    // (undocumented)\n    interface BatchOptions<TCache extends ApolloCache, TUpdateResult = void> {\n        onWatchUpdated?: (this: TCache, watch: Cache_2.WatchOptions, diff: Cache_2.DiffResult<any>, lastDiff?: Cache_2.DiffResult<any> | undefined) => any;\n        optimistic?: string | boolean;\n        removeOptimistic?: string;\n        update(cache: TCache): TUpdateResult;\n    }\n    // (undocumented)\n    type CacheIdentifierOption<TData> = {\n        id?: string;\n        from?: never;\n    } | {\n        id?: never;\n        from?: ApolloCache.FromOptionValue<TData>;\n    };\n    // (undocumented)\n    interface DiffOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Omit<ReadOptions<TData, TVariables>, \"rootId\"> {\n    }\n    // (undocumented)\n    type DiffResult<TData> = {\n        result: DataValue.Complete<TData>;\n        complete: true;\n        missing?: never;\n        fromOptimisticTransaction?: boolean;\n    } | {\n        result: DataValue.Partial<TData> | null;\n        complete: false;\n        missing?: MissingFieldError;\n        fromOptimisticTransaction?: boolean;\n    };\n    // (undocumented)\n    interface EvictOptions {\n        // (undocumented)\n        args?: Record<string, any>;\n        // (undocumented)\n        broadcast?: boolean;\n        // (undocumented)\n        fieldName?: string;\n        // (undocumented)\n        id?: string;\n    }\n    // (undocumented)\n    interface ModifyOptions<Entity extends Record<string, any> = Record<string, any>> {\n        // (undocumented)\n        broadcast?: boolean;\n        // Warning: (ae-forgotten-export) The symbol \"AllFieldsModifier\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        fields: Modifiers<Entity> | AllFieldsModifier<Entity>;\n        // (undocumented)\n        id?: string;\n        // (undocumented)\n        optimistic?: boolean;\n    }\n    // (undocumented)\n    type ReadFragmentOptions<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        variables?: TVariables;\n        returnPartialData?: boolean;\n        optimistic?: boolean;\n    } & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface ReadOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        id?: string;\n        // (undocumented)\n        optimistic: boolean;\n        // (undocumented)\n        previousResult?: any;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        // (undocumented)\n        returnPartialData?: boolean;\n        // (undocumented)\n        rootId?: string;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface ReadQueryOptions<TData, TVariables extends OperationVariables> {\n        id?: string;\n        optimistic?: boolean;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        returnPartialData?: boolean;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface ResetOptions {\n        // (undocumented)\n        discardWatches?: boolean;\n    }\n    // (undocumented)\n    type UpdateFragmentOptions<TData, TVariables extends OperationVariables> = Omit<ReadFragmentOptions<TData, TVariables> & WriteFragmentOptions<TData, TVariables>, \"data\" | \"id\" | \"from\"> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface UpdateQueryOptions<TData, TVariables extends OperationVariables> extends Omit<ReadQueryOptions<TData, TVariables> & WriteQueryOptions<TData, TVariables>, \"data\"> {\n    }\n    // (undocumented)\n    type WatchCallback<TData = unknown> = (diff: Cache_2.DiffResult<TData>, lastDiff?: Cache_2.DiffResult<TData>) => void;\n    // (undocumented)\n    interface WatchOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends DiffOptions<TData, TVariables> {\n        // (undocumented)\n        callback: WatchCallback<TData>;\n        // (undocumented)\n        immediate?: boolean;\n        // (undocumented)\n        lastDiff?: DiffResult<TData>;\n        // (undocumented)\n        watcher?: object;\n    }\n    // (undocumented)\n    type WriteFragmentOptions<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        variables?: TVariables;\n        data: Unmasked<TData>;\n        broadcast?: boolean;\n        overwrite?: boolean;\n    } & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface WriteOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        broadcast?: boolean;\n        // (undocumented)\n        dataId?: string;\n        extensions?: ExtensionsWithStreamInfo;\n        overwrite?: boolean;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        // (undocumented)\n        result: Unmasked<TData>;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface WriteQueryOptions<TData, TVariables extends OperationVariables> {\n        broadcast?: boolean;\n        data: Unmasked<TData>;\n        extensions?: ExtensionsWithStreamInfo;\n        id?: string;\n        overwrite?: boolean;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        variables?: TVariables;\n    }\n}\nexport { Cache_2 as Cache }\n\n// @public (undocumented)\nclass CacheGroup {\n    constructor(caching: boolean, parent?: CacheGroup | null);\n    // (undocumented)\n    readonly caching: boolean;\n    // (undocumented)\n    depend(dataId: string, storeFieldName: string): void;\n    // (undocumented)\n    dirty(dataId: string, storeFieldName: string): void;\n    // (undocumented)\n    keyMaker: Trie<object>;\n    // (undocumented)\n    resetCaching(): void;\n}\n\n// @public (undocumented)\nexport const cacheSlot: {\n    readonly id: string;\n    hasValue(): boolean;\n    getValue(): ApolloCache_2 | undefined;\n    withValue<TResult, TArgs extends any[], TThis = any>(value: ApolloCache_2, callback: (this: TThis, ...args: TArgs) => TResult, args?: TArgs | undefined, thisArg?: TThis | undefined): TResult;\n};\n\nexport { canonicalStringify }\n\n// @public (undocumented)\ntype CanReadFunction = (value: StoreValue) => boolean;\n\n// @public (undocumented)\nexport function createFragmentRegistry(...fragments: DocumentNode[]): FragmentRegistryAPI;\n\n// Warning: (ae-forgotten-export) The symbol \"KeyFieldsContext\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function defaultDataIdFromObject({ __typename, id, _id }: Readonly<StoreObject>, context?: KeyFieldsContext): string | undefined;\n\n// @public (undocumented)\ninterface DeleteModifier {\n    // (undocumented)\n    [_deleteModifier]: true;\n}\n\n// @public (undocumented)\nconst _deleteModifier: unique symbol;\n\n// @public (undocumented)\nexport type DiffQueryAgainstStoreOptions = ReadQueryOptions & {\n    returnPartialData?: boolean;\n};\n\n// @public (undocumented)\nexport abstract class EntityStore implements NormalizedCache {\n    constructor(policies: Policies, group: CacheGroup);\n    // Warning: (ae-forgotten-export) The symbol \"Layer\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    abstract addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // Warning: (ae-forgotten-export) The symbol \"CanReadFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    clear(): void;\n    // (undocumented)\n    protected data: NormalizedCacheObject;\n    // (undocumented)\n    delete(dataId: string, fieldName?: string, args?: Record<string, any>): boolean;\n    // (undocumented)\n    evict(options: Cache_2.EvictOptions, limit: EntityStore): boolean;\n    // (undocumented)\n    extract(): NormalizedCacheObject;\n    // (undocumented)\n    findChildRefIds(dataId: string): Record<string, true>;\n    // (undocumented)\n    gc(): string[];\n    // (undocumented)\n    get(dataId: string, fieldName: string): StoreValue;\n    // Warning: (ae-forgotten-export) The symbol \"SafeReadonly\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getFieldValue: <T = StoreValue>(objectOrReference: StoreObject | Reference | undefined, storeFieldName: string) => SafeReadonly<T>;\n    // (undocumented)\n    getRootIdSet(ids?: Set<string>): Set<string>;\n    // Warning: (ae-forgotten-export) The symbol \"StorageType\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    abstract getStorage(idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[]): StorageType;\n    // Warning: (ae-forgotten-export) The symbol \"CacheGroup\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readonly group: CacheGroup;\n    // (undocumented)\n    has(dataId: string): boolean;\n    // (undocumented)\n    protected lookup(dataId: string, dependOnExistence?: boolean): StoreObject | undefined;\n    makeCacheKey(document: DocumentNode, callback: Cache_2.WatchCallback<any>, details: string): object;\n    makeCacheKey(selectionSet: SelectionSetNode, parent: string | StoreObject, varString: string | undefined): object;\n    makeCacheKey(field: FieldNode, array: readonly any[], varString: string | undefined): object;\n    // @deprecated (undocumented)\n    makeCacheKey(...args: any[]): object;\n    // (undocumented)\n    merge(older: string | StoreObject, newer: StoreObject | string): void;\n    // (undocumented)\n    modify(dataId: string, fields: Modifier<any> | Modifiers<Record<string, any>>, exact: boolean): boolean;\n    // (undocumented)\n    readonly policies: Policies;\n    // (undocumented)\n    release(rootId: string): number;\n    // (undocumented)\n    abstract removeLayer(layerId: string): EntityStore;\n    // (undocumented)\n    replace(newData: NormalizedCacheObject | null): void;\n    // (undocumented)\n    retain(rootId: string): number;\n    // Warning: (ae-forgotten-export) The symbol \"Root\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    static Root: typeof Root;\n    // (undocumented)\n    get supportsResultCaching(): boolean;\n    // (undocumented)\n    toObject(): NormalizedCacheObject;\n    // Warning: (ae-forgotten-export) The symbol \"ToReferenceFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    toReference: ToReferenceFunction;\n}\n\n// @public (undocumented)\nexport interface FieldFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> {\n    // (undocumented)\n    args: TArgs | null;\n    // (undocumented)\n    cache: InMemoryCache;\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    field: FieldNode | null;\n    // (undocumented)\n    fieldName: string;\n    // (undocumented)\n    isReference: typeof isReference;\n    // Warning: (ae-forgotten-export) The symbol \"MergeObjectsFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    mergeObjects: MergeObjectsFunction;\n    // Warning: (ae-forgotten-export) The symbol \"ReadFieldFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readField: ReadFieldFunction;\n    // (undocumented)\n    storage: StorageType;\n    // (undocumented)\n    storeFieldName: string;\n    // (undocumented)\n    toReference: ToReferenceFunction;\n    // (undocumented)\n    variables?: TVariables;\n}\n\n// @public (undocumented)\nexport type FieldMergeFunction<TExisting = any, TIncoming = TExisting, TOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions> = (existing: SafeReadonly<TExisting> | undefined, incoming: SafeReadonly<TIncoming>, options: TOptions) => SafeReadonly<TExisting>;\n\n// @public (undocumented)\nexport interface FieldMergeFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> extends FieldFunctionOptions<TArgs, TVariables> {\n    existingData: unknown;\n    extensions: Record<string, unknown> | undefined;\n    streamFieldInfo?: Incremental.StreamFieldInfo;\n}\n\n// @public (undocumented)\nexport function fieldNameFromStoreName(storeFieldName: string): string;\n\n// @public (undocumented)\nexport type FieldPolicy<TExisting = any, TIncoming = TExisting, TReadResult = TIncoming, TReadOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions, TMergeOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions> = {\n    keyArgs?: KeySpecifier | KeyArgsFunction | false;\n    read?: FieldReadFunction<TExisting, TReadResult, TReadOptions>;\n    merge?: FieldMergeFunction<TExisting, TIncoming, TMergeOptions> | boolean;\n};\n\n// @public (undocumented)\nexport type FieldReadFunction<TExisting = any, TReadResult = TExisting, TOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions> = (existing: SafeReadonly<TExisting> | undefined, options: TOptions) => TReadResult | undefined;\n\n// @public (undocumented)\nexport interface FieldReadFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> extends FieldFunctionOptions<TArgs, TVariables> {\n}\n\n// @public (undocumented)\ninterface FieldSpecifier {\n    // (undocumented)\n    args?: Record<string, any>;\n    // (undocumented)\n    field?: FieldNode;\n    // (undocumented)\n    fieldName: string;\n    // (undocumented)\n    typename?: string;\n    // (undocumented)\n    variables?: Record<string, any>;\n}\n\n// @public (undocumented)\ntype FieldValueGetter = EntityStore[\"getFieldValue\"];\n\n// Warning: (ae-forgotten-export) The symbol \"WriteContext\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype FlavorableWriteContext = Pick<WriteContext, \"clientOnly\" | \"deferred\" | \"flavors\">;\n\n// @public (undocumented)\nexport interface FragmentRegistryAPI {\n    // (undocumented)\n    lookup(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    register(...fragments: DocumentNode[]): this;\n    // (undocumented)\n    resetCaches(): void;\n    // (undocumented)\n    transform<D extends DocumentNode>(document: D): D;\n}\n\n// @public (undocumented)\nexport type IdGetter = (value: IdGetterObj) => string | undefined;\n\n// @public (undocumented)\nexport interface IdGetterObj extends Object {\n    // (undocumented)\n    __typename?: string;\n    // (undocumented)\n    id?: string;\n    // (undocumented)\n    _id?: string;\n}\n\n// @public (undocumented)\nexport interface IgnoreModifier {\n    // (undocumented)\n    [_ignoreModifier]: true;\n}\n\n// @public (undocumented)\nconst _ignoreModifier: unique symbol;\n\n// @public (undocumented)\nexport class InMemoryCache extends ApolloCache {\n    constructor(config?: InMemoryCacheConfig);\n    // (undocumented)\n    readonly assumeImmutableResults = true;\n    batch<TUpdateResult>(options: Cache_2.BatchOptions<InMemoryCache, TUpdateResult>): TUpdateResult;\n    // Warning: (ae-forgotten-export) The symbol \"BroadcastOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    protected broadcastWatches(options?: BroadcastOptions): void;\n    // (undocumented)\n    protected config: InMemoryCacheConfig;\n    // (undocumented)\n    diff<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.DiffOptions<TData, TVariables>): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    evict(options: Cache_2.EvictOptions): boolean;\n    // (undocumented)\n    extract(optimistic?: boolean): NormalizedCacheObject;\n    // (undocumented)\n    fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string): boolean;\n    // (undocumented)\n    gc(options?: {\n        resetResultCache?: boolean;\n    }): string[];\n    // @internal @deprecated\n    getMemoryInternals?: typeof getInMemoryCacheMemoryInternals;\n    // (undocumented)\n    identify(object: StoreObject | Reference): string | undefined;\n    // (undocumented)\n    lookupFragment(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    readonly makeVar: typeof makeVar;\n    // (undocumented)\n    modify<Entity extends Record<string, any> = Record<string, any>>(options: Cache_2.ModifyOptions<Entity>): boolean;\n    // (undocumented)\n    performTransaction(update: (cache: InMemoryCache) => any, optimisticId?: string | null): any;\n    // (undocumented)\n    readonly policies: Policies;\n    // (undocumented)\n    read<TData = unknown>(options: Cache_2.ReadOptions<TData, OperationVariables> & {\n        returnPartialData: true;\n    }): TData | DeepPartial<TData> | null;\n    // (undocumented)\n    read<TData = unknown>(options: Cache_2.ReadOptions<TData, OperationVariables>): TData | null;\n    // (undocumented)\n    release(rootId: string, optimistic?: boolean): number;\n    // (undocumented)\n    removeOptimistic(idToRemove: string): void;\n    // (undocumented)\n    reset(options?: Cache_2.ResetOptions): Promise<void>;\n    // (undocumented)\n    resolvesClientField(typename: string, fieldName: string): boolean;\n    // (undocumented)\n    restore(data: NormalizedCacheObject): this;\n    // (undocumented)\n    retain(rootId: string, optimistic?: boolean): number;\n    // (undocumented)\n    transformDocument(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    watch<TData = unknown, TVariables extends OperationVariables = OperationVariables>(watch: Cache_2.WatchOptions<TData, TVariables>): () => void;\n    // (undocumented)\n    write<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.WriteOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public (undocumented)\nexport interface InMemoryCacheConfig extends ApolloReducerConfig {\n    // (undocumented)\n    fragments?: FragmentRegistryAPI;\n    // (undocumented)\n    possibleTypes?: PossibleTypesMap;\n    // (undocumented)\n    resultCaching?: boolean;\n    // (undocumented)\n    typePolicies?: TypePolicies;\n}\n\n// @public (undocumented)\ninterface InvalidateModifier {\n    // (undocumented)\n    [_invalidateModifier]: true;\n}\n\n// @public (undocumented)\nconst _invalidateModifier: unique symbol;\n\nexport { isReference }\n\n// @public (undocumented)\ntype KeyArgsFunction = (args: Record<string, any> | null, context: {\n    typename: string;\n    fieldName: string;\n    field: FieldNode | null;\n    variables?: Record<string, any>;\n}) => KeySpecifier | false | ReturnType<IdGetter>;\n\n// @public (undocumented)\ntype KeyFieldsContext = {\n    typename: string | undefined;\n    storeObject: StoreObject;\n    readField: ReadFieldFunction;\n    selectionSet?: SelectionSetNode;\n    fragmentMap?: FragmentMap;\n    keyObject?: Record<string, any>;\n};\n\n// @public (undocumented)\ntype KeyFieldsFunction = (object: Readonly<StoreObject>, context: KeyFieldsContext) => KeySpecifier | false | ReturnType<IdGetter>;\n\n// @public (undocumented)\ntype KeySpecifier = ReadonlyArray<string | KeySpecifier>;\n\n// @public (undocumented)\nclass Layer extends EntityStore {\n    constructor(id: string, parent: EntityStore, replay: (layer: EntityStore) => any, group: CacheGroup);\n    // (undocumented)\n    addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // (undocumented)\n    findChildRefIds(dataId: string): Record<string, true>;\n    // (undocumented)\n    getStorage(...args: Parameters<EntityStore[\"getStorage\"]>): StorageType;\n    // (undocumented)\n    readonly group: CacheGroup;\n    // (undocumented)\n    readonly id: string;\n    // (undocumented)\n    readonly parent: EntityStore;\n    // (undocumented)\n    removeLayer(layerId: string): EntityStore;\n    // (undocumented)\n    readonly replay: (layer: EntityStore) => any;\n    // (undocumented)\n    toObject(): NormalizedCacheObject;\n}\n\n// @public (undocumented)\nexport function makeVar<T>(value: T): ReactiveVar<T>;\n\n// @public (undocumented)\nexport interface MergeInfo {\n    // (undocumented)\n    field: FieldNode;\n    // (undocumented)\n    merge: FieldMergeFunction;\n    // (undocumented)\n    path: Array<string | number>;\n    // (undocumented)\n    typename: string | undefined;\n}\n\n// @public (undocumented)\ntype MergeObjectsFunction = <T extends StoreObject | Reference>(existing: T, incoming: T) => T;\n\n// @public (undocumented)\nexport interface MergeTree {\n    // (undocumented)\n    info?: MergeInfo;\n    // (undocumented)\n    map: Map<string | number, MergeTree>;\n}\n\n// @public (undocumented)\nexport class MissingFieldError extends Error {\n    constructor(message: string, path: MissingTree | Array<string | number>, query: DocumentNode, variables?: Record<string, any> | undefined);\n    // (undocumented)\n    readonly message: string;\n    // (undocumented)\n    readonly missing: MissingTree;\n    // (undocumented)\n    readonly path: MissingTree | Array<string | number>;\n    // (undocumented)\n    readonly query: DocumentNode;\n    // (undocumented)\n    readonly variables?: Record<string, any> | undefined;\n}\n\n// @public (undocumented)\nexport type MissingTree = string | {\n    readonly [key: string]: MissingTree;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"DeleteModifier\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"InvalidateModifier\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport type Modifier<T> = (value: T, details: ModifierDetails) => DeepPartial<T> | DeleteModifier | InvalidateModifier | undefined;\n\n// @public (undocumented)\nexport type ModifierDetails = {\n    DELETE: DeleteModifier;\n    INVALIDATE: InvalidateModifier;\n    fieldName: string;\n    storeFieldName: string;\n    readField: ReadFieldFunction;\n    canRead: CanReadFunction;\n    isReference: typeof isReference;\n    toReference: ToReferenceFunction;\n    storage: StorageType;\n};\n\n// @public (undocumented)\nexport type Modifiers<T extends Record<string, any> = Record<string, unknown>> = Partial<{\n    [FieldName in keyof T]: Modifier<StoreObjectValueMaybeReference<Exclude<T[FieldName], undefined>>>;\n}>;\n\n// @public\nexport interface NormalizedCache {\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    clear(): void;\n    // (undocumented)\n    delete(dataId: string, fieldName?: string): boolean;\n    // (undocumented)\n    get(dataId: string, fieldName: string): StoreValue;\n    // Warning: (ae-forgotten-export) The symbol \"FieldValueGetter\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getFieldValue: FieldValueGetter;\n    // (undocumented)\n    getStorage(idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[]): StorageType;\n    // (undocumented)\n    has(dataId: string): boolean;\n    // (undocumented)\n    merge(olderId: string, newerObject: StoreObject): void;\n    // (undocumented)\n    merge(olderObject: StoreObject, newerId: string): void;\n    // (undocumented)\n    modify<Entity extends Record<string, any>>(dataId: string, fields: Modifiers<Entity> | AllFieldsModifier<Entity>, exact: boolean): boolean;\n    // (undocumented)\n    release(rootId: string): number;\n    replace(newData: NormalizedCacheObject): void;\n    retain(rootId: string): number;\n    toObject(): NormalizedCacheObject;\n    // (undocumented)\n    toReference: ToReferenceFunction;\n}\n\n// @public\nexport interface NormalizedCacheObject {\n    // (undocumented)\n    [dataId: string]: StoreObject | undefined;\n    // (undocumented)\n    __META?: {\n        extraRootIds: string[];\n    };\n}\n\n// @public (undocumented)\nexport type OptimisticStoreItem = {\n    id: string;\n    data: NormalizedCacheObject;\n    transaction: Transaction;\n};\n\n// @public (undocumented)\nexport class Policies {\n    constructor(config: {\n        cache: InMemoryCache;\n        dataIdFromObject?: KeyFieldsFunction;\n        possibleTypes?: PossibleTypesMap;\n        typePolicies?: TypePolicies;\n    });\n    // (undocumented)\n    addPossibleTypes(possibleTypes: PossibleTypesMap): void;\n    // (undocumented)\n    addTypePolicies(typePolicies: TypePolicies): void;\n    // (undocumented)\n    readonly cache: InMemoryCache;\n    // (undocumented)\n    fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string | undefined, result?: Record<string, any>, variables?: Record<string, any>): boolean;\n    // (undocumented)\n    getMergeFunction(parentTypename: string | undefined, fieldName: string, childTypename: string | undefined): FieldMergeFunction | undefined;\n    // (undocumented)\n    getReadFunction(typename: string | undefined, fieldName: string): FieldReadFunction | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"FieldSpecifier\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getStoreFieldName(fieldSpec: FieldSpecifier): string;\n    // (undocumented)\n    hasKeyArgs(typename: string | undefined, fieldName: string): boolean;\n    // (undocumented)\n    identify(object: StoreObject, partialContext?: Partial<KeyFieldsContext>): [string?, StoreObject?];\n    // (undocumented)\n    readField<V = StoreValue>(options: ReadFieldOptions, context: ReadMergeModifyContext): SafeReadonly<V> | undefined;\n    // (undocumented)\n    readonly rootIdsByTypename: Record<string, string>;\n    // (undocumented)\n    readonly rootTypenamesById: Record<string, string>;\n    // (undocumented)\n    runMergeFunction(existing: StoreValue, incoming: StoreValue, { field, typename, merge, path }: MergeInfo, context: WriteContext, storage?: StorageType): any;\n    // (undocumented)\n    readonly usingPossibleTypes = false;\n}\n\n// @public (undocumented)\nexport type PossibleTypesMap = {\n    [supertype: string]: string[];\n};\n\n// @public (undocumented)\ntype ReactiveListener<T> = (value: T) => any;\n\n// @public (undocumented)\nexport interface ReactiveVar<T> {\n    // (undocumented)\n    (newValue?: T): T;\n    // (undocumented)\n    attachCache(cache: ApolloCache_2): this;\n    // (undocumented)\n    forgetCache(cache: ApolloCache_2): boolean;\n    // Warning: (ae-forgotten-export) The symbol \"ReactiveListener\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    onNextChange(listener: ReactiveListener<T>): () => void;\n}\n\n// @public (undocumented)\ninterface ReadFieldFunction {\n    // (undocumented)\n    <V = StoreValue>(options: ReadFieldOptions): SafeReadonly<V> | undefined;\n    // (undocumented)\n    <V = StoreValue>(fieldName: string, from?: StoreObject | Reference): SafeReadonly<V> | undefined;\n}\n\n// @public (undocumented)\nexport interface ReadFieldOptions extends FieldSpecifier {\n    // (undocumented)\n    from?: StoreObject | Reference;\n}\n\n// @public (undocumented)\nexport interface ReadMergeModifyContext {\n    // (undocumented)\n    extensions?: ExtensionsWithStreamInfo;\n    // (undocumented)\n    store: NormalizedCache;\n    // (undocumented)\n    variables?: OperationVariables;\n    // (undocumented)\n    varString?: string;\n}\n\n// @public (undocumented)\nexport type ReadQueryOptions = {\n    store: NormalizedCache;\n    query: DocumentNode;\n    variables?: Object;\n    previousResult?: any;\n    rootId?: string;\n    config?: ApolloReducerConfig;\n};\n\nexport { Reference }\n\n// @public (undocumented)\nclass Root extends EntityStore {\n    constructor({ policies, resultCaching, seed, }: {\n        policies: Policies;\n        resultCaching?: boolean;\n        seed?: NormalizedCacheObject;\n    });\n    // (undocumented)\n    addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // (undocumented)\n    getStorage(): StorageType;\n    // (undocumented)\n    removeLayer(): Root;\n    // (undocumented)\n    readonly storageTrie: Trie<StorageType>;\n    // Warning: (ae-forgotten-export) The symbol \"Stump\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readonly stump: Stump;\n}\n\n// @public (undocumented)\ntype SafeReadonly<T> = T extends object ? Readonly<T> : T;\n\n// @public (undocumented)\ntype StorageType = Record<string, any>;\n\nexport { StoreObject }\n\n// @public (undocumented)\ntype StoreObjectValueMaybeReference<StoreVal> = StoreVal extends ReadonlyArray<Record<string, any>> ? StoreVal extends ReadonlyArray<infer Item> ? [\nItem\n] extends [Record<string, any>] ? ReadonlyArray<AsStoreObject<Item> | Reference> : never : never : StoreVal extends Record<string, any> ? AsStoreObject<StoreVal> | Reference : StoreVal;\n\nexport { StoreValue }\n\n// @public (undocumented)\nclass Stump extends Layer {\n    constructor(root: Root);\n    // (undocumented)\n    merge(older: string | StoreObject, newer: string | StoreObject): void;\n    // (undocumented)\n    removeLayer(): this;\n}\n\n// @public (undocumented)\ntype ToReferenceFunction = (objOrIdOrRef: StoreObject | string | Reference, mergeIntoStore?: boolean) => Reference | undefined;\n\n// @public (undocumented)\nexport type Transaction = (c: ApolloCache) => void;\n\n// @public (undocumented)\nexport type TypePolicies = {\n    [__typename: string]: TypePolicy;\n};\n\n// @public (undocumented)\nexport type TypePolicy = {\n    keyFields?: KeySpecifier | KeyFieldsFunction | false;\n    merge?: FieldMergeFunction | boolean;\n    queryType?: true;\n    mutationType?: true;\n    subscriptionType?: true;\n    fields?: {\n        [fieldName: string]: FieldPolicy<any> | FieldReadFunction<any>;\n    };\n};\n\n// @public @deprecated (undocumented)\nexport type WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = ApolloCache_2.WatchFragmentOptions<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type WatchFragmentResult<TData> = ApolloCache_2.WatchFragmentResult<TData>;\n\n// @public (undocumented)\ninterface WriteContext extends ReadMergeModifyContext {\n    // (undocumented)\n    clientOnly: boolean;\n    // (undocumented)\n    deferred: boolean;\n    // Warning: (ae-forgotten-export) The symbol \"FlavorableWriteContext\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    flavors: Map<string, FlavorableWriteContext>;\n    // (undocumented)\n    readonly fragmentMap: FragmentMap;\n    // (undocumented)\n    incomingById: Map<string, {\n        storeObject: StoreObject;\n        mergeTree?: MergeTree;\n        fieldNodeSet: Set<FieldNode>;\n    }>;\n    // (undocumented)\n    lookupFragment: FragmentMapFunction;\n    // (undocumented)\n    merge<T>(existing: T, incoming: T): T;\n    // (undocumented)\n    overwrite: boolean;\n    // (undocumented)\n    readonly written: {\n        [dataId: string]: SelectionSetNode[];\n    };\n}\n\n// Warnings were encountered during analysis:\n//\n// src/cache/inmemory/policies.ts:173:3 - (ae-forgotten-export) The symbol \"KeySpecifier\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/policies.ts:173:3 - (ae-forgotten-export) The symbol \"KeyArgsFunction\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/types.ts:135:3 - (ae-forgotten-export) The symbol \"KeyFieldsFunction\" needs to be exported by the entry point index.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-core.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloCache } from '@apollo/client/cache';\nimport { ApolloLink } from '@apollo/client/link';\nimport { ApolloPayloadResult } from '@apollo/client/link';\nimport { ApolloReducerConfig } from '@apollo/client/cache';\nimport type { ApplyHKTImplementationWithDefault } from '@apollo/client/utilities/internal';\nimport { Cache as Cache_2 } from '@apollo/client/cache';\nimport { checkFetcher } from '@apollo/client/link/http';\nimport type { ClientAwarenessLink } from '@apollo/client/link/client-awareness';\nimport { CombinedGraphQLErrors } from '@apollo/client/errors';\nimport { CombinedProtocolErrors } from '@apollo/client/errors';\nimport { concat } from '@apollo/client/link';\nimport { createHttpLink } from '@apollo/client/link/http';\nimport { createSignalIfSupported } from '@apollo/client/link/http';\nimport type { DeepPartial } from '@apollo/client/utilities';\nimport { defaultDataIdFromObject } from '@apollo/client/cache';\nimport { defaultPrinter } from '@apollo/client/link/http';\nimport { DiffQueryAgainstStoreOptions } from '@apollo/client/cache';\nimport { disableExperimentalFragmentVariables } from 'graphql-tag';\nimport { disableFragmentWarnings } from 'graphql-tag';\nimport { DocumentNode } from '@apollo/client/link';\nimport type { DocumentNode as DocumentNode_2 } from 'graphql';\nimport { DocumentTransform } from '@apollo/client/utilities';\nimport { DocumentTransformCacheKey } from '@apollo/client/utilities';\nimport { empty } from '@apollo/client/link';\nimport { enableExperimentalFragmentVariables } from 'graphql-tag';\nimport { execute } from '@apollo/client/link';\nimport { extensionsSymbol } from '@apollo/client/utilities/internal';\nimport type { ExtensionsWithStreamInfo } from '@apollo/client/utilities/internal';\nimport { fallbackHttpConfig } from '@apollo/client/link/http';\nimport { FetchResult } from '@apollo/client/link';\nimport { FieldFunctionOptions } from '@apollo/client/cache';\nimport { FieldMergeFunction } from '@apollo/client/cache';\nimport { FieldPolicy } from '@apollo/client/cache';\nimport { FieldReadFunction } from '@apollo/client/cache';\nimport type { FormattedExecutionResult } from 'graphql';\nimport { FragmentType } from '@apollo/client/masking';\nimport { from } from '@apollo/client/link';\nimport { getApolloClientMemoryInternals } from '@apollo/client/utilities/internal';\nimport { gql } from 'graphql-tag';\nimport { GraphQLRequest } from '@apollo/client/link';\nimport type { HKT } from '@apollo/client/utilities';\nimport { HttpLink } from '@apollo/client/link/http';\nimport { IdGetter } from '@apollo/client/cache';\nimport { IdGetterObj } from '@apollo/client/cache';\nimport type { IgnoreModifier } from '@apollo/client/cache';\nimport type { Incremental } from '@apollo/client/incremental';\nimport { InMemoryCache } from '@apollo/client/cache';\nimport { InMemoryCacheConfig } from '@apollo/client/cache';\nimport type { InteropObservable } from 'rxjs';\nimport type { IsAny } from '@apollo/client/utilities/internal';\nimport { isNetworkRequestSettled } from '@apollo/client/utilities';\nimport { isReference } from '@apollo/client/utilities';\nimport { LinkError } from '@apollo/client/errors';\nimport type { LocalState } from '@apollo/client/local-state';\nimport { LocalStateError } from '@apollo/client/errors';\nimport { makeVar } from '@apollo/client/cache';\nimport { MaybeMasked } from '@apollo/client/masking';\nimport { MergeInfo } from '@apollo/client/cache';\nimport { MergeTree } from '@apollo/client/cache';\nimport { MissingFieldError } from '@apollo/client/cache';\nimport type { NextNotification } from 'rxjs';\nimport { NormalizedCache } from '@apollo/client/cache';\nimport { NormalizedCacheObject } from '@apollo/client/cache';\nimport { Observable } from '@apollo/client/utilities';\nimport { Observable as Observable_2 } from 'rxjs';\nimport type { ObservableNotification } from 'rxjs';\nimport type { Observer } from 'rxjs';\nimport { Operation } from '@apollo/client/link';\nimport { OperationTypeNode } from 'graphql';\nimport { OptimisticStoreItem } from '@apollo/client/cache';\nimport { parseAndCheckHttpResponse } from '@apollo/client/link/http';\nimport { PossibleTypesMap } from '@apollo/client/cache';\nimport { ReactiveVar } from '@apollo/client/cache';\nimport { ReadMergeModifyContext } from '@apollo/client/cache';\nimport { ReadQueryOptions } from '@apollo/client/cache';\nimport { Reference } from '@apollo/client/utilities';\nimport type { Reference as Reference_2 } from '@apollo/client/cache';\nimport { RequestHandler } from '@apollo/client/link';\nimport { resetCaches } from 'graphql-tag';\nimport { rewriteURIForGET } from '@apollo/client/link/http';\nimport { selectHttpOptionsAndBody } from '@apollo/client/link/http';\nimport { selectHttpOptionsAndBodyInternal } from '@apollo/client/link/http';\nimport { selectURI } from '@apollo/client/link/http';\nimport { ServerError } from '@apollo/client/errors';\nimport { ServerParseError } from '@apollo/client/errors';\nimport { setVerbosity as setLogVerbosity } from '@apollo/client/utilities/invariant';\nimport { split } from '@apollo/client/link';\nimport { StoreObject } from '@apollo/client/utilities';\nimport { StoreValue } from '@apollo/client/cache';\nimport type { Subscribable } from 'rxjs';\nimport type { Subscription } from 'rxjs';\nimport { Transaction } from '@apollo/client/cache';\nimport { Trie } from '@wry/trie';\nimport { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport { TypePolicies } from '@apollo/client/cache';\nimport { TypePolicy } from '@apollo/client/cache';\nimport { UnconventionalError } from '@apollo/client/errors';\nimport { Unmasked } from '@apollo/client/masking';\nimport type { VariablesOption } from '@apollo/client/utilities/internal';\nimport type { variablesUnknownSymbol } from '@apollo/client/utilities/internal';\nimport { WatchFragmentOptions } from '@apollo/client/cache';\nimport { WatchFragmentResult } from '@apollo/client/cache';\n\nexport { ApolloCache }\n\n// @public (undocumented)\nexport namespace ApolloClient {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface ReadQueryOptions<TData, TVariables extends OperationVariables> {\n            id?: string;\n            optimistic?: boolean;\n            query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n            returnPartialData?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface ReadFragmentOptions<TData, TVariables extends OperationVariables> {\n            fragment: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n            fragmentName?: string;\n            optimistic?: boolean;\n            returnPartialData?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> {\n            broadcast?: boolean;\n            data: Unmasked<TData>;\n            extensions?: Record<string, unknown>;\n            id?: string;\n            overwrite?: boolean;\n            query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface WriteFragmentOptions<TData, TVariables extends OperationVariables> {\n            broadcast?: boolean;\n            data: Unmasked<TData>;\n            fragment: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n            fragmentName?: string;\n            overwrite?: boolean;\n        }\n    }\n    // (undocumented)\n    export interface DefaultOptions {\n        // (undocumented)\n        mutate?: Partial<ApolloClient.MutateOptions<any, any, any>>;\n        // (undocumented)\n        query?: Partial<ApolloClient.QueryOptions<any, any>>;\n        // (undocumented)\n        watchQuery?: Partial<ApolloClient.WatchQueryOptions<any, any>>;\n    }\n    // (undocumented)\n    export interface DevtoolsOptions {\n        enabled?: boolean;\n        name?: string;\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ReadQueryOptions<TData, TVariables extends OperationVariables> extends Base.ReadQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ReadFragmentOptions<TData, TVariables extends OperationVariables> extends Base.ReadFragmentOptions<TData, TVariables> {\n            from?: ApolloCache.FromOptionValue<TData>;\n            id?: string;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteFragmentOptions<TData, TVariables extends OperationVariables> extends Base.WriteFragmentOptions<TData, TVariables> {\n            from?: ApolloCache.FromOptionValue<TData>;\n            id?: string;\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export interface Experiment {\n        // (undocumented)\n        (this: ApolloClient, options: ApolloClient.Options): void;\n        // (undocumented)\n        v: 1;\n    }\n    // (undocumented)\n    export type MutateOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = {\n        optimisticResponse?: Unmasked<NoInfer<TData>> | ((vars: TVariables, { IGNORE }: {\n            IGNORE: IgnoreModifier;\n        }) => Unmasked<NoInfer<TData>> | IgnoreModifier);\n        updateQueries?: MutationQueryReducersMap<TData>;\n        refetchQueries?: ((result: NormalizedExecutionResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude;\n        awaitRefetchQueries?: boolean;\n        update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n        onQueryUpdated?: OnQueryUpdated<any>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        fetchPolicy?: MutationFetchPolicy;\n        keepRootFields?: boolean;\n        mutation: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface MutateResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n        extensions?: Record<string, unknown>;\n    }\n    // (undocumented)\n    export interface ObservableFragment<TData = unknown> extends Observable_2<ApolloClient.WatchFragmentResult<TData>> {\n        getCurrentResult: () => ApolloClient.WatchFragmentResult<TData>;\n    }\n    // (undocumented)\n    export interface Options {\n        assumeImmutableResults?: boolean;\n        cache: ApolloCache;\n        // (undocumented)\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n        dataMasking?: boolean;\n        // (undocumented)\n        defaultContext?: Partial<DefaultContext>;\n        defaultOptions?: ApolloClient.DefaultOptions;\n        devtools?: ApolloClient.DevtoolsOptions;\n        // (undocumented)\n        documentTransform?: DocumentTransform;\n        // (undocumented)\n        enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n        experiments?: ApolloClient.Experiment[];\n        incrementalHandler?: Incremental.Handler<any>;\n        link: ApolloLink;\n        // (undocumented)\n        localState?: LocalState;\n        queryDeduplication?: boolean;\n        ssrForceFetchDelay?: number;\n        ssrMode?: boolean;\n    }\n    export type QueryOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        fetchPolicy?: FetchPolicy;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface QueryResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n    }\n    // (undocumented)\n    export type ReadFragmentOptions<TData, TVariables extends OperationVariables> = Base.ReadFragmentOptions<TData, TVariables> & VariablesOption<TVariables> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    export type ReadQueryOptions<TData, TVariables extends OperationVariables> = Base.ReadQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n    export interface RefetchQueriesOptions<TCache extends ApolloCache, TResult> {\n        include?: RefetchQueriesInclude;\n        onQueryUpdated?: OnQueryUpdated<TResult> | null;\n        optimistic?: boolean;\n        updateCache?: (cache: TCache) => void;\n    }\n    export interface RefetchQueriesResult<TResult> extends Promise<RefetchQueriesPromiseResults<TResult>>, RefetchQueriesResult.AdditionalProperties<TResult> {\n    }\n    // (undocumented)\n    export namespace RefetchQueriesResult {\n        // (undocumented)\n        export interface AdditionalProperties<TResult> {\n            queries: ObservableQuery<any>[];\n            results: InternalRefetchQueriesResult<TResult>[];\n        }\n    }\n    // (undocumented)\n    export type SubscribeOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        fetchPolicy?: FetchPolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        extensions?: Record<string, any>;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface SubscribeResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n        extensions?: Record<string, unknown>;\n    }\n    // (undocumented)\n    export type WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = ApolloCache.WatchFragmentOptions<TData, TVariables>;\n    // (undocumented)\n    export type WatchFragmentResult<TData = unknown> = ApolloCache.WatchFragmentResult<MaybeMasked<TData>>;\n    export type WatchQueryOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        fetchPolicy?: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        initialFetchPolicy?: WatchQueryFetchPolicy;\n        refetchWritePolicy?: RefetchWritePolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        pollInterval?: number;\n        notifyOnNetworkStatusChange?: boolean;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        [variablesUnknownSymbol]?: boolean;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export type WriteFragmentOptions<TData, TVariables extends OperationVariables> = Base.WriteFragmentOptions<TData, TVariables> & VariablesOption<TVariables> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    export type WriteQueryOptions<TData, TVariables extends OperationVariables> = Base.WriteQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n}\n\n// @public\nexport class ApolloClient {\n    // (undocumented)\n    __actionHookForDevTools(cb: () => any): void;\n    constructor(options: ApolloClient.Options);\n    // (undocumented)\n    __requestRaw(request: ApolloLink.Request): Observable_2<ApolloLink.Result<unknown>>;\n    // (undocumented)\n    cache: ApolloCache;\n    clearStore(): Promise<any[]>;\n    // (undocumented)\n    get defaultContext(): Partial<DefaultContext>;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    readonly devtoolsConfig: ApolloClient.DevtoolsOptions;\n    // @deprecated (undocumented)\n    disableNetworkFetches: never;\n    get documentTransform(): DocumentTransform;\n    extract(optimistic?: boolean): unknown;\n    getMemoryInternals?: typeof getApolloClientMemoryInternals;\n    getObservableQueries(include?: RefetchQueriesInclude): Set<ObservableQuery<any>>;\n    // (undocumented)\n    link: ApolloLink;\n    get localState(): LocalState | undefined;\n    set localState(localState: LocalState);\n    mutate<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache>(options: ApolloClient.MutateOptions<TData, TVariables, TCache>): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n    onClearStore(cb: () => Promise<any>): () => void;\n    onResetStore(cb: () => Promise<any>): () => void;\n    set prioritizeCacheValues(value: boolean);\n    get prioritizeCacheValues(): boolean;\n    query<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.QueryOptions<TData, TVariables>): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    queryDeduplication: boolean;\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadFragmentOptions<TData, TVariables>): Unmasked<TData> | null;\n    // @deprecated\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadFragmentOptions<TData, TVariables>, optimistic: boolean): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadQueryOptions<TData, TVariables>): Unmasked<TData> | null;\n    // @deprecated\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadQueryOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    // @deprecated\n    reFetchObservableQueries: (includeStandby?: boolean) => Promise<ApolloClient.QueryResult<any>[]>;\n    refetchObservableQueries(includeStandby?: boolean): Promise<ApolloClient.QueryResult<any>[]>;\n    refetchQueries<TCache extends ApolloCache = ApolloCache, TResult = Promise<ApolloClient.QueryResult<any>>>(options: ApolloClient.RefetchQueriesOptions<TCache, TResult>): ApolloClient.RefetchQueriesResult<TResult>;\n    resetStore(): Promise<ApolloClient.QueryResult<any>[] | null>;\n    restore(serializedState: unknown): ApolloCache;\n    setLink(newLink: ApolloLink): void;\n    stop(): void;\n    subscribe<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.SubscribeOptions<TData, TVariables>): SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    version: string;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData>>;\n    }): ApolloClient.ObservableFragment<Array<TData>>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<null>;\n    }): ApolloClient.ObservableFragment<Array<null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }): ApolloClient.ObservableFragment<Array<TData | null>>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: null;\n    }): ApolloClient.ObservableFragment<null>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: ApolloCache.FromOptionValue<TData>;\n    }): ApolloClient.ObservableFragment<TData>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables>): ApolloClient.ObservableFragment<TData | null>;\n    watchQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>): ObservableQuery<TData, TVariables>;\n    writeFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WriteFragmentOptions<TData, TVariables>): Reference_2 | undefined;\n    writeQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WriteQueryOptions<TData, TVariables>): Reference_2 | undefined;\n}\n\n// @public @deprecated (undocumented)\nexport type ApolloClientOptions = ApolloClient.Options;\n\nexport { ApolloLink }\n\nexport { ApolloPayloadResult }\n\n// @public @deprecated (undocumented)\nexport type ApolloQueryResult<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = ObservableQuery.Result<TData, TStates>;\n\nexport { ApolloReducerConfig }\n\n// @public (undocumented)\nexport const build: \"source\" | \"esm\" | \"cjs\";\n\nexport { Cache_2 as Cache }\n\nexport { checkFetcher }\n\nexport { CombinedGraphQLErrors }\n\nexport { CombinedProtocolErrors }\n\nexport { concat }\n\nexport { createHttpLink }\n\nexport { createSignalIfSupported }\n\n// @public (undocumented)\nexport type DataState<TData> = {\n    data: DataValue.Complete<TData>;\n    dataState: \"complete\";\n} | {\n    data: DataValue.Streaming<TData>;\n    dataState: \"streaming\";\n} | {\n    data: DataValue.Partial<TData>;\n    dataState: \"partial\";\n} | {\n    data: undefined;\n    dataState: \"empty\";\n};\n\n// @public (undocumented)\nexport namespace DataValue {\n    // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n    export type Complete<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Complete\", OverridableTypes.Defaults, TData>;\n    export type Partial<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Partial\", OverridableTypes.Defaults, TData>;\n    export type Streaming<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Streaming\", OverridableTypes.Defaults, TData>;\n}\n\n// @public (undocumented)\nexport interface DefaultContext extends Record<string, any> {\n    // (undocumented)\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    queryDeduplication?: boolean;\n}\n\nexport { defaultDataIdFromObject }\n\n// @public @deprecated (undocumented)\nexport type DefaultOptions = ApolloClient.DefaultOptions;\n\nexport { defaultPrinter }\n\n// @public @deprecated (undocumented)\nexport type DevtoolsOptions = ApolloClient.DevtoolsOptions;\n\nexport { DiffQueryAgainstStoreOptions }\n\nexport { disableExperimentalFragmentVariables }\n\nexport { disableFragmentWarnings }\n\nexport { DocumentNode }\n\nexport { DocumentTransform }\n\nexport { DocumentTransformCacheKey }\n\nexport { empty }\n\nexport { enableExperimentalFragmentVariables }\n\n// @public\nexport interface ErrorLike {\n    // (undocumented)\n    message: string;\n    // (undocumented)\n    name: string;\n    // (undocumented)\n    stack?: string;\n}\n\n// @public\nexport type ErrorPolicy = \"none\" | \"ignore\" | \"all\";\n\nexport { execute }\n\nexport { fallbackHttpConfig }\n\n// @public\nexport type FetchPolicy = \"cache-first\" | \"network-only\" | \"cache-only\" | \"no-cache\";\n\nexport { FetchResult }\n\nexport { FieldFunctionOptions }\n\nexport { FieldMergeFunction }\n\nexport { FieldPolicy }\n\nexport { FieldReadFunction }\n\nexport { FragmentType }\n\nexport { from }\n\n// @public (undocumented)\nexport type GetDataState<TData, TState extends DataState<TData>[\"dataState\"]> = Extract<DataState<TData>, {\n    dataState: TState;\n}>;\n\nexport { gql }\n\nexport { GraphQLRequest }\n\nexport { HttpLink }\n\nexport { IdGetter }\n\nexport { IdGetterObj }\n\nexport { InMemoryCache }\n\nexport { InMemoryCacheConfig }\n\n// Warning: (ae-forgotten-export) The symbol \"RefetchQueriesIncludeShorthand\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport type InternalRefetchQueriesInclude = InternalRefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// @public (undocumented)\nexport type InternalRefetchQueriesMap<TResult> = Map<ObservableQuery<any>, InternalRefetchQueriesResult<TResult>>;\n\n// @public (undocumented)\nexport interface InternalRefetchQueriesOptions<TCache extends ApolloCache, TResult> extends Omit<ApolloClient.RefetchQueriesOptions<TCache, TResult>, \"include\"> {\n    // (undocumented)\n    include?: InternalRefetchQueriesInclude;\n    // (undocumented)\n    removeOptimistic?: string;\n}\n\n// @public (undocumented)\nexport type InternalRefetchQueriesResult<TResult> = TResult extends boolean ? Promise<ApolloClient.QueryResult<any>> : TResult;\n\n// @public (undocumented)\nexport type InternalRefetchQueryDescriptor = RefetchQueryDescriptor | ApolloClient.QueryOptions;\n\n// @internal @deprecated (undocumented)\nexport namespace InternalTypes {\n    export type { NextFetchPolicyContext, QueryManager };\n}\n\nexport { isNetworkRequestSettled }\n\nexport { isReference }\n\nexport { LinkError }\n\nexport { LocalStateError }\n\nexport { makeVar }\n\n// @public (undocumented)\ninterface MaskFragmentOptions<TData> {\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    fragment: DocumentNode_2;\n    // (undocumented)\n    fragmentName?: string;\n}\n\n// @public (undocumented)\ninterface MaskOperationOptions<TData> {\n    cause?: object;\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    document: DocumentNode_2;\n    // (undocumented)\n    fetchPolicy?: WatchQueryFetchPolicy;\n}\n\nexport { MaybeMasked }\n\nexport { MergeInfo }\n\nexport { MergeTree }\n\nexport { MissingFieldError }\n\n// @public @deprecated (undocumented)\nexport type MutateResult<TData = unknown> = ApolloClient.MutateResult<TData>;\n\n// @public (undocumented)\nexport type MutationFetchPolicy = Extract<FetchPolicy, \"network-only\" | \"no-cache\">;\n\n// @public @deprecated (undocumented)\nexport type MutationOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = ApolloClient.MutateOptions<TData, TVariables, TCache>;\n\n// @public (undocumented)\nexport type MutationQueryReducer<T> = (previousResult: Record<string, any>, options: {\n    mutationResult: NormalizedExecutionResult<Unmasked<T>>;\n    queryName: string | undefined;\n    queryVariables: Record<string, any>;\n}) => Record<string, any>;\n\n// @public (undocumented)\nexport type MutationQueryReducersMap<T = {\n    [key: string]: any;\n}> = {\n    [queryName: string]: MutationQueryReducer<T>;\n};\n\n// @public (undocumented)\ninterface MutationStoreValue {\n    // (undocumented)\n    error: Error | null;\n    // (undocumented)\n    loading: boolean;\n    // (undocumented)\n    mutation: DocumentNode_2;\n    // (undocumented)\n    variables: Record<string, any>;\n}\n\n// @public (undocumented)\nexport type MutationUpdaterFunction<TData, TVariables extends OperationVariables, TCache extends ApolloCache> = (cache: TCache, result: FormattedExecutionResult<Unmasked<TData>>, options: {\n    context?: DefaultContext;\n    variables?: TVariables;\n}) => void;\n\n// @public\nexport enum NetworkStatus {\n    error = 8,\n    fetchMore = 3,\n    loading = 1,\n    poll = 6,\n    ready = 7,\n    refetch = 4,\n    setVariables = 2,\n    streaming = 9\n}\n\n// @public (undocumented)\ninterface NextFetchPolicyContext<TData, TVariables extends OperationVariables> {\n    // (undocumented)\n    initialFetchPolicy: WatchQueryFetchPolicy;\n    // (undocumented)\n    observable: ObservableQuery<TData, TVariables>;\n    // (undocumented)\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n    // (undocumented)\n    reason: \"after-fetch\" | \"variables-changed\";\n}\n\nexport { NormalizedCache }\n\nexport { NormalizedCacheObject }\n\n// @public\nexport type NormalizedExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = Omit<FormattedExecutionResult<TData, TExtensions>, \"data\"> & GetDataState<TData, \"streaming\" | \"complete\">;\n\nexport { Observable }\n\n// @public (undocumented)\ninterface ObservableAndInfo<TData> {\n    // (undocumented)\n    fromLink: boolean;\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    observable: Observable_2<QueryNotification.Value<TData>>;\n}\n\n// @public (undocumented)\nexport namespace ObservableQuery {\n    // @internal @deprecated\n    export interface CacheWatchOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Cache_2.WatchOptions<TData, TVariables> {\n        // @deprecated\n        lastOwnDiff?: Cache_2.DiffResult<TData>;\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ObservableMethods<TData, OperatorResult> {\n            pipe(...operators: OperatorFunctionChain<ObservableQuery.Result<TData>, OperatorResult>): Observable_2<OperatorResult>;\n            subscribe(observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)): Subscription;\n        }\n        // (undocumented)\n        export type OperatorFunctionChain<From, To> = [];\n    }\n    // (undocumented)\n    export type FetchMoreOptions<TData, TVariables extends OperationVariables, TFetchData = TData, TFetchVars extends OperationVariables = TVariables> = {\n        query?: DocumentNode_2 | TypedDocumentNode<TFetchData, TFetchVars>;\n        variables?: Partial<NoInfer<TFetchVars>>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        updateQuery?: (previousQueryResult: Unmasked<TData>, options: {\n            fetchMoreResult: Unmasked<TFetchData>;\n            variables: TFetchVars;\n        }) => Unmasked<TData>;\n    };\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        fetchPolicy: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        initialFetchPolicy: WatchQueryFetchPolicy;\n        refetchWritePolicy?: RefetchWritePolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        pollInterval?: number;\n        notifyOnNetworkStatusChange?: boolean;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n        query: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        variables: TVariables;\n    };\n    // (undocumented)\n    export type Result<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = {\n        error?: ErrorLike;\n        loading: boolean;\n        networkStatus: NetworkStatus;\n        partial: boolean;\n    } & GetDataState<TData, TStates>;\n    export interface ResultPromise<T> extends Promise<T> {\n        retain(): this;\n    }\n    // (undocumented)\n    export interface SubscribeToMoreOptions<TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> {\n        // (undocumented)\n        context?: DefaultContext;\n        // (undocumented)\n        document: DocumentNode_2 | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;\n        // (undocumented)\n        onError?: (error: ErrorLike) => void;\n        // (undocumented)\n        updateQuery?: SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n        // (undocumented)\n        variables?: TSubscriptionVariables;\n    }\n}\n\n// @public (undocumented)\nexport class ObservableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables> implements Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>, InteropObservable<ObservableQuery.Result<MaybeMasked<TData>>> {\n    // (undocumented)\n    [\"@@observable\"]: () => Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>;\n    // (undocumented)\n    [Symbol.observable]: () => Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>;\n    constructor({ queryManager, options, transformedQuery, }: {\n        queryManager: QueryManager;\n        options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n        transformedQuery?: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n        queryId?: string;\n    });\n    // @internal @deprecated (undocumented)\n    applyOptions(newOptions: Partial<ObservableQuery.Options<TData, TVariables>>): void;\n    fetchMore<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(options: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>): Promise<ApolloClient.QueryResult<TFetchData>>;\n    // @internal @deprecated (undocumented)\n    getCacheDiff({ optimistic }?: {\n        optimistic?: boolean | undefined;\n    }): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    getCurrentResult(): ObservableQuery.Result<MaybeMasked<TData>>;\n    // (undocumented)\n    hasObservers(): boolean;\n    // @internal @deprecated\n    _lastWrite?: unknown;\n    // @internal @deprecated (undocumented)\n    notify(scheduled?: boolean): void;\n    // (undocumented)\n    readonly options: ObservableQuery.Options<TData, TVariables>;\n    pipe: Observable_2<ObservableQuery.Result<MaybeMasked<TData>>>[\"pipe\"];\n    // (undocumented)\n    get query(): TypedDocumentNode<TData, TVariables>;\n    // (undocumented)\n    readonly queryName?: string;\n    refetch(variables?: Partial<TVariables>): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;\n    reobserve(newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>): ObservableQuery.ResultPromise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // @internal @deprecated\n    reset(): void;\n    setVariables(variables: TVariables): Promise<ApolloClient.QueryResult<TData>>;\n    startPolling(pollInterval: number): void;\n    stop(): void;\n    stopPolling(): void;\n    subscribe: (observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)) => Subscription;\n    subscribeToMore<TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>): () => void;\n    updateQuery(mapFn: UpdateQueryMapFn<TData, TVariables>): void;\n    get variables(): TVariables;\n}\n\n// @public (undocumented)\nexport type OnQueryUpdated<TResult> = (observableQuery: ObservableQuery<any>, diff: Cache_2.DiffResult<any>, lastDiff: Cache_2.DiffResult<any> | undefined) => boolean | TResult;\n\nexport { Operation }\n\n// @public (undocumented)\nexport type OperationVariables = Record<string, any>;\n\nexport { OptimisticStoreItem }\n\n// @public (undocumented)\nnamespace OverridableTypes {\n    // (undocumented)\n    interface Complete extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n    // (undocumented)\n    interface Defaults {\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Complete: Complete;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Partial: Partial;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Streaming: Streaming;\n    }\n    // (undocumented)\n    interface Partial extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: DeepPartial<this[\"arg1\"]>;\n    }\n    // (undocumented)\n    interface Streaming extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n}\n\nexport { parseAndCheckHttpResponse }\n\nexport { PossibleTypesMap }\n\n// @public (undocumented)\nnamespace QueryManager {\n    // (undocumented)\n    type Result<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = ObservableQuery.Result<TData, TStates> & {\n        [extensionsSymbol]?: ExtensionsWithStreamInfo;\n    };\n}\n\n// @public (undocumented)\nclass QueryManager {\n    // Warning: (ae-forgotten-export) The symbol \"QueryManagerOptions\" needs to be exported by the entry point index.d.ts\n    constructor(options: QueryManagerOptions);\n    // (undocumented)\n    readonly assumeImmutableResults: boolean;\n    // (undocumented)\n    broadcastQueries(): void;\n    // (undocumented)\n    get cache(): ApolloCache;\n    // (undocumented)\n    clearStore(options?: Cache_2.ResetOptions): Promise<void>;\n    // (undocumented)\n    readonly client: ApolloClient;\n    readonly clientOptions: ApolloClient.Options;\n    // (undocumented)\n    readonly dataMasking: boolean;\n    // (undocumented)\n    readonly defaultContext: Partial<DefaultContext>;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    readonly documentTransform: DocumentTransform;\n    // (undocumented)\n    protected fetchCancelFns: Map<string, (error: any) => any>;\n    // Warning: (ae-forgotten-export) The symbol \"ObservableAndInfo\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    fetchObservableWithInfo<TData, TVariables extends OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>, { networkStatus, query, fetchQueryOperator, onCacheHit, observableQuery, exposeExtensions, }: {\n        networkStatus?: NetworkStatus;\n        query?: DocumentNode_2;\n        fetchQueryOperator?: <T>(source: Observable_2<T>) => Observable_2<T>;\n        onCacheHit?: () => void;\n        observableQuery?: ObservableQuery<TData, TVariables> | undefined;\n        exposeExtensions?: boolean;\n    }): ObservableAndInfo<TData>;\n    // (undocumented)\n    fetchQuery<TData, TVariables extends OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>, networkStatus?: NetworkStatus): Promise<ApolloClient.QueryResult<TData>>;\n    // (undocumented)\n    generateRequestId(): number;\n    // Warning: (ae-forgotten-export) The symbol \"TransformCacheEntry\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getDocumentInfo(document: DocumentNode_2): TransformCacheEntry;\n    // (undocumented)\n    getObservableQueries(include?: InternalRefetchQueriesInclude): Set<ObservableQuery<any, OperationVariables>>;\n    // (undocumented)\n    getVariables<TVariables extends OperationVariables>(document: DocumentNode_2, variables?: TVariables): TVariables;\n    // (undocumented)\n    readonly incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    protected inFlightLinkObservables: Trie<{\n        observable?: Observable_2<ApolloLink.Result<any>>;\n        restart?: () => void;\n    }>;\n    // (undocumented)\n    get link(): ApolloLink;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"MaskFragmentOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    maskFragment<TData = unknown>(options: MaskFragmentOptions<TData>): TData;\n    // Warning: (ae-forgotten-export) The symbol \"MaskOperationOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    maskOperation<TData = unknown>(options: MaskOperationOptions<TData>): MaybeMasked<TData>;\n    // (undocumented)\n    mutate<TData, TVariables extends OperationVariables, TCache extends ApolloCache>({ mutation, variables, optimisticResponse, updateQueries, refetchQueries, awaitRefetchQueries, update: updateWithProxyFn, onQueryUpdated, fetchPolicy, errorPolicy, keepRootFields, context, }: ApolloClient.MutateOptions<TData, TVariables, TCache> & {\n        errorPolicy: ErrorPolicy;\n        fetchPolicy: MutationFetchPolicy;\n    }): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    mutationStore?: {\n        [mutationId: string]: MutationStoreValue;\n    };\n    obsQueries: Set<ObservableQuery<any, any>>;\n    prioritizeCacheValues: boolean;\n    // (undocumented)\n    query<TData, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.QueryOptions<TData, TVariables>): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    refetchObservableQueries(includeStandby?: boolean): Promise<ApolloClient.QueryResult<any>[]>;\n    // (undocumented)\n    refetchQueries<TResult>({ updateCache, include, optimistic, removeOptimistic, onQueryUpdated, }: InternalRefetchQueriesOptions<ApolloCache, TResult>): InternalRefetchQueriesMap<TResult>;\n    // (undocumented)\n    readonly ssrMode: boolean;\n    // (undocumented)\n    startGraphQLSubscription<TData = unknown>(options: ApolloClient.SubscribeOptions<TData>): SubscriptionObservable<ApolloClient.SubscribeResult<TData>>;\n    stop(): void;\n    // (undocumented)\n    transform(document: DocumentNode_2): DocumentNode_2;\n    // (undocumented)\n    watchQuery<TData, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>): ObservableQuery<TData, TVariables>;\n}\n\n// @public (undocumented)\ninterface QueryManagerOptions {\n    // (undocumented)\n    assumeImmutableResults: boolean;\n    // (undocumented)\n    client: ApolloClient;\n    // (undocumented)\n    clientOptions: ApolloClient.Options;\n    // (undocumented)\n    dataMasking: boolean;\n    // (undocumented)\n    defaultContext: Partial<DefaultContext> | undefined;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    documentTransform: DocumentTransform | null | undefined;\n    // (undocumented)\n    incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // (undocumented)\n    onBroadcast: undefined | (() => void);\n    // (undocumented)\n    queryDeduplication: boolean;\n    // (undocumented)\n    ssrMode: boolean;\n}\n\n// @public (undocumented)\nnamespace QueryNotification {\n    // (undocumented)\n    type FromCache<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n        source: \"cache\";\n    };\n    // (undocumented)\n    type FromNetwork<TData> = ObservableNotification<ObservableQuery.Result<TData>> & {\n        source: \"network\";\n    };\n    // (undocumented)\n    type NewNetworkStatus = NextNotification<{\n        resetError?: boolean;\n    }> & {\n        source: \"newNetworkStatus\";\n    };\n    // (undocumented)\n    type SetResult<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n        source: \"setResult\";\n    };\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    type Value<TData> = FromCache<TData> | FromNetwork<TData> | NewNetworkStatus | SetResult<TData>;\n}\n\n// @public @deprecated (undocumented)\nexport type QueryOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.QueryOptions<TData, TVariables>;\n\nexport { ReactiveVar }\n\nexport { ReadMergeModifyContext }\n\nexport { ReadQueryOptions }\n\nexport { Reference }\n\n// @public (undocumented)\nexport type RefetchQueriesInclude = RefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// @public (undocumented)\ntype RefetchQueriesIncludeShorthand = \"all\" | \"active\";\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesOptions<TCache extends ApolloCache, TResult> = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n\n// @public (undocumented)\nexport type RefetchQueriesPromiseResults<TResult> = IsAny<TResult> extends true ? any[] : TResult extends boolean ? ApolloClient.QueryResult<any>[] : TResult extends PromiseLike<infer U> ? U[] : TResult[];\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesResult<TResult> = ApolloClient.RefetchQueriesResult<TResult>;\n\n// @public (undocumented)\nexport type RefetchQueryDescriptor = string | DocumentNode_2;\n\n// @public (undocumented)\nexport type RefetchWritePolicy = \"merge\" | \"overwrite\";\n\nexport { RequestHandler }\n\nexport { resetCaches }\n\nexport { rewriteURIForGET }\n\nexport { selectHttpOptionsAndBody }\n\nexport { selectHttpOptionsAndBodyInternal }\n\nexport { selectURI }\n\nexport { ServerError }\n\nexport { ServerParseError }\n\nexport { setLogVerbosity }\n\nexport { split }\n\nexport { StoreObject }\n\nexport { StoreValue }\n\n// @public (undocumented)\nexport interface SubscribeToMoreFunction<TData, TVariables extends OperationVariables = OperationVariables> {\n    // (undocumented)\n    <TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>): () => void;\n}\n\n// @public @deprecated (undocumented)\nexport type SubscribeToMoreOptions<TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\n// @public (undocumented)\nexport type SubscribeToMoreUpdateQueryFn<TData = unknown, TVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData> = {\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables> & {\n        subscriptionData: {\n            data: Unmasked<TSubscriptionData>;\n        };\n    }): Unmasked<TData> | void;\n};\n\n// @public\nexport interface SubscriptionObservable<T> extends Observable_2<T> {\n    restart: () => void;\n}\n\n// @public @deprecated (undocumented)\nexport type SubscriptionOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.SubscribeOptions<TData, TVariables>;\n\nexport { Transaction }\n\n// @public (undocumented)\ninterface TransformCacheEntry {\n    // (undocumented)\n    asQuery: DocumentNode_2;\n    // (undocumented)\n    clientQuery: DocumentNode_2 | null;\n    // (undocumented)\n    defaultVars: OperationVariables;\n    // (undocumented)\n    hasClientExports: boolean;\n    // (undocumented)\n    hasForcedResolvers: boolean;\n    // (undocumented)\n    hasIncrementalDirective: boolean;\n    // (undocumented)\n    hasNonreactiveDirective: boolean;\n    // (undocumented)\n    nonReactiveQuery: DocumentNode_2;\n    // (undocumented)\n    operationType: OperationTypeNode | undefined;\n    // (undocumented)\n    serverQuery: DocumentNode_2 | null;\n    // (undocumented)\n    violation?: Error | undefined;\n}\n\nexport { TypedDocumentNode }\n\n// @public (undocumented)\nexport interface TypeOverrides {\n}\n\nexport { TypePolicies }\n\nexport { TypePolicy }\n\nexport { UnconventionalError }\n\nexport { Unmasked }\n\n// @public (undocumented)\nexport interface UpdateQueryMapFn<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n    // (undocumented)\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables>): Unmasked<TData> | void;\n}\n\n// @public (undocumented)\nexport type UpdateQueryOptions<TData, TVariables extends OperationVariables> = {\n    variables?: TVariables;\n} & ({\n    complete: true;\n    previousData: Unmasked<TData>;\n} | {\n    complete: false;\n    previousData: DeepPartial<Unmasked<TData>> | undefined;\n});\n\n// @public (undocumented)\nexport const version: string;\n\nexport { WatchFragmentOptions }\n\nexport { WatchFragmentResult }\n\n// @public (undocumented)\nexport type WatchQueryFetchPolicy = FetchPolicy | \"cache-and-network\" | \"standby\";\n\n// @public @deprecated (undocumented)\nexport type WatchQueryOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.WatchQueryOptions<TData, TVariables>;\n\n// Warnings were encountered during analysis:\n//\n// src/core/ApolloClient.ts:375:5 - (ae-forgotten-export) The symbol \"NextFetchPolicyContext\" needs to be exported by the entry point index.d.ts\n// src/core/ObservableQuery.ts:371:5 - (ae-forgotten-export) The symbol \"QueryManager\" needs to be exported by the entry point index.d.ts\n// src/core/QueryManager.ts:195:5 - (ae-forgotten-export) The symbol \"MutationStoreValue\" needs to be exported by the entry point index.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-dev.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public (undocumented)\ninterface ErrorCodes {\n    // (undocumented)\n    [key: number]: {\n        file: string;\n        condition?: string;\n        message?: string;\n    };\n}\n\n// @public\nexport type ErrorMessageHandler = {\n    (message: string | number, args: string[]): string | undefined;\n};\n\n// @public (undocumented)\nexport function loadDevMessages(): void;\n\n// Warning: (ae-forgotten-export) The symbol \"ErrorCodes\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport function loadErrorMessageHandler(...errorCodes: ErrorCodes[]): ErrorMessageHandler & ErrorCodes;\n\n// @public (undocumented)\nexport function loadErrorMessages(): void;\n\n// @public\nexport function setErrorMessageHandler(handler: ErrorMessageHandler): void;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-errors.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloLink } from '@apollo/client/link';\nimport { ErrorLike } from '@apollo/client';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { GraphQLFormattedError } from 'graphql';\n\n// @public (undocumented)\nexport namespace CombinedGraphQLErrors {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function formatMessage(errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions): string;\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly data: Record<string, unknown> | null | undefined;\n            readonly errors: ReadonlyArray<GraphQLFormattedError>;\n            readonly extensions: Record<string, unknown> | undefined;\n        }\n        export function is(error: unknown): boolean;\n    }\n    export type MessageFormatter = (errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions) => string;\n    // (undocumented)\n    export interface MessageFormatterOptions {\n        defaultFormatMessage: (errors: ReadonlyArray<GraphQLFormattedError>) => string;\n        result: ApolloLink.Result<unknown>;\n    }\n}\n\n// @public\nexport class CombinedGraphQLErrors extends Error {\n    constructor(result: FormattedExecutionResult<any>);\n    constructor(result: ApolloLink.Result<any>, errors: ReadonlyArray<GraphQLFormattedError>);\n    readonly data: Record<string, unknown> | null | undefined;\n    readonly errors: ReadonlyArray<GraphQLFormattedError>;\n    readonly extensions: Record<string, unknown> | undefined;\n    static formatMessage: CombinedGraphQLErrors.MessageFormatter;\n    static is(error: unknown): error is CombinedGraphQLErrors;\n}\n\n// @public (undocumented)\nexport namespace CombinedProtocolErrors {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function formatMessage(errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions): string;\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly errors: ReadonlyArray<GraphQLFormattedError>;\n        }\n    }\n    export type MessageFormatter = (errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions) => string;\n    // (undocumented)\n    export interface MessageFormatterOptions {\n        defaultFormatMessage: (errors: ReadonlyArray<GraphQLFormattedError>) => string;\n    }\n}\n\n// @public\nexport class CombinedProtocolErrors extends Error {\n    constructor(protocolErrors: Array<GraphQLFormattedError> | ReadonlyArray<GraphQLFormattedError>);\n    readonly errors: ReadonlyArray<GraphQLFormattedError>;\n    static formatMessage: CombinedProtocolErrors.MessageFormatter;\n    static is(error: unknown): error is CombinedProtocolErrors;\n}\n\n// @public (undocumented)\nexport function graphQLResultHasProtocolErrors<T extends {}>(result: T): result is T & {\n    extensions: Record<string | symbol, any>;\n};\n\n// @public (undocumented)\nexport function isErrorLike(error: unknown): error is ErrorLike;\n\n// @public\nexport const LinkError: {\n    is: (error: unknown) => boolean;\n};\n\n// @public (undocumented)\nexport namespace LocalStateError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly path?: Array<string | number>;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        path?: Array<string | number>;\n        // (undocumented)\n        sourceError?: unknown;\n    }\n}\n\n// @public\nexport class LocalStateError extends Error {\n    constructor(message: string, options?: LocalStateError.Options);\n    static is(error: unknown): error is LocalStateError;\n    readonly path?: Array<string | number>;\n}\n\n// @public (undocumented)\nexport const PROTOCOL_ERRORS_SYMBOL: unique symbol;\n\n// @internal @deprecated\nexport function registerLinkError(error: ErrorLike): void;\n\n// @public (undocumented)\nexport namespace ServerError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly bodyText: string;\n            readonly response: Response;\n            readonly statusCode: number;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        bodyText: string;\n        // (undocumented)\n        response: Response;\n    }\n}\n\n// @public\nexport class ServerError extends Error {\n    constructor(message: string, options: ServerError.Options);\n    readonly bodyText: string;\n    static is(error: unknown): error is ServerError;\n    readonly response: Response;\n    readonly statusCode: number;\n}\n\n// @public (undocumented)\nexport namespace ServerParseError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly bodyText: string;\n            readonly response: Response;\n            readonly statusCode: number;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        bodyText: string;\n        // (undocumented)\n        response: Response;\n    }\n}\n\n// @public\nexport class ServerParseError extends Error {\n    constructor(originalParseError: unknown, options: ServerParseError.Options);\n    readonly bodyText: string;\n    static is(error: unknown): error is ServerParseError;\n    readonly response: Response;\n    readonly statusCode: number;\n}\n\n// @public (undocumented)\nexport function toErrorLike(error: unknown): ErrorLike;\n\n// @public\nexport class UnconventionalError extends Error {\n    constructor(errorType: unknown);\n    static is(error: unknown): error is UnconventionalError;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-incremental.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloLink } from '@apollo/client/link';\nimport type { DeepPartial } from '@apollo/client/utilities';\nimport type { DocumentNode } from 'graphql';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { GraphQLFormattedError } from 'graphql';\nimport type { HKT } from '@apollo/client/utilities';\n\n// @public (undocumented)\nnamespace Defer20220824Handler {\n    // (undocumented)\n    type Chunk<TData extends Record<string, unknown>> = InitialResult<TData> | SubsequentResult<TData>;\n    // (undocumented)\n    interface Defer20220824Result extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        arg2: unknown;\n        // (undocumented)\n        return: Defer20220824Handler.Chunk<Record<string, unknown>>;\n    }\n    // (undocumented)\n    type IncrementalDeferResult<TData = Record<string, unknown>> = {\n        data?: TData | null;\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        extensions?: Record<string, unknown>;\n        path?: Incremental.Path;\n        label?: string;\n    };\n    // (undocumented)\n    type IncrementalResult<TData = Record<string, unknown>> = IncrementalDeferResult<TData> | IncrementalStreamResult<TData>;\n    // (undocumented)\n    type IncrementalStreamResult<TData = Array<unknown>> = {\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        items?: TData;\n        path?: Incremental.Path;\n        label?: string;\n        extensions?: Record<string, unknown>;\n    };\n    // (undocumented)\n    type InitialResult<TData = Record<string, unknown>> = {\n        data?: TData | null | undefined;\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        extensions?: Record<string, unknown>;\n        hasNext: boolean;\n        incremental?: ReadonlyArray<IncrementalResult<TData>>;\n    };\n    // (undocumented)\n    type SubsequentResult<TData = Record<string, unknown>> = {\n        extensions?: Record<string, unknown>;\n        hasNext: boolean;\n        incremental?: Array<IncrementalResult<TData>>;\n    };\n    // (undocumented)\n    interface TypeOverrides {\n        // (undocumented)\n        AdditionalApolloLinkResultTypes: Defer20220824Result;\n    }\n}\n\n// @public\nclass Defer20220824Handler implements Incremental.Handler<Defer20220824Handler.Chunk<any>> {\n    // (undocumented)\n    extractErrors(result: ApolloLink.Result<any>): GraphQLFormattedError[] | undefined;\n    // (undocumented)\n    isIncrementalResult(result: Record<string, any>): result is Defer20220824Handler.SubsequentResult | Defer20220824Handler.InitialResult;\n    // (undocumented)\n    prepareRequest(request: ApolloLink.Request): ApolloLink.Request;\n    // Warning: (ae-forgotten-export) The symbol \"DeferRequest\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    startRequest<TData extends Record<string, unknown>>(_: {\n        query: DocumentNode;\n    }): DeferRequest<TData>;\n}\nexport { Defer20220824Handler }\nexport { Defer20220824Handler as GraphQL17Alpha2Handler }\n\n// @public (undocumented)\nclass DeferRequest<TData extends Record<string, unknown>> implements Incremental.IncrementalRequest<Defer20220824Handler.Chunk<TData>, TData> {\n    // (undocumented)\n    handle(cacheData: TData | DeepPartial<TData> | null | undefined, chunk: Defer20220824Handler.Chunk<TData>): FormattedExecutionResult<TData>;\n    // (undocumented)\n    hasNext: boolean;\n}\n\n// @public (undocumented)\nexport namespace GraphQL17Alpha9Handler {\n    // (undocumented)\n    export type Chunk<TData> = InitialResult<TData> | SubsequentResult<TData>;\n    // (undocumented)\n    export interface CompletedResult {\n        // (undocumented)\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        // (undocumented)\n        id: string;\n    }\n    // (undocumented)\n    export interface GraphQL17Alpha9Result extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        arg2: unknown;\n        // (undocumented)\n        return: GraphQL17Alpha9Handler.Chunk<Record<string, unknown>>;\n    }\n    // (undocumented)\n    export interface IncrementalDeferResult<TData = Record<string, unknown>> {\n        // (undocumented)\n        data: TData;\n        // (undocumented)\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        // (undocumented)\n        extensions?: Record<string, unknown>;\n        // (undocumented)\n        id: string;\n        // (undocumented)\n        subPath?: Incremental.Path;\n    }\n    // (undocumented)\n    export type IncrementalResult<TData = unknown> = IncrementalDeferResult<TData> | IncrementalStreamResult<TData>;\n    // (undocumented)\n    export interface IncrementalStreamResult<TData = ReadonlyArray<unknown>> {\n        // (undocumented)\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        // (undocumented)\n        extensions?: Record<string, unknown>;\n        // (undocumented)\n        id: string;\n        // (undocumented)\n        items: TData;\n        // (undocumented)\n        subPath?: Incremental.Path;\n    }\n    // (undocumented)\n    export type InitialResult<TData = Record<string, unknown>> = {\n        data: TData;\n        errors?: ReadonlyArray<GraphQLFormattedError>;\n        pending: ReadonlyArray<PendingResult>;\n        hasNext: boolean;\n        extensions?: Record<string, unknown>;\n    };\n    // (undocumented)\n    export interface PendingResult {\n        // (undocumented)\n        id: string;\n        // (undocumented)\n        label?: string;\n        // (undocumented)\n        path: Incremental.Path;\n    }\n    // (undocumented)\n    export type SubsequentResult<TData = unknown> = {\n        hasNext: boolean;\n        pending?: ReadonlyArray<PendingResult>;\n        incremental?: ReadonlyArray<IncrementalResult<TData>>;\n        completed?: ReadonlyArray<CompletedResult>;\n        extensions?: Record<string, unknown>;\n    };\n    // (undocumented)\n    export interface TypeOverrides {\n        // (undocumented)\n        AdditionalApolloLinkResultTypes: GraphQL17Alpha9Result;\n    }\n}\n\n// @public\nexport class GraphQL17Alpha9Handler implements Incremental.Handler<GraphQL17Alpha9Handler.Chunk<any>> {\n    // @internal @deprecated (undocumented)\n    extractErrors(result: ApolloLink.Result<any>): GraphQLFormattedError[] | undefined;\n    // @internal @deprecated (undocumented)\n    isIncrementalResult(result: ApolloLink.Result<any>): result is GraphQL17Alpha9Handler.InitialResult | GraphQL17Alpha9Handler.SubsequentResult;\n    // @internal @deprecated (undocumented)\n    prepareRequest(request: ApolloLink.Request): ApolloLink.Request;\n    // Warning: (ae-forgotten-export) The symbol \"IncrementalRequest\" needs to be exported by the entry point index.d.ts\n    //\n    // @internal @deprecated (undocumented)\n    startRequest<TData>(_: {\n        query: DocumentNode;\n    }): IncrementalRequest<TData>;\n}\n\n// @public (undocumented)\nexport namespace Incremental {\n    // @internal @deprecated (undocumented)\n    export interface Handler<Chunk extends Record<string, unknown> = Record<string, unknown>> {\n        // (undocumented)\n        extractErrors: (result: ApolloLink.Result<any>) => readonly GraphQLFormattedError[] | undefined | void;\n        // (undocumented)\n        isIncrementalResult: (result: ApolloLink.Result<any>) => result is Chunk;\n        // (undocumented)\n        prepareRequest: (request: ApolloLink.Request) => ApolloLink.Request;\n        // (undocumented)\n        startRequest: <TData extends Record<string, unknown>>(request: {\n            query: DocumentNode;\n        }) => IncrementalRequest<Chunk, TData>;\n    }\n    // (undocumented)\n    export interface IncrementalRequest<Chunk extends Record<string, unknown>, TData> {\n        // (undocumented)\n        handle: (cacheData: TData | DeepPartial<TData> | undefined | null, chunk: Chunk) => FormattedExecutionResult<TData>;\n        // (undocumented)\n        hasNext: boolean;\n    }\n    // (undocumented)\n    export type Path = ReadonlyArray<string | number>;\n    // @internal @deprecated (undocumented)\n    export interface StreamFieldInfo {\n        // (undocumented)\n        isFirstChunk: boolean;\n        // (undocumented)\n        isLastChunk: boolean;\n    }\n}\n\n// @public (undocumented)\nclass IncrementalRequest<TData> implements Incremental.IncrementalRequest<GraphQL17Alpha9Handler.Chunk<TData>, TData> {\n    // (undocumented)\n    handle(cacheData: TData | DeepPartial<TData> | null | undefined, chunk: GraphQL17Alpha9Handler.Chunk<TData>): FormattedExecutionResult<TData>;\n    // (undocumented)\n    hasNext: boolean;\n}\n\n// @public (undocumented)\nexport namespace NotImplementedHandler {\n    // (undocumented)\n    export interface NotImplementedResult extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        arg2: unknown;\n        // (undocumented)\n        return: never;\n    }\n    // (undocumented)\n    export interface TypeOverrides {\n        // (undocumented)\n        AdditionalApolloLinkResultTypes: NotImplementedResult;\n    }\n}\n\n// @public (undocumented)\nexport class NotImplementedHandler implements Incremental.Handler<never> {\n    // (undocumented)\n    extractErrors(): void;\n    // (undocumented)\n    isIncrementalResult(_: any): _ is never;\n    // (undocumented)\n    prepareRequest(request: ApolloLink.Request): ApolloLink.Request;\n    // (undocumented)\n    startRequest: any;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloClient } from '@apollo/client';\nimport type { ApplyHKTImplementationWithDefault } from '@apollo/client/utilities/internal';\nimport type { DefaultContext } from '@apollo/client';\nimport { DocumentNode } from 'graphql';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { GraphQLFormattedError } from 'graphql';\nimport type { NotImplementedHandler } from '@apollo/client/incremental';\nimport type { Observable } from 'rxjs';\nimport type { OperationTypeNode } from 'graphql';\nimport type { OperationVariables } from '@apollo/client';\nimport type { TypeOverrides } from '@apollo/client';\n\n// @public (undocumented)\nexport namespace ApolloLink {\n    // (undocumented)\n    export type AdditionalResultTypes<TData = Record<string, any>, TExtensions = Record<string, any>> = ApplyHKTImplementationWithDefault<TypeOverrides, \"AdditionalApolloLinkResultTypes\", NotImplementedHandler.TypeOverrides, TData, TExtensions>;\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function ForwardFunction(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n        export function RequestHandler(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n    }\n    export interface ExecuteContext {\n        client: ApolloClient;\n    }\n    export type ForwardFunction = (operation: ApolloLink.Operation) => Observable<ApolloLink.Result>;\n    export interface Operation {\n        readonly client: ApolloClient;\n        extensions: Record<string, any>;\n        getContext: () => Readonly<ApolloLink.OperationContext>;\n        operationName: string | undefined;\n        operationType: OperationTypeNode;\n        query: DocumentNode;\n        setContext: {\n            (context: Partial<ApolloLink.OperationContext>): void;\n            (updateContext: (previousContext: Readonly<ApolloLink.OperationContext>) => Partial<ApolloLink.OperationContext>): void;\n        };\n        variables: OperationVariables;\n    }\n    export interface OperationContext extends DefaultContext {\n    }\n    export interface Request {\n        context?: DefaultContext;\n        extensions?: Record<string, any>;\n        query: DocumentNode;\n        variables?: OperationVariables;\n    }\n    export type RequestHandler = (operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction) => Observable<ApolloLink.Result>;\n    // (undocumented)\n    export type Result<TData = Record<string, any>, TExtensions = Record<string, any>> = FormattedExecutionResult<TData, TExtensions> | AdditionalResultTypes<TData, TExtensions>;\n}\n\n// @public\nexport class ApolloLink {\n    constructor(request?: ApolloLink.RequestHandler);\n    // @deprecated\n    static concat(...links: ApolloLink[]): ApolloLink;\n    concat(...links: ApolloLink[]): ApolloLink;\n    static empty(): ApolloLink;\n    static execute(link: ApolloLink, request: ApolloLink.Request, context: ApolloLink.ExecuteContext): Observable<ApolloLink.Result>;\n    static from(links: ApolloLink[]): ApolloLink;\n    // @internal @deprecated\n    getMemoryInternals?: () => unknown;\n    // @internal @deprecated\n    readonly left?: ApolloLink;\n    request(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n    // @internal @deprecated\n    readonly right?: ApolloLink;\n    static split(test: (op: ApolloLink.Operation) => boolean, left: ApolloLink, right?: ApolloLink): ApolloLink;\n    split(test: (op: ApolloLink.Operation) => boolean, left: ApolloLink, right?: ApolloLink): ApolloLink;\n}\n\n// @public (undocumented)\nexport interface ApolloPayloadResult<TData = Record<string, any>, TExtensions = Record<string, any>> {\n    // (undocumented)\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    // (undocumented)\n    payload: FormattedExecutionResult<TData, TExtensions> | null;\n}\n\n// @public @deprecated (undocumented)\nexport const concat: typeof ApolloLink.concat;\n\nexport { DocumentNode }\n\n// @public @deprecated (undocumented)\nexport const empty: typeof ApolloLink.empty;\n\n// @public (undocumented)\nexport const execute: typeof ApolloLink.execute;\n\n// @public @deprecated (undocumented)\nexport type FetchResult<TData = Record<string, any>, TExtensions = Record<string, any>> = ApolloLink.Result<TData, TExtensions>;\n\n// @public @deprecated (undocumented)\nexport const from: typeof ApolloLink.from;\n\n// @public @deprecated (undocumented)\nexport type GraphQLRequest = ApolloLink.Request;\n\n// @public @deprecated (undocumented)\nexport type Operation = ApolloLink.Operation;\n\n// @public @deprecated (undocumented)\nexport type RequestHandler = ApolloLink.RequestHandler;\n\n// @public @deprecated (undocumented)\nexport const split: typeof ApolloLink.split;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_batch-http.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { BaseHttpLink } from '@apollo/client/link/http';\nimport { BatchLink } from '@apollo/client/link/batch';\nimport { ClientAwarenessLink } from '@apollo/client/link/client-awareness';\nimport { Observable } from 'rxjs';\n\n// @public (undocumented)\nexport namespace BaseBatchHttpLink {\n    export interface ContextOptions extends BaseHttpLink.ContextOptions {\n    }\n    export interface Options extends BatchLink.Shared.Options, BaseHttpLink.Shared.Options {\n        batchMax?: number;\n    }\n}\n\n// @public\nexport class BaseBatchHttpLink extends ApolloLink {\n    constructor(options?: BaseBatchHttpLink.Options);\n    // (undocumented)\n    request(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n}\n\n// @public (undocumented)\nexport namespace BatchHttpLink {\n    export interface ContextOptions extends BaseBatchHttpLink.ContextOptions, ClientAwarenessLink.ContextOptions {\n    }\n    export interface Options extends BaseBatchHttpLink.Options, ClientAwarenessLink.Options {\n    }\n}\n\n// @public\nexport class BatchHttpLink extends ApolloLink {\n    constructor(options?: BatchHttpLink.Options);\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_batch.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { Observable } from 'rxjs';\n\n// @public (undocumented)\nexport namespace BatchLink {\n    export type BatchHandler = (operations: ApolloLink.Operation[], forward: ApolloLink.ForwardFunction[]) => Observable<ApolloLink.Result[]>;\n    export interface Options extends Shared.Options {\n        batchHandler?: BatchLink.BatchHandler;\n        batchMax?: number;\n    }\n    // (undocumented)\n    export namespace Shared {\n        export interface Options {\n            batchDebounce?: boolean;\n            batchInterval?: number;\n            batchKey?: (operation: ApolloLink.Operation) => string;\n            batchMax?: number;\n        }\n    }\n}\n\n// @public\nexport class BatchLink extends ApolloLink {\n    constructor(options?: BatchLink.Options);\n    // (undocumented)\n    request(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_client-awareness.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\n\n// @public (undocumented)\nexport namespace ClientAwarenessLink {\n    // (undocumented)\n    export interface ClientAwarenessOptions {\n        name?: string;\n        transport?: \"headers\" | false;\n        version?: string;\n    }\n    export interface ContextOptions {\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    }\n    // (undocumented)\n    export interface EnhancedClientAwarenessOptions {\n        transport?: \"headers\" | \"extensions\" | false;\n    }\n    // (undocumented)\n    export interface Options {\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n        enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n    }\n}\n\n// @public\nexport class ClientAwarenessLink extends ApolloLink {\n    constructor(options?: ClientAwarenessLink.Options);\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_context.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\n\n// @public @deprecated (undocumented)\nexport function setContext(setter: SetContextLink.LegacyContextSetter): SetContextLink;\n\n// @public (undocumented)\nexport namespace SetContextLink {\n    export type ContextSetter = (prevContext: Readonly<ApolloLink.OperationContext>, operation: SetContextLink.SetContextOperation) => Promise<Partial<ApolloLink.OperationContext>> | Partial<ApolloLink.OperationContext>;\n    // @deprecated (undocumented)\n    export type LegacyContextSetter = (operation: SetContextLink.SetContextOperation, prevContext: Readonly<ApolloLink.OperationContext>) => Promise<Partial<ApolloLink.OperationContext>> | Partial<ApolloLink.OperationContext>;\n    // (undocumented)\n    export namespace SetContextLinkDocumentationTypes {\n        export function ContextSetter(prevContext: Readonly<ApolloLink.OperationContext>, operation: SetContextLink.SetContextOperation): Promise<Partial<ApolloLink.OperationContext>> | Partial<ApolloLink.OperationContext>;\n    }\n    export type SetContextOperation = Omit<ApolloLink.Operation, \"getContext\" | \"setContext\">;\n}\n\n// @public\nexport class SetContextLink extends ApolloLink {\n    constructor(setter: SetContextLink.ContextSetter);\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_error.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { ErrorLike } from '@apollo/client';\nimport { Observable } from 'rxjs';\n\n// @public (undocumented)\nexport namespace ErrorLink {\n    export interface ErrorHandler {\n        // (undocumented)\n        (options: ErrorHandlerOptions): Observable<ApolloLink.Result> | void;\n    }\n    export interface ErrorHandlerOptions {\n        error: ErrorLike;\n        forward: ApolloLink.ForwardFunction;\n        operation: ApolloLink.Operation;\n        result?: ApolloLink.Result;\n    }\n    // (undocumented)\n    export namespace ErrorLinkDocumentationTypes {\n        export function ErrorHandler(options: ErrorHandlerOptions): Observable<ApolloLink.Result> | void;\n    }\n}\n\n// @public\nexport class ErrorLink extends ApolloLink {\n    constructor(errorHandler: ErrorLink.ErrorHandler);\n}\n\n// @public @deprecated (undocumented)\nexport function onError(errorHandler: ErrorLink.ErrorHandler): ErrorLink;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_http.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { ASTNode } from 'graphql';\nimport { ClientAwarenessLink } from '@apollo/client/link/client-awareness';\nimport type { print as print_2 } from 'graphql';\n\n// @public (undocumented)\nexport namespace BaseHttpLink {\n    // (undocumented)\n    export interface Body {\n        // (undocumented)\n        extensions?: Record<string, any>;\n        // (undocumented)\n        operationName?: string;\n        // (undocumented)\n        query?: string;\n        // (undocumented)\n        variables?: Record<string, any>;\n    }\n    export interface ContextOptions {\n        credentials?: RequestCredentials;\n        fetchOptions?: RequestInit;\n        headers?: Record<string, string>;\n        http?: BaseHttpLink.HttpOptions;\n        uri?: string | BaseHttpLink.UriFunction;\n    }\n    export interface HttpOptions {\n        accept?: string[];\n        includeExtensions?: boolean;\n        includeQuery?: boolean;\n        preserveHeaderCase?: boolean;\n    }\n    export interface Options extends Shared.Options {\n        useGETForQueries?: boolean;\n    }\n    // (undocumented)\n    export type Printer = (node: ASTNode, originalPrint: typeof print_2) => string;\n    // (undocumented)\n    export namespace Shared {\n        export interface Options {\n            credentials?: RequestCredentials;\n            fetch?: typeof fetch;\n            fetchOptions?: RequestInit;\n            headers?: Record<string, string>;\n            includeExtensions?: boolean;\n            includeUnusedVariables?: boolean;\n            preserveHeaderCase?: boolean;\n            print?: BaseHttpLink.Printer;\n            uri?: string | BaseHttpLink.UriFunction;\n        }\n    }\n    // (undocumented)\n    export type UriFunction = (operation: ApolloLink.Operation) => string;\n}\n\n// @public\nexport class BaseHttpLink extends ApolloLink {\n    constructor(options?: BaseHttpLink.Options);\n}\n\n// @public (undocumented)\nexport const checkFetcher: (fetcher: typeof fetch | undefined) => void;\n\n// @public @deprecated (undocumented)\nexport const createHttpLink: (options?: HttpLink.Options) => HttpLink;\n\n// @public @deprecated (undocumented)\nexport const createSignalIfSupported: () => {\n    controller: boolean;\n    signal: boolean;\n} | {\n    controller: AbortController;\n    signal: AbortSignal;\n};\n\n// @public (undocumented)\nexport const defaultPrinter: BaseHttpLink.Printer;\n\n// @public (undocumented)\nexport const fallbackHttpConfig: {\n    http: BaseHttpLink.HttpOptions;\n    headers: {\n        accept: string;\n        \"content-type\": string;\n    };\n    options: {\n        method: string;\n    };\n};\n\n// @public (undocumented)\ninterface HttpConfig {\n    // (undocumented)\n    credentials?: any;\n    // (undocumented)\n    headers?: Record<string, string>;\n    // (undocumented)\n    http?: BaseHttpLink.HttpOptions;\n    // (undocumented)\n    options?: any;\n}\n\n// @public (undocumented)\nexport namespace HttpLink {\n    export interface ContextOptions extends BaseHttpLink.ContextOptions, ClientAwarenessLink.ContextOptions {\n    }\n    export interface Options extends BaseHttpLink.Options, ClientAwarenessLink.Options {\n    }\n}\n\n// @public\nexport class HttpLink extends ApolloLink {\n    constructor(options?: HttpLink.Options);\n}\n\n// @public (undocumented)\nexport function parseAndCheckHttpResponse(operations: ApolloLink.Operation | ApolloLink.Operation[]): (response: Response) => Promise<any>;\n\n// @public (undocumented)\nexport function rewriteURIForGET(chosenURI: string, body: BaseHttpLink.Body): {\n    parseError: unknown;\n    newURI?: undefined;\n} | {\n    newURI: string;\n    parseError?: undefined;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"HttpConfig\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function selectHttpOptionsAndBody(operation: ApolloLink.Operation, fallbackConfig: HttpConfig, ...configs: Array<HttpConfig>): {\n    options: HttpConfig & Record<string, any>;\n    body: BaseHttpLink.Body;\n};\n\n// @public (undocumented)\nexport function selectHttpOptionsAndBodyInternal(operation: ApolloLink.Operation, printer: BaseHttpLink.Printer, ...configs: HttpConfig[]): {\n    options: HttpConfig & Record<string, any>;\n    body: BaseHttpLink.Body;\n};\n\n// @public (undocumented)\nexport const selectURI: (operation: ApolloLink.Operation, fallbackURI?: string | ((operation: ApolloLink.Operation) => string)) => any;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_persisted-queries.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { DocumentNode } from 'graphql';\nimport type { ErrorLike } from '@apollo/client';\nimport type { FormattedExecutionResult } from 'graphql';\n\n// @public @deprecated (undocumented)\nexport const createPersistedQueryLink: (options: PersistedQueryLink.Options) => PersistedQueryLink;\n\n// @public (undocumented)\nexport namespace PersistedQueryLink {\n    // (undocumented)\n    export namespace Base {\n        export interface Options {\n            disable?: (options: PersistedQueryLink.DisableFunctionOptions) => boolean;\n            retry?: (options: PersistedQueryLink.RetryFunctionOptions) => boolean;\n            useGETForHashedQueries?: boolean;\n        }\n    }\n    export interface DisableFunctionOptions extends PersistedQueryLink.RetryFunctionOptions {\n    }\n    export interface ErrorMeta {\n        persistedQueryNotFound: boolean;\n        persistedQueryNotSupported: boolean;\n    }\n    export type GenerateHashFunction = (document: DocumentNode) => string | PromiseLike<string>;\n    export interface GenerateHashOptions extends Base.Options {\n        generateHash: PersistedQueryLink.GenerateHashFunction;\n        // (undocumented)\n        sha256?: never;\n    }\n    export type Options = PersistedQueryLink.SHA256Options | PersistedQueryLink.GenerateHashOptions;\n    // (undocumented)\n    export namespace PersistedQueryLinkDocumentationTypes {\n        export function GenerateHashFunction(document: DocumentNode): string | PromiseLike<string>;\n        export function SHA256Function(queryString: string): string | PromiseLike<string>;\n    }\n    export interface RetryFunctionOptions {\n        error: ErrorLike;\n        meta: PersistedQueryLink.ErrorMeta;\n        operation: ApolloLink.Operation;\n        result?: FormattedExecutionResult;\n    }\n    export type SHA256Function = (queryString: string) => string | PromiseLike<string>;\n    export interface SHA256Options extends Base.Options {\n        // (undocumented)\n        generateHash?: never;\n        sha256: PersistedQueryLink.SHA256Function;\n    }\n}\n\n// @public\nexport class PersistedQueryLink extends ApolloLink {\n    constructor(options: PersistedQueryLink.Options);\n    // (undocumented)\n    resetHashCache: () => void;\n}\n\n// @public (undocumented)\nexport const VERSION = 1;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_remove-typename.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\n\n// @public\nexport const KEEP = \"__KEEP\";\n\n// @public @deprecated (undocumented)\nexport function removeTypenameFromVariables(options?: RemoveTypenameFromVariablesLink.Options): RemoveTypenameFromVariablesLink;\n\n// @public (undocumented)\nexport namespace RemoveTypenameFromVariablesLink {\n    export interface KeepTypenameConfig {\n        // (undocumented)\n        [key: string]: typeof KEEP | RemoveTypenameFromVariablesLink.KeepTypenameConfig;\n    }\n    export interface Options {\n        except?: RemoveTypenameFromVariablesLink.KeepTypenameConfig;\n    }\n}\n\n// @public\nexport class RemoveTypenameFromVariablesLink extends ApolloLink {\n    constructor(options?: RemoveTypenameFromVariablesLink.Options);\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_retry.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { ErrorLike } from '@apollo/client';\nimport { Observable } from 'rxjs';\n\n// @public (undocumented)\nexport namespace RetryLink {\n    export type AttemptsFunction = (attempt: number, operation: ApolloLink.Operation, error: ErrorLike) => boolean | Promise<boolean>;\n    export interface AttemptsOptions {\n        max?: number;\n        retryIf?: (error: ErrorLike, operation: ApolloLink.Operation) => boolean | Promise<boolean>;\n    }\n    export type DelayFunction = (attempt: number, operation: ApolloLink.Operation, error: ErrorLike) => number;\n    export interface DelayOptions {\n        initial?: number;\n        jitter?: boolean;\n        max?: number;\n    }\n    export interface Options {\n        attempts?: RetryLink.AttemptsOptions | RetryLink.AttemptsFunction;\n        delay?: RetryLink.DelayOptions | RetryLink.DelayFunction;\n    }\n    // (undocumented)\n    export namespace RetryLinkDocumentationTypes {\n        export function AttemptsFunction(attempt: number, operation: ApolloLink.Operation, error: ErrorLike): boolean | Promise<boolean>;\n        export function DelayFunction(attempt: number, operation: ApolloLink.Operation, error: ErrorLike): number;\n    }\n}\n\n// @public\nexport class RetryLink extends ApolloLink {\n    constructor(options?: RetryLink.Options);\n    // (undocumented)\n    request(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_schema.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { GraphQLSchema } from 'graphql';\nimport { Observable } from 'rxjs';\n\n// @public (undocumented)\nexport namespace SchemaLink {\n    export interface Options {\n        context?: SchemaLink.ResolverContext | SchemaLink.ResolverContextFunction;\n        rootValue?: any;\n        schema: GraphQLSchema;\n        validate?: boolean;\n    }\n    export type ResolverContext = Record<string, any>;\n    export type ResolverContextFunction = (operation: ApolloLink.Operation) => SchemaLink.ResolverContext | PromiseLike<SchemaLink.ResolverContext>;\n    // (undocumented)\n    export namespace SchemaLinkDocumentationTypes {\n        export function ResolverContextFunction(operation: ApolloLink.Operation): SchemaLink.ResolverContext | PromiseLike<SchemaLink.ResolverContext>;\n    }\n}\n\n// @public\nexport class SchemaLink extends ApolloLink {\n    constructor(options: SchemaLink.Options);\n    // (undocumented)\n    context: SchemaLink.Options[\"context\"];\n    // (undocumented)\n    request(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n    // (undocumented)\n    rootValue: SchemaLink.Options[\"rootValue\"];\n    // (undocumented)\n    schema: SchemaLink.Options[\"schema\"];\n    // (undocumented)\n    validate: boolean;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_subscriptions.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { Client } from 'graphql-ws';\nimport { Observable } from 'rxjs';\n\n// @public\nexport class GraphQLWsLink extends ApolloLink {\n    constructor(client: Client);\n    // (undocumented)\n    readonly client: Client;\n    // (undocumented)\n    request(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_utils.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloLink } from '@apollo/client/link';\nimport type { DocumentNode } from 'graphql';\n\n// @public (undocumented)\nexport function createOperation(request: ApolloLink.Request, { client }: ApolloLink.ExecuteContext): ApolloLink.Operation;\n\n// @public (undocumented)\nexport function filterOperationVariables(variables: Record<string, any>, query: DocumentNode): {\n    [x: string]: any;\n};\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-link_ws.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { ClientOptions } from 'subscriptions-transport-ws';\nimport type { Observable } from 'rxjs';\nimport { SubscriptionClient } from 'subscriptions-transport-ws';\n\n// @public (undocumented)\nexport namespace WebSocketLink {\n    export interface Configuration {\n        options?: ClientOptions;\n        uri: string;\n        webSocketImpl?: any;\n    }\n}\n\n// @public @deprecated\nexport class WebSocketLink extends ApolloLink {\n    constructor(paramsOrClient: WebSocketLink.Configuration | SubscriptionClient);\n    // (undocumented)\n    request(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-local-state.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloClient } from '@apollo/client';\nimport type { DefaultContext } from '@apollo/client';\nimport type { DocumentNode } from 'graphql';\nimport type { FieldNode } from 'graphql';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { FragmentMap } from '@apollo/client/utilities/internal';\nimport type { NoInfer as NoInfer_2 } from '@apollo/client/utilities/internal';\nimport type { OperationVariables } from '@apollo/client';\nimport type { RemoveIndexSignature } from '@apollo/client/utilities/internal';\nimport type { TypedDocumentNode } from '@apollo/client';\nimport type { WatchQueryFetchPolicy } from '@apollo/client';\n\n// @public (undocumented)\ntype InferContextValueFromResolvers<TResolvers> = TResolvers extends {\n    [typename: string]: infer TFieldResolvers;\n} ? TFieldResolvers extends ({\n    [field: string]: LocalState.Resolver<any, any, infer TContext, any>;\n}) ? unknown extends TContext ? DefaultContext : TContext : DefaultContext : DefaultContext;\n\n// @public (undocumented)\nexport namespace LocalState {\n    // (undocumented)\n    export type ContextFunction<TContext> = (options: ContextFunctionOptions) => TContext;\n    // (undocumented)\n    export interface ContextFunctionOptions {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        document: DocumentNode;\n        // (undocumented)\n        phase: \"exports\" | \"resolve\";\n        // (undocumented)\n        requestContext: DefaultContext;\n        // (undocumented)\n        variables: OperationVariables;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"MaybeRequireContextFunction\" needs to be exported by the entry point index.d.ts\n    export type Options<TResolvers extends Resolvers = Resolvers, TContext = DefaultContext> = {\n        context?: ContextFunction<TContext>;\n        resolvers?: TResolvers;\n    } & MaybeRequireContextFunction<TContext>;\n    // (undocumented)\n    export type Path = Array<string | number>;\n    export type Resolver<TResult = unknown, TParent = unknown, TContext = DefaultContext, TArgs = Record<string, unknown>> = (rootValue: TParent, args: TArgs, context: {\n        requestContext: TContext;\n        client: ApolloClient;\n        phase: \"exports\" | \"resolve\";\n    }, info: {\n        field: FieldNode;\n        fragmentMap: FragmentMap;\n        path: Path;\n    }) => TResult | Promise<TResult>;\n    export interface Resolvers<TContext = any> {\n        // (undocumented)\n        [typename: string]: {\n            [field: string]: Resolver<any, any, TContext, any>;\n        };\n    }\n    // (undocumented)\n    export type RootValueFunction<TRootValue> = (context: RootValueFunctionContext) => TRootValue;\n    // (undocumented)\n    export interface RootValueFunctionContext {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        context: DefaultContext;\n        // (undocumented)\n        document: DocumentNode;\n        // (undocumented)\n        phase: \"exports\" | \"resolve\";\n        // (undocumented)\n        variables: OperationVariables;\n    }\n}\n\n// Warning: (ae-forgotten-export) The symbol \"InferContextValueFromResolvers\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport class LocalState<TResolvers extends LocalState.Resolvers = LocalState.Resolvers<DefaultContext>, TContext = InferContextValueFromResolvers<TResolvers>> {\n    constructor(...[options]: {} extends TResolvers ? [\n    options?: LocalState.Options<TResolvers, NoInfer_2<TContext>>\n    ] : [\n    options: LocalState.Options<TResolvers, NoInfer_2<TContext>> & {\n        resolvers: TResolvers;\n    }\n    ]);\n    addResolvers(resolvers: TResolvers): void;\n    // (undocumented)\n    execute<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ document, client, context, remoteResult, variables, onlyRunForcedResolvers, returnPartialData, fetchPolicy, }: {\n        document: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        client: ApolloClient;\n        context: DefaultContext | undefined;\n        remoteResult: FormattedExecutionResult<any> | undefined;\n        variables: TVariables | undefined;\n        onlyRunForcedResolvers?: boolean;\n        returnPartialData?: boolean;\n        fetchPolicy: WatchQueryFetchPolicy;\n    }): Promise<FormattedExecutionResult<TData>>;\n    // (undocumented)\n    getExportedVariables<TVariables extends OperationVariables = OperationVariables>({ document, client, context, variables, }: {\n        document: DocumentNode | TypedDocumentNode<any, TVariables>;\n        client: ApolloClient;\n        context: DefaultContext | undefined;\n        variables: Partial<NoInfer_2<TVariables>>;\n    }): Promise<TVariables>;\n}\n\n// @public (undocumented)\ntype MaybeRequireContextFunction<TContext> = {} extends RemoveIndexSignature<TContext> ? {} : {\n    context: LocalState.ContextFunction<TContext>;\n};\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-masking.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache } from '@apollo/client';\nimport type { ApplyHKTImplementationWithDefault } from '@apollo/client/utilities/internal';\nimport type { DocumentNode } from '@apollo/client';\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nimport type { HKT } from '@apollo/client/utilities';\nimport type { IsAny } from '@apollo/client/utilities/internal';\nimport type { Prettify } from '@apollo/client/utilities/internal';\nimport type { Primitive } from '@apollo/client/utilities/internal';\nimport type { RemoveIndexSignature } from '@apollo/client/utilities/internal';\nimport type { TypedDocumentNode } from '@apollo/client';\nimport type { TypeOverrides } from '@apollo/client';\n\n// Warning: (ae-forgotten-export) The symbol \"MergeUnions\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"ExtractByMatchingTypeNames\" needs to be exported by the entry point index.d.ts\n//\n// @public\ntype CombineByTypeName<T extends {\n    __typename?: string;\n}> = {\n    [TypeName in NonNullable<T[\"__typename\"]>]: Prettify<MergeUnions<ExtractByMatchingTypeNames<T, TypeName>>>;\n}[NonNullable<T[\"__typename\"]>];\n\n// Warning: (ae-forgotten-export) The symbol \"CombineByTypeName\" needs to be exported by the entry point index.d.ts\n//\n// @public\ntype CombineIntersection<T> = Exclude<T, {\n    __typename?: string;\n}> | CombineByTypeName<Extract<T, {\n    __typename?: string;\n}>>;\n\n// Warning: (ae-forgotten-export) The symbol \"Exact\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype ContainsFragmentsRefs<TData, Seen = never> = true extends (IsAny<TData>) ? false : TData extends object ? Exact<TData> extends Seen ? false : \" $fragmentRefs\" extends keyof RemoveIndexSignature<TData> ? true : ContainsFragmentsRefs<TData[keyof TData], Seen | Exact<TData>> : false;\n\n// @internal @deprecated (undocumented)\nexport const disableWarningsSlot: {\n    readonly id: string;\n    hasValue(): boolean;\n    getValue(): boolean | undefined;\n    withValue<TResult, TArgs extends any[], TThis = any>(value: boolean, callback: (this: TThis, ...args: TArgs) => TResult, args?: TArgs | undefined, thisArg?: TThis | undefined): TResult;\n};\n\n// @public (undocumented)\ntype DistributedRequiredExclude<T, U> = T extends any ? Required<T> extends Required<U> ? Required<U> extends Required<T> ? never : T : T : T;\n\n// @public (undocumented)\ntype Exact<in out T> = (x: T) => T;\n\n// @public\ntype ExtractByMatchingTypeNames<Union extends {\n    __typename?: string;\n}, TypeName extends string> = Union extends any ? TypeName extends NonNullable<Union[\"__typename\"]> ? Omit<Union, \"__typename\"> & {\n    [K in keyof Union as K extends \"__typename\" ? K : never]: TypeName;\n} : never : never;\n\n// Warning: (ae-forgotten-export) The symbol \"PreserveTypes\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport type FragmentType<TFragmentDataOrTypedDocumentNode> = ApplyHKTImplementationWithDefault<TypeOverrides, \"FragmentType\", PreserveTypes.TypeOverrides, TFragmentDataOrTypedDocumentNode extends (DocumentTypeDecoration<infer TFragmentData, any>) ? TFragmentData : TFragmentDataOrTypedDocumentNode>;\n\n// @public (undocumented)\nexport namespace GraphQLCodegenDataMasking {\n    // (undocumented)\n    export type FragmentType<TData> = [\n    TData\n    ] extends [{\n        \" $fragmentName\"?: infer TKey;\n    }] ? TKey extends string ? {\n        \" $fragmentRefs\"?: {\n            [key in TKey]: TData;\n        };\n    } : never : never;\n    // (undocumented)\n    export namespace HKTImplementation {\n        // (undocumented)\n        export interface FragmentType extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: GraphQLCodegenDataMasking.FragmentType<this[\"arg1\"]>;\n        }\n        // (undocumented)\n        export interface MaybeMasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: GraphQLCodegenDataMasking.MaybeMasked<this[\"arg1\"]>;\n        }\n        // (undocumented)\n        export interface Unmasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: GraphQLCodegenDataMasking.Unmasked<this[\"arg1\"]>;\n        }\n    }\n    export type MaybeMasked<TData> = TData;\n    // (undocumented)\n    export interface TypeOverrides {\n        // (undocumented)\n        FragmentType: HKTImplementation.FragmentType;\n        // (undocumented)\n        MaybeMasked: HKTImplementation.MaybeMasked;\n        // (undocumented)\n        Unmasked: HKTImplementation.Unmasked;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"ContainsFragmentsRefs\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"UnwrapFragmentRefs\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"RemoveFragmentName\" needs to be exported by the entry point index.d.ts\n    export type Unmasked<TData> = true extends IsAny<TData> ? TData : TData extends object ? true extends ContainsFragmentsRefs<TData> ? UnwrapFragmentRefs<RemoveFragmentName<TData>> : TData : TData;\n}\n\n// @internal @deprecated (undocumented)\nexport function maskFragment<TData = unknown>(data: TData, document: TypedDocumentNode<TData> | DocumentNode, cache: ApolloCache, fragmentName?: string): TData;\n\n// @internal @deprecated (undocumented)\nexport function maskOperation<TData = unknown>(data: TData, document: DocumentNode | TypedDocumentNode<TData>, cache: ApolloCache): TData;\n\n// @public\nexport type MaybeMasked<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"MaybeMasked\", PreserveTypes.TypeOverrides, TData>;\n\n// Warning: (ae-forgotten-export) The symbol \"CombineIntersection\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype MergeObjects<T, U> = Prettify<{\n    [k in keyof T]: k extends keyof U ? [\n    NonNullable<T[k]>,\n    NonNullable<U[k]>\n    ] extends ([\n    infer TK extends object,\n    infer UK extends object\n    ]) ? TK extends unknown[] ? UK extends unknown[] ? CombineIntersection<TK[number] | UK[number]>[] | Extract<T[k] | U[k], undefined | null> : T[k] : CombineIntersection<TK | UK> | Extract<T[k] | U[k], undefined | null> : T[k] : T[k];\n} & Pick<U, Exclude<keyof U, keyof T>>>;\n\n// Warning: (ae-forgotten-export) The symbol \"MergeUnionsAcc\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"takeOneFromUnion\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype MergeUnions<TUnion> = MergeUnionsAcc<TUnion, takeOneFromUnion<TUnion>, never>;\n\n// Warning: (ae-forgotten-export) The symbol \"DistributedRequiredExclude\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"MergeObjects\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype MergeUnionsAcc<TUnion, Curr, Merged> = [\nCurr\n] extends [never] ? Merged : MergeUnionsAcc<DistributedRequiredExclude<TUnion, Curr>, takeOneFromUnion<DistributedRequiredExclude<TUnion, Curr>>, [\nMerged\n] extends [never] ? Curr : MergeObjects<Curr, Merged>>;\n\n// @public (undocumented)\nnamespace PreserveTypes {\n    // (undocumented)\n    type FragmentType<_TData> = never;\n    // (undocumented)\n    namespace HKTImplementation {\n        // (undocumented)\n        interface FragmentType extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: never;\n        }\n        // (undocumented)\n        interface MaybeMasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: this[\"arg1\"];\n        }\n        // (undocumented)\n        interface Unmasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: this[\"arg1\"];\n        }\n    }\n    // (undocumented)\n    type MaybeMasked<TData> = TData;\n    // (undocumented)\n    interface TypeOverrides {\n        // Warning: (ae-forgotten-export) The symbol \"PreserveTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        FragmentType: HKTImplementation.FragmentType;\n        // (undocumented)\n        MaybeMasked: HKTImplementation.MaybeMasked;\n        // (undocumented)\n        Unmasked: HKTImplementation.Unmasked;\n    }\n    // (undocumented)\n    type Unmasked<TData> = TData;\n}\n\n// @public (undocumented)\ntype RemoveFragmentName<T> = T extends any ? Omit<T, \" $fragmentName\"> : T;\n\n// Warning: (ae-forgotten-export) The symbol \"unionToIntersection\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype takeOneFromUnion<T> = unionToIntersection<T extends T ? (x: T) => 0 : never> extends ((x: infer U) => 0) ? U : never;\n\n// @public (undocumented)\ntype unionToIntersection<T> = (T extends unknown ? (x: T) => unknown : never) extends ((x: infer U) => unknown) ? U : never;\n\n// @public\nexport type Unmasked<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Unmasked\", PreserveTypes.TypeOverrides, TData>;\n\n// @public (undocumented)\ntype UnwrapFragmentRefs<TData> = true extends IsAny<TData> ? TData : TData extends any ? TData extends Primitive ? TData : string extends keyof TData ? TData : keyof TData extends never ? TData : TData extends {\n    \" $fragmentRefs\"?: infer FragmentRefs;\n} ? UnwrapFragmentRefs<CombineIntersection<Omit<TData, \" $fragmentRefs\"> | RemoveFragmentName<NonNullable<NonNullable<FragmentRefs>[keyof NonNullable<FragmentRefs>]>>>> : TData extends object ? {\n    [K in keyof TData]: UnwrapFragmentRefs<TData[K]>;\n} : TData : never;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-react.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache } from '@apollo/client';\nimport type { ApolloCache as ApolloCache_2 } from '@apollo/client/cache';\nimport type { ApolloClient } from '@apollo/client';\nimport type { DataState } from '@apollo/client';\nimport type { DataValue } from '@apollo/client';\nimport type { DefaultContext } from '@apollo/client';\nimport type { DocumentationTypes } from '@apollo/client/utilities/internal';\nimport type { DocumentNode } from 'graphql';\nimport type { DocumentNode as DocumentNode_2 } from '@apollo/client';\nimport type { ErrorLike } from '@apollo/client';\nimport type { ErrorPolicy } from '@apollo/client';\nimport type { FetchMoreFunction } from '@apollo/client/react/internal';\nimport type { FetchPolicy } from '@apollo/client';\nimport type { GetDataState } from '@apollo/client';\nimport type { HookWrappers } from '@apollo/client/react/internal';\nimport type { IgnoreModifier } from '@apollo/client/cache';\nimport type { InternalRefetchQueriesInclude } from '@apollo/client';\nimport type { InternalTypes as InternalTypes_2 } from '@apollo/client';\nimport type { MaybeMasked } from '@apollo/client';\nimport type { MaybeMasked as MaybeMasked_2 } from '@apollo/client/masking';\nimport type { MissingTree } from '@apollo/client/cache';\nimport type { MutationFetchPolicy } from '@apollo/client';\nimport type { MutationQueryReducersMap } from '@apollo/client';\nimport type { MutationUpdaterFunction } from '@apollo/client';\nimport { NetworkStatus } from '@apollo/client';\nimport type { NoInfer as NoInfer_2 } from '@apollo/client/utilities/internal';\nimport type { NormalizedExecutionResult } from '@apollo/client';\nimport type { ObservableQuery } from '@apollo/client';\nimport type { OnQueryUpdated } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport { PreloadedQueryRef } from '@apollo/client/react/internal';\nimport type { PreloadedQueryRef as PreloadedQueryRef_2 } from '@apollo/client/react';\nimport type { Prettify } from '@apollo/client/utilities/internal';\nimport { QueryRef } from '@apollo/client/react/internal';\nimport type { QueryRef as QueryRef_2 } from '@apollo/client/react';\nimport type { ReactiveVar } from '@apollo/client';\nimport type * as ReactTypes from 'react';\nimport type { RefetchFunction } from '@apollo/client/react/internal';\nimport type { RefetchWritePolicy } from '@apollo/client';\nimport type { SubscribeToMoreFunction } from '@apollo/client';\nimport type { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport type { TypedDocumentNode as TypedDocumentNode_2 } from '@apollo/client';\nimport type { Unmasked } from '@apollo/client';\nimport type { UpdateQueryMapFn } from '@apollo/client';\nimport type { VariablesOption } from '@apollo/client/utilities/internal';\nimport type { WatchQueryFetchPolicy } from '@apollo/client';\nimport type { wrapperSymbol } from '@apollo/client/react/internal';\n\n// @public (undocumented)\nexport interface ApolloContextValue {\n    // (undocumented)\n    [wrapperSymbol]?: HookWrappers;\n    // (undocumented)\n    client?: ApolloClient;\n}\n\n// @public (undocumented)\nexport namespace ApolloProvider {\n    // (undocumented)\n    export interface Props {\n        // (undocumented)\n        children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n        // (undocumented)\n        client: ApolloClient;\n    }\n}\n\n// @public (undocumented)\nexport const ApolloProvider: ReactTypes.FC<ApolloProvider.Props>;\n\n// @public @deprecated (undocumented)\nexport type BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type BackgroundQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useBackgroundQuery.Options<TVariables>;\n\n// @public\nexport function createQueryPreloader(client: ApolloClient): PreloadQueryFunction;\n\n// @public (undocumented)\nexport function getApolloContext(): ReactTypes.Context<ApolloContextValue>;\n\n// @internal @deprecated (undocumented)\nexport namespace InternalTypes {\n    export type { HookWrappers };\n}\n\n// @public @deprecated (undocumented)\nexport type LazyQueryExecFunction<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery.ExecFunction<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryHookExecOptions<TVariables extends OperationVariables = OperationVariables> = useLazyQuery.ExecOptions<TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery.Result<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryResultTuple<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery.ResultTuple<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LoadableQueryFetchPolicy = useLoadableQuery.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type LoadableQueryHookOptions = useLoadableQuery.Options;\n\n// @public @deprecated (undocumented)\nexport type LoadQueryFunction<TVariables extends OperationVariables> = useLoadableQuery.LoadQueryFunction<TVariables>;\n\n// @public (undocumented)\ntype MakeRequiredVariablesOptional<TVariables extends OperationVariables, TConfiguredVariables extends Partial<TVariables>> = Prettify<{\n    [K in keyof TVariables as K extends keyof TConfiguredVariables ? K : never]?: TVariables[K];\n} & Omit<TVariables, keyof TConfiguredVariables>>;\n\n// @public @deprecated (undocumented)\nexport type MutationFunctionOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, _TContext = DefaultContext, TCache extends ApolloCache = ApolloCache> = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n\n// @public @deprecated (undocumented)\nexport type MutationHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, _TContext = DefaultContext, TCache extends ApolloCache = ApolloCache> = useMutation.Options<TData, TVariables, TCache>;\n\n// @public @deprecated (undocumented)\nexport type MutationResult<TData = unknown> = useMutation.Result<TData>;\n\n// @public @deprecated (undocumented)\nexport type MutationTuple<TData, TVariables extends OperationVariables, _TContext = DefaultContext, TCache extends ApolloCache = ApolloCache> = useMutation.ResultTuple<TData, TVariables, TCache>;\n\n// @public @deprecated (undocumented)\nexport type OnDataOptions<TData = unknown> = useSubscription.OnDataOptions<TData>;\n\n// @public @deprecated (undocumented)\nexport type OnSubscriptionDataOptions<TData = unknown> = useSubscription.OnSubscriptionDataOptions<TData>;\n\nexport { PreloadedQueryRef }\n\n// @public (undocumented)\nexport type PreloadQueryFetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n\n// @public\nexport interface PreloadQueryFunction {\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        returnPartialData: true;\n        errorPolicy: \"ignore\" | \"all\";\n    }): PreloadedQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        errorPolicy: \"ignore\" | \"all\";\n    }): PreloadedQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        returnPartialData: true;\n    }): PreloadedQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\n    options?: PreloadQueryOptions<NoInfer_2<TVariables>>\n    ] : [options: PreloadQueryOptions<NoInfer_2<TVariables>>]): PreloadedQueryRef_2<TData, TVariables, \"complete\" | \"streaming\">;\n    toPromise<TQueryRef extends PreloadedQueryRef_2<any, any, any>>(queryRef: TQueryRef): Promise<TQueryRef>;\n}\n\n// @public (undocumented)\nexport type PreloadQueryOptions<TVariables extends OperationVariables = OperationVariables> = {\n    context?: DefaultContext;\n    errorPolicy?: ErrorPolicy;\n    fetchPolicy?: PreloadQueryFetchPolicy;\n    returnPartialData?: boolean;\n    refetchWritePolicy?: RefetchWritePolicy;\n} & VariablesOption<TVariables>;\n\n// @public @deprecated (undocumented)\nexport type QueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQuery.Options<TData, TVariables>;\n\nexport { QueryRef }\n\n// @public @deprecated (undocumented)\nexport type QueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQuery.Result<TData, TVariables>;\n\n// @public (undocumented)\nexport const reactCompilerVersion: string;\n\n// @public (undocumented)\ntype ResetFunction = () => void;\n\n// @public (undocumented)\nexport type SkipToken = typeof skipToken;\n\n// @public (undocumented)\nexport const skipToken: unique symbol;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSubscription.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSubscription.Result<TData>;\n\n// @public @deprecated (undocumented)\nexport type SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type SuspenseQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSuspenseQuery.Options<TVariables>;\n\n// @public (undocumented)\nexport function useApolloClient(override?: ApolloClient): ApolloClient;\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    fetchPolicy: \"no-cache\";\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: false;\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: boolean;\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken): [undefined, useBackgroundQuery.Result<TData, TVariables>];\n\n// @public\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n})): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n})): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useBackgroundQuery.Options<NoInfer_2<TVariables>>\n] : [options: useBackgroundQuery.Options<NoInfer_2<TVariables>>]): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>]): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>): [\nQueryRef_2<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport namespace useBackgroundQuery {\n    import _self = useBackgroundQuery;\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options {\n            client?: ApolloClient;\n            context?: DefaultContext;\n            errorPolicy?: ErrorPolicy;\n            fetchPolicy?: FetchPolicy;\n            queryKey?: string | number | any[];\n            refetchWritePolicy?: RefetchWritePolicy;\n            returnPartialData?: boolean;\n            // @deprecated\n            skip?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useBackgroundQuery {\n            // (undocumented)\n            export interface Options<TVariables extends OperationVariables = OperationVariables> extends Base.Options, DocumentationTypes.VariableOptions<TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useBackgroundQuery {\n            // (undocumented)\n            export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends useBackgroundQuery.Result<TData, TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | useBackgroundQuery.Options<TVariables>): [\n        QueryRef_2<TData, TVariables> | undefined,\n        useBackgroundQuery.Result<TData, TVariables>\n        ];\n    }\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export type Options<TVariables extends OperationVariables = OperationVariables> = Base.Options & VariablesOption<TVariables>;\n    // (undocumented)\n    export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n}\n\n// @public @deprecated (undocumented)\nexport type UseBackgroundQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useBackgroundQuery.Result<TData, TVariables>;\n\n// @public\nexport function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment.Options<TData, TVariables> & {\n    from: Array<useFragment.FromOptionValue<TData>>;\n}): useFragment.Result<Array<TData>>;\n\n// @public\nexport function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment.Options<TData, TVariables> & {\n    from: Array<null>;\n}): useFragment.Result<Array<null>>;\n\n// @public\nexport function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment.Options<TData, TVariables> & {\n    from: Array<useFragment.FromOptionValue<TData> | null>;\n}): useFragment.Result<Array<TData | null>>;\n\n// @public\nexport function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment.Options<TData, TVariables>): useFragment.Result<TData>;\n\n// @public (undocumented)\nexport namespace useFragment {\n    import _self = useFragment;\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useFragment {\n            // (undocumented)\n            export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends useFragment.Options<TData, TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useFragment {\n            // (undocumented)\n            export interface Result<TData> {\n                // (undocumented)\n                complete: boolean;\n                // (undocumented)\n                data: MaybeMasked_2<TData> | DataValue.Partial<MaybeMasked_2<TData>>;\n                missing?: MissingTree;\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ fragment, from, fragmentName, variables, optimistic, client, }: useFragment.Options<TData, TVariables>): useFragment.Result<TData>;\n    }\n    export type FromOptionValue<TData> = ApolloCache_2.FromOptionValue<TData>;\n    // (undocumented)\n    export interface Options<TData, TVariables extends OperationVariables> {\n        client?: ApolloClient;\n        fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n        fragmentName?: string;\n        from: useFragment.FromOptionValue<TData> | Array<useFragment.FromOptionValue<TData> | null> | null;\n        optimistic?: boolean;\n        variables?: NoInfer_2<TVariables>;\n    }\n    // (undocumented)\n    export type Result<TData> = ({\n        complete: true;\n        missing?: never;\n    } & GetDataState<MaybeMasked_2<TData>, \"complete\">) | {\n        complete: false;\n        missing?: MissingTree;\n        data: TData extends Array<infer TItem> ? Array<DataValue.Partial<TItem> | null> : DataValue.Partial<TData>;\n        dataState: \"partial\";\n    };\n}\n\n// @public @deprecated (undocumented)\nexport type UseFragmentOptions<TData, TVariables extends OperationVariables> = useFragment.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type UseFragmentResult<TData> = useFragment.Result<TData>;\n\n// @public\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport namespace useLazyQuery {\n    import _self = useLazyQuery;\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Result<TData, TVariables extends OperationVariables> {\n            client: ApolloClient;\n            error?: ErrorLike;\n            fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>) => Promise<ApolloClient.QueryResult<MaybeMasked<TFetchData>>>;\n            loading: boolean;\n            networkStatus: NetworkStatus;\n            observable: ObservableQuery<TData, TVariables>;\n            previousData?: MaybeMasked<TData>;\n            refetch: (variables?: Partial<TVariables>) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n            startPolling: (pollInterval: number) => void;\n            stopPolling: () => void;\n            subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n            updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useLazyQuery {\n            // (undocumented)\n            export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends useLazyQuery.Options<TData, TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useLazyQuery {\n            // (undocumented)\n            export interface Result<TData, TVariables extends OperationVariables> extends Base.Result<TData, TVariables>, DocumentationTypes.DataState<TData>, DocumentationTypes.VariableOptions<TVariables> {\n                called: boolean;\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useLazyQuery {\n            // (undocumented)\n            export interface ExecOptions<TVariables extends OperationVariables> extends DocumentationTypes.VariableOptions<TVariables> {\n                context?: DefaultContext;\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useLazyQuery {\n            import ResultTuple = _self.ResultTuple;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery.Options<TData, TVariables>): useLazyQuery.ResultTuple<TData, TVariables>;\n    }\n    // (undocumented)\n    export type ExecFunction<TData, TVariables extends OperationVariables> = (...args: {} extends TVariables ? [\n    options?: useLazyQuery.ExecOptions<TVariables>\n    ] : [options: useLazyQuery.ExecOptions<TVariables>]) => ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;\n    // (undocumented)\n    export type ExecOptions<TVariables extends OperationVariables = OperationVariables> = {\n        context?: DefaultContext;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        client?: ApolloClient;\n        errorPolicy?: ErrorPolicy;\n        fetchPolicy?: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: InternalTypes_2.NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        notifyOnNetworkStatusChange?: boolean;\n        pollInterval?: number;\n        refetchWritePolicy?: RefetchWritePolicy;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n    }\n    // (undocumented)\n    export type Result<TData, TVariables extends OperationVariables, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = Base.Result<TData, TVariables> & (({\n        called: true;\n        variables: TVariables;\n    } & GetDataState<MaybeMasked<TData>, TStates>) | {\n        called: false;\n        variables: Partial<TVariables>;\n        data: undefined;\n        dataState: \"empty\";\n    });\n    // (undocumented)\n    export type ResultTuple<TData, TVariables extends OperationVariables, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = [\n    execute: ExecFunction<TData, TVariables>,\n    result: useLazyQuery.Result<TData, TVariables, TStates>\n    ];\n}\n\n// @public\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    returnPartialData: true;\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options?: useLoadableQuery.Options): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport namespace useLoadableQuery {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options): useLoadableQuery.Result<TData, TVariables>;\n    }\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export interface Handlers<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        // Warning: (ae-forgotten-export) The symbol \"ResetFunction\" needs to be exported by the entry point index.d.ts\n        reset: ResetFunction;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n    // (undocumented)\n    export type LoadQueryFunction<TVariables extends OperationVariables> = (...args: {} extends TVariables ? [variables?: TVariables] : [variables: TVariables]) => void;\n    // (undocumented)\n    export interface Options {\n        client?: ApolloClient;\n        context?: DefaultContext;\n        errorPolicy?: ErrorPolicy;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        refetchWritePolicy?: RefetchWritePolicy;\n        returnPartialData?: boolean;\n    }\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = [\n    loadQuery: LoadQueryFunction<TVariables>,\n    queryRef: QueryRef_2<TData, TVariables, TStates> | null,\n    handlers: Handlers<TData, TVariables>\n    ];\n}\n\n// @public @deprecated (undocumented)\nexport type UseLoadableQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLoadableQuery.Result<TData, TVariables>;\n\n// Warning: (ae-forgotten-export) The symbol \"MakeRequiredVariablesOptional\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport function useMutation<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache, TConfiguredVariables extends Partial<TVariables> = {}>(mutation: DocumentNode_2 | TypedDocumentNode<TData, TVariables>, options?: useMutation.Options<NoInfer_2<TData>, NoInfer_2<TVariables>, TCache, {\n    [K in keyof TConfiguredVariables]: K extends keyof TVariables ? TConfiguredVariables[K] : never;\n}>): useMutation.ResultTuple<TData, MakeRequiredVariablesOptional<TVariables, TConfiguredVariables>, TCache>;\n\n// @public (undocumented)\nexport namespace useMutation {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useMutation<TData = unknown, TVariables extends OperationVariables = OperationVariables>(mutation: DocumentNode_2 | TypedDocumentNode<TData, TVariables>, options?: useMutation.Options<TData, TVariables>): useMutation.ResultTuple<TData, TVariables>;\n    }\n    // (undocumented)\n    export type MutationFunction<TData, TVariables extends OperationVariables, TCache extends ApolloCache = ApolloCache> = (...[options]: {} extends TVariables ? [\n    options?: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables?: TVariables;\n    }\n    ] : [\n    options: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables: TVariables;\n    }\n    ]) => Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    export type MutationFunctionOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = Options<TData, TVariables, TCache> & {\n        context?: DefaultContext | ((hookContext: DefaultContext | undefined) => DefaultContext);\n    };\n    // (undocumented)\n    export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache, TConfiguredVariables extends Partial<TVariables> = Partial<TVariables>> {\n        awaitRefetchQueries?: boolean;\n        client?: ApolloClient;\n        context?: DefaultContext;\n        errorPolicy?: ErrorPolicy;\n        fetchPolicy?: MutationFetchPolicy;\n        keepRootFields?: boolean;\n        notifyOnNetworkStatusChange?: boolean;\n        onCompleted?: (data: MaybeMasked<TData>, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onError?: (error: ErrorLike, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onQueryUpdated?: OnQueryUpdated<any>;\n        optimisticResponse?: Unmasked<NoInfer_2<TData>> | ((vars: TVariables, { IGNORE }: {\n            IGNORE: IgnoreModifier;\n        }) => Unmasked<NoInfer_2<TData>> | IgnoreModifier);\n        refetchQueries?: ((result: NormalizedExecutionResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude;\n        update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n        updateQueries?: MutationQueryReducersMap<TData>;\n        variables?: Partial<TVariables> & TConfiguredVariables;\n    }\n    // (undocumented)\n    export interface Result<TData = unknown> {\n        called: boolean;\n        client: ApolloClient;\n        data: MaybeMasked<TData> | null | undefined;\n        error: ErrorLike | undefined;\n        loading: boolean;\n        reset: () => void;\n    }\n    // (undocumented)\n    export type ResultTuple<TData, TVariables extends OperationVariables, TCache extends ApolloCache = ApolloCache> = [\n    mutate: MutationFunction<TData, TVariables, TCache>,\n    result: Result<TData>\n    ];\n}\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken): useQuery.Result<TData, TVariables, \"empty\", Record<string, never>>;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n})): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\", Partial<TVariables>>;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n})): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\", Partial<TVariables>>;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken | useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: SkipToken | useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\", Partial<TVariables>>;\n\n// @public (undocumented)\nexport namespace useQuery {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext;\n            errorPolicy?: ErrorPolicy;\n            fetchPolicy?: WatchQueryFetchPolicy;\n            initialFetchPolicy?: WatchQueryFetchPolicy;\n            nextFetchPolicy?: WatchQueryFetchPolicy | ((this: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: InternalTypes_2.NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n            notifyOnNetworkStatusChange?: boolean;\n            pollInterval?: number;\n            refetchWritePolicy?: RefetchWritePolicy;\n            returnPartialData?: boolean;\n            skip?: boolean;\n            skipPollAttempt?: () => boolean;\n            ssr?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TReturnVariables extends OperationVariables = TVariables> {\n            client: ApolloClient;\n            error?: ErrorLike;\n            fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>) => Promise<ApolloClient.QueryResult<MaybeMasked_2<TFetchData>>>;\n            loading: boolean;\n            networkStatus: NetworkStatus;\n            observable: ObservableQuery<TData, TVariables>;\n            previousData?: MaybeMasked_2<TData>;\n            refetch: (variables?: Partial<TVariables>) => Promise<ApolloClient.QueryResult<MaybeMasked_2<TData>>>;\n            startPolling: (pollInterval: number) => void;\n            stopPolling: () => void;\n            subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n            updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;\n            variables: TReturnVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useQuery {\n            // (undocumented)\n            export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables>, DocumentationTypes.VariableOptions<TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useQuery {\n            // (undocumented)\n            export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Result<TData, TVariables>, DocumentationTypes.DataState<TData> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery.Options<TData, TVariables>): useQuery.Result<TData, TVariables>;\n    }\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"], TReturnVariables extends OperationVariables = TVariables> = Base.Result<TData, TVariables, TReturnVariables> & GetDataState<MaybeMasked_2<TData>, TStates>;\n}\n\n// @public (undocumented)\nexport namespace useQuery {\n    var // (undocumented)\n    ssrDisabledResult: ObservableQuery.Result<any, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n}\n\n// @public\nexport function useQueryRefHandlers<TData = unknown, TVariables extends OperationVariables = OperationVariables>(queryRef: QueryRef_2<TData, TVariables, DataState<TData>[\"dataState\"]>): useQueryRefHandlers.Result<TData, TVariables>;\n\n// @public (undocumented)\nexport namespace useQueryRefHandlers {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useQueryRefHandlers<TData = unknown, TVariables extends OperationVariables = OperationVariables>(queryRef: QueryRef_2<TData, TVariables>): useQueryRefHandlers.Result<TData, TVariables>;\n    }\n    // (undocumented)\n    export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n}\n\n// @public @deprecated (undocumented)\nexport type UseQueryRefHandlersResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQueryRefHandlers.Result<TData, TVariables>;\n\n// @public\nexport function useReactiveVar<T>(rv: ReactiveVar<T>): T;\n\n// @public\nexport function useReadQuery<TData, TStates extends DataState<TData>[\"dataState\"]>(queryRef: QueryRef_2<TData, any, TStates>): useReadQuery.Result<TData, TStates>;\n\n// @public (undocumented)\nexport namespace useReadQuery {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Result<TData = unknown> {\n            error: ErrorLike | undefined;\n            networkStatus: NetworkStatus;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useReadQuery {\n            // (undocumented)\n            export interface Result<TData = unknown> extends Base.Result<TData>, DocumentationTypes.DataState<TData> {\n            }\n        }\n        export function useReadQuery<TData>(queryRef: QueryRef_2<TData>): useReadQuery.Result<TData>;\n    }\n    // (undocumented)\n    export type Result<TData = unknown, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = Base.Result<TData> & GetDataState<MaybeMasked_2<TData>, TStates>;\n}\n\n// @public @deprecated (undocumented)\nexport type UseReadQueryResult<TData = unknown> = useReadQuery.Result<TData>;\n\n// @public\nexport function useSubscription<TData = unknown, TVariables extends OperationVariables = OperationVariables>(subscription: DocumentNode | TypedDocumentNode<TData, TVariables>, ...[options]: {} extends (TVariables) ? [\noptions?: useSubscription.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useSubscription.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useSubscription.Result<TData>;\n\n// @public (undocumented)\nexport namespace useSubscription {\n    import _self = useSubscription;\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext;\n            errorPolicy?: ErrorPolicy;\n            extensions?: Record<string, any>;\n            fetchPolicy?: FetchPolicy;\n            ignoreResults?: boolean;\n            onComplete?: () => void;\n            onData?: (options: OnDataOptions<TData>) => any;\n            onError?: (error: ErrorLike) => void;\n            shouldResubscribe?: boolean | ((options: Options<TData, TVariables>) => boolean);\n            skip?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSubscription {\n            // (undocumented)\n            export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables>, DocumentationTypes.VariableOptions<TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSubscription {\n            // (undocumented)\n            export interface Result<TData = unknown> extends useSubscription.Result<TData> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useSubscription<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options?: useSubscription.Options<TData, TVariables>): useSubscription.Result<TData>;\n    }\n    // (undocumented)\n    export interface OnDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        data: OnDataResult<TData>;\n    }\n    // (undocumented)\n    export type OnDataResult<TData = unknown> = Omit<Result<TData>, \"restart\">;\n    // (undocumented)\n    export interface OnSubscriptionDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        subscriptionData: OnDataResult<TData>;\n    }\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    export interface Result<TData = unknown> {\n        data?: MaybeMasked_2<TData>;\n        error?: ErrorLike;\n        loading: boolean;\n        restart: () => void;\n    }\n}\n\n// @public\nexport function useSuspenseFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<useSuspenseFragment.FromOptionValue<TData>>;\n}): useSuspenseFragment.Result<Array<TData>>;\n\n// @public\nexport function useSuspenseFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<null>;\n}): useSuspenseFragment.Result<Array<null>>;\n\n// @public\nexport function useSuspenseFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<useSuspenseFragment.FromOptionValue<TData> | null>;\n}): useSuspenseFragment.Result<Array<TData | null>>;\n\n// @public\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: useSuspenseFragment.FromOptionValue<TData>;\n}): useSuspenseFragment.Result<TData>;\n\n// @public\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: null;\n}): useSuspenseFragment.Result<null>;\n\n// @public\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: useSuspenseFragment.FromOptionValue<TData> | null;\n}): useSuspenseFragment.Result<TData | null>;\n\n// @public\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables>): useSuspenseFragment.Result<TData>;\n\n// @public (undocumented)\nexport namespace useSuspenseFragment {\n    import _self = useSuspenseFragment;\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export type Options<TData, TVariables extends OperationVariables> = {\n            fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n            fragmentName?: string;\n            from: useSuspenseFragment.FromOptionValue<TData> | Array<useSuspenseFragment.FromOptionValue<TData> | null> | null;\n            optimistic?: boolean;\n            client?: ApolloClient;\n        };\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSuspenseFragment {\n            // (undocumented)\n            export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables>, DocumentationTypes.VariableOptions<TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSuspenseFragment {\n            // (undocumented)\n            export interface Result<TData = unknown> extends useSuspenseFragment.Result<TData> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables>): useSuspenseFragment.Result<TData>;\n    }\n    export type FromOptionValue<TData> = ApolloCache_2.FromOptionValue<TData>;\n    // (undocumented)\n    export type Options<TData, TVariables extends OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<NoInfer_2<TVariables>>;\n    // (undocumented)\n    export interface Result<TData> {\n        // (undocumented)\n        data: DataValue.Complete<MaybeMasked_2<TData>>;\n    }\n}\n\n// @public @deprecated (undocumented)\nexport type UseSuspenseFragmentOptions<TData, TVariables extends OperationVariables> = useSuspenseFragment.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type UseSuspenseFragmentResult<TData> = useSuspenseFragment.Result<TData>;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: true;\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"empty\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useSuspenseQuery.Result<TData, TVariables, \"partial\" | \"streaming\" | \"complete\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n})): useSuspenseQuery.Result<TData, TVariables, \"empty\" | \"streaming\" | \"complete\" | \"partial\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useSuspenseQuery.Options<NoInfer_2<TVariables>>\n] : [options: useSuspenseQuery.Options<NoInfer_2<TVariables>>]): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>]): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport namespace useSuspenseQuery {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options<TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext;\n            errorPolicy?: ErrorPolicy;\n            fetchPolicy?: FetchPolicy;\n            queryKey?: string | number | any[];\n            refetchWritePolicy?: RefetchWritePolicy;\n            returnPartialData?: boolean;\n            // @deprecated\n            skip?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client: ApolloClient;\n            error: ErrorLike | undefined;\n            fetchMore: FetchMoreFunction<TData, TVariables>;\n            networkStatus: NetworkStatus;\n            refetch: RefetchFunction<TData, TVariables>;\n            subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSuspenseQuery {\n            // (undocumented)\n            export interface Options<TVariables extends OperationVariables = OperationVariables> extends Base.Options<TVariables>, DocumentationTypes.VariableOptions<TVariables> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export namespace useSuspenseQuery {\n            // (undocumented)\n            export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Result<TData, TVariables>, DocumentationTypes.DataState<TData> {\n            }\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options?: useSuspenseQuery.Options<TVariables>): useSuspenseQuery.Result<TData, TVariables>;\n    }\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export type Options<TVariables extends OperationVariables = OperationVariables> = Base.Options<TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = Base.Result<TData, TVariables> & GetDataState<MaybeMasked<TData>, TStates>;\n}\n\n// @public @deprecated (undocumented)\nexport type UseSuspenseQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSuspenseQuery.Result<TData, TVariables>;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-react_compiled.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache } from '@apollo/client/cache';\nimport type { ApolloCache as ApolloCache_2 } from '@apollo/client';\nimport type { ApolloClient } from '@apollo/client';\nimport { ApolloLink } from '@apollo/client/link';\nimport type { ApolloQueryResult as ApolloQueryResult_2 } from '@apollo/client';\nimport type { ApplyHKTImplementationWithDefault } from '@apollo/client/utilities/internal';\nimport type { Cache as Cache_2 } from '@apollo/client/cache';\nimport type { ClientAwarenessLink } from '@apollo/client/link/client-awareness';\nimport type { DataProxy } from '@apollo/client/cache';\nimport type { DataState as DataState_2 } from '@apollo/client';\nimport type { DeepPartial } from '@apollo/client/utilities';\nimport type { DefaultContext as DefaultContext_2 } from '@apollo/client';\nimport type { DocumentationTypes } from '@apollo/client/utilities/internal';\nimport type { DocumentNode } from 'graphql';\nimport type { DocumentNode as DocumentNode_2 } from '@apollo/client';\nimport { DocumentTransform } from '@apollo/client/utilities';\nimport type { ErrorLike as ErrorLike_2 } from '@apollo/client';\nimport type { ErrorPolicy as ErrorPolicy_2 } from '@apollo/client';\nimport type { FetchMoreFunction } from '@apollo/client/react/internal';\nimport type { FetchMoreOptions as FetchMoreOptions_2 } from '@apollo/client';\nimport type { FetchPolicy as FetchPolicy_2 } from '@apollo/client';\nimport type { FetchResult } from '@apollo/client/link';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { FragmentType } from '@apollo/client/masking';\nimport { getApolloClientMemoryInternals } from '@apollo/client/utilities/internal';\nimport type { GetDataState as GetDataState_2 } from '@apollo/client';\nimport { gql } from '@apollo/client';\nimport type { GraphQLRequest } from '@apollo/client/link';\nimport type { HKT } from '@apollo/client/utilities';\nimport type { HookWrappers } from '@apollo/client/react/internal';\nimport type { IgnoreModifier } from '@apollo/client/cache';\nimport type { Incremental } from '@apollo/client/incremental';\nimport type { InternalRefetchQueriesInclude as InternalRefetchQueriesInclude_2 } from '@apollo/client';\nimport type { InteropObservable } from 'rxjs';\nimport type { IsAny } from '@apollo/client/utilities/internal';\nimport type { LocalState } from '@apollo/client/local-state';\nimport type { MaybeMasked } from '@apollo/client/masking';\nimport type { MaybeMasked as MaybeMasked_2 } from '@apollo/client';\nimport type { MissingTree } from '@apollo/client/cache';\nimport type { MutateResult as MutateResult_2 } from '@apollo/client';\nimport type { MutationFetchPolicy as MutationFetchPolicy_2 } from '@apollo/client';\nimport type { MutationQueryReducersMap as MutationQueryReducersMap_2 } from '@apollo/client';\nimport type { MutationUpdaterFunction as MutationUpdaterFunction_2 } from '@apollo/client';\nimport { NetworkStatus as NetworkStatus_2 } from '@apollo/client';\nimport type { NextNotification } from 'rxjs';\nimport type { NoInfer as NoInfer_2 } from '@apollo/client/utilities/internal';\nimport type { NormalizedExecutionResult as NormalizedExecutionResult_2 } from '@apollo/client';\nimport { Observable } from 'rxjs';\nimport type { ObservableNotification } from 'rxjs';\nimport type { ObservableQuery as ObservableQuery_2 } from '@apollo/client';\nimport type { Observer } from 'rxjs';\nimport type { OnQueryUpdated as OnQueryUpdated_2 } from '@apollo/client';\nimport { OperationTypeNode } from 'graphql';\nimport type { OperationVariables } from '@apollo/client';\nimport { PreloadedQueryRef } from '@apollo/client/react/internal';\nimport type { Prettify } from '@apollo/client/utilities/internal';\nimport { QueryRef } from '@apollo/client/react/internal';\nimport type { QueryResult as QueryResult_3 } from '@apollo/client';\nimport type { ReactiveVar } from '@apollo/client';\nimport type * as ReactTypes from 'react';\nimport type { Reference } from '@apollo/client/cache';\nimport type { Reference as Reference_2 } from '@apollo/client';\nimport type { RefetchFunction } from '@apollo/client/react/internal';\nimport type { RefetchWritePolicy as RefetchWritePolicy_2 } from '@apollo/client';\nimport type { StoreObject } from '@apollo/client/cache';\nimport type { StoreObject as StoreObject_2 } from '@apollo/client';\nimport type { Subscribable } from 'rxjs';\nimport type { SubscribeToMoreFunction } from '@apollo/client';\nimport type { Subscription } from 'rxjs';\nimport { Trie } from '@wry/trie';\nimport { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport type { TypedDocumentNode as TypedDocumentNode_2 } from '@apollo/client';\nimport type { Unmasked } from '@apollo/client/masking';\nimport type { Unmasked as Unmasked_2 } from '@apollo/client';\nimport type { UpdateQueryMapFn as UpdateQueryMapFn_2 } from '@apollo/client';\nimport type { VariablesOption } from '@apollo/client/utilities/internal';\nimport type { WatchFragmentOptions } from '@apollo/client/cache';\nimport type { WatchFragmentResult } from '@apollo/client/cache';\nimport type { WatchQueryFetchPolicy } from '@apollo/client';\nimport type { WatchQueryOptions } from '@apollo/client';\nimport type { wrapperSymbol } from '@apollo/client/react/internal';\n\n// @public\nclass ApolloClient_2 implements DataProxy {\n    // (undocumented)\n    __actionHookForDevTools(cb: () => any): void;\n    // Warning: (ae-forgotten-export) The symbol \"ApolloClientOptions\" needs to be exported by the entry point index.compiled.d.ts\n    constructor(options: ApolloClientOptions);\n    // (undocumented)\n    __requestRaw(payload: GraphQLRequest): Observable<FetchResult<unknown>>;\n    // (undocumented)\n    cache: ApolloCache;\n    clearStore(): Promise<any[]>;\n    // Warning: (ae-forgotten-export) The symbol \"DefaultContext\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    get defaultContext(): Partial<DefaultContext>;\n    // (undocumented)\n    defaultOptions: DefaultOptions;\n    // Warning: (ae-forgotten-export) The symbol \"DevtoolsOptions\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    readonly devtoolsConfig: DevtoolsOptions;\n    // @deprecated (undocumented)\n    disableNetworkFetches: never;\n    get documentTransform(): DocumentTransform;\n    extract(optimistic?: boolean): unknown;\n    getMemoryInternals?: typeof getApolloClientMemoryInternals;\n    // Warning: (ae-forgotten-export) The symbol \"RefetchQueriesInclude\" needs to be exported by the entry point index.compiled.d.ts\n    getObservableQueries(include?: RefetchQueriesInclude): Set<ObservableQuery<any>>;\n    // (undocumented)\n    link: ApolloLink;\n    get localState(): LocalState | undefined;\n    set localState(localState: LocalState);\n    // Warning: (ae-forgotten-export) The symbol \"MutationOptions\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"MutateResult\" needs to be exported by the entry point index.compiled.d.ts\n    mutate<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2, TCache extends ApolloCache = ApolloCache>(options: MutationOptions<TData, TVariables, TCache>): Promise<MutateResult<MaybeMasked<TData>>>;\n    onClearStore(cb: () => Promise<any>): () => void;\n    onResetStore(cb: () => Promise<any>): () => void;\n    set prioritizeCacheValues(value: boolean);\n    get prioritizeCacheValues(): boolean;\n    // Warning: (ae-forgotten-export) The symbol \"QueryOptions\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryResult_2\" needs to be exported by the entry point index.compiled.d.ts\n    query<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2>(options: QueryOptions<TVariables, TData>): Promise<QueryResult_2<MaybeMasked<TData>>>;\n    // (undocumented)\n    queryDeduplication: boolean;\n    readFragment<T = unknown, TVariables = OperationVariables_2>(options: DataProxy.Fragment<TVariables, T>, optimistic?: boolean): Unmasked<T> | null;\n    readQuery<TData = unknown, TVariables = OperationVariables_2>(options: DataProxy.Query<TVariables, TData>, optimistic?: boolean): Unmasked<TData> | null;\n    // @deprecated\n    reFetchObservableQueries: (includeStandby?: boolean) => Promise<QueryResult_2<any>[]>;\n    refetchObservableQueries(includeStandby?: boolean): Promise<QueryResult_2<any>[]>;\n    // Warning: (ae-forgotten-export) The symbol \"RefetchQueriesOptions\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"RefetchQueriesResult\" needs to be exported by the entry point index.compiled.d.ts\n    refetchQueries<TCache extends ApolloCache = ApolloCache, TResult = Promise<QueryResult_2<any>>>(options: RefetchQueriesOptions<TCache, TResult>): RefetchQueriesResult<TResult>;\n    resetStore(): Promise<QueryResult_2<any>[] | null>;\n    restore(serializedState: unknown): ApolloCache;\n    setLink(newLink: ApolloLink): void;\n    stop(): void;\n    // Warning: (ae-forgotten-export) The symbol \"SubscriptionOptions\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"SubscriptionObservable\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"SubscribeResult\" needs to be exported by the entry point index.compiled.d.ts\n    subscribe<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2>(options: SubscriptionOptions<TVariables, TData>): SubscriptionObservable<SubscribeResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    version: string;\n    watchFragment<TData = unknown, TVariables = OperationVariables_2>(options: WatchFragmentOptions<TData, TVariables>): Observable<WatchFragmentResult<TData>>;\n    // Warning: (ae-forgotten-export) The symbol \"OperationVariables_2\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"WatchQueryOptions_2\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"ObservableQuery\" needs to be exported by the entry point index.compiled.d.ts\n    watchQuery<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2>(options: WatchQueryOptions_2<TVariables, TData>): ObservableQuery<TData, TVariables>;\n    writeFragment<TData = unknown, TVariables = OperationVariables_2>(options: DataProxy.WriteFragmentOptions<TData, TVariables>): Reference | undefined;\n    writeQuery<TData = unknown, TVariables = OperationVariables_2>(options: DataProxy.WriteQueryOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public (undocumented)\ninterface ApolloClientOptions {\n    assumeImmutableResults?: boolean;\n    cache: ApolloCache;\n    // (undocumented)\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    dataMasking?: boolean;\n    // (undocumented)\n    defaultContext?: Partial<DefaultContext>;\n    defaultOptions?: DefaultOptions;\n    devtools?: DevtoolsOptions;\n    // (undocumented)\n    documentTransform?: DocumentTransform;\n    // (undocumented)\n    enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n    incrementalHandler?: Incremental.Handler<any>;\n    link: ApolloLink;\n    // (undocumented)\n    localState?: LocalState;\n    queryDeduplication?: boolean;\n    ssrForceFetchDelay?: number;\n    ssrMode?: boolean;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"ApolloConsumer_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\nexport const ApolloConsumer: ReactTypes.FC<ApolloConsumer_2.Props>;\n\n// @public (undocumented)\nnamespace ApolloConsumer_2 {\n    // (undocumented)\n    interface Props {\n        // (undocumented)\n        children: (client: ApolloClient) => ReactTypes.ReactNode;\n    }\n}\n\n// @public (undocumented)\nconst ApolloConsumer: ReactTypes.FC<ApolloConsumer_2.Props>;\n\n// @public (undocumented)\nexport interface ApolloContextValue {\n    // (undocumented)\n    [wrapperSymbol]?: HookWrappers;\n    // (undocumented)\n    client?: ApolloClient;\n}\n\n// @public (undocumented)\nexport namespace ApolloProvider {\n    // (undocumented)\n    export interface Props {\n        // (undocumented)\n        children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n        // (undocumented)\n        client: ApolloClient;\n    }\n}\n\n// @public (undocumented)\nexport const ApolloProvider: ReactTypes.FC<ApolloProvider.Props>;\n\n// Warning: (ae-forgotten-export) The symbol \"DataState\" needs to be exported by the entry point index.compiled.d.ts\n// Warning: (ae-forgotten-export) The symbol \"GetDataState\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ntype ApolloQueryResult<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = {\n    error?: ErrorLike;\n    loading: boolean;\n    networkStatus: NetworkStatus;\n    partial: boolean;\n} & GetDataState<TData, TStates>;\n\n// Warning: (ae-forgotten-export) The symbol \"useBackgroundQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type BackgroundQueryHookFetchPolicy = useBackgroundQuery_2.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type BackgroundQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useBackgroundQuery_2.Options<TVariables>;\n\n// @public\nexport function createQueryPreloader(client: ApolloClient): PreloadQueryFunction;\n\n// @public (undocumented)\ntype DataState<TData> = {\n    data: DataValue.Complete<TData>;\n    dataState: \"complete\";\n} | {\n    data: DataValue.Streaming<TData>;\n    dataState: \"streaming\";\n} | {\n    data: DataValue.Partial<TData>;\n    dataState: \"partial\";\n} | {\n    data: undefined;\n    dataState: \"empty\";\n};\n\n// @public (undocumented)\nnamespace DataValue {\n    // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.compiled.d.ts\n    type Complete<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Complete\", OverridableTypes.Defaults, TData>;\n    type Partial<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Partial\", OverridableTypes.Defaults, TData>;\n    type Streaming<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Streaming\", OverridableTypes.Defaults, TData>;\n}\n\n// @public (undocumented)\ninterface DefaultContext extends Record<string, any> {\n    // (undocumented)\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    queryDeduplication?: boolean;\n}\n\n// @public (undocumented)\ninterface DefaultOptions {\n    // (undocumented)\n    mutate?: Partial<MutationOptions<any, any, any>>;\n    // (undocumented)\n    query?: Partial<QueryOptions<any, any>>;\n    // (undocumented)\n    watchQuery?: Partial<WatchQueryOptions_2<any, any>>;\n}\n\n// @public (undocumented)\ninterface DevtoolsOptions {\n    enabled?: boolean;\n    name?: string;\n}\n\n// @public\ninterface ErrorLike {\n    // (undocumented)\n    message: string;\n    // (undocumented)\n    name: string;\n    // (undocumented)\n    stack?: string;\n}\n\n// @public\ntype ErrorPolicy = \"none\" | \"ignore\" | \"all\";\n\n// @public (undocumented)\ntype FetchMoreOptions<TData, TVariables extends OperationVariables_2, TFetchData = TData, TFetchVars extends OperationVariables_2 = TVariables> = {\n    query?: DocumentNode | TypedDocumentNode<TFetchData, TFetchVars>;\n    variables?: Partial<NoInfer<TFetchVars>>;\n    errorPolicy?: ErrorPolicy;\n    context?: DefaultContext;\n    updateQuery?: (previousQueryResult: Unmasked<TData>, options: {\n        fetchMoreResult: Unmasked<TFetchData>;\n        variables: TFetchVars;\n    }) => Unmasked<TData>;\n};\n\n// @public\ntype FetchPolicy = \"cache-first\" | \"network-only\" | \"cache-only\" | \"no-cache\";\n\n// @public (undocumented)\ntype From<TData> = StoreObject_2 | Reference_2 | FragmentType<NoInfer_2<TData>> | string | null;\n\n// @public (undocumented)\ntype From_2<TData> = StoreObject_2 | Reference_2 | FragmentType<NoInfer_2<TData>> | string | null;\n\n// @public (undocumented)\nexport function getApolloContext(): ReactTypes.Context<ApolloContextValue>;\n\n// @public (undocumented)\ntype GetDataState<TData, TState extends DataState<TData>[\"dataState\"]> = Extract<DataState<TData>, {\n    dataState: TState;\n}>;\n\nexport { gql }\n\n// Warning: (ae-forgotten-export) The symbol \"InternalRefetchQueryDescriptor\" needs to be exported by the entry point index.compiled.d.ts\n// Warning: (ae-forgotten-export) The symbol \"RefetchQueriesIncludeShorthand\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ntype InternalRefetchQueriesInclude = InternalRefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// Warning: (ae-forgotten-export) The symbol \"InternalRefetchQueriesResult\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ntype InternalRefetchQueriesMap<TResult> = Map<ObservableQuery<any>, InternalRefetchQueriesResult<TResult>>;\n\n// @public (undocumented)\ninterface InternalRefetchQueriesOptions<TCache extends ApolloCache, TResult> extends Omit<RefetchQueriesOptions<TCache, TResult>, \"include\"> {\n    // Warning: (ae-forgotten-export) The symbol \"InternalRefetchQueriesInclude\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    include?: InternalRefetchQueriesInclude;\n    // (undocumented)\n    removeOptimistic?: string;\n}\n\n// @public (undocumented)\ntype InternalRefetchQueriesResult<TResult> = TResult extends boolean ? Promise<QueryResult_2<any>> : TResult;\n\n// Warning: (ae-forgotten-export) The symbol \"RefetchQueryDescriptor\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ntype InternalRefetchQueryDescriptor = RefetchQueryDescriptor | QueryOptions;\n\n// Warning: (ae-forgotten-export) The symbol \"useLazyQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type LazyQueryExecFunction<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery_2.ExecFunction<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryHookExecOptions<TVariables extends OperationVariables = OperationVariables> = useLazyQuery_2.ExecOptions<TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery_2.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery_2.Result<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type LazyQueryResultTuple<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLazyQuery_2.ResultTuple<TData, TVariables>;\n\n// Warning: (ae-forgotten-export) The symbol \"useLoadableQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type LoadableQueryFetchPolicy = useLoadableQuery_2.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type LoadableQueryHookOptions = useLoadableQuery_2.Options;\n\n// @public @deprecated (undocumented)\nexport type LoadQueryFunction<TVariables extends OperationVariables> = useLoadableQuery_2.LoadQueryFunction<TVariables>;\n\n// @public (undocumented)\ntype MakeRequiredVariablesOptional<TVariables extends OperationVariables, TConfiguredVariables extends Partial<TVariables>> = Prettify<{\n    [K in keyof TVariables as K extends keyof TConfiguredVariables ? K : never]?: TVariables[K];\n} & Omit<TVariables, keyof TConfiguredVariables>>;\n\n// @public (undocumented)\ntype MakeRequiredVariablesOptional_2<TVariables extends OperationVariables, TConfiguredVariables extends Partial<TVariables>> = Prettify<{\n    [K in keyof TVariables as K extends keyof TConfiguredVariables ? K : never]?: TVariables[K];\n} & Omit<TVariables, keyof TConfiguredVariables>>;\n\n// @public (undocumented)\ninterface MaskFragmentOptions<TData> {\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    fragment: DocumentNode;\n    // (undocumented)\n    fragmentName?: string;\n}\n\n// @public (undocumented)\ninterface MaskOperationOptions<TData> {\n    cause?: object;\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    document: DocumentNode;\n    // Warning: (ae-forgotten-export) The symbol \"WatchQueryFetchPolicy_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    fetchPolicy?: WatchQueryFetchPolicy_2;\n}\n\n// @public (undocumented)\ninterface MutateResult<TData = unknown> {\n    data: TData | undefined;\n    error?: ErrorLike;\n    extensions?: Record<string, unknown>;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"FetchPolicy\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ntype MutationFetchPolicy = Extract<FetchPolicy, \"network-only\" | \"no-cache\">;\n\n// Warning: (ae-forgotten-export) The symbol \"useMutation_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type MutationFunctionOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, _TContext = DefaultContext_2, TCache extends ApolloCache_2 = ApolloCache_2> = useMutation_2.MutationFunctionOptions<TData, TVariables, TCache>;\n\n// @public @deprecated (undocumented)\nexport type MutationHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, _TContext = DefaultContext_2, TCache extends ApolloCache_2 = ApolloCache_2> = useMutation_2.Options<TData, TVariables, TCache>;\n\n// @public (undocumented)\ntype MutationOptions<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2, TCache extends ApolloCache = ApolloCache> = {\n    optimisticResponse?: Unmasked<NoInfer_2<TData>> | ((vars: TVariables, { IGNORE }: {\n        IGNORE: IgnoreModifier;\n    }) => Unmasked<NoInfer_2<TData>> | IgnoreModifier);\n    updateQueries?: MutationQueryReducersMap<TData>;\n    refetchQueries?: ((result: NormalizedExecutionResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude;\n    awaitRefetchQueries?: boolean;\n    update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n    onQueryUpdated?: OnQueryUpdated<any>;\n    errorPolicy?: ErrorPolicy;\n    context?: DefaultContext;\n    fetchPolicy?: MutationFetchPolicy;\n    keepRootFields?: boolean;\n    mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;\n} & VariablesOption<NoInfer_2<TVariables>>;\n\n// @public (undocumented)\ntype MutationQueryReducer<T> = (previousResult: Record<string, any>, options: {\n    mutationResult: NormalizedExecutionResult<Unmasked<T>>;\n    queryName: string | undefined;\n    queryVariables: Record<string, any>;\n}) => Record<string, any>;\n\n// @public (undocumented)\ntype MutationQueryReducersMap<T = {\n    [key: string]: any;\n}> = {\n    [queryName: string]: MutationQueryReducer<T>;\n};\n\n// @public @deprecated (undocumented)\nexport type MutationResult<TData = unknown> = useMutation_2.Result<TData>;\n\n// @public (undocumented)\ninterface MutationStoreValue {\n    // (undocumented)\n    error: Error | null;\n    // (undocumented)\n    loading: boolean;\n    // (undocumented)\n    mutation: DocumentNode;\n    // (undocumented)\n    variables: Record<string, any>;\n}\n\n// @public @deprecated (undocumented)\nexport type MutationTuple<TData, TVariables extends OperationVariables, _TContext = DefaultContext_2, TCache extends ApolloCache_2 = ApolloCache_2> = useMutation_2.ResultTuple<TData, TVariables, TCache>;\n\n// @public (undocumented)\ntype MutationUpdaterFunction<TData, TVariables, TCache extends ApolloCache> = (cache: TCache, result: FormattedExecutionResult<Unmasked<TData>>, options: {\n    context?: DefaultContext;\n    variables?: TVariables;\n}) => void;\n\n// @public\nenum NetworkStatus {\n    error = 8,\n    fetchMore = 3,\n    loading = 1,\n    poll = 6,\n    ready = 7,\n    refetch = 4,\n    setVariables = 2,\n    streaming = 9\n}\n\n// @public (undocumented)\ninterface NextFetchPolicyContext<TData, TVariables extends OperationVariables_2> {\n    // (undocumented)\n    initialFetchPolicy: WatchQueryFetchPolicy_2;\n    // (undocumented)\n    observable: ObservableQuery<TData, TVariables>;\n    // (undocumented)\n    options: WatchQueryOptions_2<TVariables, TData>;\n    // (undocumented)\n    reason: \"after-fetch\" | \"variables-changed\";\n}\n\n// @public\ntype NormalizedExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = Omit<FormattedExecutionResult<TData, TExtensions>, \"data\"> & GetDataState<TData, \"streaming\" | \"complete\">;\n\n// @public (undocumented)\ninterface ObservableAndInfo<TData> {\n    // (undocumented)\n    fromLink: boolean;\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    observable: Observable<QueryNotification.Value<TData>>;\n}\n\n// @public (undocumented)\nnamespace ObservableQuery {\n    // @internal @deprecated\n    interface CacheWatchOptions<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2> extends Cache_2.WatchOptions<TData, TVariables> {\n        // @deprecated\n        lastOwnDiff?: Cache_2.DiffResult<TData>;\n    }\n    // (undocumented)\n    type Options<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2> = {\n        fetchPolicy: WatchQueryFetchPolicy_2;\n        nextFetchPolicy?: WatchQueryFetchPolicy_2 | ((this: WatchQueryOptions_2<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy_2, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy_2);\n        initialFetchPolicy: WatchQueryFetchPolicy_2;\n        refetchWritePolicy?: RefetchWritePolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        pollInterval?: number;\n        notifyOnNetworkStatusChange?: boolean;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        variables: TVariables;\n    };\n    interface ResultPromise<T> extends Promise<T> {\n        retain(): this;\n    }\n}\n\n// Warning: (ae-forgotten-export) The symbol \"ApolloQueryResult\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\nclass ObservableQuery<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2> implements Subscribable<ApolloQueryResult<MaybeMasked<TData>>>, InteropObservable<ApolloQueryResult<MaybeMasked<TData>>> {\n    // (undocumented)\n    [\"@@observable\"]: () => Subscribable<ApolloQueryResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    [Symbol.observable]: () => Subscribable<ApolloQueryResult<MaybeMasked<TData>>>;\n    constructor({ queryManager, options, transformedQuery, }: {\n        queryManager: QueryManager;\n        options: WatchQueryOptions_2<TVariables, TData>;\n        transformedQuery?: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        queryId?: string;\n    });\n    // @internal @deprecated (undocumented)\n    applyOptions(newOptions: Partial<ObservableQuery.Options<TData, TVariables>>): void;\n    // Warning: (ae-forgotten-export) The symbol \"FetchMoreOptions\" needs to be exported by the entry point index.compiled.d.ts\n    fetchMore<TFetchData = TData, TFetchVars extends OperationVariables_2 = TVariables>(options: FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>): Promise<QueryResult_2<TFetchData>>;\n    // @internal @deprecated (undocumented)\n    getCacheDiff({ optimistic }?: {\n        optimistic?: boolean | undefined;\n    }): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    getCurrentResult(): ApolloQueryResult<MaybeMasked<TData>>;\n    // (undocumented)\n    hasObservers(): boolean;\n    // @internal @deprecated\n    _lastWrite?: unknown;\n    // @internal @deprecated (undocumented)\n    notify(scheduled?: boolean): void;\n    // (undocumented)\n    readonly options: ObservableQuery.Options<TData, TVariables>;\n    // (undocumented)\n    pipe: Observable<ApolloQueryResult<MaybeMasked<TData>>>[\"pipe\"];\n    // (undocumented)\n    get query(): TypedDocumentNode<TData, TVariables>;\n    // (undocumented)\n    readonly queryName?: string;\n    refetch(variables?: Partial<TVariables>): ObservableQuery.ResultPromise<QueryResult_2<TData>>;\n    reobserve(newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>): ObservableQuery.ResultPromise<QueryResult_2<MaybeMasked<TData>>>;\n    // @internal @deprecated\n    reset(): void;\n    setVariables(variables: TVariables): Promise<QueryResult_2<TData>>;\n    startPolling(pollInterval: number): void;\n    stop(): void;\n    stopPolling(): void;\n    // (undocumented)\n    subscribe: (observer: Partial<Observer<ApolloQueryResult<MaybeMasked<TData>>>> | ((value: ApolloQueryResult<MaybeMasked<TData>>) => void)) => Subscription;\n    // Warning: (ae-forgotten-export) The symbol \"SubscribeToMoreOptions\" needs to be exported by the entry point index.compiled.d.ts\n    subscribeToMore<TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables_2 = TVariables>(options: SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>): () => void;\n    // Warning: (ae-forgotten-export) The symbol \"UpdateQueryMapFn\" needs to be exported by the entry point index.compiled.d.ts\n    updateQuery(mapFn: UpdateQueryMapFn<TData, TVariables>): void;\n    get variables(): TVariables;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"useSubscription_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type OnDataOptions<TData = unknown> = useSubscription_2.OnDataOptions<TData>;\n\n// @public (undocumented)\ntype OnQueryUpdated<TResult> = (observableQuery: ObservableQuery<any>, diff: Cache_2.DiffResult<any>, lastDiff: Cache_2.DiffResult<any> | undefined) => boolean | TResult;\n\n// @public @deprecated (undocumented)\nexport type OnSubscriptionDataOptions<TData = unknown> = useSubscription_2.OnSubscriptionDataOptions<TData>;\n\n// @public (undocumented)\ntype OperationVariables_2 = Record<string, any>;\n\n// @public (undocumented)\nnamespace OverridableTypes {\n    // (undocumented)\n    interface Complete extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n    // (undocumented)\n    interface Defaults {\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.compiled.d.ts\n        //\n        // (undocumented)\n        Complete: Complete;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.compiled.d.ts\n        //\n        // (undocumented)\n        Partial: Partial;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.compiled.d.ts\n        //\n        // (undocumented)\n        Streaming: Streaming;\n    }\n    // (undocumented)\n    interface Partial extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: DeepPartial<this[\"arg1\"]>;\n    }\n    // (undocumented)\n    interface Streaming extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n        {};\n}\n\nexport { PreloadedQueryRef }\n\n// @public (undocumented)\nexport type PreloadQueryFetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n\n// @public\nexport interface PreloadQueryFunction {\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        returnPartialData: true;\n        errorPolicy: \"ignore\" | \"all\";\n    }): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        errorPolicy: \"ignore\" | \"all\";\n    }): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: PreloadQueryOptions<NoInfer_2<TVariables>> & {\n        returnPartialData: true;\n    }): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n    <TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\n    options?: PreloadQueryOptions<NoInfer_2<TVariables>>\n    ] : [options: PreloadQueryOptions<NoInfer_2<TVariables>>]): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\">;\n    toPromise<TQueryRef extends PreloadedQueryRef<any, any, any>>(queryRef: TQueryRef): Promise<TQueryRef>;\n}\n\n// @public (undocumented)\nexport type PreloadQueryOptions<TVariables extends OperationVariables = OperationVariables> = {\n    context?: DefaultContext_2;\n    errorPolicy?: ErrorPolicy_2;\n    fetchPolicy?: PreloadQueryFetchPolicy;\n    returnPartialData?: boolean;\n    refetchWritePolicy?: RefetchWritePolicy_2;\n} & VariablesOption<TVariables>;\n\n// Warning: (ae-forgotten-export) The symbol \"useQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type QueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQuery_2.Options<TData, TVariables>;\n\n// @public (undocumented)\nclass QueryManager {\n    // Warning: (ae-forgotten-export) The symbol \"QueryManagerOptions\" needs to be exported by the entry point index.compiled.d.ts\n    constructor(options: QueryManagerOptions);\n    // (undocumented)\n    readonly assumeImmutableResults: boolean;\n    // (undocumented)\n    broadcastQueries(): void;\n    // (undocumented)\n    get cache(): ApolloCache;\n    // (undocumented)\n    clearStore(options?: Cache_2.ResetOptions): Promise<void>;\n    // Warning: (ae-forgotten-export) The symbol \"ApolloClient_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    readonly client: ApolloClient_2;\n    readonly clientOptions: ApolloClientOptions;\n    // (undocumented)\n    readonly dataMasking: boolean;\n    // (undocumented)\n    readonly defaultContext: Partial<DefaultContext>;\n    // Warning: (ae-forgotten-export) The symbol \"DefaultOptions\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    defaultOptions: DefaultOptions;\n    // (undocumented)\n    readonly documentTransform: DocumentTransform;\n    // (undocumented)\n    protected fetchCancelFns: Map<string, (error: any) => any>;\n    // Warning: (ae-forgotten-export) The symbol \"ObservableAndInfo\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    fetchObservableWithInfo<TData, TVars extends OperationVariables_2>(options: WatchQueryOptions_2<TVars, TData>, { networkStatus, query, fetchQueryOperator, onCacheHit, observableQuery, }: {\n        networkStatus?: NetworkStatus;\n        query?: DocumentNode;\n        fetchQueryOperator?: <T>(source: Observable<T>) => Observable<T>;\n        onCacheHit?: () => void;\n        observableQuery?: ObservableQuery<TData, TVars> | undefined;\n    }): ObservableAndInfo<TData>;\n    // (undocumented)\n    fetchQuery<TData, TVars extends OperationVariables_2>(options: WatchQueryOptions_2<TVars, TData>, networkStatus?: NetworkStatus): Promise<QueryResult_2<TData>>;\n    // (undocumented)\n    generateRequestId(): number;\n    // Warning: (ae-forgotten-export) The symbol \"TransformCacheEntry\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    getDocumentInfo(document: DocumentNode): TransformCacheEntry;\n    // (undocumented)\n    getObservableQueries(include?: InternalRefetchQueriesInclude): Set<ObservableQuery<any, OperationVariables_2>>;\n    // (undocumented)\n    getVariables<TVariables>(document: DocumentNode, variables?: TVariables): TVariables;\n    // (undocumented)\n    readonly incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    protected inFlightLinkObservables: Trie<{\n        observable?: Observable<FetchResult<any>>;\n        restart?: () => void;\n    }>;\n    // (undocumented)\n    get link(): ApolloLink;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"MaskFragmentOptions\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    maskFragment<TData = unknown>(options: MaskFragmentOptions<TData>): TData;\n    // Warning: (ae-forgotten-export) The symbol \"MaskOperationOptions\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    maskOperation<TData = unknown>(options: MaskOperationOptions<TData>): MaybeMasked<TData>;\n    // (undocumented)\n    mutate<TData, TVariables extends OperationVariables_2, TCache extends ApolloCache>({ mutation, variables, optimisticResponse, updateQueries, refetchQueries, awaitRefetchQueries, update: updateWithProxyFn, onQueryUpdated, fetchPolicy, errorPolicy, keepRootFields, context, }: MutationOptions<TData, TVariables, TCache> & {\n        errorPolicy: ErrorPolicy;\n        fetchPolicy: MutationFetchPolicy;\n    }): Promise<MutateResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    mutationStore?: {\n        [mutationId: string]: MutationStoreValue;\n    };\n    obsQueries: Set<ObservableQuery<any, any>>;\n    prioritizeCacheValues: boolean;\n    // (undocumented)\n    query<TData, TVars extends OperationVariables_2 = OperationVariables_2>(options: QueryOptions<TVars, TData>): Promise<QueryResult_2<MaybeMasked<TData>>>;\n    // (undocumented)\n    refetchObservableQueries(includeStandby?: boolean): Promise<QueryResult_2<any>[]>;\n    // Warning: (ae-forgotten-export) The symbol \"InternalRefetchQueriesOptions\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"InternalRefetchQueriesMap\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    refetchQueries<TResult>({ updateCache, include, optimistic, removeOptimistic, onQueryUpdated, }: InternalRefetchQueriesOptions<ApolloCache, TResult>): InternalRefetchQueriesMap<TResult>;\n    // (undocumented)\n    readonly ssrMode: boolean;\n    // (undocumented)\n    startGraphQLSubscription<TData = unknown>(options: SubscriptionOptions): SubscriptionObservable<SubscribeResult<TData>>;\n    stop(): void;\n    // (undocumented)\n    transform(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    watchQuery<T, TVariables extends OperationVariables_2 = OperationVariables_2>(options: WatchQueryOptions_2<TVariables, T>): ObservableQuery<T, TVariables>;\n}\n\n// @public (undocumented)\ninterface QueryManagerOptions {\n    // (undocumented)\n    assumeImmutableResults: boolean;\n    // (undocumented)\n    client: ApolloClient_2;\n    // (undocumented)\n    clientOptions: ApolloClientOptions;\n    // (undocumented)\n    dataMasking: boolean;\n    // (undocumented)\n    defaultContext: Partial<DefaultContext> | undefined;\n    // (undocumented)\n    defaultOptions: DefaultOptions;\n    // (undocumented)\n    documentTransform: DocumentTransform | null | undefined;\n    // (undocumented)\n    incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // (undocumented)\n    onBroadcast: undefined | (() => void);\n    // (undocumented)\n    queryDeduplication: boolean;\n    // (undocumented)\n    ssrMode: boolean;\n}\n\n// @public (undocumented)\nnamespace QueryNotification {\n    // (undocumented)\n    type FromCache<TData> = NextNotification<ApolloQueryResult<TData>> & {\n        source: \"cache\";\n    };\n    // (undocumented)\n    type FromNetwork<TData> = ObservableNotification<ApolloQueryResult<TData>> & {\n        source: \"network\";\n    };\n    // (undocumented)\n    type NewNetworkStatus<TData> = NextNotification<{\n        resetError?: boolean;\n    }> & {\n        source: \"newNetworkStatus\";\n    };\n    // (undocumented)\n    type SetResult<TData> = NextNotification<ApolloQueryResult<TData>> & {\n        source: \"setResult\";\n    };\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type Value<TData> = FromCache<TData> | FromNetwork<TData> | NewNetworkStatus<TData> | SetResult<TData>;\n}\n\n// @public\ntype QueryOptions<TVariables extends OperationVariables_2 = OperationVariables_2, TData = unknown> = {\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    errorPolicy?: ErrorPolicy;\n    context?: DefaultContext;\n    fetchPolicy?: FetchPolicy;\n} & VariablesOption<NoInfer_2<TVariables>>;\n\nexport { QueryRef }\n\n// @public @deprecated (undocumented)\nexport type QueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQuery_2.Result<TData, TVariables>;\n\n// @public (undocumented)\ninterface QueryResult_2<TData = unknown> {\n    data: TData | undefined;\n    error?: ErrorLike;\n}\n\n// @public (undocumented)\nexport const reactCompilerVersion: string = \"19.1.0-rc.2\";\n\n// @public (undocumented)\ntype RefetchQueriesInclude = RefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// @public (undocumented)\ntype RefetchQueriesIncludeShorthand = \"all\" | \"active\";\n\n// @public (undocumented)\ninterface RefetchQueriesOptions<TCache extends ApolloCache, TResult> {\n    // (undocumented)\n    include?: RefetchQueriesInclude;\n    // (undocumented)\n    onQueryUpdated?: OnQueryUpdated<TResult> | null;\n    // (undocumented)\n    optimistic?: boolean;\n    // (undocumented)\n    updateCache?: (cache: TCache) => void;\n}\n\n// @public (undocumented)\ntype RefetchQueriesPromiseResults<TResult> = IsAny<TResult> extends true ? any[] : TResult extends boolean ? QueryResult_2<any>[] : TResult extends PromiseLike<infer U> ? U[] : TResult[];\n\n// Warning: (ae-forgotten-export) The symbol \"RefetchQueriesPromiseResults\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\ninterface RefetchQueriesResult<TResult> extends Promise<RefetchQueriesPromiseResults<TResult>> {\n    // (undocumented)\n    queries: ObservableQuery<any>[];\n    // (undocumented)\n    results: InternalRefetchQueriesResult<TResult>[];\n}\n\n// @public (undocumented)\ntype RefetchQueryDescriptor = string | DocumentNode;\n\n// @public (undocumented)\ntype RefetchWritePolicy = \"merge\" | \"overwrite\";\n\n// @public (undocumented)\ntype ResetFunction = () => void;\n\n// @public (undocumented)\ntype ResetFunction_2 = () => void;\n\n// @public (undocumented)\nexport type SkipToken = typeof skipToken;\n\n// @public (undocumented)\nexport const skipToken: unique symbol;\n\n// @public (undocumented)\ntype SkipToken_2 = typeof skipToken_2;\n\n// @public (undocumented)\nconst skipToken_2: unique symbol;\n\n// @public (undocumented)\ninterface SubscribeResult<TData = unknown> {\n    data: TData | undefined;\n    error?: ErrorLike;\n    extensions?: Record<string, unknown>;\n}\n\n// @public (undocumented)\ninterface SubscribeToMoreOptions<TData = unknown, TSubscriptionVariables extends OperationVariables_2 = OperationVariables_2, TSubscriptionData = TData, TVariables extends OperationVariables_2 = TSubscriptionVariables> {\n    // (undocumented)\n    context?: DefaultContext;\n    // (undocumented)\n    document: DocumentNode | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;\n    // (undocumented)\n    onError?: (error: ErrorLike) => void;\n    // Warning: (ae-forgotten-export) The symbol \"SubscribeToMoreUpdateQueryFn\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    updateQuery?: SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n    // (undocumented)\n    variables?: TSubscriptionVariables;\n}\n\n// @public (undocumented)\ntype SubscribeToMoreUpdateQueryFn<TData = unknown, TVariables extends OperationVariables_2 = OperationVariables_2, TSubscriptionData = TData> = {\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables> & {\n        subscriptionData: {\n            data: Unmasked<TSubscriptionData>;\n        };\n    }): Unmasked<TData> | void;\n};\n\n// @public @deprecated (undocumented)\nexport type SubscriptionHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSubscription_2.Options<TData, TVariables>;\n\n// @public\ninterface SubscriptionObservable<T> extends Observable<T> {\n    restart: () => void;\n}\n\n// @public (undocumented)\ntype SubscriptionOptions<TVariables extends OperationVariables_2 = OperationVariables_2, TData = unknown> = {\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    fetchPolicy?: FetchPolicy;\n    errorPolicy?: ErrorPolicy;\n    context?: DefaultContext;\n    extensions?: Record<string, any>;\n} & VariablesOption<NoInfer_2<TVariables>>;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSubscription_2.Result<TData>;\n\n// Warning: (ae-forgotten-export) The symbol \"useSuspenseQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type SuspenseQueryHookFetchPolicy = useSuspenseQuery_2.FetchPolicy;\n\n// @public @deprecated (undocumented)\nexport type SuspenseQueryHookOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSuspenseQuery_2.Options<TVariables>;\n\n// @public (undocumented)\ninterface TransformCacheEntry {\n    // (undocumented)\n    asQuery: DocumentNode;\n    // (undocumented)\n    clientQuery: DocumentNode | null;\n    // (undocumented)\n    defaultVars: OperationVariables_2;\n    // (undocumented)\n    hasClientExports: boolean;\n    // (undocumented)\n    hasForcedResolvers: boolean;\n    // (undocumented)\n    hasIncrementalDirective: boolean;\n    // (undocumented)\n    hasNonreactiveDirective: boolean;\n    // (undocumented)\n    nonReactiveQuery: DocumentNode;\n    // (undocumented)\n    operationType: OperationTypeNode | undefined;\n    // (undocumented)\n    serverQuery: DocumentNode | null;\n    // (undocumented)\n    violation?: Error | undefined;\n}\n\n// @public (undocumented)\ninterface UpdateQueryMapFn<TData = unknown, TVariables = OperationVariables_2> {\n    // (undocumented)\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables>): Unmasked<TData> | void;\n}\n\n// @public (undocumented)\ntype UpdateQueryOptions<TData, TVariables> = {\n    variables?: TVariables;\n} & ({\n    complete: true;\n    previousData: Unmasked<TData>;\n} | {\n    complete: false;\n    previousData: DeepPartial<Unmasked<TData>> | undefined;\n});\n\n// @public (undocumented)\nexport function useApolloClient(override?: ApolloClient): ApolloClient;\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    fetchPolicy: \"no-cache\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: false;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken): [undefined, useBackgroundQuery.Result<TData, TVariables>];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n})): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useBackgroundQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n})): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useBackgroundQuery.Options<NoInfer_2<TVariables>>\n] : [options: useBackgroundQuery.Options<NoInfer_2<TVariables>>]): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>]): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | useBackgroundQuery.Options<NoInfer_2<TVariables>>): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nexport namespace useBackgroundQuery {\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export type Options<TVariables extends OperationVariables = OperationVariables> = {\n        client?: ApolloClient;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        errorPolicy?: ErrorPolicy_2;\n        context?: DefaultContext_2;\n        returnPartialData?: boolean;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        skip?: boolean;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n    };\n}\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    fetchPolicy: \"no-cache\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: false;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// Warning: (ae-forgotten-export) The symbol \"SkipToken_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2): [undefined, useBackgroundQuery_2.Result<TData, TVariables>];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2 | (useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: false;\n})): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2 | (useBackgroundQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n})): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useBackgroundQuery_2.Options<NoInfer_2<TVariables>>\n] : [options: useBackgroundQuery_2.Options<NoInfer_2<TVariables>>]): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\">,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken_2 | useBackgroundQuery_2.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken_2 | useBackgroundQuery_2.Options<NoInfer_2<TVariables>>]): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nfunction useBackgroundQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2 | useBackgroundQuery_2.Options<NoInfer_2<TVariables>>): [\nQueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\nuseBackgroundQuery_2.Result<TData, TVariables>\n];\n\n// @public (undocumented)\nnamespace useBackgroundQuery_2 {\n    // (undocumented)\n    type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    type Options<TVariables extends OperationVariables = OperationVariables> = {\n        client?: ApolloClient;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        errorPolicy?: ErrorPolicy_2;\n        context?: DefaultContext_2;\n        returnPartialData?: boolean;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        skip?: boolean;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n    };\n}\n\n// @public @deprecated (undocumented)\nexport type UseBackgroundQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useBackgroundQuery_2.Result<TData, TVariables>;\n\n// @public (undocumented)\nexport function useFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment.Options<TData, TVariables>): useFragment.Result<TData>;\n\n// @public (undocumented)\nexport namespace useFragment {\n    // (undocumented)\n    export interface Options<TData, TVariables> {\n        client?: ApolloClient;\n        fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n        fragmentName?: string;\n        // (undocumented)\n        from: StoreObject | Reference | FragmentType<NoInfer_2<TData>> | string | null;\n        optimistic?: boolean;\n        variables?: NoInfer_2<TVariables>;\n    }\n    // (undocumented)\n    export type Result<TData> = {\n        data: MaybeMasked<TData>;\n        complete: true;\n        missing?: never;\n    } | {\n        data: DeepPartial<MaybeMasked<TData>>;\n        complete: false;\n        missing?: MissingTree;\n    };\n}\n\n// @public (undocumented)\nfunction useFragment_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: useFragment_2.Options<TData, TVariables>): useFragment_2.Result<TData>;\n\n// @public (undocumented)\nnamespace useFragment_2 {\n    // (undocumented)\n    interface Options<TData, TVariables> {\n        client?: ApolloClient;\n        fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n        fragmentName?: string;\n        // (undocumented)\n        from: StoreObject | Reference | FragmentType<NoInfer_2<TData>> | string | null;\n        optimistic?: boolean;\n        variables?: NoInfer_2<TVariables>;\n    }\n    // (undocumented)\n    type Result<TData> = {\n        data: MaybeMasked<TData>;\n        complete: true;\n        missing?: never;\n    } | {\n        data: DeepPartial<MaybeMasked<TData>>;\n        complete: false;\n        missing?: MissingTree;\n    };\n}\n\n// Warning: (ae-forgotten-export) The symbol \"useFragment_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type UseFragmentOptions<TData, TVariables> = useFragment_2.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type UseFragmentResult<TData> = useFragment_2.Result<TData>;\n\n// @public (undocumented)\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nexport function useLazyQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: useLazyQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>): useLazyQuery.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport namespace useLazyQuery {\n    // (undocumented)\n    export type ExecFunction<TData, TVariables extends OperationVariables> = (...args: {} extends TVariables ? [\n    options?: useLazyQuery.ExecOptions<TVariables>\n    ] : [options: useLazyQuery.ExecOptions<TVariables>]) => ObservableQuery_2.ResultPromise<QueryResult_3<TData>>;\n    // (undocumented)\n    export type ExecOptions<TVariables extends OperationVariables = OperationVariables> = {\n        context?: DefaultContext_2;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        client?: ApolloClient;\n        errorPolicy?: ErrorPolicy_2;\n        fetchPolicy?: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        notifyOnNetworkStatusChange?: boolean;\n        pollInterval?: number;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n    }\n    // (undocumented)\n    export type Result<TData, TVariables extends OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        startPolling: (pollInterval: number) => void;\n        stopPolling: () => void;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        updateQuery: (mapFn: UpdateQueryMapFn_2<TData, TVariables>) => void;\n        refetch: (variables?: Partial<TVariables>) => Promise<QueryResult_3<MaybeMasked_2<TData>>>;\n        fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreOptions_2<TData, TVariables, TFetchData, TFetchVars>) => Promise<QueryResult_3<MaybeMasked_2<TFetchData>>>;\n        client: ApolloClient;\n        observable: ObservableQuery_2<TData, TVariables>;\n        previousData?: MaybeMasked_2<TData>;\n        error?: ErrorLike_2;\n        loading: boolean;\n        networkStatus: NetworkStatus_2;\n    } & (({\n        called: true;\n        variables: TVariables;\n    } & GetDataState_2<MaybeMasked_2<TData>, TStates>) | {\n        called: false;\n        variables: Partial<TVariables>;\n        data: undefined;\n        dataState: \"empty\";\n    });\n    // (undocumented)\n    export type ResultTuple<TData, TVariables extends OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = [\n    execute: ExecFunction<TData, TVariables>,\n    result: useLazyQuery.Result<TData, TVariables, TStates>\n    ];\n}\n\n// @public (undocumented)\nfunction useLazyQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useLazyQuery_2.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nfunction useLazyQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: useLazyQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useLazyQuery_2.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nfunction useLazyQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: useLazyQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>): useLazyQuery_2.ResultTuple<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nnamespace useLazyQuery_2 {\n    // (undocumented)\n    type ExecFunction<TData, TVariables extends OperationVariables> = (...args: {} extends TVariables ? [\n    options?: useLazyQuery_2.ExecOptions<TVariables>\n    ] : [options: useLazyQuery_2.ExecOptions<TVariables>]) => ObservableQuery_2.ResultPromise<QueryResult_3<TData>>;\n    // (undocumented)\n    type ExecOptions<TVariables extends OperationVariables = OperationVariables> = {\n        context?: DefaultContext_2;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        client?: ApolloClient;\n        errorPolicy?: ErrorPolicy_2;\n        fetchPolicy?: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        notifyOnNetworkStatusChange?: boolean;\n        pollInterval?: number;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n    }\n    // (undocumented)\n    type Result<TData, TVariables extends OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        startPolling: (pollInterval: number) => void;\n        stopPolling: () => void;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        updateQuery: (mapFn: UpdateQueryMapFn_2<TData, TVariables>) => void;\n        refetch: (variables?: Partial<TVariables>) => Promise<QueryResult_3<MaybeMasked_2<TData>>>;\n        fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreOptions_2<TData, TVariables, TFetchData, TFetchVars>) => Promise<QueryResult_3<MaybeMasked_2<TFetchData>>>;\n        client: ApolloClient;\n        observable: ObservableQuery_2<TData, TVariables>;\n        previousData?: MaybeMasked_2<TData>;\n        error?: ErrorLike_2;\n        loading: boolean;\n        networkStatus: NetworkStatus_2;\n    } & (({\n        called: true;\n        variables: TVariables;\n    } & GetDataState_2<MaybeMasked_2<TData>, TStates>) | {\n        called: false;\n        variables: Partial<TVariables>;\n        data: undefined;\n        dataState: \"empty\";\n    });\n    // Warning: (ae-forgotten-export) The symbol \"useLazyQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type ResultTuple<TData, TVariables extends OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = [\n    execute: ExecFunction<TData, TVariables>,\n    result: useLazyQuery_2.Result<TData, TVariables, TStates>\n    ];\n}\n\n// @public (undocumented)\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public (undocumented)\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery.Options & {\n    returnPartialData: true;\n}): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nexport function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options?: useLoadableQuery.Options): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport namespace useLoadableQuery {\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export type LoadQueryFunction<TVariables extends OperationVariables> = (...args: {} extends TVariables ? [variables?: TVariables] : [variables: TVariables]) => void;\n    // (undocumented)\n    export interface Options {\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        returnPartialData?: boolean;\n    }\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = [\n    loadQuery: LoadQueryFunction<TVariables>,\n    queryRef: QueryRef<TData, TVariables, TStates> | null,\n    handlers: {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        reset: ResetFunction;\n    }\n    ];\n}\n\n// @public (undocumented)\nfunction useLoadableQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery_2.Options & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public (undocumented)\nfunction useLoadableQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery_2.Options & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useLoadableQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nfunction useLoadableQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useLoadableQuery_2.Options & {\n    returnPartialData: true;\n}): useLoadableQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n\n// @public\nfunction useLoadableQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options?: useLoadableQuery_2.Options): useLoadableQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nnamespace useLoadableQuery_2 {\n    // (undocumented)\n    type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    type LoadQueryFunction<TVariables extends OperationVariables> = (...args: {} extends TVariables ? [variables?: TVariables] : [variables: TVariables]) => void;\n    // (undocumented)\n    interface Options {\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        // Warning: (ae-forgotten-export) The symbol \"useLoadableQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        returnPartialData?: boolean;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"useLoadableQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = [\n    loadQuery: LoadQueryFunction<TVariables>,\n    queryRef: QueryRef<TData, TVariables, TStates> | null,\n    handlers: {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n        reset: ResetFunction_2;\n    }\n    ];\n}\n\n// @public @deprecated (undocumented)\nexport type UseLoadableQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useLoadableQuery_2.Result<TData, TVariables>;\n\n// Warning: (ae-forgotten-export) The symbol \"MakeRequiredVariablesOptional\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public\nexport function useMutation<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2, TConfiguredVariables extends Partial<TVariables> = {}>(mutation: DocumentNode_2 | TypedDocumentNode<TData, TVariables>, options?: useMutation.Options<NoInfer_2<TData>, NoInfer_2<TVariables>, TCache, {\n    [K in keyof TConfiguredVariables]: K extends keyof TVariables ? TConfiguredVariables[K] : never;\n}>): useMutation.ResultTuple<TData, MakeRequiredVariablesOptional<TVariables, TConfiguredVariables>, TCache>;\n\n// @public (undocumented)\nexport namespace useMutation {\n    // (undocumented)\n    export type MutationFunction<TData, TVariables extends OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = (...[options]: {} extends TVariables ? [\n    options?: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables?: TVariables;\n    }\n    ] : [\n    options: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables: TVariables;\n    }\n    ]) => Promise<MutateResult_2<MaybeMasked_2<TData>>>;\n    // (undocumented)\n    export type MutationFunctionOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = Options<TData, TVariables, TCache> & {\n        mutation?: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n    };\n    // (undocumented)\n    export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2, TConfiguredVariables extends Partial<TVariables> = Partial<TVariables>> {\n        awaitRefetchQueries?: boolean;\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        fetchPolicy?: MutationFetchPolicy_2;\n        keepRootFields?: boolean;\n        notifyOnNetworkStatusChange?: boolean;\n        onCompleted?: (data: MaybeMasked_2<TData>, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onError?: (error: ErrorLike_2, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onQueryUpdated?: OnQueryUpdated_2<any>;\n        optimisticResponse?: Unmasked_2<NoInfer_2<TData>> | ((vars: TVariables, { IGNORE }: {\n            IGNORE: IgnoreModifier;\n        }) => Unmasked_2<NoInfer_2<TData>> | IgnoreModifier);\n        refetchQueries?: ((result: NormalizedExecutionResult_2<Unmasked_2<TData>>) => InternalRefetchQueriesInclude_2) | InternalRefetchQueriesInclude_2;\n        update?: MutationUpdaterFunction_2<TData, TVariables, TCache>;\n        updateQueries?: MutationQueryReducersMap_2<TData>;\n        variables?: TConfiguredVariables;\n    }\n    // (undocumented)\n    export interface Result<TData = unknown> {\n        called: boolean;\n        client: ApolloClient;\n        data: MaybeMasked_2<TData> | null | undefined;\n        error: ErrorLike_2 | undefined;\n        loading: boolean;\n        reset: () => void;\n    }\n    // (undocumented)\n    export type ResultTuple<TData, TVariables extends OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = [\n    mutate: MutationFunction<TData, TVariables, TCache>,\n    result: Result<TData>\n    ];\n}\n\n// Warning: (ae-forgotten-export) The symbol \"MakeRequiredVariablesOptional_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public\nfunction useMutation_2<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2, TConfiguredVariables extends Partial<TVariables> = {}>(mutation: DocumentNode_2 | TypedDocumentNode<TData, TVariables>, options?: useMutation_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>, TCache, {\n    [K in keyof TConfiguredVariables]: K extends keyof TVariables ? TConfiguredVariables[K] : never;\n}>): useMutation_2.ResultTuple<TData, MakeRequiredVariablesOptional_2<TVariables, TConfiguredVariables>, TCache>;\n\n// @public (undocumented)\nnamespace useMutation_2 {\n    // Warning: (ae-forgotten-export) The symbol \"useMutation_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type MutationFunction<TData, TVariables extends OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = (...[options]: {} extends TVariables ? [\n    options?: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables?: TVariables;\n    }\n    ] : [\n    options: MutationFunctionOptions<TData, TVariables, TCache> & {\n        variables: TVariables;\n    }\n    ]) => Promise<MutateResult_2<MaybeMasked_2<TData>>>;\n    // Warning: (ae-forgotten-export) The symbol \"useMutation_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type MutationFunctionOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = Options<TData, TVariables, TCache> & {\n        mutation?: DocumentNode_2 | TypedDocumentNode<TData, TVariables>;\n    };\n    // (undocumented)\n    interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2, TConfiguredVariables extends Partial<TVariables> = Partial<TVariables>> {\n        awaitRefetchQueries?: boolean;\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        fetchPolicy?: MutationFetchPolicy_2;\n        keepRootFields?: boolean;\n        notifyOnNetworkStatusChange?: boolean;\n        onCompleted?: (data: MaybeMasked_2<TData>, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onError?: (error: ErrorLike_2, clientOptions?: Options<TData, TVariables, TCache>) => void;\n        onQueryUpdated?: OnQueryUpdated_2<any>;\n        optimisticResponse?: Unmasked_2<NoInfer_2<TData>> | ((vars: TVariables, { IGNORE }: {\n            IGNORE: IgnoreModifier;\n        }) => Unmasked_2<NoInfer_2<TData>> | IgnoreModifier);\n        refetchQueries?: ((result: NormalizedExecutionResult_2<Unmasked_2<TData>>) => InternalRefetchQueriesInclude_2) | InternalRefetchQueriesInclude_2;\n        update?: MutationUpdaterFunction_2<TData, TVariables, TCache>;\n        updateQueries?: MutationQueryReducersMap_2<TData>;\n        variables?: TConfiguredVariables;\n    }\n    // (undocumented)\n    interface Result<TData = unknown> {\n        called: boolean;\n        client: ApolloClient;\n        data: MaybeMasked_2<TData> | null | undefined;\n        error: ErrorLike_2 | undefined;\n        loading: boolean;\n        reset: () => void;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"useMutation_2\" needs to be exported by the entry point index.compiled.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"useMutation_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type ResultTuple<TData, TVariables extends OperationVariables, TCache extends ApolloCache_2 = ApolloCache_2> = [\n    mutate: MutationFunction<TData, TVariables, TCache>,\n    result: Result<TData>\n    ];\n}\n\n// @public (undocumented)\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nexport function useQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useQuery.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport namespace useQuery {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext_2;\n            errorPolicy?: ErrorPolicy_2;\n            fetchPolicy?: WatchQueryFetchPolicy;\n            initialFetchPolicy?: WatchQueryFetchPolicy;\n            nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n            notifyOnNetworkStatusChange?: boolean;\n            pollInterval?: number;\n            refetchWritePolicy?: RefetchWritePolicy_2;\n            returnPartialData?: boolean;\n            skip?: boolean;\n            skipPollAttempt?: () => boolean;\n            ssr?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client: ApolloClient;\n            error?: ErrorLike_2;\n            fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreOptions_2<TData, TVariables, TFetchData, TFetchVars>) => Promise<QueryResult_3<MaybeMasked<TFetchData>>>;\n            loading: boolean;\n            networkStatus: NetworkStatus_2;\n            observable: ObservableQuery_2<TData, TVariables>;\n            previousData?: MaybeMasked<TData>;\n            refetch: (variables?: Partial<TVariables>) => Promise<QueryResult_3<MaybeMasked<TData>>>;\n            startPolling: (pollInterval: number) => void;\n            stopPolling: () => void;\n            subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n            updateQuery: (mapFn: UpdateQueryMapFn_2<TData, TVariables>) => void;\n            variables: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Result<TData, TVariables>, DocumentationTypes.DataState<TData> {\n        }\n    }\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = Base.Result<TData, TVariables> & GetDataState_2<MaybeMasked<TData>, TStates>;\n}\n\n// @public (undocumented)\nexport namespace useQuery {\n    var // (undocumented)\n    ssrDisabledResult: ApolloQueryResult_2<any>;\n}\n\n// @public (undocumented)\nfunction useQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useQuery_2.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nfunction useQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>> & {\n    returnPartialData: boolean;\n}): useQuery_2.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nfunction useQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useQuery_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useQuery_2.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nnamespace useQuery_2 {\n    // (undocumented)\n    namespace Base {\n        // (undocumented)\n        interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext_2;\n            errorPolicy?: ErrorPolicy_2;\n            fetchPolicy?: WatchQueryFetchPolicy;\n            initialFetchPolicy?: WatchQueryFetchPolicy;\n            nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n            notifyOnNetworkStatusChange?: boolean;\n            pollInterval?: number;\n            refetchWritePolicy?: RefetchWritePolicy_2;\n            returnPartialData?: boolean;\n            skip?: boolean;\n            skipPollAttempt?: () => boolean;\n            ssr?: boolean;\n        }\n    }\n    // (undocumented)\n    namespace Base {\n        // (undocumented)\n        interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client: ApolloClient;\n            error?: ErrorLike_2;\n            fetchMore: <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: FetchMoreOptions_2<TData, TVariables, TFetchData, TFetchVars>) => Promise<QueryResult_3<MaybeMasked<TFetchData>>>;\n            loading: boolean;\n            networkStatus: NetworkStatus_2;\n            observable: ObservableQuery_2<TData, TVariables>;\n            previousData?: MaybeMasked<TData>;\n            refetch: (variables?: Partial<TVariables>) => Promise<QueryResult_3<MaybeMasked<TData>>>;\n            startPolling: (pollInterval: number) => void;\n            stopPolling: () => void;\n            subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n            updateQuery: (mapFn: UpdateQueryMapFn_2<TData, TVariables>) => void;\n            variables: TVariables;\n        }\n    }\n    // (undocumented)\n    namespace DocumentationTypes {\n        // (undocumented)\n        interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    namespace DocumentationTypes {\n        // (undocumented)\n        interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Result<TData, TVariables>, DocumentationTypes.DataState<TData> {\n        }\n    }\n    // Warning: (ae-forgotten-export) The symbol \"useQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = Base.Result<TData, TVariables> & GetDataState_2<MaybeMasked<TData>, TStates>;\n}\n\n// @public (undocumented)\nnamespace useQuery_2 {\n    var // (undocumented)\n    ssrDisabledResult: ApolloQueryResult_2<any>;\n}\n\n// @public\nexport function useQueryRefHandlers<TData = unknown, TVariables extends OperationVariables = OperationVariables>(queryRef: QueryRef<TData, TVariables, DataState_2<TData>[\"dataState\"]>): useQueryRefHandlers.Result<TData, TVariables>;\n\n// @public (undocumented)\nexport namespace useQueryRefHandlers {\n    // (undocumented)\n    export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n}\n\n// @public\nfunction useQueryRefHandlers_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(queryRef: QueryRef<TData, TVariables, DataState_2<TData>[\"dataState\"]>): useQueryRefHandlers_2.Result<TData, TVariables>;\n\n// @public (undocumented)\nnamespace useQueryRefHandlers_2 {\n    // (undocumented)\n    interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n}\n\n// Warning: (ae-forgotten-export) The symbol \"useQueryRefHandlers_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type UseQueryRefHandlersResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useQueryRefHandlers_2.Result<TData, TVariables>;\n\n// @public\nexport function useReactiveVar<T>(rv: ReactiveVar<T>): T;\n\n// @public (undocumented)\nexport function useReadQuery<TData, TStates extends DataState_2<TData>[\"dataState\"]>(queryRef: QueryRef<TData, any, TStates>): useReadQuery.Result<TData, TStates>;\n\n// @public (undocumented)\nexport namespace useReadQuery {\n    // (undocumented)\n    export type Result<TData = unknown, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        error: ErrorLike_2 | undefined;\n        networkStatus: NetworkStatus_2;\n    } & GetDataState_2<MaybeMasked<TData>, TStates>;\n}\n\n// @public (undocumented)\nfunction useReadQuery_2<TData, TStates extends DataState_2<TData>[\"dataState\"]>(queryRef: QueryRef<TData, any, TStates>): useReadQuery_2.Result<TData, TStates>;\n\n// @public (undocumented)\nnamespace useReadQuery_2 {\n    // (undocumented)\n    type Result<TData = unknown, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        error: ErrorLike_2 | undefined;\n        networkStatus: NetworkStatus_2;\n    } & GetDataState_2<MaybeMasked<TData>, TStates>;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"useReadQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type UseReadQueryResult<TData = unknown> = useReadQuery_2.Result<TData>;\n\n// @public\nexport function useSubscription<TData = unknown, TVariables extends OperationVariables = OperationVariables>(subscription: DocumentNode | TypedDocumentNode<TData, TVariables>, ...[options]: {} extends (TVariables) ? [\noptions?: useSubscription.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useSubscription.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useSubscription.Result<TData>;\n\n// @public (undocumented)\nexport namespace useSubscription {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext_2;\n            errorPolicy?: ErrorPolicy_2;\n            extensions?: Record<string, any>;\n            fetchPolicy?: FetchPolicy_2;\n            ignoreResults?: boolean;\n            onComplete?: () => void;\n            onData?: (options: OnDataOptions<TData>) => any;\n            onError?: (error: ErrorLike_2) => void;\n            shouldResubscribe?: boolean | ((options: Options<TData, TVariables>) => boolean);\n            skip?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export interface OnDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        data: OnDataResult<TData>;\n    }\n    // (undocumented)\n    export type OnDataResult<TData = unknown> = Omit<Result<TData>, \"restart\">;\n    // (undocumented)\n    export interface OnSubscriptionDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        subscriptionData: OnDataResult<TData>;\n    }\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    export interface Result<TData = unknown> {\n        data?: MaybeMasked<TData>;\n        error?: ErrorLike_2;\n        loading: boolean;\n        // (undocumented)\n        restart: () => void;\n    }\n}\n\n// @public\nfunction useSubscription_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(subscription: DocumentNode | TypedDocumentNode<TData, TVariables>, ...[options]: {} extends (TVariables) ? [\noptions?: useSubscription_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>\n] : [options: useSubscription_2.Options<NoInfer_2<TData>, NoInfer_2<TVariables>>]): useSubscription_2.Result<TData>;\n\n// @public (undocumented)\nnamespace useSubscription_2 {\n    // (undocumented)\n    namespace Base {\n        // (undocumented)\n        interface Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n            client?: ApolloClient;\n            context?: DefaultContext_2;\n            errorPolicy?: ErrorPolicy_2;\n            extensions?: Record<string, any>;\n            fetchPolicy?: FetchPolicy_2;\n            ignoreResults?: boolean;\n            onComplete?: () => void;\n            // Warning: (ae-forgotten-export) The symbol \"useSubscription_2\" needs to be exported by the entry point index.compiled.d.ts\n            onData?: (options: OnDataOptions<TData>) => any;\n            onError?: (error: ErrorLike_2) => void;\n            shouldResubscribe?: boolean | ((options: Options<TData, TVariables>) => boolean);\n            skip?: boolean;\n        }\n    }\n    // (undocumented)\n    namespace DocumentationTypes {\n        // (undocumented)\n        interface Result<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Base.Options<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    interface OnDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // Warning: (ae-forgotten-export) The symbol \"useSubscription_2\" needs to be exported by the entry point index.compiled.d.ts\n        //\n        // (undocumented)\n        data: OnDataResult<TData>;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"useSubscription_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type OnDataResult<TData = unknown> = Omit<Result<TData>, \"restart\">;\n    // (undocumented)\n    interface OnSubscriptionDataOptions<TData = unknown> {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        subscriptionData: OnDataResult<TData>;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"useSubscription_2\" needs to be exported by the entry point index.compiled.d.ts\n    //\n    // (undocumented)\n    type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n    // (undocumented)\n    interface Result<TData = unknown> {\n        data?: MaybeMasked<TData>;\n        error?: ErrorLike_2;\n        loading: boolean;\n        // (undocumented)\n        restart: () => void;\n    }\n}\n\n// @public (undocumented)\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: NonNullable<From<TData>>;\n}): useSuspenseFragment.Result<TData>;\n\n// @public (undocumented)\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: null;\n}): useSuspenseFragment.Result<null>;\n\n// @public (undocumented)\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: From<TData>;\n}): useSuspenseFragment.Result<TData | null>;\n\n// @public (undocumented)\nexport function useSuspenseFragment<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment.Options<TData, TVariables>): useSuspenseFragment.Result<TData>;\n\n// @public (undocumented)\nexport namespace useSuspenseFragment {\n    // (undocumented)\n    export type Options<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n        fragmentName?: string;\n        from: From<TData>;\n        optimistic?: boolean;\n        client?: ApolloClient;\n    } & VariablesOption<NoInfer_2<TVariables>>;\n    // (undocumented)\n    export type Result<TData> = {\n        data: MaybeMasked<TData>;\n    };\n}\n\n// @public (undocumented)\nfunction useSuspenseFragment_2<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment_2.Options<TData, TVariables> & {\n    from: NonNullable<From_2<TData>>;\n}): useSuspenseFragment_2.Result<TData>;\n\n// @public (undocumented)\nfunction useSuspenseFragment_2<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment_2.Options<TData, TVariables> & {\n    from: null;\n}): useSuspenseFragment_2.Result<null>;\n\n// @public (undocumented)\nfunction useSuspenseFragment_2<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment_2.Options<TData, TVariables> & {\n    from: From_2<TData>;\n}): useSuspenseFragment_2.Result<TData | null>;\n\n// @public (undocumented)\nfunction useSuspenseFragment_2<TData, TVariables extends OperationVariables = OperationVariables>(options: useSuspenseFragment_2.Options<TData, TVariables>): useSuspenseFragment_2.Result<TData>;\n\n// @public (undocumented)\nnamespace useSuspenseFragment_2 {\n    // (undocumented)\n    type Options<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>;\n        fragmentName?: string;\n        from: From_2<TData>;\n        optimistic?: boolean;\n        client?: ApolloClient;\n    } & VariablesOption<NoInfer_2<TVariables>>;\n    // (undocumented)\n    type Result<TData> = {\n        data: MaybeMasked<TData>;\n    };\n}\n\n// Warning: (ae-forgotten-export) The symbol \"useSuspenseFragment_2\" needs to be exported by the entry point index.compiled.d.ts\n//\n// @public @deprecated (undocumented)\nexport type UseSuspenseFragmentOptions<TData, TVariables extends OperationVariables> = useSuspenseFragment_2.Options<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type UseSuspenseFragmentResult<TData> = useSuspenseFragment_2.Result<TData>;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: true;\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"empty\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useSuspenseQuery.Result<TData, TVariables, \"partial\" | \"streaming\" | \"complete\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | (useSuspenseQuery.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n})): useSuspenseQuery.Result<TData, TVariables, \"empty\" | \"streaming\" | \"complete\" | \"partial\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useSuspenseQuery.Options<NoInfer_2<TVariables>>\n] : [options: useSuspenseQuery.Options<NoInfer_2<TVariables>>]): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>]): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken | useSuspenseQuery.Options<NoInfer_2<TVariables>>): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nexport namespace useSuspenseQuery {\n    // (undocumented)\n    export type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    export type Options<TVariables extends OperationVariables = OperationVariables> = {\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        returnPartialData?: boolean;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        skip?: boolean;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    export type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        client: ApolloClient;\n        error: ErrorLike_2 | undefined;\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        networkStatus: NetworkStatus_2;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    } & GetDataState_2<MaybeMasked_2<TData>, TStates>;\n}\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n}): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n    returnPartialData: true;\n}): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"empty\" | \"streaming\" | \"partial\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n}): useSuspenseQuery_2.Result<TData, TVariables, \"partial\" | \"streaming\" | \"complete\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    skip: boolean;\n}): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2 | (useSuspenseQuery_2.Options<NoInfer_2<TVariables>> & {\n    returnPartialData: true;\n})): useSuspenseQuery_2.Result<TData, TVariables, \"empty\" | \"streaming\" | \"complete\" | \"partial\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: useSuspenseQuery_2.Options<NoInfer_2<TVariables>>\n] : [options: useSuspenseQuery_2.Options<NoInfer_2<TVariables>>]): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, ...[options]: {} extends TVariables ? [\noptions?: SkipToken_2 | useSuspenseQuery_2.Options<NoInfer_2<TVariables>>\n] : [options: SkipToken_2 | useSuspenseQuery_2.Options<NoInfer_2<TVariables>>]): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nfunction useSuspenseQuery_2<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode_2 | TypedDocumentNode_2<TData, TVariables>, options: SkipToken_2 | useSuspenseQuery_2.Options<NoInfer_2<TVariables>>): useSuspenseQuery_2.Result<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n// @public (undocumented)\nnamespace useSuspenseQuery_2 {\n    // (undocumented)\n    type FetchPolicy = Extract<WatchQueryFetchPolicy, \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\">;\n    // (undocumented)\n    type Options<TVariables extends OperationVariables = OperationVariables> = {\n        client?: ApolloClient;\n        context?: DefaultContext_2;\n        errorPolicy?: ErrorPolicy_2;\n        returnPartialData?: boolean;\n        refetchWritePolicy?: RefetchWritePolicy_2;\n        fetchPolicy?: FetchPolicy;\n        queryKey?: string | number | any[];\n        skip?: boolean;\n    } & VariablesOption<TVariables>;\n    // (undocumented)\n    type Result<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState_2<TData>[\"dataState\"] = DataState_2<TData>[\"dataState\"]> = {\n        client: ApolloClient;\n        error: ErrorLike_2 | undefined;\n        fetchMore: FetchMoreFunction<TData, TVariables>;\n        networkStatus: NetworkStatus_2;\n        refetch: RefetchFunction<TData, TVariables>;\n        subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    } & GetDataState_2<MaybeMasked_2<TData>, TStates>;\n}\n\n// @public @deprecated (undocumented)\nexport type UseSuspenseQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = useSuspenseQuery_2.Result<TData, TVariables>;\n\n// @public (undocumented)\ntype WatchQueryFetchPolicy_2 = FetchPolicy | \"cache-and-network\" | \"standby\";\n\n// @public\ntype WatchQueryOptions_2<TVariables extends OperationVariables_2 = OperationVariables_2, TData = unknown> = {\n    fetchPolicy?: WatchQueryFetchPolicy_2;\n    nextFetchPolicy?: WatchQueryFetchPolicy_2 | ((this: WatchQueryOptions_2<TVariables, TData>, currentFetchPolicy: WatchQueryFetchPolicy_2, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy_2);\n    initialFetchPolicy?: WatchQueryFetchPolicy_2;\n    refetchWritePolicy?: RefetchWritePolicy;\n    errorPolicy?: ErrorPolicy;\n    context?: DefaultContext;\n    pollInterval?: number;\n    notifyOnNetworkStatusChange?: boolean;\n    returnPartialData?: boolean;\n    skipPollAttempt?: () => boolean;\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n} & VariablesOption<NoInfer_2<TVariables>>;\n\n// Warnings were encountered during analysis:\n//\n// src/core/ObservableQuery.ts:65:3 - (ae-forgotten-export) The symbol \"ErrorPolicy\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/ObservableQuery.ts:145:5 - (ae-forgotten-export) The symbol \"NextFetchPolicyContext\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/ObservableQuery.ts:157:5 - (ae-forgotten-export) The symbol \"RefetchWritePolicy\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/ObservableQuery.ts:305:5 - (ae-forgotten-export) The symbol \"QueryManager\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/QueryManager.ts:187:5 - (ae-forgotten-export) The symbol \"MutationStoreValue\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/types.ts:309:3 - (ae-forgotten-export) The symbol \"ErrorLike\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/types.ts:313:3 - (ae-forgotten-export) The symbol \"NetworkStatus\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/types.ts:321:7 - (ae-forgotten-export) The symbol \"DataValue\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/types.ts:371:3 - (ae-forgotten-export) The symbol \"MutationQueryReducer\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:178:3 - (ae-forgotten-export) The symbol \"UpdateQueryOptions\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:261:3 - (ae-forgotten-export) The symbol \"MutationQueryReducersMap\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:264:3 - (ae-forgotten-export) The symbol \"NormalizedExecutionResult\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:274:3 - (ae-forgotten-export) The symbol \"MutationUpdaterFunction\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:277:3 - (ae-forgotten-export) The symbol \"OnQueryUpdated\" needs to be exported by the entry point index.compiled.d.ts\n// src/core/watchQueryOptions.ts:286:3 - (ae-forgotten-export) The symbol \"MutationFetchPolicy\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useBackgroundQuery.ts:64:5 - (ae-forgotten-export) The symbol \"useBackgroundQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useLoadableQuery.ts:70:7 - (ae-forgotten-export) The symbol \"ResetFunction\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useLoadableQuery.ts:70:7 - (ae-forgotten-export) The symbol \"ResetFunction_2\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useSuspenseFragment.ts:75:5 - (ae-forgotten-export) The symbol \"From\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useSuspenseFragment.ts:75:5 - (ae-forgotten-export) The symbol \"From_2\" needs to be exported by the entry point index.compiled.d.ts\n// src/react/hooks/useSuspenseQuery.ts:66:5 - (ae-forgotten-export) The symbol \"useSuspenseQuery_2\" needs to be exported by the entry point index.compiled.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-react_internal.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloClient } from '@apollo/client';\nimport type { DataState } from '@apollo/client';\nimport type { DecoratedPromise } from '@apollo/client/utilities/internal';\nimport type { DocumentNode } from 'graphql';\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nimport type { InternalTypes } from '@apollo/client/react';\nimport type { MaybeMasked } from '@apollo/client/masking';\nimport type { MaybeMasked as MaybeMasked_2 } from '@apollo/client';\nimport type { ObservableQuery } from '@apollo/client';\nimport type { OperationVariables } from '@apollo/client';\nimport type { ResultOf } from '@graphql-typed-document-node/core';\nimport type { VariablesOf } from '@graphql-typed-document-node/core';\n\n// Warning: (ae-forgotten-export) The symbol \"WrappedQueryRef\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function assertWrappedQueryRef<TData, TVariables extends OperationVariables, TStates extends DataState<TData>[\"dataState\"]>(queryRef: QueryRef<TData, TVariables, TStates>): asserts queryRef is WrappedQueryRef<TData, TVariables, TStates>;\n\n// @public (undocumented)\nexport function assertWrappedQueryRef<TData, TVariables extends OperationVariables, TStates extends DataState<TData>[\"dataState\"]>(queryRef: QueryRef<TData, TVariables, TStates> | undefined | null): asserts queryRef is WrappedQueryRef<TData, TVariables, TStates> | undefined | null;\n\n// @public (undocumented)\nexport type CacheKey = [\nquery: DocumentNode,\nstringifiedVariables: string,\n...queryKey: any[]\n];\n\n// @public (undocumented)\nexport type FetchMoreFunction<TData, TVariables extends OperationVariables> = <TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(fetchMoreOptions: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>) => Promise<ApolloClient.QueryResult<MaybeMasked_2<TData>>>;\n\n// @public (undocumented)\ntype FragmentCacheKey = [\nfragment: DocumentNode,\nstringifiedVariables: string,\ncacheId: string | null\n];\n\n// @public (undocumented)\nexport interface FragmentKey {\n    // (undocumented)\n    __fragmentKey?: string;\n}\n\n// @public (undocumented)\nclass FragmentReference<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n    // Warning: (ae-forgotten-export) The symbol \"FragmentReferenceOptions\" needs to be exported by the entry point index.d.ts\n    constructor(client: ApolloClient, watchFragmentOptions: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: string | null | Array<string | null>;\n    }, options: FragmentReferenceOptions);\n    // (undocumented)\n    readonly key: FragmentKey;\n    // Warning: (ae-forgotten-export) The symbol \"Listener_2\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    listen(listener: Listener_2<MaybeMasked<TData>>): () => void;\n    // (undocumented)\n    readonly observable: ApolloClient.ObservableFragment<TData | null>;\n    // Warning: (ae-forgotten-export) The symbol \"FragmentRefPromise\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    promise: FragmentRefPromise<MaybeMasked<TData>>;\n    // (undocumented)\n    retain(): () => void;\n}\n\n// @public (undocumented)\ninterface FragmentReferenceOptions {\n    // (undocumented)\n    autoDisposeTimeoutMs?: number;\n    // (undocumented)\n    onDispose?: () => void;\n}\n\n// @public (undocumented)\ntype FragmentRefPromise<TData> = DecoratedPromise<TData>;\n\n// Warning: (ae-forgotten-export) The symbol \"SuspenseCache\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function getSuspenseCache(client: ApolloClient & {\n    [suspenseCacheSymbol]?: SuspenseCache;\n}): SuspenseCache;\n\n// Warning: (ae-forgotten-export) The symbol \"QueryRefPromise\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function getWrappedPromise<TData, TStates extends DataState<TData>[\"dataState\"]>(queryRef: WrappedQueryRef<TData, any, TStates>): QueryRefPromise<TData, TStates>;\n\n// @public (undocumented)\nexport type HookWrappers = InternalTypes.HookWrappers;\n\n// @public (undocumented)\nexport class InternalQueryReference<TData = unknown, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> {\n    // Warning: (ae-forgotten-export) The symbol \"InternalQueryReferenceOptions\" needs to be exported by the entry point index.d.ts\n    constructor(observable: ObservableQuery<TData, any>, options: InternalQueryReferenceOptions);\n    // (undocumented)\n    applyOptions(watchQueryOptions: ObservedOptions): QueryRefPromise<TData, TStates>;\n    // Warning: (ae-forgotten-export) The symbol \"ObservedOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    didChangeOptions(watchQueryOptions: ObservedOptions): boolean;\n    // (undocumented)\n    get disposed(): boolean;\n    // (undocumented)\n    fetchMore(options: ObservableQuery.FetchMoreOptions<TData, any, any, any>): Promise<ApolloClient.QueryResult<TData>>;\n    // (undocumented)\n    readonly key: QueryKey;\n    // Warning: (ae-forgotten-export) The symbol \"Listener\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    listen(listener: Listener<TData, TStates>): () => void;\n    // (undocumented)\n    readonly observable: ObservableQuery<TData>;\n    // (undocumented)\n    promise: QueryRefPromise<TData, TStates>;\n    // (undocumented)\n    refetch(variables: OperationVariables | undefined): Promise<ApolloClient.QueryResult<TData>>;\n    // (undocumented)\n    reinitialize(): void;\n    // (undocumented)\n    result: ObservableQuery.Result<MaybeMasked<TData>, TStates>;\n    // (undocumented)\n    retain(): () => void;\n    // (undocumented)\n    softRetain(): () => void;\n    // (undocumented)\n    get watchQueryOptions(): ObservableQuery.Options<TData, OperationVariables>;\n}\n\n// @public (undocumented)\ninterface InternalQueryReferenceOptions {\n    // (undocumented)\n    autoDisposeTimeoutMs?: number;\n    // (undocumented)\n    onDispose?: () => void;\n}\n\n// @public (undocumented)\ntype Listener<TData, TStates extends DataState<TData>[\"dataState\"]> = (promise: QueryRefPromise<TData, TStates>) => void;\n\n// @public (undocumented)\ntype Listener_2<TData> = (promise: FragmentRefPromise<TData>) => void;\n\n// @public (undocumented)\nconst OBSERVED_CHANGED_OPTIONS: readonly [\"context\", \"errorPolicy\", \"fetchPolicy\", \"refetchWritePolicy\", \"returnPartialData\"];\n\n// Warning: (ae-forgotten-export) The symbol \"OBSERVED_CHANGED_OPTIONS\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype ObservedOptions = Pick<ApolloClient.WatchQueryOptions, (typeof OBSERVED_CHANGED_OPTIONS)[number]>;\n\n// @public (undocumented)\nconst PRELOADED_QUERY_REF_BRAND: unique symbol;\n\n// @public\nexport interface PreloadedQueryRef<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\"> extends QueryRef<TData, TVariables, TStates> {\n    // @internal @deprecated (undocumented)\n    [PRELOADED_QUERY_REF_BRAND]: typeof PRELOADED_QUERY_REF_BRAND;\n}\n\n// @public (undocumented)\nconst PROMISE_SYMBOL: unique symbol;\n\n// @public (undocumented)\nconst QUERY_REF_BRAND: unique symbol;\n\n// @public (undocumented)\nconst QUERY_REFERENCE_SYMBOL: unique symbol;\n\n// @public (undocumented)\nexport interface QueryKey {\n    // (undocumented)\n    __queryKey?: string;\n}\n\n// @public\nexport interface QueryRef<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\"> {\n    // @internal @deprecated (undocumented)\n    [QUERY_REF_BRAND]?(variables: TVariables): {\n        data: TData;\n        states: TStates;\n    };\n}\n\n// @public (undocumented)\nexport namespace QueryRef {\n    // (undocumented)\n    export type ForQuery<Document extends DocumentTypeDecoration<any, any>, TStates extends DataState<ResultOf<Document>>[\"dataState\"] = \"complete\" | \"streaming\"> = QueryRef<ResultOf<Document>, VariablesOf<Document>, TStates>;\n}\n\n// @public (undocumented)\ntype QueryRefPromise<TData, TStates extends DataState<TData>[\"dataState\"]> = DecoratedPromise<ObservableQuery.Result<MaybeMasked<TData>, TStates>>;\n\n// @public (undocumented)\nexport type RefetchFunction<TData, TVariables extends OperationVariables> = (variables?: Partial<TVariables>) => Promise<ApolloClient.QueryResult<TData>>;\n\n// @public (undocumented)\nclass SuspenseCache {\n    constructor(options?: SuspenseCacheOptions);\n    // (undocumented)\n    add(cacheKey: CacheKey, queryRef: InternalQueryReference<any, any>): void;\n    // Warning: (ae-forgotten-export) The symbol \"FragmentCacheKey\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"FragmentReference\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getFragmentRef<TData, TVariables extends OperationVariables>(cacheKey: FragmentCacheKey, client: ApolloClient, options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: string | null | Array<string | null>;\n    }): FragmentReference<TData, TVariables>;\n    // (undocumented)\n    getQueryRef<TData = unknown, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]>(cacheKey: CacheKey, createObservable: () => ObservableQuery<TData>): InternalQueryReference<TData, TStates>;\n}\n\n// @public (undocumented)\nexport interface SuspenseCacheOptions {\n    autoDisposeTimeoutMs?: number;\n}\n\n// @public (undocumented)\nconst suspenseCacheSymbol: unique symbol;\n\n// @public (undocumented)\nexport function unwrapQueryRef<TData, TStates extends DataState<TData>[\"dataState\"]>(queryRef: WrappedQueryRef<TData, any, TStates>): InternalQueryReference<TData, TStates>;\n\n// @public (undocumented)\nexport function unwrapQueryRef<TData, TStates extends DataState<TData>[\"dataState\"]>(queryRef: Partial<WrappedQueryRef<TData, any, TStates>>): undefined | InternalQueryReference<TData, TStates>;\n\n// @public (undocumented)\nexport function updateWrappedQueryRef<TData, TStates extends DataState<TData>[\"dataState\"]>(queryRef: WrappedQueryRef<TData, any, TStates>, promise: QueryRefPromise<TData, TStates>): void;\n\n// @internal @deprecated\ninterface WrappedQueryRef<TData = unknown, TVariables extends OperationVariables = OperationVariables, TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\"> extends QueryRef<TData, TVariables, TStates> {\n    // @deprecated (undocumented)\n    [PROMISE_SYMBOL]: QueryRefPromise<TData, TStates>;\n    // @deprecated (undocumented)\n    readonly [QUERY_REFERENCE_SYMBOL]: InternalQueryReference<TData, TStates>;\n}\n\n// @public (undocumented)\nexport const wrapperSymbol: unique symbol;\n\n// @public (undocumented)\nexport function wrapQueryRef<TData, TVariables extends OperationVariables, TStates extends DataState<TData>[\"dataState\"]>(internalQueryRef: InternalQueryReference<TData, TStates>): WrappedQueryRef<TData, TVariables, TStates>;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-react_internal_compiler-runtime.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public\nexport const c: any;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-react_ssr.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloClient } from '@apollo/client';\nimport type * as ReactTypes from 'react';\n\n// @public @deprecated (undocumented)\nexport function getDataFromTree(tree: ReactTypes.ReactNode, context?: {\n    [key: string]: any;\n}): Promise<string>;\n\n// Warning: (ae-forgotten-export) The symbol \"GetMarkupFromTreeOptions\" needs to be exported by the entry point index.d.ts\n//\n// @public @deprecated (undocumented)\nexport function getMarkupFromTree({ tree, context, renderFunction, }: GetMarkupFromTreeOptions): Promise<string>;\n\n// @public (undocumented)\ntype GetMarkupFromTreeOptions = {\n    tree: ReactTypes.ReactNode;\n    context?: {\n        [key: string]: any;\n    };\n    renderFunction?: prerenderStatic.RenderToString | prerenderStatic.RenderToStringPromise;\n};\n\n// @public\nexport function prerenderStatic<Prerender extends prerenderStatic.PrerenderFunction = prerenderStatic.PrerenderFunction>({ tree, context, renderFunction, signal, ignoreResults, diagnostics, maxRerenders, }: prerenderStatic.Options<Prerender>): Promise<prerenderStatic.Result<Prerender>>;\n\n// @public (undocumented)\nexport namespace prerenderStatic {\n    // (undocumented)\n    export interface Diagnostics {\n        renderCount: number;\n    }\n    // (undocumented)\n    export interface Options<Prerender extends PrerenderFunction = PrerenderFunction> {\n        context?: {\n            client?: ApolloClient;\n        };\n        diagnostics?: boolean;\n        ignoreResults?: boolean;\n        maxRerenders?: number;\n        renderFunction: Prerender;\n        signal?: AbortSignal;\n        tree: ReactTypes.ReactNode;\n    }\n    export type PrerenderFunction = RenderToString | RenderToStringPromise | PrerenderToWebStream | PrerenderToNodeStream | ((reactNode: ReactTypes.ReactNode) => ReturnType<RenderToString> | ReturnType<RenderToStringPromise> | ReturnType<PrerenderToWebStream> | ReturnType<PrerenderToNodeStream>);\n    // (undocumented)\n    export type PrerenderToNodeStream = (reactNode: ReactTypes.ReactNode) => Promise<{\n        prelude: AsyncIterable<string | Buffer>;\n    }>;\n    // (undocumented)\n    export type PrerenderToWebStream = (reactNode: ReactTypes.ReactNode) => Promise<{\n        prelude: ReadableStream<Uint8Array>;\n    }>;\n    // (undocumented)\n    export type RenderToString = (element: ReactTypes.ReactNode) => string;\n    // (undocumented)\n    export type RenderToStringPromise = (element: ReactTypes.ReactNode) => PromiseLike<string>;\n    // (undocumented)\n    export interface Result<Prerender extends PrerenderFunction = PrerenderFunction> {\n        aborted: boolean;\n        diagnostics?: Diagnostics;\n        renderFnResult: ReturnType<Prerender> extends PromiseLike<infer U> ? U : ReturnType<Prerender>;\n        result: string;\n    }\n}\n\n// @public @deprecated (undocumented)\nexport function renderToStringWithData(component: ReactTypes.ReactElement<any>): Promise<string>;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-testing.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport { ApolloLink } from '@apollo/client/link';\nimport type { DocumentNode } from 'graphql';\nimport { FormattedExecutionResult } from 'graphql';\nimport { Observable } from 'rxjs';\nimport type { OperationVariables } from '@apollo/client';\nimport type { Unmasked } from '@apollo/client/masking';\n\n// @internal @deprecated (undocumented)\ntype CovariantUnaryFunction<out Arg, out Ret> = {\n    fn(arg: Arg): Ret;\n}[\"fn\"];\n\n// @public @deprecated (undocumented)\nexport type MockedRequest<TVariables extends OperationVariables = Record<string, any>> = MockLink.MockedRequest<TVariables>;\n\n// @public @deprecated (undocumented)\nexport type MockedResponse<TData = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> = MockLink.MockedResponse<TData, TVariables>;\n\n// @public (undocumented)\nexport namespace MockLink {\n    // (undocumented)\n    export interface DefaultOptions {\n        // (undocumented)\n        delay?: MockLink.Delay;\n    }\n    // (undocumented)\n    export type Delay = number | DelayFunction;\n    // (undocumented)\n    export type DelayFunction = (operation: ApolloLink.Operation) => number;\n    // (undocumented)\n    export interface MockedRequest<TVariables extends OperationVariables = OperationVariables> {\n        // (undocumented)\n        query: DocumentNode;\n        // Warning: (ae-forgotten-export) The symbol \"VariableMatcher\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        variables?: TVariables | VariableMatcher<TVariables>;\n    }\n    // (undocumented)\n    export interface MockedResponse<\n    /** @ts-ignore */\n    out TData = Record<string, any>, out TVariables extends OperationVariables = Record<string, any>> {\n        // (undocumented)\n        delay?: number | MockLink.DelayFunction;\n        // (undocumented)\n        error?: Error;\n        // (undocumented)\n        maxUsageCount?: number;\n        // (undocumented)\n        request: MockedRequest<TVariables>;\n        // (undocumented)\n        result?: ApolloLink.Result<Unmasked<TData>> | ResultFunction<ApolloLink.Result<Unmasked<TData>>, TVariables>;\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        defaultOptions?: DefaultOptions;\n        // (undocumented)\n        showWarnings?: boolean;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"CovariantUnaryFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    export type ResultFunction<T, V = Record<string, any>> = CovariantUnaryFunction<V, T>;\n}\n\n// @public (undocumented)\nexport class MockLink extends ApolloLink {\n    constructor(mockedResponses: ReadonlyArray<MockLink.MockedResponse<Record<string, any>, Record<string, any>>>, options?: MockLink.Options);\n    // (undocumented)\n    addMockedResponse(mockedResponse: MockLink.MockedResponse): void;\n    // (undocumented)\n    static defaultOptions: MockLink.DefaultOptions;\n    // (undocumented)\n    operation: ApolloLink.Operation;\n    // (undocumented)\n    request(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n    // (undocumented)\n    showWarnings: boolean;\n}\n\n// @public @deprecated (undocumented)\nexport type MockLinkOptions = MockLink.Options;\n\n// @public (undocumented)\nexport namespace MockSubscriptionLink {\n    // (undocumented)\n    export interface Result {\n        // (undocumented)\n        delay?: number;\n        // (undocumented)\n        error?: Error;\n        // (undocumented)\n        result?: ApolloLink.Result;\n    }\n}\n\n// @public (undocumented)\nexport class MockSubscriptionLink extends ApolloLink {\n    constructor();\n    // (undocumented)\n    onSetup(listener: any): void;\n    // (undocumented)\n    onUnsubscribe(listener: any): void;\n    // (undocumented)\n    operation?: ApolloLink.Operation;\n    // (undocumented)\n    request(operation: ApolloLink.Operation): Observable<FormattedExecutionResult<Record<string, any>, Record<string, any>>>;\n    // (undocumented)\n    setups: any[];\n    // (undocumented)\n    simulateComplete(): void;\n    // (undocumented)\n    simulateResult(result: MockSubscriptionLink.Result, complete?: boolean): void;\n    // (undocumented)\n    unsubscribers: any[];\n}\n\n// @public (undocumented)\nexport function realisticDelay({ min, max, }?: {\n    min?: number;\n    max?: number;\n}): MockLink.DelayFunction;\n\n// @public @deprecated (undocumented)\nexport type ResultFunction<T, V = Record<string, any>> = MockLink.ResultFunction<T, V>;\n\n// @public (undocumented)\ntype VariableMatcher<V = Record<string, any>> = CovariantUnaryFunction<V, boolean>;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-testing_internal.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloClient } from '@apollo/client';\nimport { ApolloLink } from '@apollo/client';\nimport { ApolloLink as ApolloLink_2 } from '@apollo/client/link';\nimport type { ApolloPayloadResult } from '@apollo/client';\nimport type { ExecuteContext } from '@apollo/client/link';\nimport { FetchResult } from '@apollo/client';\nimport type { GraphQLFormattedError } from 'graphql-17-alpha2';\nimport type { GraphQLRequest } from '@apollo/client';\nimport { HttpLink } from '@apollo/client/link/http';\nimport type { InitialIncrementalExecutionResult } from 'graphql-17-alpha2';\nimport type { MaskedDocumentNode } from '@apollo/client/masking';\nimport type { MockedProviderProps } from '@apollo/client/testing/react';\nimport type { MockLink } from '@apollo/client/testing';\nimport type { Observable } from 'rxjs';\nimport { Observable as Observable_2 } from '@apollo/client';\nimport { Operation } from '@apollo/client';\nimport type { Queries } from '@testing-library/dom';\nimport type { queries } from '@testing-library/dom';\nimport * as React_2 from 'react';\nimport type * as ReactDOMClient from 'react-dom/client';\nimport type { RenderHookOptions } from '@testing-library/react';\nimport type { RenderHookResult } from '@testing-library/react';\nimport type { RenderOptions } from '@testing-library/react';\nimport type { RenderResult } from '@testing-library/react';\nimport type { Subscribable } from 'rxjs';\nimport type { SubsequentIncrementalExecutionResult } from 'graphql-17-alpha2';\nimport type { TypedDocumentNode } from '@apollo/client';\n\n// @public (undocumented)\nexport function actAsync<T>(scope: () => T | Promise<T>): Promise<T>;\n\n// @public (undocumented)\nexport function addDelayToMocks<T extends MockLink.MockedResponse<unknown>[]>(mocks: T, delay?: number, override?: boolean): {\n    request: MockLink.MockedRequest<Record<string, any>>;\n    maxUsageCount?: number;\n    result?: FetchResult<unknown> | MockLink.ResultFunction<FetchResult<unknown>, Record<string, any>> | undefined;\n    error?: Error;\n    delay: number | MockLink.DelayFunction;\n}[];\n\n// @public (undocumented)\ntype ConsoleMethod = \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n\n// @public (undocumented)\nexport function createClientWrapper(client: ApolloClient, Wrapper?: React_2.JSXElementConstructor<{\n    children: React_2.ReactNode;\n}>): React_2.JSXElementConstructor<{\n    children: React_2.ReactNode;\n}>;\n\n// @public (undocumented)\nexport function createMockWrapper(renderOptions: MockedProviderProps, Wrapper?: React_2.JSXElementConstructor<{\n    children: React_2.ReactNode;\n}>): React_2.JSXElementConstructor<{\n    children: React_2.ReactNode;\n}>;\n\n// @public (undocumented)\nexport function createOperationWithDefaultContext(context: any, operation: GraphQLRequest, executeContext?: ExecuteContext): Operation;\n\n// @public (undocumented)\nexport function enableFakeTimers(config?: FakeTimersConfig | LegacyFakeTimersConfig): Disposable;\n\n// @public (undocumented)\nexport function executeWithDefaultContext(link: ApolloLink_2, operation: GraphQLRequest, context?: ExecuteContext): Observable_2<FetchResult>;\n\n// @public (undocumented)\ntype HydrateableContainer = Parameters<(typeof ReactDOMClient)[\"hydrateRoot\"]>[0];\n\n// @public (undocumented)\ntype HydrateableContainer_2 = Parameters<(typeof ReactDOMClient)[\"hydrateRoot\"]>[0];\n\n// @public (undocumented)\ninterface Letter {\n    // (undocumented)\n    __typename: \"Letter\";\n    // (undocumented)\n    letter: string;\n    // (undocumented)\n    position: number;\n}\n\n// @public (undocumented)\nexport interface MaskedVariablesCaseData {\n    // (undocumented)\n    character: {\n        __typename: \"Character\";\n        id: string;\n    } & {\n        \" $fragmentRefs\"?: {\n            MaskedVariablesCaseFragment: MaskedVariablesCaseFragment;\n        };\n    };\n}\n\n// @public (undocumented)\ntype MaskedVariablesCaseFragment = {\n    __typename: \"Character\";\n    name: string;\n} & {\n    \" $fragmentName\"?: \"MaskedVariablesCaseFragment\";\n};\n\n// @public (undocumented)\nexport function mockDeferStream<TData = Record<string, unknown>, TExtensions = Record<string, unknown>>(): {\n    httpLink: HttpLink;\n    enqueueInitialChunk(chunk: InitialIncrementalExecutionResult<TData, TExtensions>): void;\n    enqueueSubsequentChunk(chunk: SubsequentIncrementalExecutionResult<TData, TExtensions>): void;\n    enqueueErrorChunk(errors: GraphQLFormattedError[]): void;\n};\n\n// @public (undocumented)\nexport function mockMultipartSubscriptionStream<TData = Record<string, unknown>, TExtensions = Record<string, unknown>>(): {\n    httpLink: HttpLink;\n    enqueueHeartbeat: () => void;\n    enqueuePayloadResult(payload: ApolloPayloadResult<TData, TExtensions>[\"payload\"], hasNext?: boolean): void;\n    enqueueProtocolErrors(errors: ApolloPayloadResult[\"errors\"]): void;\n};\n\n// @public (undocumented)\ntype ObservableEvent<T> = {\n    type: \"next\";\n    value: T;\n} | {\n    type: \"error\";\n    error: any;\n} | {\n    type: \"complete\";\n};\n\n// @public (undocumented)\nexport class ObservableStream<T> {\n    // (undocumented)\n    [Symbol.dispose](): void;\n    constructor(observable: Observable<T> | Subscribable<T>);\n    // (undocumented)\n    getCurrent(): T | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"TakeOptions\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"ObservableEvent\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    peek({ timeout }?: TakeOptions): Promise<ObservableEvent<T>>;\n    // (undocumented)\n    take({ timeout }?: TakeOptions): Promise<{\n        type: \"error\";\n        error: any;\n    } | {\n        type: \"complete\";\n    } | {\n        type: \"next\";\n        value: T;\n    }>;\n    // (undocumented)\n    takeComplete(options?: TakeOptions): Promise<void>;\n    // (undocumented)\n    takeError(options?: TakeOptions): Promise<any>;\n    // (undocumented)\n    takeNext(options?: TakeOptions): Promise<T>;\n    // (undocumented)\n    unsubscribe(): void;\n}\n\n// @public (undocumented)\nexport interface PaginatedCaseData {\n    // Warning: (ae-forgotten-export) The symbol \"Letter\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    letters: Letter[];\n}\n\n// @public (undocumented)\nexport interface PaginatedCaseVariables {\n    // (undocumented)\n    limit?: number;\n    // (undocumented)\n    offset?: number;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"RendererableContainer\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"HydrateableContainer\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function renderAsync<Q extends Queries = typeof queries, Container extends RendererableContainer | HydrateableContainer = HTMLElement, BaseElement extends RendererableContainer | HydrateableContainer = Container>(ui: React.ReactNode, options: RenderOptions<Q, Container, BaseElement>): Promise<RenderResult<Q, Container, BaseElement>>;\n\n// @public (undocumented)\nexport function renderAsync(ui: React.ReactNode, options?: Omit<RenderOptions, \"queries\"> | undefined): Promise<RenderResult>;\n\n// @public (undocumented)\ntype RendererableContainer = ReactDOMClient.Container;\n\n// @public (undocumented)\ntype RendererableContainer_2 = ReactDOMClient.Container;\n\n// Warning: (ae-forgotten-export) The symbol \"RendererableContainer_2\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"HydrateableContainer_2\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function renderHookAsync<Result, Props, Q extends Queries = typeof queries, Container extends RendererableContainer_2 | HydrateableContainer_2 = HTMLElement, BaseElement extends RendererableContainer_2 | HydrateableContainer_2 = Container>(renderCallback: (initialProps: Props) => Result, options?: RenderHookOptions<Props, Q, Container, BaseElement> | undefined): Promise<RenderHookResult<Result, Props>>;\n\n// @public\nexport function resetApolloContext(): void;\n\n// @public (undocumented)\nexport function setupMaskedVariablesCase(): {\n    mocks: MockLink.MockedResponse<MaskedVariablesCaseData, Record<string, any>>[];\n    query: MaskedDocumentNode<MaskedVariablesCaseData, VariablesCaseVariables>;\n    unmaskedQuery: TypedDocumentNode<MaskedVariablesCaseData, VariablesCaseVariables>;\n};\n\n// @public (undocumented)\nexport function setupPaginatedCase(): {\n    query: TypedDocumentNode<PaginatedCaseData, PaginatedCaseVariables>;\n    link: ApolloLink;\n    data: {\n        __typename: string;\n        letter: string;\n        position: number;\n    }[];\n};\n\n// @public (undocumented)\nexport function setupSimpleCase(): {\n    query: TypedDocumentNode<SimpleCaseData, Record<string, never>>;\n    mocks: MockLink.MockedResponse<SimpleCaseData, Record<string, any>>[];\n};\n\n// @public (undocumented)\nexport function setupVariablesCase(): {\n    mocks: MockLink.MockedResponse<VariablesCaseData, VariablesCaseVariables>[];\n    query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables>;\n};\n\n// @public (undocumented)\nexport interface SimpleCaseData {\n    // (undocumented)\n    greeting: string;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"ConsoleMethod\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype Spies<Keys extends ConsoleMethod[]> = Record<Keys[number], jest.SpyInstance<void, any[], any>>;\n\n// Warning: (ae-forgotten-export) The symbol \"Spies\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function spyOnConsole<Keys extends ConsoleMethod[]>(...spyOn: Keys): Spies<Keys> & Disposable;\n\n// @public (undocumented)\nexport namespace spyOnConsole {\n    var // (undocumented)\n    takeSnapshots: <Keys extends ConsoleMethod[]>(...spyOn: Keys) => Spies<Keys> & Disposable;\n}\n\n// @public (undocumented)\ninterface TakeOptions {\n    // (undocumented)\n    timeout?: number;\n}\n\n// @public (undocumented)\nexport interface VariablesCaseData {\n    // (undocumented)\n    character: {\n        __typename: \"Character\";\n        id: string;\n        name: string;\n    };\n}\n\n// @public (undocumented)\nexport interface VariablesCaseVariables {\n    // (undocumented)\n    id: string;\n}\n\n// @public (undocumented)\nexport function wait(ms: number): Promise<void>;\n\n// @internal @deprecated (undocumented)\nexport function withCleanup<T extends object>(item: T, cleanup: (item: T) => void): T & Disposable;\n\n// @public (undocumented)\nexport function withProdMode(): {\n    prevDEV: boolean;\n} & Disposable;\n\n// Warnings were encountered during analysis:\n//\n// src/testing/internal/scenarios/index.ts:81:7 - (ae-forgotten-export) The symbol \"MaskedVariablesCaseFragment\" needs to be exported by the entry point index.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-testing_react.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache } from '@apollo/client/cache';\nimport { ApolloClient } from '@apollo/client';\nimport type { ApolloLink } from '@apollo/client/link';\nimport type { LocalState } from '@apollo/client/local-state';\nimport { MockLink } from '@apollo/client/testing';\nimport * as React_2 from 'react';\n\n// Warning: (ae-forgotten-export) The symbol \"MockedProviderState\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport class MockedProvider extends React_2.Component<MockedProviderProps, MockedProviderState> {\n    constructor(props: MockedProviderProps);\n    // (undocumented)\n    componentWillUnmount(): void;\n    // (undocumented)\n    render(): React_2.JSX.Element | null;\n}\n\n// @public (undocumented)\nexport interface MockedProviderProps {\n    // (undocumented)\n    cache?: ApolloCache;\n    // (undocumented)\n    childProps?: object;\n    // (undocumented)\n    children?: any;\n    // (undocumented)\n    defaultOptions?: ApolloClient.DefaultOptions;\n    devtools?: ApolloClient.Options[\"devtools\"];\n    // (undocumented)\n    link?: ApolloLink;\n    // (undocumented)\n    localState?: LocalState;\n    // (undocumented)\n    mockLinkDefaultOptions?: MockLink.DefaultOptions;\n    // (undocumented)\n    mocks?: ReadonlyArray<MockLink.MockedResponse<any, any>>;\n    // (undocumented)\n    showWarnings?: boolean;\n}\n\n// @public (undocumented)\ninterface MockedProviderState {\n    // (undocumented)\n    client: ApolloClient;\n}\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ASTNode } from 'graphql';\nimport { canonicalStringify } from '@apollo/client/utilities/internal';\nimport { DeepOmit } from '@apollo/client/utilities/internal';\nimport type { DocumentNode } from 'graphql';\nimport type { DocumentNode as DocumentNode_2 } from '@apollo/client';\nimport type { FieldNode } from 'graphql';\nimport type { FieldPolicy } from '@apollo/client/cache';\nimport type { FormattedExecutionResult } from 'graphql';\nimport { getMainDefinition } from '@apollo/client/utilities/internal';\nimport type { NetworkStatus } from '@apollo/client';\nimport { Observable } from 'rxjs';\nimport type { Primitive } from '@apollo/client/utilities/internal';\nimport type { Reference as Reference_2 } from '@apollo/client/cache';\n\n// @public\nexport const addTypenameToDocument: (<TNode extends ASTNode>(doc: TNode) => TNode) & {\n    added(field: FieldNode): boolean;\n};\n\n// @public\nexport type AsStoreObject<T extends {\n    __typename?: string;\n}> = {\n    [K in keyof T]: T[K];\n};\n\n// @public\nexport interface CacheSizes {\n    \"cache.fragmentQueryDocuments\": number;\n    \"documentTransform.cache\": number;\n    \"fragmentRegistry.findFragmentSpreads\": number;\n    \"fragmentRegistry.lookup\": number;\n    \"fragmentRegistry.transform\": number;\n    \"inMemoryCache.executeSelectionSet\": number;\n    \"inMemoryCache.executeSubSelectedArray\": number;\n    \"inMemoryCache.maybeBroadcastWatch\": number;\n    \"PersistedQueryLink.persistedQueryHashes\": number;\n    \"queryManager.getDocumentInfo\": number;\n    \"removeTypenameFromVariables.getVariableDefinitions\": number;\n    canonicalStringify: number;\n    checkDocument: number;\n    print: number;\n}\n\n// @public\nexport const cacheSizes: Partial<CacheSizes>;\n\nexport { canonicalStringify }\n\n// Warning: (ae-forgotten-export) The symbol \"KeyArgs\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport function concatPagination<T = Reference_2>(keyArgs?: KeyArgs): FieldPolicy<T[]>;\n\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialPrimitive\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialMap\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialReadonlyMap\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialSet\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialReadonlySet\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialObject\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport type DeepPartial<T> = T extends DeepPartialPrimitive ? T : T extends Map<infer TKey, infer TValue> ? DeepPartialMap<TKey, TValue> : T extends ReadonlyMap<infer TKey, infer TValue> ? DeepPartialReadonlyMap<TKey, TValue> : T extends Set<infer TItem> ? DeepPartialSet<TItem> : T extends ReadonlySet<infer TItem> ? DeepPartialReadonlySet<TItem> : T extends (...args: any[]) => unknown ? T | undefined : T extends object ? T extends (ReadonlyArray<infer TItem>) ? TItem[] extends (T) ? readonly TItem[] extends T ? ReadonlyArray<DeepPartial<TItem>> : Array<DeepPartial<TItem>> : DeepPartialObject<T> : DeepPartialObject<T> : unknown;\n\n// @public (undocumented)\ntype DeepPartialMap<TKey, TValue> = {} & Map<DeepPartial<TKey>, DeepPartial<TValue>>;\n\n// @public (undocumented)\ntype DeepPartialObject<T extends object> = {\n    [K in keyof T]?: DeepPartial<T[K]>;\n};\n\n// @public (undocumented)\ntype DeepPartialPrimitive = Primitive | Date | RegExp;\n\n// @public (undocumented)\ntype DeepPartialReadonlyMap<TKey, TValue> = {} & ReadonlyMap<DeepPartial<TKey>, DeepPartial<TValue>>;\n\n// @public (undocumented)\ntype DeepPartialReadonlySet<T> = {} & ReadonlySet<DeepPartial<T>>;\n\n// @public (undocumented)\ntype DeepPartialSet<T> = {} & Set<DeepPartial<T>>;\n\n// @public\nexport class DocumentTransform {\n    // Warning: (ae-forgotten-export) The symbol \"TransformFn\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"DocumentTransformOptions\" needs to be exported by the entry point index.d.ts\n    constructor(transform: TransformFn, options?: DocumentTransformOptions);\n    concat(otherTransform: DocumentTransform): DocumentTransform;\n    static identity(): DocumentTransform;\n    // @internal @deprecated\n    readonly left?: DocumentTransform;\n    resetCache(): void;\n    // @internal @deprecated\n    readonly right?: DocumentTransform;\n    static split(predicate: (document: DocumentNode) => boolean, left: DocumentTransform, right?: DocumentTransform): DocumentTransform & {\n        left: DocumentTransform;\n        right: DocumentTransform;\n    };\n    transformDocument(document: DocumentNode): DocumentNode;\n}\n\n// @public (undocumented)\nexport type DocumentTransformCacheKey = ReadonlyArray<unknown>;\n\n// @public (undocumented)\ninterface DocumentTransformOptions {\n    cache?: boolean;\n    getCacheKey?: (document: DocumentNode) => DocumentTransformCacheKey | undefined;\n}\n\nexport { getMainDefinition }\n\n// @beta\nexport interface HKT {\n    // (undocumented)\n    arg1: unknown;\n    // (undocumented)\n    arg2: unknown;\n    // (undocumented)\n    arg3: unknown;\n    // (undocumented)\n    arg4: unknown;\n    // (undocumented)\n    return: unknown;\n}\n\n// @public\nexport function isFormattedExecutionResult(result?: object): result is FormattedExecutionResult;\n\n// @public\nexport function isMutationOperation(document: DocumentNode_2): boolean;\n\n// @public\nexport function isNetworkRequestInFlight(networkStatus?: NetworkStatus): boolean;\n\n// @public\nexport function isNetworkRequestSettled(networkStatus?: NetworkStatus): boolean;\n\n// @public\nexport function isQueryOperation(document: DocumentNode_2): boolean;\n\n// @public\nexport function isReference(obj: any): obj is Reference;\n\n// @public\nexport function isSubscriptionOperation(document: DocumentNode_2): boolean;\n\n// @public (undocumented)\ntype KeyArgs = FieldPolicy<any>[\"keyArgs\"];\n\nexport { Observable }\n\n// @public\nexport function offsetLimitPagination<T = Reference_2>(keyArgs?: KeyArgs): FieldPolicy<T[]>;\n\n// @public\nconst print_2: ((ast: ASTNode) => string) & {\n    reset(): void;\n};\nexport { print_2 as print }\n\n// @public\nexport interface Reference {\n    // (undocumented)\n    readonly __ref: string;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"TExistingRelay\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"TIncomingRelay\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype RelayFieldPolicy<TNode> = FieldPolicy<TExistingRelay<TNode> | null, TIncomingRelay<TNode> | null, TIncomingRelay<TNode> | null>;\n\n// Warning: (ae-forgotten-export) The symbol \"RelayFieldPolicy\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport function relayStylePagination<TNode extends Reference_2 = Reference_2>(keyArgs?: KeyArgs): RelayFieldPolicy<TNode>;\n\n// @public\nexport interface StoreObject {\n    // (undocumented)\n    [storeFieldName: string]: StoreValue;\n    // (undocumented)\n    __typename?: string;\n}\n\n// @public\nexport type StoreValue = number | string | string[] | Reference | Reference[] | null | undefined | void | Object;\n\n// @public\nexport function stripTypename<T>(value: T): DeepOmit<T, \"__typename\">;\n\n// @public (undocumented)\ntype TExistingRelay<TNode> = Readonly<{\n    edges: TRelayEdge<TNode>[];\n    pageInfo: TRelayPageInfo;\n}>;\n\n// @public (undocumented)\ntype TIncomingRelay<TNode> = {\n    edges?: TRelayEdge<TNode>[];\n    pageInfo?: TRelayPageInfo;\n};\n\n// @public (undocumented)\ntype TransformFn = (document: DocumentNode) => DocumentNode;\n\n// @public (undocumented)\ntype TRelayEdge<TNode> = {\n    cursor?: string;\n    node: TNode;\n} | (Reference_2 & {\n    cursor?: string;\n});\n\n// @public (undocumented)\ntype TRelayPageInfo = {\n    hasPreviousPage: boolean;\n    hasNextPage: boolean;\n    startCursor: string;\n    endCursor: string;\n};\n\n// Warnings were encountered during analysis:\n//\n// src/utilities/policies/pagination.ts:86:3 - (ae-forgotten-export) The symbol \"TRelayEdge\" needs to be exported by the entry point index.d.ts\n// src/utilities/policies/pagination.ts:87:3 - (ae-forgotten-export) The symbol \"TRelayPageInfo\" needs to be exported by the entry point index.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_environment.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public (undocumented)\nexport const __DEV__: boolean;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_internal.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ApolloCache } from '@apollo/client';\nimport type { ApolloClient } from '@apollo/client';\nimport type { ASTNode } from 'graphql';\nimport type { DataValue } from '@apollo/client';\nimport type { DirectiveNode } from 'graphql';\nimport type { DocumentNode } from 'graphql';\nimport type { ErrorLike } from '@apollo/client';\nimport type { FieldNode } from 'graphql';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { FragmentDefinitionNode } from 'graphql';\nimport type { GraphQLFormattedError } from 'graphql';\nimport type { HKT } from '@apollo/client/utilities';\nimport type { Incremental } from '@apollo/client/incremental';\nimport type { InlineFragmentNode } from 'graphql';\nimport type { MaybeMasked } from '@apollo/client';\nimport type { NetworkStatus } from '@apollo/client';\nimport { Observable } from 'rxjs';\nimport type { ObservableQuery } from '@apollo/client';\nimport type { Observer } from 'rxjs';\nimport type { OperationDefinitionNode } from 'graphql';\nimport type { OperationTypeNode } from 'graphql';\nimport type { OperationVariables } from '@apollo/client';\nimport type { OperatorFunction } from 'rxjs';\nimport type { Reference } from '@apollo/client/utilities';\nimport type { SelectionNode } from 'graphql';\nimport type { SelectionSetNode } from 'graphql';\nimport { StrongCache } from '@wry/caches';\nimport type { Subscription } from 'rxjs';\nimport type { Trie } from '@wry/trie';\nimport { WeakCache } from '@wry/caches';\n\n// @internal @deprecated (undocumented)\nexport type ApplyHKT<fn extends HKT, arg1, arg2 = never, arg3 = never, arg4 = never> = (fn & {\n    arg1: arg1;\n    arg2: arg2;\n    arg3: arg3;\n    arg4: arg4;\n})[\"return\"];\n\n// @internal @deprecated (undocumented)\nexport type ApplyHKTImplementationWithDefault<Implementation, Name extends string, DefaultImplementation extends Record<Name, HKT>, arg1, arg2 = never, arg3 = never, arg4 = never> = ApplyHKT<Implementation extends {\n    [name in Name]: infer Implementation extends HKT;\n} ? Implementation : DefaultImplementation[Name], arg1, arg2, arg3, arg4>;\n\n// @internal @deprecated (undocumented)\nexport function argumentsObjectFromField(field: FieldNode | DirectiveNode, variables?: Record<string, any>): Object | null;\n\n// @internal @deprecated\nexport const AutoCleanedStrongCache: typeof StrongCache;\n\n// @internal @deprecated (undocumented)\nexport type AutoCleanedStrongCache<K, V> = StrongCache<K, V>;\n\n// @internal @deprecated\nexport const AutoCleanedWeakCache: typeof WeakCache;\n\n// @internal @deprecated (undocumented)\nexport type AutoCleanedWeakCache<K extends object, V> = WeakCache<K, V>;\n\n// @public\nexport function bindCacheKey(...prebound: object[]): (...args: any) => object;\n\n// @public\nexport const canonicalStringify: ((value: any) => string) & {\n    reset(): void;\n};\n\n// @internal @deprecated (undocumented)\nexport const canUseDOM: boolean;\n\n// @internal @deprecated\nexport const checkDocument: (doc: DocumentNode, expectedType?: OperationTypeNode) => void;\n\n// @internal @deprecated\nexport function cloneDeep<T>(value: T): T;\n\n// @public\nexport function combineLatestBatched<T>(observables: Array<Observable<T> & {\n    dirty?: boolean;\n}>): Observable<T[]>;\n\n// Warning: (ae-forgotten-export) The symbol \"TupleToIntersection\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated\nexport function compact<TArgs extends any[]>(...objects: TArgs): TupleToIntersection<TArgs>;\n\n// @internal @deprecated\nexport function createFragmentMap(fragments?: FragmentDefinitionNode[]): FragmentMap;\n\n// @internal @deprecated (undocumented)\nexport function createFulfilledPromise<TValue>(value: TValue): FulfilledPromise<TValue>;\n\n// @internal @deprecated (undocumented)\nexport function createRejectedPromise<TValue = unknown>(reason: unknown): RejectedPromise<TValue>;\n\n// @public (undocumented)\nexport function dealias(fieldValue: Record<string, any> | null | undefined, selectionSet: SelectionSetNode): {\n    [x: string]: any;\n} | null | undefined;\n\n// @internal @deprecated (undocumented)\nexport type DecoratedPromise<TValue> = PendingPromise<TValue> | FulfilledPromise<TValue> | RejectedPromise<TValue>;\n\n// @internal @deprecated (undocumented)\nexport function decoratePromise<TValue>(promise: Promise<TValue>): DecoratedPromise<TValue>;\n\n// @internal @deprecated (undocumented)\nexport namespace DeepMerger {\n    // (undocumented)\n    export type ArrayMergeStrategy = \"truncate\" | \"combine\";\n    // (undocumented)\n    export interface MergeOptions {\n        // (undocumented)\n        atPath?: ReadonlyArray<string | number>;\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        arrayMerge?: DeepMerger.ArrayMergeStrategy;\n        // Warning: (ae-forgotten-export) The symbol \"ReconcilerFunction\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        reconciler?: ReconcilerFunction;\n    }\n}\n\n// @internal @deprecated (undocumented)\nexport class DeepMerger {\n    constructor(options?: DeepMerger.Options);\n    // (undocumented)\n    isObject: typeof isNonNullObject;\n    // (undocumented)\n    merge(target: any, source: any, mergeOptions?: DeepMerger.MergeOptions): any;\n    // (undocumented)\n    shallowCopyForMerge<T>(value: T): T;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"DeepOmitPrimitive\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepOmitArray\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\nexport type DeepOmit<T, K> = T extends DeepOmitPrimitive ? T : {\n    [P in keyof T as P extends K ? never : P]: T[P] extends infer TP ? TP extends DeepOmitPrimitive ? TP : TP extends any[] ? DeepOmitArray<TP, K> : DeepOmit<TP, K> : never;\n};\n\n// Warning: (ae-incompatible-release-tags) The symbol \"DeepOmitArray\" is marked as @public, but its signature references \"DeepOmit\" which is marked as @internal\n//\n// @public (undocumented)\ntype DeepOmitArray<T extends any[], K> = {\n    [P in keyof T]: DeepOmit<T[P], K>;\n};\n\n// Warning: (ae-incompatible-release-tags) The symbol \"DeepOmitPrimitive\" is marked as @public, but its signature references \"Primitive\" which is marked as @internal\n//\n// @public (undocumented)\ntype DeepOmitPrimitive = Primitive | Function;\n\n// @public (undocumented)\ntype Directives = {\n    [directiveName: string]: {\n        [argName: string]: any;\n    };\n};\n\n// @public\nexport namespace DocumentationTypes {\n    // (undocumented)\n    export interface ApolloQueryResult<TData> extends DataState<TData> {\n        error?: ErrorLike;\n        loading: boolean;\n        networkStatus: NetworkStatus;\n        // @deprecated\n        partial: boolean;\n    }\n    // (undocumented)\n    export interface DataState<TData> {\n        data?: DataValue.Complete<TData> | DataValue.Streaming<TData> | DataValue.Partial<TData> | undefined;\n        dataState: \"complete\" | \"streaming\" | \"partial\" | \"empty\";\n    }\n    // (undocumented)\n    export interface RxjsObservable<TData> {\n        // (undocumented)\n        pipe<OperatorResult>(...operators: [\n        OperatorFunction<Observable<ApolloQueryResult<TData>>, OperatorResult>\n        ] | [\n        OperatorFunction<Observable<ApolloQueryResult<TData>>, unknown>,\n        ...OperatorFunction<unknown, unknown>[],\n        OperatorFunction<unknown, OperatorResult>\n        ]): Observable<OperatorResult>;\n        // (undocumented)\n        subscribe(observer: Partial<Observer<ApolloQueryResult<MaybeMasked<TData>>>> | ((value: ApolloQueryResult<MaybeMasked<TData>>) => void)): Subscription;\n    }\n    // (undocumented)\n    export interface VariableOptions<TVariables extends OperationVariables> {\n        variables?: TVariables;\n    }\n}\n\n// @public (undocumented)\nexport function equalByQuery(query: DocumentNode, { data: aData, ...aRest }: Partial<ObservableQuery.Result<unknown>>, { data: bData, ...bRest }: Partial<ObservableQuery.Result<unknown>>, variables?: OperationVariables): boolean;\n\n// @internal @deprecated\nexport const extensionsSymbol: unique symbol;\n\n// @public\nexport interface ExtensionsWithStreamInfo extends Record<string, unknown> {\n    // (undocumented)\n    [streamInfoSymbol]?: {\n        deref(): StreamInfoTrie | undefined;\n    };\n}\n\n// @public (undocumented)\nexport function filterMap<T, R>(fn: (value: T, context: undefined) => R | undefined): OperatorFunction<T, R>;\n\n// @public (undocumented)\nexport function filterMap<T, R, Context>(fn: (value: T, context: Context) => R | undefined, makeContext: () => NoInfer<Context>): OperatorFunction<T, R>;\n\n// @internal @deprecated\nexport interface FragmentMap {\n    // (undocumented)\n    [fragmentName: string]: FragmentDefinitionNode;\n}\n\n// @internal @deprecated (undocumented)\nexport type FragmentMapFunction = (fragmentName: string) => FragmentDefinitionNode | null;\n\n// @internal @deprecated (undocumented)\nexport interface FulfilledPromise<TValue> extends Promise<TValue> {\n    // (undocumented)\n    status: \"fulfilled\";\n    // (undocumented)\n    value: TValue;\n}\n\n// @internal @deprecated\nexport const getApolloCacheMemoryInternals: (() => {\n    cache: {\n        fragmentQueryDocuments: number | undefined;\n    };\n}) | undefined;\n\n// @internal @deprecated\nexport const getApolloClientMemoryInternals: (() => {\n    limits: {\n        [k: string]: number;\n    };\n    sizes: {\n        cache?: {\n            fragmentQueryDocuments: number | undefined;\n        } | undefined;\n        addTypenameDocumentTransform?: {\n            cache: number;\n        }[] | undefined;\n        inMemoryCache?: {\n            executeSelectionSet: number | undefined;\n            executeSubSelectedArray: number | undefined;\n            maybeBroadcastWatch: number | undefined;\n        } | undefined;\n        fragmentRegistry?: {\n            findFragmentSpreads: number | undefined;\n            lookup: number | undefined;\n            transform: number | undefined;\n        } | undefined;\n        print: number | undefined;\n        canonicalStringify: number | undefined;\n        links: unknown[];\n        queryManager: {\n            getDocumentInfo: number;\n            documentTransforms: {\n                cache: number;\n            }[];\n        };\n    };\n}) | undefined;\n\n// @internal @deprecated (undocumented)\nexport function getDefaultValues(definition: OperationDefinitionNode | undefined): Record<string, any>;\n\n// @internal @deprecated (undocumented)\nexport function getFragmentDefinition(doc: DocumentNode): FragmentDefinitionNode;\n\n// @internal @deprecated (undocumented)\nexport function getFragmentDefinitions(doc: DocumentNode): FragmentDefinitionNode[];\n\n// @internal @deprecated (undocumented)\nexport function getFragmentFromSelection(selection: SelectionNode, fragmentMap?: FragmentMap | FragmentMapFunction): InlineFragmentNode | FragmentDefinitionNode | null;\n\n// @internal @deprecated\nexport function getFragmentQueryDocument(document: DocumentNode, fragmentName?: string): DocumentNode;\n\n// @internal @deprecated (undocumented)\nexport function getGraphQLErrorsFromResult(result: {\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n}): Array<GraphQLFormattedError>;\n\n// @internal @deprecated\nexport const getInMemoryCacheMemoryInternals: (() => {\n    addTypenameDocumentTransform: {\n        cache: number;\n    }[];\n    inMemoryCache: {\n        executeSelectionSet: number | undefined;\n        executeSubSelectedArray: number | undefined;\n        maybeBroadcastWatch: number | undefined;\n    };\n    fragmentRegistry: {\n        findFragmentSpreads: number | undefined;\n        lookup: number | undefined;\n        transform: number | undefined;\n    };\n    cache: {\n        fragmentQueryDocuments: number | undefined;\n    };\n}) | undefined;\n\n// @public\nexport function getMainDefinition(queryDoc: DocumentNode): OperationDefinitionNode | FragmentDefinitionNode;\n\n// @internal @deprecated (undocumented)\nexport function getOperationDefinition(doc: DocumentNode): OperationDefinitionNode | undefined;\n\n// @internal @deprecated (undocumented)\nexport function getOperationName<TFallback extends string | null | undefined = undefined>(doc: DocumentNode, fallback?: TFallback): string | TFallback;\n\n// @internal @deprecated (undocumented)\nexport function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode;\n\n// Warning: (ae-forgotten-export) The symbol \"Directives\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\nexport const getStoreKeyName: ((fieldName: string, args?: Record<string, any> | null, directives?: Directives) => string) & {\n    setStringify(s: typeof storeKeyNameStringify): (value: any) => string;\n};\n\n// @public (undocumented)\nconst globalCaches: {\n    print?: () => number;\n    canonicalStringify?: () => number;\n};\n\n// @internal @deprecated (undocumented)\nexport function graphQLResultHasError(result: FormattedExecutionResult<any>): boolean;\n\n// @internal @deprecated (undocumented)\nexport function hasDirectives(names: string[], root: ASTNode, all?: boolean): boolean;\n\n// @public (undocumented)\nexport function hasForcedResolvers(document: ASTNode): boolean;\n\n// @internal @deprecated (undocumented)\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n\n// @internal @deprecated\nexport const isArray: (a: any) => a is any[] | readonly any[];\n\n// @internal @deprecated (undocumented)\nexport function isDocumentNode(value: unknown): value is DocumentNode;\n\n// @internal @deprecated (undocumented)\nexport function isField(selection: SelectionNode): selection is FieldNode;\n\n// @internal @deprecated (undocumented)\nexport function isNonEmptyArray<T>(value: ArrayLike<T> | null | undefined): value is Array<T>;\n\n// @internal @deprecated (undocumented)\nexport function isNonNullObject(obj: unknown): obj is Record<string | number, any>;\n\n// @internal @deprecated (undocumented)\nexport function isPlainObject(obj: unknown): obj is Record<string | number, any>;\n\n// @internal @deprecated (undocumented)\nexport function makeReference(id: string): Reference;\n\n// @internal @deprecated\nexport function makeUniqueId(prefix: string): string;\n\n// @public (undocumented)\nexport const mapObservableFragmentMemoized: <From, To>(observable: ApolloCache.ObservableFragment<From>, _cacheKey: symbol, mapFn: (from: ApolloCache.WatchFragmentResult<From>) => ApolloCache.WatchFragmentResult<To>) => ApolloCache.ObservableFragment<To>;\n\n// @internal @deprecated (undocumented)\nexport function maybeDeepFreeze<T>(obj: T): T;\n\n// @internal @deprecated (undocumented)\nexport function mergeDeep<T extends any[]>(...sources: T): TupleToIntersection<T>;\n\n// @internal @deprecated (undocumented)\nexport function mergeDeepArray<T>(sources: T[]): T;\n\n// Warning: (ae-forgotten-export) The symbol \"OptionsUnion\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\nexport function mergeOptions<TDefaultOptions extends Partial<OptionsUnion<any, any>>, TOptions extends TDefaultOptions>(defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined, options: TOptions | Partial<TOptions>): TOptions & TDefaultOptions;\n\n// @public @deprecated\ntype NoInfer_2<T> = [T][T extends any ? 0 : never];\nexport { NoInfer_2 as NoInfer }\n\n// @internal @deprecated (undocumented)\nexport function omitDeep<T, K extends string>(value: T, key: K): DeepOmit<T, K>;\n\n// @public (undocumented)\ntype OptionsUnion<TData, TVariables extends OperationVariables> = ApolloClient.WatchQueryOptions<TData, TVariables> | ApolloClient.QueryOptions<TData, TVariables> | ApolloClient.MutateOptions<TData, TVariables, any>;\n\n// @internal @deprecated (undocumented)\nexport interface PendingPromise<TValue> extends Promise<TValue> {\n    // (undocumented)\n    status: \"pending\";\n}\n\n// @internal @deprecated (undocumented)\nexport type Prettify<T> = {\n    [K in keyof T]: T[K];\n} & {};\n\n// @public (undocumented)\nexport function preventUnhandledRejection<T>(promise: Promise<T>): Promise<T>;\n\n// @internal @deprecated (undocumented)\nexport type Primitive = null | undefined | string | number | boolean | symbol | bigint;\n\n// Warning: (ae-incompatible-release-tags) The symbol \"ReconcilerFunction\" is marked as @public, but its signature references \"DeepMerger\" which is marked as @internal\n//\n// @public (undocumented)\ntype ReconcilerFunction = (this: DeepMerger, target: Record<string | number, any>, source: Record<string | number, any>, property: string | number) => any;\n\n// Warning: (ae-forgotten-export) The symbol \"globalCaches\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function registerGlobalCache(name: keyof typeof globalCaches, getSize: () => number): void;\n\n// @internal @deprecated (undocumented)\nexport interface RejectedPromise<TValue> extends Promise<TValue> {\n    // (undocumented)\n    reason: unknown;\n    // (undocumented)\n    status: \"rejected\";\n}\n\n// @public (undocumented)\ntype RemoveDirectiveConfig = {\n    name?: string;\n    test?: (node: DirectiveNode) => boolean;\n    remove?: boolean;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"RemoveDirectiveConfig\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\nexport function removeDirectivesFromDocument(directives: RemoveDirectiveConfig[], doc: DocumentNode): DocumentNode | null;\n\n// @internal @deprecated (undocumented)\nexport type RemoveIndexSignature<T> = {\n    [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K];\n};\n\n// @public (undocumented)\nexport function removeMaskedFragmentSpreads(document: DocumentNode): DocumentNode;\n\n// @internal @deprecated (undocumented)\nexport function resultKeyNameFromField(field: FieldNode): string;\n\n// @internal @deprecated (undocumented)\nexport function shouldInclude({ directives }: SelectionNode, variables?: Record<string, any>): boolean;\n\n// @internal @deprecated (undocumented)\nexport function storeKeyNameFromField(field: FieldNode, variables?: Object): string;\n\n// @public (undocumented)\nlet storeKeyNameStringify: (value: any) => string;\n\n// @public\nexport const streamInfoSymbol: unique symbol;\n\n// @internal @deprecated (undocumented)\nexport type StreamInfoTrie = Trie<{\n    current: Incremental.StreamFieldInfo;\n    previous?: {\n        incoming: unknown;\n        streamFieldInfo: Incremental.StreamFieldInfo;\n        result: unknown;\n    };\n}>;\n\n// @internal @deprecated (undocumented)\nexport function stringifyForDisplay(value: any, space?: number): string;\n\n// @internal @deprecated (undocumented)\nexport function toQueryResult<TData = unknown>(value: ObservableQuery.Result<TData>): ApolloClient.QueryResult<TData>;\n\n// @public (undocumented)\ntype TupleToIntersection<T extends any[]> = T extends [infer A] ? A : T extends [infer A, infer B] ? A & B : T extends [infer A, infer B, infer C] ? A & B & C : T extends [infer A, infer B, infer C, infer D] ? A & B & C & D : T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E : T extends (infer U)[] ? U : any;\n\n// @internal @deprecated (undocumented)\nexport type VariablesOption<TVariables extends OperationVariables> = {} extends TVariables ? {\n    variables?: TVariables;\n} : {\n    variables: TVariables;\n};\n\n// @internal @deprecated\nexport const variablesUnknownSymbol: unique symbol;\n\n// Warnings were encountered during analysis:\n//\n// src/utilities/internal/getStoreKeyName.ts:89:1 - (ae-forgotten-export) The symbol \"storeKeyNameStringify\" needs to be exported by the entry point index.d.ts\n// src/utilities/internal/types/ExtensionsWithStreamDetails.ts:11:5 - (ae-incompatible-release-tags) The symbol \"deref\" is marked as @public, but its signature references \"StreamInfoTrie\" which is marked as @internal\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_internal_globals.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public (undocumented)\nconst global_2: typeof globalThis & Window;\nexport { global_2 as global }\n\n// @public (undocumented)\nexport function maybe<T>(thunk: () => T): T | undefined;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_internal_ponyfills.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public (undocumented)\nconst FinalizationRegistry_2: FinalizationRegistryConstructor;\nexport { FinalizationRegistry_2 as FinalizationRegistry }\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_invariant.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public (undocumented)\nexport const ApolloErrorMessageHandler: unique symbol;\n\n// @public (undocumented)\nexport function invariant(condition: any, ...args: [message?: string | number, ...any[]]): asserts condition;\n\n// @public (undocumented)\nexport namespace invariant {\n    var // (undocumented)\n    debug: {\n        (...data: any[]): void;\n        (message?: any, ...optionalParams: any[]): void;\n    };\n    var // (undocumented)\n    log: {\n        (...data: any[]): void;\n        (message?: any, ...optionalParams: any[]): void;\n    };\n    var // (undocumented)\n    warn: {\n        (...data: any[]): void;\n        (message?: any, ...optionalParams: any[]): void;\n    };\n    var // (undocumented)\n    error: {\n        (...data: any[]): void;\n        (message?: any, ...optionalParams: any[]): void;\n    };\n}\n\n// @public (undocumented)\nexport class InvariantError extends Error {\n    constructor(message?: string);\n}\n\n// @public\nexport function newInvariantError(message?: string | number, ...optionalParams: unknown[]): InvariantError;\n\n// Warning: (ae-forgotten-export) The symbol \"VerbosityLevel\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function setVerbosity(level: VerbosityLevel): VerbosityLevel;\n\n// Warning: (ae-forgotten-export) The symbol \"verbosityLevels\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype VerbosityLevel = (typeof verbosityLevels)[number];\n\n// @public (undocumented)\nconst verbosityLevels: readonly [\"debug\", \"log\", \"warn\", \"error\", \"silent\"];\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-utilities_subscriptions_relay.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { GraphQLResponse } from 'relay-runtime';\nimport { Observable } from 'relay-runtime';\nimport type { OperationVariables } from '@apollo/client';\nimport type { RequestParameters } from 'relay-runtime';\n\n// Warning: (ae-forgotten-export) The symbol \"CreateMultipartSubscriptionOptions\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function createFetchMultipartSubscription(uri: string, { fetch: preferredFetch, headers }?: CreateMultipartSubscriptionOptions): (operation: RequestParameters, variables: OperationVariables) => Observable<GraphQLResponse>;\n\n// @public (undocumented)\ntype CreateMultipartSubscriptionOptions = {\n    fetch?: WindowOrWorkerGlobalScope[\"fetch\"];\n    headers?: Record<string, string>;\n};\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-v4-migration.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public @deprecated (undocumented)\nexport const addNonReactiveToNamedFragments: never;\n\n// @public @deprecated (undocumented)\nexport const ApolloConsumer: never;\n\n// @public @deprecated (undocumented)\nexport type ApolloConsumerProps = never;\n\n// @public @deprecated (undocumented)\nexport class ApolloError {\n}\n\n// @public @deprecated (undocumented)\nexport type ApolloErrorOptions = never;\n\n// @public @deprecated (undocumented)\nexport const asyncMap: never;\n\n// @public @deprecated (undocumented)\nexport type BaseMutationOptions = never;\n\n// @public @deprecated (undocumented)\nexport type BaseQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport type BatchableRequest = never;\n\n// @public @deprecated (undocumented)\nexport const buildQueryFromSelectionSet: never;\n\n// @public @deprecated (undocumented)\nexport const canUseAsyncIteratorSymbol: never;\n\n// @public @deprecated (undocumented)\nexport const canUseLayoutEffect: never;\n\n// @public @deprecated (undocumented)\nexport const canUseSymbol: never;\n\n// @public @deprecated (undocumented)\nexport const canUseWeakMap: never;\n\n// @public @deprecated (undocumented)\nexport const canUseWeakSet: never;\n\n// @public @deprecated (undocumented)\nexport type ChildDataProps = never;\n\n// @public @deprecated (undocumented)\nexport type ChildMutateProps = never;\n\n// @public @deprecated (undocumented)\nexport type ChildProps = never;\n\n// @public @deprecated (undocumented)\nexport type ClientParseError = never;\n\n// @public @deprecated (undocumented)\nexport type CommonOptions = never;\n\n// @public @deprecated (undocumented)\nexport class Concast {\n}\n\n// @public @deprecated (undocumented)\nexport type ConcastSourcesArray = never;\n\n// @public @deprecated (undocumented)\nexport type ConcastSourcesIterable = never;\n\n// @public @deprecated (undocumented)\nexport const createMockClient: never;\n\n// @public @deprecated (undocumented)\nexport const createSchemaFetch: never;\n\n// @public @deprecated (undocumented)\nexport const createTestSchema: never;\n\n// @public @deprecated (undocumented)\nexport type DataProps = never;\n\n// @public @deprecated (undocumented)\nexport const DataProxy: never;\n\n// @public @deprecated (undocumented)\nexport type DataValue = never;\n\n// @public @deprecated (undocumented)\nexport const defaultCacheSizes: never;\n\n// @public @deprecated (undocumented)\nexport type DirectiveInfo = never;\n\n// @public @deprecated (undocumented)\nexport type Directives = never;\n\n// @public @deprecated (undocumented)\nconst DocumentType_2: never;\nexport { DocumentType_2 as DocumentType }\n\n// @public @deprecated (undocumented)\nexport type FetchMoreQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport const fixObservableSubclass: never;\n\n// @public @deprecated (undocumented)\nexport type FragmentMatcher = never;\n\n// @public @deprecated (undocumented)\nexport const fromError: never;\n\n// @public @deprecated (undocumented)\nexport const fromPromise: never;\n\n// @public @deprecated (undocumented)\nexport type GetDirectiveConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getDirectiveNames: never;\n\n// @public @deprecated (undocumented)\nexport const getFragmentMaskMode: never;\n\n// @public @deprecated (undocumented)\nexport type GetFragmentSpreadConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getInclusionDirectives: never;\n\n// @public @deprecated (undocumented)\nexport type GetNodeConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getTypenameFromResult: never;\n\n// @public @deprecated (undocumented)\nexport const graphql: never;\n\n// @public @deprecated (undocumented)\nexport type GraphQLErrors = never;\n\n// @public @deprecated (undocumented)\nexport const hasAllDirectives: never;\n\n// @public @deprecated (undocumented)\nexport const hasAnyDirectives: never;\n\n// @public @deprecated (undocumented)\nexport const hasClientExports: never;\n\n// @public @deprecated (undocumented)\nexport type IDocumentDefinition = never;\n\n// @public @deprecated (undocumented)\nexport type InclusionDirectives = never;\n\n// @public @deprecated (undocumented)\nexport const isApolloError: never;\n\n// @public @deprecated (undocumented)\nexport const isApolloPayloadResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchIncrementalResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchInitialResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchResult: never;\n\n// @public @deprecated (undocumented)\nexport const isFullyUnmaskedOperation: never;\n\n// @public @deprecated (undocumented)\nexport const isInlineFragment: never;\n\n// @public @deprecated (undocumented)\nexport const isStatefulPromise: never;\n\n// @public @deprecated (undocumented)\nexport type IsStrictlyAny = never;\n\n// @public @deprecated (undocumented)\nexport const itAsync: never;\n\n// @public @deprecated (undocumented)\nexport const iterateObserversSafely: never;\n\n// @public @deprecated (undocumented)\nexport type Masked = never;\n\n// @public @deprecated (undocumented)\nexport type MaskedDocumentNode = never;\n\n// @public @deprecated (undocumented)\nexport const mergeIncrementalData: never;\n\n// @public @deprecated (undocumented)\nexport type MethodKeys = never;\n\n// @public @deprecated (undocumented)\nexport const mockObservableLink: never;\n\n// @public @deprecated (undocumented)\nexport const mockSingleLink: never;\n\n// @public @deprecated (undocumented)\nexport type MutateProps = never;\n\n// @public @deprecated (undocumented)\nexport const Mutation: never;\n\n// @public @deprecated (undocumented)\nexport type MutationComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type MutationDataOptions = never;\n\n// @public @deprecated (undocumented)\nexport type MutationUpdaterFn = never;\n\n// @public @deprecated (undocumented)\nexport type NetworkError = never;\n\n// @public @deprecated (undocumented)\nexport type ObservableQueryFields = never;\n\n// @public @deprecated (undocumented)\nexport const ObservableSubscription: never;\n\n// @public @deprecated (undocumented)\nexport const Observer: never;\n\n// @public @deprecated (undocumented)\nexport type OnlyRequiredProperties = never;\n\n// @public @deprecated (undocumented)\nexport const OperationBatcher: never;\n\n// @public @deprecated (undocumented)\nexport const operationName: never;\n\n// @public @deprecated (undocumented)\nexport type OperationOption = never;\n\n// @public @deprecated (undocumented)\nexport type OptionProps = never;\n\n// @public @deprecated (undocumented)\nexport const parser: never;\n\n// @public @deprecated (undocumented)\nexport type PromiseWithState = never;\n\n// @public @deprecated (undocumented)\nexport type PureQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport const Query: never;\n\n// @public @deprecated (undocumented)\nexport type QueryComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type QueryControls = never;\n\n// @public @deprecated (undocumented)\nexport type QueryDataOptions = never;\n\n// @public @deprecated (undocumented)\nexport type QueryLazyOptions = never;\n\n// @public @deprecated (undocumented)\nexport type ReconcilerFunction = never;\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesFunction = never;\n\n// @public (undocumented)\nexport namespace Removals {\n    // @deprecated (undocumented)\n    export type defer = never;\n    // @deprecated (undocumented)\n    export type errors = never;\n    // @deprecated (undocumented)\n    export type HOC = never;\n    // @deprecated (undocumented)\n    export type implementationDetail = never;\n    // @deprecated (undocumented)\n    export type internal = never;\n    // @deprecated (undocumented)\n    export type internalTesting = never;\n    // @deprecated (undocumented)\n    export type removedType = never;\n    // @deprecated (undocumented)\n    export type removedValue = never;\n    // @deprecated (undocumented)\n    export type renderProp = never;\n    // @deprecated (undocumented)\n    export type rxjs = never;\n    // @deprecated (undocumented)\n    export type testingLibrary = never;\n    // @deprecated (undocumented)\n    export type utility = never;\n}\n\n// @public @deprecated (undocumented)\nexport type RemoveArgumentsConfig = never;\n\n// @public @deprecated (undocumented)\nexport const removeArgumentsFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport const removeClientSetsFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport const removeConnectionDirectiveFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport type RemoveDirectiveConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveFragmentDefinitionConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveFragmentSpreadConfig = never;\n\n// @public @deprecated (undocumented)\nexport const removeFragmentSpreadFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport type RemoveNodeConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveVariableDefinitionConfig = never;\n\n// @public @deprecated (undocumented)\nexport const RenderPromises: never;\n\n// @public @deprecated (undocumented)\nexport const resetApolloContext: never;\n\n// @public @deprecated (undocumented)\nexport type Resolver = never;\n\n// @public @deprecated (undocumented)\nexport type Resolvers = never;\n\n// @public @deprecated (undocumented)\nexport const serializeFetchParameter: never;\n\n// @public @deprecated (undocumented)\nexport const subscribeAndCount: never;\n\n// @public @deprecated (undocumented)\nexport const Subscription: never;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionCurrentObservable = never;\n\n// @public @deprecated (undocumented)\nexport const throwServerError: never;\n\n// @public @deprecated (undocumented)\nexport const tick: never;\n\n// @public @deprecated (undocumented)\nexport const toPromise: never;\n\n// @public @deprecated (undocumented)\nexport const transformOperation: never;\n\n// @public @deprecated (undocumented)\nexport type TupleToIntersection = never;\n\n// @public @deprecated (undocumented)\nexport type UnionToIntersection = never;\n\n// @public @deprecated (undocumented)\nexport const validateOperation: never;\n\n// @public @deprecated (undocumented)\nexport const valueToObjectRepresentation: never;\n\n// @public @deprecated (undocumented)\nexport type VariableValue = never;\n\n// @public @deprecated (undocumented)\nexport const verifyDocumentType: never;\n\n// @public @deprecated (undocumented)\nexport const wait: never;\n\n// @public @deprecated (undocumented)\nexport const withApollo: never;\n\n// @public @deprecated (undocumented)\nexport type WithApolloClient = never;\n\n// @public @deprecated (undocumented)\nexport const withErrorSpy: never;\n\n// @public @deprecated (undocumented)\nexport const withLogSpy: never;\n\n// @public @deprecated (undocumented)\nexport const withMutation: never;\n\n// @public @deprecated (undocumented)\nexport const withQuery: never;\n\n// @public @deprecated (undocumented)\nexport const withSubscription: never;\n\n// @public @deprecated (undocumented)\nexport const withWarningSpy: never;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report-zz_removals.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\n// @public @deprecated (undocumented)\nexport const addNonReactiveToNamedFragments: never;\n\n// @public @deprecated (undocumented)\nexport const ApolloConsumer: never;\n\n// @public @deprecated (undocumented)\nexport type ApolloConsumerProps = never;\n\n// @public @deprecated (undocumented)\nexport class ApolloError {\n}\n\n// @public @deprecated (undocumented)\nexport type ApolloErrorOptions = never;\n\n// @public @deprecated (undocumented)\nexport const asyncMap: never;\n\n// @public @deprecated (undocumented)\nexport type BaseMutationOptions = never;\n\n// @public @deprecated (undocumented)\nexport type BaseQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport type BatchableRequest = never;\n\n// @public @deprecated (undocumented)\nexport const buildQueryFromSelectionSet: never;\n\n// @public @deprecated (undocumented)\nexport const canUseAsyncIteratorSymbol: never;\n\n// @public @deprecated (undocumented)\nexport const canUseLayoutEffect: never;\n\n// @public @deprecated (undocumented)\nexport const canUseSymbol: never;\n\n// @public @deprecated (undocumented)\nexport const canUseWeakMap: never;\n\n// @public @deprecated (undocumented)\nexport const canUseWeakSet: never;\n\n// @public @deprecated (undocumented)\nexport type ChildDataProps = never;\n\n// @public @deprecated (undocumented)\nexport type ChildMutateProps = never;\n\n// @public @deprecated (undocumented)\nexport type ChildProps = never;\n\n// @public @deprecated (undocumented)\nexport type ClientParseError = never;\n\n// @public @deprecated (undocumented)\nexport type CommonOptions = never;\n\n// @public @deprecated (undocumented)\nexport class Concast {\n}\n\n// @public @deprecated (undocumented)\nexport type ConcastSourcesArray = never;\n\n// @public @deprecated (undocumented)\nexport type ConcastSourcesIterable = never;\n\n// @public @deprecated (undocumented)\nexport const createMockClient: never;\n\n// @public @deprecated (undocumented)\nexport const createSchemaFetch: never;\n\n// @public @deprecated (undocumented)\nexport const createTestSchema: never;\n\n// @public @deprecated (undocumented)\nexport type DataProps = never;\n\n// @public @deprecated (undocumented)\nexport const DataProxy: never;\n\n// @public @deprecated (undocumented)\nexport type DataValue = never;\n\n// @public @deprecated (undocumented)\nexport const defaultCacheSizes: never;\n\n// @public @deprecated (undocumented)\nexport type DirectiveInfo = never;\n\n// @public @deprecated (undocumented)\nexport type Directives = never;\n\n// @public @deprecated (undocumented)\nconst DocumentType_2: never;\nexport { DocumentType_2 as DocumentType }\n\n// @public @deprecated (undocumented)\nexport type FetchMoreQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport const fixObservableSubclass: never;\n\n// @public @deprecated (undocumented)\nexport type FragmentMatcher = never;\n\n// @public @deprecated (undocumented)\nexport const fromError: never;\n\n// @public @deprecated (undocumented)\nexport const fromPromise: never;\n\n// @public @deprecated (undocumented)\nexport type GetDirectiveConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getDirectiveNames: never;\n\n// @public @deprecated (undocumented)\nexport const getFragmentMaskMode: never;\n\n// @public @deprecated (undocumented)\nexport type GetFragmentSpreadConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getInclusionDirectives: never;\n\n// @public @deprecated (undocumented)\nexport type GetNodeConfig = never;\n\n// @public @deprecated (undocumented)\nexport const getTypenameFromResult: never;\n\n// @public @deprecated (undocumented)\nexport const graphql: never;\n\n// @public @deprecated (undocumented)\nexport type GraphQLErrors = never;\n\n// @public @deprecated (undocumented)\nexport const hasAllDirectives: never;\n\n// @public @deprecated (undocumented)\nexport const hasAnyDirectives: never;\n\n// @public @deprecated (undocumented)\nexport const hasClientExports: never;\n\n// @public @deprecated (undocumented)\nexport type IDocumentDefinition = never;\n\n// @public @deprecated (undocumented)\nexport type InclusionDirectives = never;\n\n// @public @deprecated (undocumented)\nexport const isApolloError: never;\n\n// @public @deprecated (undocumented)\nexport const isApolloPayloadResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchIncrementalResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchInitialResult: never;\n\n// @public @deprecated (undocumented)\nexport const isExecutionPatchResult: never;\n\n// @public @deprecated (undocumented)\nexport const isFullyUnmaskedOperation: never;\n\n// @public @deprecated (undocumented)\nexport const isInlineFragment: never;\n\n// @public @deprecated (undocumented)\nexport const isStatefulPromise: never;\n\n// @public @deprecated (undocumented)\nexport type IsStrictlyAny = never;\n\n// @public @deprecated (undocumented)\nexport const itAsync: never;\n\n// @public @deprecated (undocumented)\nexport const iterateObserversSafely: never;\n\n// @public @deprecated (undocumented)\nexport const mergeIncrementalData: never;\n\n// @public @deprecated (undocumented)\nexport type MethodKeys = never;\n\n// @public @deprecated (undocumented)\nexport const mockObservableLink: never;\n\n// @public @deprecated (undocumented)\nexport const mockSingleLink: never;\n\n// @public @deprecated (undocumented)\nexport type MutateProps = never;\n\n// @public @deprecated (undocumented)\nexport const Mutation: never;\n\n// @public @deprecated (undocumented)\nexport type MutationComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type MutationDataOptions = never;\n\n// @public @deprecated (undocumented)\nexport type MutationUpdaterFn = never;\n\n// @public @deprecated (undocumented)\nexport type NetworkError = never;\n\n// @public @deprecated (undocumented)\nexport type ObservableQueryFields = never;\n\n// @public @deprecated (undocumented)\nexport const ObservableSubscription: never;\n\n// @public @deprecated (undocumented)\nexport const Observer: never;\n\n// @public @deprecated (undocumented)\nexport type OnlyRequiredProperties = never;\n\n// @public @deprecated (undocumented)\nexport const OperationBatcher: never;\n\n// @public @deprecated (undocumented)\nexport const operationName: never;\n\n// @public @deprecated (undocumented)\nexport type OperationOption = never;\n\n// @public @deprecated (undocumented)\nexport type OptionProps = never;\n\n// @public @deprecated (undocumented)\nexport const parser: never;\n\n// @public @deprecated (undocumented)\nexport type PromiseWithState = never;\n\n// @public @deprecated (undocumented)\nexport type PureQueryOptions = never;\n\n// @public @deprecated (undocumented)\nexport const Query: never;\n\n// @public @deprecated (undocumented)\nexport type QueryComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type QueryControls = never;\n\n// @public @deprecated (undocumented)\nexport type QueryDataOptions = never;\n\n// @public @deprecated (undocumented)\nexport type QueryLazyOptions = never;\n\n// @public @deprecated (undocumented)\nexport type ReconcilerFunction = never;\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesFunction = never;\n\n// @public\nexport namespace Removals {\n    // @deprecated (undocumented)\n    export type defer = never;\n    // @deprecated (undocumented)\n    export type errors = never;\n    // @deprecated (undocumented)\n    export type HOC = never;\n    // @deprecated (undocumented)\n    export type implementationDetail = never;\n    // @deprecated (undocumented)\n    export type internal = never;\n    // @deprecated (undocumented)\n    export type internalTesting = never;\n    // @deprecated (undocumented)\n    export type removedType = never;\n    // @deprecated (undocumented)\n    export type removedValue = never;\n    // @deprecated (undocumented)\n    export type renderProp = never;\n    // @deprecated (undocumented)\n    export type rxjs = never;\n    // @deprecated (undocumented)\n    export type testingLibrary = never;\n    // @deprecated (undocumented)\n    export type utility = never;\n}\n\n// @public @deprecated (undocumented)\nexport type RemoveArgumentsConfig = never;\n\n// @public @deprecated (undocumented)\nexport const removeArgumentsFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport const removeClientSetsFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport const removeConnectionDirectiveFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport type RemoveDirectiveConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveFragmentDefinitionConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveFragmentSpreadConfig = never;\n\n// @public @deprecated (undocumented)\nexport const removeFragmentSpreadFromDocument: never;\n\n// @public @deprecated (undocumented)\nexport type RemoveNodeConfig = never;\n\n// @public @deprecated (undocumented)\nexport type RemoveVariableDefinitionConfig = never;\n\n// @public @deprecated (undocumented)\nexport const RenderPromises: never;\n\n// @public @deprecated (undocumented)\nexport const resetApolloContext: never;\n\n// @public @deprecated (undocumented)\nexport type Resolver = never;\n\n// @public @deprecated (undocumented)\nexport type Resolvers = never;\n\n// @public @deprecated (undocumented)\nexport const serializeFetchParameter: never;\n\n// @public @deprecated (undocumented)\nexport const subscribeAndCount: never;\n\n// @public @deprecated (undocumented)\nexport const Subscription: never;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionComponentOptions = never;\n\n// @public @deprecated (undocumented)\nexport type SubscriptionCurrentObservable = never;\n\n// @public @deprecated (undocumented)\nexport const throwServerError: never;\n\n// @public @deprecated (undocumented)\nexport const tick: never;\n\n// @public @deprecated (undocumented)\nexport const toPromise: never;\n\n// @public @deprecated (undocumented)\nexport const transformOperation: never;\n\n// @public @deprecated (undocumented)\nexport type TupleToIntersection = never;\n\n// @public @deprecated (undocumented)\nexport type UnionToIntersection = never;\n\n// @public @deprecated (undocumented)\nexport const validateOperation: never;\n\n// @public @deprecated (undocumented)\nexport const valueToObjectRepresentation: never;\n\n// @public @deprecated (undocumented)\nexport type VariableValue = never;\n\n// @public @deprecated (undocumented)\nexport const verifyDocumentType: never;\n\n// @public @deprecated (undocumented)\nexport const wait: never;\n\n// @public @deprecated (undocumented)\nexport const withApollo: never;\n\n// @public @deprecated (undocumented)\nexport type WithApolloClient = never;\n\n// @public @deprecated (undocumented)\nexport const withErrorSpy: never;\n\n// @public @deprecated (undocumented)\nexport const withLogSpy: never;\n\n// @public @deprecated (undocumented)\nexport const withMutation: never;\n\n// @public @deprecated (undocumented)\nexport const withQuery: never;\n\n// @public @deprecated (undocumented)\nexport const withSubscription: never;\n\n// @public @deprecated (undocumented)\nexport const withWarningSpy: never;\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".api-reports/api-report.api.md",
    "content": "## API Report File for \"@apollo/client\"\n\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\n\n```ts\n\nimport type { ASTNode } from 'graphql';\nimport { disableExperimentalFragmentVariables } from 'graphql-tag';\nimport { disableFragmentWarnings } from 'graphql-tag';\nimport { DocumentNode } from 'graphql';\nimport type { DocumentTypeDecoration } from '@graphql-typed-document-node/core';\nimport { enableExperimentalFragmentVariables } from 'graphql-tag';\nimport type { FieldNode } from 'graphql';\nimport type { FormattedExecutionResult } from 'graphql';\nimport type { FragmentDefinitionNode } from 'graphql';\nimport { gql } from 'graphql-tag';\nimport type { GraphQLFormattedError } from 'graphql';\nimport type { InlineFragmentNode } from 'graphql';\nimport type { InteropObservable } from 'rxjs';\nimport type { NextNotification } from 'rxjs';\nimport { Observable } from 'rxjs';\nimport type { ObservableNotification } from 'rxjs';\nimport type { Observer } from 'rxjs';\nimport { OperationTypeNode } from 'graphql';\nimport type { print as print_2 } from 'graphql';\nimport { resetCaches } from 'graphql-tag';\nimport type { SelectionSetNode } from 'graphql';\nimport type { Subscribable } from 'rxjs';\nimport type { Subscription } from 'rxjs';\nimport { Trie } from '@wry/trie';\nimport { TypedDocumentNode } from '@graphql-typed-document-node/core';\n\n// Warning: (ae-forgotten-export) The symbol \"Modifier\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"StoreObjectValueMaybeReference\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype AllFieldsModifier<Entity extends Record<string, any>> = Modifier<Entity[keyof Entity] extends infer Value ? StoreObjectValueMaybeReference<Exclude<Value, undefined>> : never>;\n\n// @public (undocumented)\nexport namespace ApolloCache {\n    // Warning: (ae-forgotten-export) The symbol \"NoInfer_2\" needs to be exported by the entry point index.d.ts\n    export type FromOptionValue<TData> = StoreObject | Reference | FragmentType<NoInfer_2<TData>> | string;\n    // (undocumented)\n    export interface ObservableFragment<TData = unknown> extends Observable<ApolloCache.WatchFragmentResult<TData>> {\n        getCurrentResult: () => ApolloCache.WatchFragmentResult<TData>;\n    }\n    export interface WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        from: ApolloCache.FromOptionValue<TData> | Array<ApolloCache.FromOptionValue<TData> | null> | null;\n        optimistic?: boolean;\n        variables?: TVariables;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"IsAny\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"Prettify\" needs to be exported by the entry point index.d.ts\n    export type WatchFragmentResult<TData = unknown> = true extends IsAny<TData> ? ({\n        complete: true;\n        missing?: never;\n    } & GetDataState<any, \"complete\">) | ({\n        complete: false;\n        missing?: MissingTree;\n    } & GetDataState<any, \"partial\">) : TData extends null | null[] ? Prettify<{\n        complete: true;\n        missing?: never;\n    } & GetDataState<TData, \"complete\">> : Prettify<{\n        complete: true;\n        missing?: never;\n    } & GetDataState<TData, \"complete\">> | {\n        complete: false;\n        missing?: MissingTree;\n        data: TData extends Array<infer TItem> ? Array<DataValue.Partial<TItem> | null> : DataValue.Partial<TData>;\n        dataState: \"partial\";\n    };\n}\n\n// @public (undocumented)\nexport abstract class ApolloCache {\n    // (undocumented)\n    readonly assumeImmutableResults: boolean;\n    batch<U>(options: Cache_2.BatchOptions<this, U>): U;\n    abstract diff<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: Cache_2.DiffOptions<TData, TVariables>): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    abstract evict(options: Cache_2.EvictOptions): boolean;\n    abstract extract(optimistic?: boolean): unknown;\n    // (undocumented)\n    abstract fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string): boolean;\n    // (undocumented)\n    gc(): string[];\n    // Warning: (ae-forgotten-export) The symbol \"getApolloCacheMemoryInternals\" needs to be exported by the entry point index.d.ts\n    //\n    // @internal @deprecated\n    getMemoryInternals?: typeof getApolloCacheMemoryInternals;\n    // (undocumented)\n    identify(object: StoreObject | Reference): string | undefined;\n    // (undocumented)\n    lookupFragment(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    modify<Entity extends Record<string, any> = Record<string, any>>(options: Cache_2.ModifyOptions<Entity>): boolean;\n    protected onAfterBroadcast: (cb: () => void) => void;\n    // (undocumented)\n    abstract performTransaction(transaction: Transaction, optimisticId?: string | null): void;\n    // (undocumented)\n    abstract read<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: Cache_2.ReadOptions<TData, TVariables>): Unmasked<TData> | null;\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ fragment, variables, fragmentName, id, from, optimistic, returnPartialData, }: Cache_2.ReadFragmentOptions<TData, TVariables>): Unmasked<TData> | null;\n    // (undocumented)\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.ReadFragmentOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ query, variables, id, optimistic, returnPartialData, }: Cache_2.ReadQueryOptions<TData, TVariables>): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.ReadQueryOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    // (undocumented)\n    recordOptimisticTransaction(transaction: Transaction, optimisticId: string): void;\n    // (undocumented)\n    abstract removeOptimistic(id: string): void;\n    // (undocumented)\n    abstract reset(options?: Cache_2.ResetOptions): Promise<void>;\n    resolvesClientField?(typename: string, fieldName: string): boolean;\n    abstract restore(serializedState: unknown): this;\n    // (undocumented)\n    transformDocument(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    transformForLink(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    updateFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.UpdateFragmentOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void): Unmasked<TData> | null;\n    // (undocumented)\n    updateQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.UpdateQueryOptions<TData, TVariables>, update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void): Unmasked<TData> | null;\n    // (undocumented)\n    abstract watch<TData = unknown, TVariables extends OperationVariables = OperationVariables>(watch: Cache_2.WatchOptions<TData, TVariables>): () => void;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData>>;\n    }): ApolloCache.ObservableFragment<Array<Unmasked<TData>>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<null>;\n    }): ApolloCache.ObservableFragment<Array<null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }): ApolloCache.ObservableFragment<Array<Unmasked<TData> | null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: null;\n    }): ApolloCache.ObservableFragment<null>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n        from: ApolloCache.FromOptionValue<TData>;\n    }): ApolloCache.ObservableFragment<Unmasked<TData>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloCache.WatchFragmentOptions<TData, TVariables>): ApolloCache.ObservableFragment<Unmasked<TData> | null>;\n    // (undocumented)\n    abstract write<TData = unknown, TVariables extends OperationVariables = OperationVariables>(write: Cache_2.WriteOptions<TData, TVariables>): Reference | undefined;\n    writeFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ data, fragment, fragmentName, variables, overwrite, id, from, broadcast, }: Cache_2.WriteFragmentOptions<TData, TVariables>): Reference | undefined;\n    writeQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ data, query, variables, overwrite, id, broadcast, }: Cache_2.WriteQueryOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public (undocumented)\nexport namespace ApolloClient {\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface ReadQueryOptions<TData, TVariables extends OperationVariables> {\n            id?: string;\n            optimistic?: boolean;\n            query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n            returnPartialData?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface ReadFragmentOptions<TData, TVariables extends OperationVariables> {\n            fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n            fragmentName?: string;\n            optimistic?: boolean;\n            returnPartialData?: boolean;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> {\n            broadcast?: boolean;\n            data: Unmasked<TData>;\n            extensions?: Record<string, unknown>;\n            id?: string;\n            overwrite?: boolean;\n            query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        }\n    }\n    // (undocumented)\n    export namespace Base {\n        // (undocumented)\n        export interface WriteFragmentOptions<TData, TVariables extends OperationVariables> {\n            broadcast?: boolean;\n            data: Unmasked<TData>;\n            fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n            fragmentName?: string;\n            overwrite?: boolean;\n        }\n    }\n    // (undocumented)\n    export interface DefaultOptions {\n        // (undocumented)\n        mutate?: Partial<ApolloClient.MutateOptions<any, any, any>>;\n        // (undocumented)\n        query?: Partial<ApolloClient.QueryOptions<any, any>>;\n        // (undocumented)\n        watchQuery?: Partial<ApolloClient.WatchQueryOptions<any, any>>;\n    }\n    // (undocumented)\n    export interface DevtoolsOptions {\n        enabled?: boolean;\n        name?: string;\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ReadQueryOptions<TData, TVariables extends OperationVariables> extends Base.ReadQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ReadFragmentOptions<TData, TVariables extends OperationVariables> extends Base.ReadFragmentOptions<TData, TVariables> {\n            from?: ApolloCache.FromOptionValue<TData>;\n            id?: string;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteQueryOptions<TData, TVariables extends OperationVariables> extends Base.WriteQueryOptions<TData, TVariables> {\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface WriteFragmentOptions<TData, TVariables extends OperationVariables> extends Base.WriteFragmentOptions<TData, TVariables> {\n            from?: ApolloCache.FromOptionValue<TData>;\n            id?: string;\n            variables?: TVariables;\n        }\n    }\n    // (undocumented)\n    export interface Experiment {\n        // (undocumented)\n        (this: ApolloClient, options: ApolloClient.Options): void;\n        // (undocumented)\n        v: 1;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"VariablesOption\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    export type MutateOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = {\n        optimisticResponse?: Unmasked<NoInfer<TData>> | ((vars: TVariables, { IGNORE }: {\n            IGNORE: IgnoreModifier;\n        }) => Unmasked<NoInfer<TData>> | IgnoreModifier);\n        updateQueries?: MutationQueryReducersMap<TData>;\n        refetchQueries?: ((result: NormalizedExecutionResult<Unmasked<TData>>) => InternalRefetchQueriesInclude) | InternalRefetchQueriesInclude;\n        awaitRefetchQueries?: boolean;\n        update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n        onQueryUpdated?: OnQueryUpdated<any>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        fetchPolicy?: MutationFetchPolicy;\n        keepRootFields?: boolean;\n        mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface MutateResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n        extensions?: Record<string, unknown>;\n    }\n    // (undocumented)\n    export interface ObservableFragment<TData = unknown> extends Observable<ApolloClient.WatchFragmentResult<TData>> {\n        getCurrentResult: () => ApolloClient.WatchFragmentResult<TData>;\n    }\n    // (undocumented)\n    export interface Options {\n        assumeImmutableResults?: boolean;\n        cache: ApolloCache;\n        // Warning: (ae-forgotten-export) The symbol \"ClientAwarenessLink\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n        dataMasking?: boolean;\n        // (undocumented)\n        defaultContext?: Partial<DefaultContext>;\n        defaultOptions?: ApolloClient.DefaultOptions;\n        devtools?: ApolloClient.DevtoolsOptions;\n        // (undocumented)\n        documentTransform?: DocumentTransform;\n        // (undocumented)\n        enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n        experiments?: ApolloClient.Experiment[];\n        // Warning: (ae-forgotten-export) The symbol \"Incremental\" needs to be exported by the entry point index.d.ts\n        incrementalHandler?: Incremental.Handler<any>;\n        link: ApolloLink;\n        // Warning: (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        localState?: LocalState;\n        queryDeduplication?: boolean;\n        ssrForceFetchDelay?: number;\n        ssrMode?: boolean;\n    }\n    export type QueryOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        fetchPolicy?: FetchPolicy;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface QueryResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n    }\n    // (undocumented)\n    export type ReadFragmentOptions<TData, TVariables extends OperationVariables> = Base.ReadFragmentOptions<TData, TVariables> & VariablesOption<TVariables> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    export type ReadQueryOptions<TData, TVariables extends OperationVariables> = Base.ReadQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n    export interface RefetchQueriesOptions<TCache extends ApolloCache, TResult> {\n        include?: RefetchQueriesInclude;\n        onQueryUpdated?: OnQueryUpdated<TResult> | null;\n        optimistic?: boolean;\n        updateCache?: (cache: TCache) => void;\n    }\n    export interface RefetchQueriesResult<TResult> extends Promise<RefetchQueriesPromiseResults<TResult>>, RefetchQueriesResult.AdditionalProperties<TResult> {\n    }\n    // (undocumented)\n    export namespace RefetchQueriesResult {\n        // (undocumented)\n        export interface AdditionalProperties<TResult> {\n            queries: ObservableQuery<any>[];\n            results: InternalRefetchQueriesResult<TResult>[];\n        }\n    }\n    // (undocumented)\n    export type SubscribeOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        fetchPolicy?: FetchPolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        extensions?: Record<string, any>;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export interface SubscribeResult<TData = unknown> {\n        data: TData | undefined;\n        error?: ErrorLike;\n        extensions?: Record<string, unknown>;\n    }\n    // (undocumented)\n    export type WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = ApolloCache.WatchFragmentOptions<TData, TVariables>;\n    // (undocumented)\n    export type WatchFragmentResult<TData = unknown> = ApolloCache.WatchFragmentResult<MaybeMasked<TData>>;\n    export type WatchQueryOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        fetchPolicy?: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        initialFetchPolicy?: WatchQueryFetchPolicy;\n        refetchWritePolicy?: RefetchWritePolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        pollInterval?: number;\n        notifyOnNetworkStatusChange?: boolean;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        [variablesUnknownSymbol]?: boolean;\n    } & VariablesOption<NoInfer<TVariables>>;\n    // (undocumented)\n    export type WriteFragmentOptions<TData, TVariables extends OperationVariables> = Base.WriteFragmentOptions<TData, TVariables> & VariablesOption<TVariables> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    export type WriteQueryOptions<TData, TVariables extends OperationVariables> = Base.WriteQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n}\n\n// @public\nexport class ApolloClient {\n    // (undocumented)\n    __actionHookForDevTools(cb: () => any): void;\n    constructor(options: ApolloClient.Options);\n    // (undocumented)\n    __requestRaw(request: ApolloLink.Request): Observable<ApolloLink.Result<unknown>>;\n    // (undocumented)\n    cache: ApolloCache;\n    clearStore(): Promise<any[]>;\n    // (undocumented)\n    get defaultContext(): Partial<DefaultContext>;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    readonly devtoolsConfig: ApolloClient.DevtoolsOptions;\n    // @deprecated (undocumented)\n    disableNetworkFetches: never;\n    get documentTransform(): DocumentTransform;\n    extract(optimistic?: boolean): unknown;\n    // Warning: (ae-forgotten-export) The symbol \"getApolloClientMemoryInternals\" needs to be exported by the entry point index.d.ts\n    getMemoryInternals?: typeof getApolloClientMemoryInternals;\n    getObservableQueries(include?: RefetchQueriesInclude): Set<ObservableQuery<any>>;\n    // (undocumented)\n    link: ApolloLink;\n    get localState(): LocalState | undefined;\n    set localState(localState: LocalState);\n    mutate<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache>(options: ApolloClient.MutateOptions<TData, TVariables, TCache>): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n    onClearStore(cb: () => Promise<any>): () => void;\n    onResetStore(cb: () => Promise<any>): () => void;\n    set prioritizeCacheValues(value: boolean);\n    get prioritizeCacheValues(): boolean;\n    query<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.QueryOptions<TData, TVariables>): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    queryDeduplication: boolean;\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadFragmentOptions<TData, TVariables>): Unmasked<TData> | null;\n    // @deprecated\n    readFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadFragmentOptions<TData, TVariables>, optimistic: boolean): Unmasked<TData> | null;\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadQueryOptions<TData, TVariables>): Unmasked<TData> | null;\n    // @deprecated\n    readQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.ReadQueryOptions<TData, TVariables>,\n    optimistic: boolean): Unmasked<TData> | null;\n    // @deprecated\n    reFetchObservableQueries: (includeStandby?: boolean) => Promise<ApolloClient.QueryResult<any>[]>;\n    refetchObservableQueries(includeStandby?: boolean): Promise<ApolloClient.QueryResult<any>[]>;\n    refetchQueries<TCache extends ApolloCache = ApolloCache, TResult = Promise<ApolloClient.QueryResult<any>>>(options: ApolloClient.RefetchQueriesOptions<TCache, TResult>): ApolloClient.RefetchQueriesResult<TResult>;\n    resetStore(): Promise<ApolloClient.QueryResult<any>[] | null>;\n    restore(serializedState: unknown): ApolloCache;\n    setLink(newLink: ApolloLink): void;\n    stop(): void;\n    subscribe<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.SubscribeOptions<TData, TVariables>): SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    version: string;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData>>;\n    }): ApolloClient.ObservableFragment<Array<TData>>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<null>;\n    }): ApolloClient.ObservableFragment<Array<null>>;\n    // (undocumented)\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }): ApolloClient.ObservableFragment<Array<TData | null>>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: null;\n    }): ApolloClient.ObservableFragment<null>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n        from: ApolloCache.FromOptionValue<TData>;\n    }): ApolloClient.ObservableFragment<TData>;\n    watchFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchFragmentOptions<TData, TVariables>): ApolloClient.ObservableFragment<TData | null>;\n    watchQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>): ObservableQuery<TData, TVariables>;\n    writeFragment<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WriteFragmentOptions<TData, TVariables>): Reference | undefined;\n    writeQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WriteQueryOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public @deprecated (undocumented)\nexport type ApolloClientOptions = ApolloClient.Options;\n\n// @public (undocumented)\nexport namespace ApolloLink {\n    // Warning: (ae-forgotten-export) The symbol \"ApplyHKTImplementationWithDefault\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"NotImplementedHandler\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    export type AdditionalResultTypes<TData = Record<string, any>, TExtensions = Record<string, any>> = ApplyHKTImplementationWithDefault<TypeOverrides, \"AdditionalApolloLinkResultTypes\", NotImplementedHandler.TypeOverrides, TData, TExtensions>;\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function ForwardFunction(operation: ApolloLink.Operation): Observable<ApolloLink.Result>;\n        export function RequestHandler(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n    }\n    export interface ExecuteContext {\n        client: ApolloClient;\n    }\n    export type ForwardFunction = (operation: ApolloLink.Operation) => Observable<ApolloLink.Result>;\n    export interface Operation {\n        readonly client: ApolloClient;\n        extensions: Record<string, any>;\n        getContext: () => Readonly<ApolloLink.OperationContext>;\n        operationName: string | undefined;\n        operationType: OperationTypeNode;\n        query: DocumentNode;\n        setContext: {\n            (context: Partial<ApolloLink.OperationContext>): void;\n            (updateContext: (previousContext: Readonly<ApolloLink.OperationContext>) => Partial<ApolloLink.OperationContext>): void;\n        };\n        variables: OperationVariables;\n    }\n    export interface OperationContext extends DefaultContext {\n    }\n    export interface Request {\n        context?: DefaultContext;\n        extensions?: Record<string, any>;\n        query: DocumentNode;\n        variables?: OperationVariables;\n    }\n    export type RequestHandler = (operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction) => Observable<ApolloLink.Result>;\n    // (undocumented)\n    export type Result<TData = Record<string, any>, TExtensions = Record<string, any>> = FormattedExecutionResult<TData, TExtensions> | AdditionalResultTypes<TData, TExtensions>;\n}\n\n// @public\nexport class ApolloLink {\n    constructor(request?: ApolloLink.RequestHandler);\n    // @deprecated\n    static concat(...links: ApolloLink[]): ApolloLink;\n    concat(...links: ApolloLink[]): ApolloLink;\n    static empty(): ApolloLink;\n    static execute(link: ApolloLink, request: ApolloLink.Request, context: ApolloLink.ExecuteContext): Observable<ApolloLink.Result>;\n    static from(links: ApolloLink[]): ApolloLink;\n    // @internal @deprecated\n    getMemoryInternals?: () => unknown;\n    // @internal @deprecated\n    readonly left?: ApolloLink;\n    request(operation: ApolloLink.Operation, forward: ApolloLink.ForwardFunction): Observable<ApolloLink.Result>;\n    // @internal @deprecated\n    readonly right?: ApolloLink;\n    static split(test: (op: ApolloLink.Operation) => boolean, left: ApolloLink, right?: ApolloLink): ApolloLink;\n    split(test: (op: ApolloLink.Operation) => boolean, left: ApolloLink, right?: ApolloLink): ApolloLink;\n}\n\n// @public (undocumented)\nexport interface ApolloPayloadResult<TData = Record<string, any>, TExtensions = Record<string, any>> {\n    // (undocumented)\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    // (undocumented)\n    payload: FormattedExecutionResult<TData, TExtensions> | null;\n}\n\n// @public @deprecated (undocumented)\nexport type ApolloQueryResult<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = ObservableQuery.Result<TData, TStates>;\n\n// @public (undocumented)\nexport type ApolloReducerConfig = {\n    dataIdFromObject?: KeyFieldsFunction;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"HKT\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\ntype ApplyHKT<fn extends HKT, arg1, arg2 = never, arg3 = never, arg4 = never> = (fn & {\n    arg1: arg1;\n    arg2: arg2;\n    arg3: arg3;\n    arg4: arg4;\n})[\"return\"];\n\n// Warning: (ae-forgotten-export) The symbol \"ApplyHKT\" needs to be exported by the entry point index.d.ts\n//\n// @internal @deprecated (undocumented)\ntype ApplyHKTImplementationWithDefault<Implementation, Name extends string, DefaultImplementation extends Record<Name, HKT>, arg1, arg2 = never, arg3 = never, arg4 = never> = ApplyHKT<Implementation extends {\n    [name in Name]: infer Implementation extends HKT;\n} ? Implementation : DefaultImplementation[Name], arg1, arg2, arg3, arg4>;\n\n// @public\ntype AsStoreObject<T extends {\n    __typename?: string;\n}> = {\n    [K in keyof T]: T[K];\n};\n\n// @public (undocumented)\nnamespace BaseHttpLink {\n    // (undocumented)\n    interface Body {\n        // (undocumented)\n        extensions?: Record<string, any>;\n        // (undocumented)\n        operationName?: string;\n        // (undocumented)\n        query?: string;\n        // (undocumented)\n        variables?: Record<string, any>;\n    }\n    interface ContextOptions {\n        credentials?: RequestCredentials;\n        fetchOptions?: RequestInit;\n        headers?: Record<string, string>;\n        http?: BaseHttpLink.HttpOptions;\n        uri?: string | BaseHttpLink.UriFunction;\n    }\n    interface HttpOptions {\n        accept?: string[];\n        includeExtensions?: boolean;\n        includeQuery?: boolean;\n        preserveHeaderCase?: boolean;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"BaseHttpLink\" needs to be exported by the entry point index.d.ts\n    interface Options extends Shared.Options {\n        useGETForQueries?: boolean;\n    }\n    // (undocumented)\n    type Printer = (node: ASTNode, originalPrint: typeof print_2) => string;\n    // (undocumented)\n    namespace Shared {\n        interface Options {\n            credentials?: RequestCredentials;\n            fetch?: typeof fetch;\n            fetchOptions?: RequestInit;\n            headers?: Record<string, string>;\n            includeExtensions?: boolean;\n            includeUnusedVariables?: boolean;\n            preserveHeaderCase?: boolean;\n            print?: BaseHttpLink.Printer;\n            uri?: string | BaseHttpLink.UriFunction;\n        }\n    }\n    // (undocumented)\n    type UriFunction = (operation: ApolloLink.Operation) => string;\n}\n\n// @public\nclass BaseHttpLink extends ApolloLink {\n    constructor(options?: BaseHttpLink.Options);\n}\n\n// @public (undocumented)\ntype BroadcastOptions = Pick<Cache_2.BatchOptions<InMemoryCache>, \"optimistic\" | \"onWatchUpdated\">;\n\n// @public (undocumented)\nexport const build: \"source\" | \"esm\" | \"cjs\";\n\n// @public (undocumented)\nnamespace Cache_2 {\n    // (undocumented)\n    interface BatchOptions<TCache extends ApolloCache, TUpdateResult = void> {\n        onWatchUpdated?: (this: TCache, watch: Cache_2.WatchOptions, diff: Cache_2.DiffResult<any>, lastDiff?: Cache_2.DiffResult<any> | undefined) => any;\n        optimistic?: string | boolean;\n        removeOptimistic?: string;\n        update(cache: TCache): TUpdateResult;\n    }\n    // (undocumented)\n    type CacheIdentifierOption<TData> = {\n        id?: string;\n        from?: never;\n    } | {\n        id?: never;\n        from?: ApolloCache.FromOptionValue<TData>;\n    };\n    // (undocumented)\n    interface DiffOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Omit<ReadOptions<TData, TVariables>, \"rootId\"> {\n    }\n    // (undocumented)\n    type DiffResult<TData> = {\n        result: DataValue.Complete<TData>;\n        complete: true;\n        missing?: never;\n        fromOptimisticTransaction?: boolean;\n    } | {\n        result: DataValue.Partial<TData> | null;\n        complete: false;\n        missing?: MissingFieldError;\n        fromOptimisticTransaction?: boolean;\n    };\n    // (undocumented)\n    interface EvictOptions {\n        // (undocumented)\n        args?: Record<string, any>;\n        // (undocumented)\n        broadcast?: boolean;\n        // (undocumented)\n        fieldName?: string;\n        // (undocumented)\n        id?: string;\n    }\n    // (undocumented)\n    interface ModifyOptions<Entity extends Record<string, any> = Record<string, any>> {\n        // (undocumented)\n        broadcast?: boolean;\n        // Warning: (ae-forgotten-export) The symbol \"Modifiers\" needs to be exported by the entry point index.d.ts\n        // Warning: (ae-forgotten-export) The symbol \"AllFieldsModifier\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        fields: Modifiers<Entity> | AllFieldsModifier<Entity>;\n        // (undocumented)\n        id?: string;\n        // (undocumented)\n        optimistic?: boolean;\n    }\n    // (undocumented)\n    type ReadFragmentOptions<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        variables?: TVariables;\n        returnPartialData?: boolean;\n        optimistic?: boolean;\n    } & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface ReadOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        id?: string;\n        // (undocumented)\n        optimistic: boolean;\n        // (undocumented)\n        previousResult?: any;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        // (undocumented)\n        returnPartialData?: boolean;\n        // (undocumented)\n        rootId?: string;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface ReadQueryOptions<TData, TVariables extends OperationVariables> {\n        id?: string;\n        optimistic?: boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        returnPartialData?: boolean;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface ResetOptions {\n        // (undocumented)\n        discardWatches?: boolean;\n    }\n    // (undocumented)\n    type UpdateFragmentOptions<TData, TVariables extends OperationVariables> = Omit<ReadFragmentOptions<TData, TVariables> & WriteFragmentOptions<TData, TVariables>, \"data\" | \"id\" | \"from\"> & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface UpdateQueryOptions<TData, TVariables extends OperationVariables> extends Omit<ReadQueryOptions<TData, TVariables> & WriteQueryOptions<TData, TVariables>, \"data\"> {\n    }\n    // (undocumented)\n    type WatchCallback<TData = unknown> = (diff: Cache_2.DiffResult<TData>, lastDiff?: Cache_2.DiffResult<TData>) => void;\n    // (undocumented)\n    interface WatchOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends DiffOptions<TData, TVariables> {\n        // (undocumented)\n        callback: WatchCallback<TData>;\n        // (undocumented)\n        immediate?: boolean;\n        // (undocumented)\n        lastDiff?: DiffResult<TData>;\n        // (undocumented)\n        watcher?: object;\n    }\n    // (undocumented)\n    type WriteFragmentOptions<TData, TVariables extends OperationVariables> = {\n        fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        fragmentName?: string;\n        variables?: TVariables;\n        data: Unmasked<TData>;\n        broadcast?: boolean;\n        overwrite?: boolean;\n    } & Cache_2.CacheIdentifierOption<TData>;\n    // (undocumented)\n    interface WriteOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n        broadcast?: boolean;\n        // (undocumented)\n        dataId?: string;\n        // Warning: (ae-forgotten-export) The symbol \"ExtensionsWithStreamInfo\" needs to be exported by the entry point index.d.ts\n        extensions?: ExtensionsWithStreamInfo;\n        overwrite?: boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        // (undocumented)\n        result: Unmasked<TData>;\n        variables?: TVariables;\n    }\n    // (undocumented)\n    interface WriteQueryOptions<TData, TVariables extends OperationVariables> {\n        broadcast?: boolean;\n        data: Unmasked<TData>;\n        extensions?: ExtensionsWithStreamInfo;\n        id?: string;\n        overwrite?: boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        variables?: TVariables;\n    }\n}\nexport { Cache_2 as Cache }\n\n// @public (undocumented)\nclass CacheGroup {\n    constructor(caching: boolean, parent?: CacheGroup | null);\n    // (undocumented)\n    readonly caching: boolean;\n    // (undocumented)\n    depend(dataId: string, storeFieldName: string): void;\n    // (undocumented)\n    dirty(dataId: string, storeFieldName: string): void;\n    // (undocumented)\n    keyMaker: Trie<object>;\n    // (undocumented)\n    resetCaching(): void;\n}\n\n// @public (undocumented)\ntype CanReadFunction = (value: StoreValue) => boolean;\n\n// @public (undocumented)\nexport const checkFetcher: (fetcher: typeof fetch | undefined) => void;\n\n// @public (undocumented)\nnamespace ClientAwarenessLink {\n    // (undocumented)\n    interface ClientAwarenessOptions {\n        name?: string;\n        transport?: \"headers\" | false;\n        version?: string;\n    }\n    interface ContextOptions {\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    }\n    // (undocumented)\n    interface EnhancedClientAwarenessOptions {\n        transport?: \"headers\" | \"extensions\" | false;\n    }\n    // (undocumented)\n    interface Options {\n        clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n        enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n    }\n}\n\n// @public\nclass ClientAwarenessLink extends ApolloLink {\n    constructor(options?: ClientAwarenessLink.Options);\n}\n\n// @public (undocumented)\nexport namespace CombinedGraphQLErrors {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function formatMessage(errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions): string;\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly data: Record<string, unknown> | null | undefined;\n            readonly errors: ReadonlyArray<GraphQLFormattedError>;\n            readonly extensions: Record<string, unknown> | undefined;\n        }\n        export function is(error: unknown): boolean;\n    }\n    export type MessageFormatter = (errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions) => string;\n    // (undocumented)\n    export interface MessageFormatterOptions {\n        defaultFormatMessage: (errors: ReadonlyArray<GraphQLFormattedError>) => string;\n        result: ApolloLink.Result<unknown>;\n    }\n}\n\n// @public\nexport class CombinedGraphQLErrors extends Error {\n    constructor(result: FormattedExecutionResult<any>);\n    constructor(result: ApolloLink.Result<any>, errors: ReadonlyArray<GraphQLFormattedError>);\n    readonly data: Record<string, unknown> | null | undefined;\n    readonly errors: ReadonlyArray<GraphQLFormattedError>;\n    readonly extensions: Record<string, unknown> | undefined;\n    static formatMessage: CombinedGraphQLErrors.MessageFormatter;\n    static is(error: unknown): error is CombinedGraphQLErrors;\n}\n\n// @public (undocumented)\nexport namespace CombinedProtocolErrors {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        export function formatMessage(errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions): string;\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly errors: ReadonlyArray<GraphQLFormattedError>;\n        }\n    }\n    export type MessageFormatter = (errors: ReadonlyArray<GraphQLFormattedError>, options: MessageFormatterOptions) => string;\n    // (undocumented)\n    export interface MessageFormatterOptions {\n        defaultFormatMessage: (errors: ReadonlyArray<GraphQLFormattedError>) => string;\n    }\n}\n\n// @public\nexport class CombinedProtocolErrors extends Error {\n    constructor(protocolErrors: Array<GraphQLFormattedError> | ReadonlyArray<GraphQLFormattedError>);\n    readonly errors: ReadonlyArray<GraphQLFormattedError>;\n    static formatMessage: CombinedProtocolErrors.MessageFormatter;\n    static is(error: unknown): error is CombinedProtocolErrors;\n}\n\n// @public @deprecated (undocumented)\nexport const concat: typeof ApolloLink.concat;\n\n// @public @deprecated (undocumented)\nexport const createHttpLink: (options?: HttpLink.Options) => HttpLink;\n\n// @public @deprecated (undocumented)\nexport const createSignalIfSupported: () => {\n    controller: boolean;\n    signal: boolean;\n} | {\n    controller: AbortController;\n    signal: AbortSignal;\n};\n\n// @public (undocumented)\nexport type DataState<TData> = {\n    data: DataValue.Complete<TData>;\n    dataState: \"complete\";\n} | {\n    data: DataValue.Streaming<TData>;\n    dataState: \"streaming\";\n} | {\n    data: DataValue.Partial<TData>;\n    dataState: \"partial\";\n} | {\n    data: undefined;\n    dataState: \"empty\";\n};\n\n// @public (undocumented)\nexport namespace DataValue {\n    // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n    export type Complete<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Complete\", OverridableTypes.Defaults, TData>;\n    export type Partial<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Partial\", OverridableTypes.Defaults, TData>;\n    export type Streaming<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Streaming\", OverridableTypes.Defaults, TData>;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialPrimitive\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialMap\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialReadonlyMap\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialSet\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialReadonlySet\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeepPartialObject\" needs to be exported by the entry point index.d.ts\n//\n// @public\ntype DeepPartial<T> = T extends DeepPartialPrimitive ? T : T extends Map<infer TKey, infer TValue> ? DeepPartialMap<TKey, TValue> : T extends ReadonlyMap<infer TKey, infer TValue> ? DeepPartialReadonlyMap<TKey, TValue> : T extends Set<infer TItem> ? DeepPartialSet<TItem> : T extends ReadonlySet<infer TItem> ? DeepPartialReadonlySet<TItem> : T extends (...args: any[]) => unknown ? T | undefined : T extends object ? T extends (ReadonlyArray<infer TItem>) ? TItem[] extends (T) ? readonly TItem[] extends T ? ReadonlyArray<DeepPartial<TItem>> : Array<DeepPartial<TItem>> : DeepPartialObject<T> : DeepPartialObject<T> : unknown;\n\n// Warning: (ae-forgotten-export) The symbol \"DeepPartial\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype DeepPartialMap<TKey, TValue> = {} & Map<DeepPartial<TKey>, DeepPartial<TValue>>;\n\n// @public (undocumented)\ntype DeepPartialObject<T extends object> = {\n    [K in keyof T]?: DeepPartial<T[K]>;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"Primitive\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype DeepPartialPrimitive = Primitive | Date | RegExp;\n\n// @public (undocumented)\ntype DeepPartialReadonlyMap<TKey, TValue> = {} & ReadonlyMap<DeepPartial<TKey>, DeepPartial<TValue>>;\n\n// @public (undocumented)\ntype DeepPartialReadonlySet<T> = {} & ReadonlySet<DeepPartial<T>>;\n\n// @public (undocumented)\ntype DeepPartialSet<T> = {} & Set<DeepPartial<T>>;\n\n// @public (undocumented)\nexport interface DefaultContext extends Record<string, any> {\n    // (undocumented)\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    queryDeduplication?: boolean;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"KeyFieldsContext\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function defaultDataIdFromObject({ __typename, id, _id }: Readonly<StoreObject>, context?: KeyFieldsContext): string | undefined;\n\n// @public @deprecated (undocumented)\nexport type DefaultOptions = ApolloClient.DefaultOptions;\n\n// Warning: (ae-forgotten-export) The symbol \"BaseHttpLink\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport const defaultPrinter: BaseHttpLink.Printer;\n\n// @public (undocumented)\ninterface DeleteModifier {\n    // (undocumented)\n    [_deleteModifier]: true;\n}\n\n// @public (undocumented)\nconst _deleteModifier: unique symbol;\n\n// @public @deprecated (undocumented)\nexport type DevtoolsOptions = ApolloClient.DevtoolsOptions;\n\n// @public (undocumented)\nexport type DiffQueryAgainstStoreOptions = ReadQueryOptions & {\n    returnPartialData?: boolean;\n};\n\nexport { disableExperimentalFragmentVariables }\n\nexport { disableFragmentWarnings }\n\nexport { DocumentNode }\n\n// @public\nexport class DocumentTransform {\n    // Warning: (ae-forgotten-export) The symbol \"TransformFn\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"DocumentTransformOptions\" needs to be exported by the entry point index.d.ts\n    constructor(transform: TransformFn, options?: DocumentTransformOptions);\n    concat(otherTransform: DocumentTransform): DocumentTransform;\n    static identity(): DocumentTransform;\n    // @internal @deprecated\n    readonly left?: DocumentTransform;\n    resetCache(): void;\n    // @internal @deprecated\n    readonly right?: DocumentTransform;\n    static split(predicate: (document: DocumentNode) => boolean, left: DocumentTransform, right?: DocumentTransform): DocumentTransform & {\n        left: DocumentTransform;\n        right: DocumentTransform;\n    };\n    transformDocument(document: DocumentNode): DocumentNode;\n}\n\n// @public (undocumented)\nexport type DocumentTransformCacheKey = ReadonlyArray<unknown>;\n\n// @public (undocumented)\ninterface DocumentTransformOptions {\n    cache?: boolean;\n    getCacheKey?: (document: DocumentNode) => DocumentTransformCacheKey | undefined;\n}\n\n// @public @deprecated (undocumented)\nexport const empty: typeof ApolloLink.empty;\n\nexport { enableExperimentalFragmentVariables }\n\n// @public (undocumented)\nabstract class EntityStore implements NormalizedCache {\n    constructor(policies: Policies, group: CacheGroup);\n    // Warning: (ae-forgotten-export) The symbol \"Layer\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    abstract addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // Warning: (ae-forgotten-export) The symbol \"CanReadFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    clear(): void;\n    // (undocumented)\n    protected data: NormalizedCacheObject;\n    // (undocumented)\n    delete(dataId: string, fieldName?: string, args?: Record<string, any>): boolean;\n    // (undocumented)\n    evict(options: Cache_2.EvictOptions, limit: EntityStore): boolean;\n    // (undocumented)\n    extract(): NormalizedCacheObject;\n    // (undocumented)\n    findChildRefIds(dataId: string): Record<string, true>;\n    // (undocumented)\n    gc(): string[];\n    // (undocumented)\n    get(dataId: string, fieldName: string): StoreValue;\n    // Warning: (ae-forgotten-export) The symbol \"SafeReadonly\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getFieldValue: <T = StoreValue>(objectOrReference: StoreObject | Reference | undefined, storeFieldName: string) => SafeReadonly<T>;\n    // (undocumented)\n    getRootIdSet(ids?: Set<string>): Set<string>;\n    // Warning: (ae-forgotten-export) The symbol \"StorageType\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    abstract getStorage(idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[]): StorageType;\n    // Warning: (ae-forgotten-export) The symbol \"CacheGroup\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readonly group: CacheGroup;\n    // (undocumented)\n    has(dataId: string): boolean;\n    // (undocumented)\n    protected lookup(dataId: string, dependOnExistence?: boolean): StoreObject | undefined;\n    makeCacheKey(document: DocumentNode, callback: Cache_2.WatchCallback<any>, details: string): object;\n    makeCacheKey(selectionSet: SelectionSetNode, parent: string | StoreObject, varString: string | undefined): object;\n    makeCacheKey(field: FieldNode, array: readonly any[], varString: string | undefined): object;\n    // @deprecated (undocumented)\n    makeCacheKey(...args: any[]): object;\n    // (undocumented)\n    merge(older: string | StoreObject, newer: StoreObject | string): void;\n    // (undocumented)\n    modify(dataId: string, fields: Modifier<any> | Modifiers<Record<string, any>>, exact: boolean): boolean;\n    // Warning: (ae-forgotten-export) The symbol \"Policies\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readonly policies: Policies;\n    // (undocumented)\n    release(rootId: string): number;\n    // (undocumented)\n    abstract removeLayer(layerId: string): EntityStore;\n    // (undocumented)\n    replace(newData: NormalizedCacheObject | null): void;\n    // (undocumented)\n    retain(rootId: string): number;\n    // Warning: (ae-forgotten-export) The symbol \"Root\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    static Root: typeof Root;\n    // (undocumented)\n    get supportsResultCaching(): boolean;\n    // (undocumented)\n    toObject(): NormalizedCacheObject;\n    // Warning: (ae-forgotten-export) The symbol \"ToReferenceFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    toReference: ToReferenceFunction;\n}\n\n// @public\nexport interface ErrorLike {\n    // (undocumented)\n    message: string;\n    // (undocumented)\n    name: string;\n    // (undocumented)\n    stack?: string;\n}\n\n// @public\nexport type ErrorPolicy = \"none\" | \"ignore\" | \"all\";\n\n// @public (undocumented)\nexport const execute: typeof ApolloLink.execute;\n\n// @internal @deprecated\nconst extensionsSymbol: unique symbol;\n\n// @public\ninterface ExtensionsWithStreamInfo extends Record<string, unknown> {\n    // (undocumented)\n    [streamInfoSymbol]?: {\n        deref(): StreamInfoTrie | undefined;\n    };\n}\n\n// @public (undocumented)\nexport const fallbackHttpConfig: {\n    http: BaseHttpLink.HttpOptions;\n    headers: {\n        accept: string;\n        \"content-type\": string;\n    };\n    options: {\n        method: string;\n    };\n};\n\n// @public\nexport type FetchPolicy = \"cache-first\" | \"network-only\" | \"cache-only\" | \"no-cache\";\n\n// @public @deprecated (undocumented)\nexport type FetchResult<TData = Record<string, any>, TExtensions = Record<string, any>> = ApolloLink.Result<TData, TExtensions>;\n\n// @public (undocumented)\nexport interface FieldFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> {\n    // (undocumented)\n    args: TArgs | null;\n    // (undocumented)\n    cache: InMemoryCache;\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    field: FieldNode | null;\n    // (undocumented)\n    fieldName: string;\n    // (undocumented)\n    isReference: typeof isReference;\n    // Warning: (ae-forgotten-export) The symbol \"MergeObjectsFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    mergeObjects: MergeObjectsFunction;\n    // Warning: (ae-forgotten-export) The symbol \"ReadFieldFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readField: ReadFieldFunction;\n    // (undocumented)\n    storage: StorageType;\n    // (undocumented)\n    storeFieldName: string;\n    // (undocumented)\n    toReference: ToReferenceFunction;\n    // (undocumented)\n    variables?: TVariables;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"FieldMergeFunctionOptions\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport type FieldMergeFunction<TExisting = any, TIncoming = TExisting, TOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions> = (existing: SafeReadonly<TExisting> | undefined, incoming: SafeReadonly<TIncoming>, options: TOptions) => SafeReadonly<TExisting>;\n\n// @public (undocumented)\ninterface FieldMergeFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> extends FieldFunctionOptions<TArgs, TVariables> {\n    existingData: unknown;\n    extensions: Record<string, unknown> | undefined;\n    streamFieldInfo?: Incremental.StreamFieldInfo;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"FieldReadFunctionOptions\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport type FieldPolicy<TExisting = any, TIncoming = TExisting, TReadResult = TIncoming, TReadOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions, TMergeOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions> = {\n    keyArgs?: KeySpecifier | KeyArgsFunction | false;\n    read?: FieldReadFunction<TExisting, TReadResult, TReadOptions>;\n    merge?: FieldMergeFunction<TExisting, TIncoming, TMergeOptions> | boolean;\n};\n\n// @public (undocumented)\nexport type FieldReadFunction<TExisting = any, TReadResult = TExisting, TOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions> = (existing: SafeReadonly<TExisting> | undefined, options: TOptions) => TReadResult | undefined;\n\n// @public (undocumented)\ninterface FieldReadFunctionOptions<TArgs = Record<string, any>, TVariables extends OperationVariables = Record<string, any>> extends FieldFunctionOptions<TArgs, TVariables> {\n}\n\n// @public (undocumented)\ninterface FieldSpecifier {\n    // (undocumented)\n    args?: Record<string, any>;\n    // (undocumented)\n    field?: FieldNode;\n    // (undocumented)\n    fieldName: string;\n    // (undocumented)\n    typename?: string;\n    // (undocumented)\n    variables?: Record<string, any>;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"EntityStore\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype FieldValueGetter = EntityStore[\"getFieldValue\"];\n\n// Warning: (ae-forgotten-export) The symbol \"WriteContext\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype FlavorableWriteContext = Pick<WriteContext, \"clientOnly\" | \"deferred\" | \"flavors\">;\n\n// @internal @deprecated\ninterface FragmentMap {\n    // (undocumented)\n    [fragmentName: string]: FragmentDefinitionNode;\n}\n\n// @internal @deprecated (undocumented)\ntype FragmentMapFunction = (fragmentName: string) => FragmentDefinitionNode | null;\n\n// @public (undocumented)\ninterface FragmentRegistryAPI {\n    // (undocumented)\n    lookup(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    register(...fragments: DocumentNode[]): this;\n    // (undocumented)\n    resetCaches(): void;\n    // (undocumented)\n    transform<D extends DocumentNode>(document: D): D;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"PreserveTypes\" needs to be exported by the entry point index.d.ts\n//\n// @public\nexport type FragmentType<TFragmentDataOrTypedDocumentNode> = ApplyHKTImplementationWithDefault<TypeOverrides, \"FragmentType\", PreserveTypes.TypeOverrides, TFragmentDataOrTypedDocumentNode extends (DocumentTypeDecoration<infer TFragmentData, any>) ? TFragmentData : TFragmentDataOrTypedDocumentNode>;\n\n// @public @deprecated (undocumented)\nexport const from: typeof ApolloLink.from;\n\n// @internal @deprecated\nconst getApolloCacheMemoryInternals: (() => {\n    cache: {\n        fragmentQueryDocuments: number | undefined;\n    };\n}) | undefined;\n\n// @internal @deprecated\nconst getApolloClientMemoryInternals: (() => {\n    limits: {\n        [k: string]: number;\n    };\n    sizes: {\n        cache?: {\n            fragmentQueryDocuments: number | undefined;\n        } | undefined;\n        addTypenameDocumentTransform?: {\n            cache: number;\n        }[] | undefined;\n        inMemoryCache?: {\n            executeSelectionSet: number | undefined;\n            executeSubSelectedArray: number | undefined;\n            maybeBroadcastWatch: number | undefined;\n        } | undefined;\n        fragmentRegistry?: {\n            findFragmentSpreads: number | undefined;\n            lookup: number | undefined;\n            transform: number | undefined;\n        } | undefined;\n        print: number | undefined;\n        canonicalStringify: number | undefined;\n        links: unknown[];\n        queryManager: {\n            getDocumentInfo: number;\n            documentTransforms: {\n                cache: number;\n            }[];\n        };\n    };\n}) | undefined;\n\n// @public (undocumented)\nexport type GetDataState<TData, TState extends DataState<TData>[\"dataState\"]> = Extract<DataState<TData>, {\n    dataState: TState;\n}>;\n\n// @internal @deprecated\nconst getInMemoryCacheMemoryInternals: (() => {\n    addTypenameDocumentTransform: {\n        cache: number;\n    }[];\n    inMemoryCache: {\n        executeSelectionSet: number | undefined;\n        executeSubSelectedArray: number | undefined;\n        maybeBroadcastWatch: number | undefined;\n    };\n    fragmentRegistry: {\n        findFragmentSpreads: number | undefined;\n        lookup: number | undefined;\n        transform: number | undefined;\n    };\n    cache: {\n        fragmentQueryDocuments: number | undefined;\n    };\n}) | undefined;\n\nexport { gql }\n\n// @public @deprecated (undocumented)\nexport type GraphQLRequest = ApolloLink.Request;\n\n// @beta\ninterface HKT {\n    // (undocumented)\n    arg1: unknown;\n    // (undocumented)\n    arg2: unknown;\n    // (undocumented)\n    arg3: unknown;\n    // (undocumented)\n    arg4: unknown;\n    // (undocumented)\n    return: unknown;\n}\n\n// @public (undocumented)\ninterface HttpConfig {\n    // (undocumented)\n    credentials?: any;\n    // (undocumented)\n    headers?: Record<string, string>;\n    // (undocumented)\n    http?: BaseHttpLink.HttpOptions;\n    // (undocumented)\n    options?: any;\n}\n\n// @public (undocumented)\nexport namespace HttpLink {\n    export interface ContextOptions extends BaseHttpLink.ContextOptions, ClientAwarenessLink.ContextOptions {\n    }\n    export interface Options extends BaseHttpLink.Options, ClientAwarenessLink.Options {\n    }\n}\n\n// @public\nexport class HttpLink extends ApolloLink {\n    constructor(options?: HttpLink.Options);\n}\n\n// @public (undocumented)\nexport type IdGetter = (value: IdGetterObj) => string | undefined;\n\n// @public (undocumented)\nexport interface IdGetterObj extends Object {\n    // (undocumented)\n    __typename?: string;\n    // (undocumented)\n    id?: string;\n    // (undocumented)\n    _id?: string;\n}\n\n// @public (undocumented)\ninterface IgnoreModifier {\n    // (undocumented)\n    [_ignoreModifier]: true;\n}\n\n// @public (undocumented)\nconst _ignoreModifier: unique symbol;\n\n// @public (undocumented)\nnamespace Incremental {\n    // @internal @deprecated (undocumented)\n    interface Handler<Chunk extends Record<string, unknown> = Record<string, unknown>> {\n        // (undocumented)\n        extractErrors: (result: ApolloLink.Result<any>) => readonly GraphQLFormattedError[] | undefined | void;\n        // (undocumented)\n        isIncrementalResult: (result: ApolloLink.Result<any>) => result is Chunk;\n        // (undocumented)\n        prepareRequest: (request: ApolloLink.Request) => ApolloLink.Request;\n        // Warning: (ae-forgotten-export) The symbol \"Incremental\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        startRequest: <TData extends Record<string, unknown>>(request: {\n            query: DocumentNode;\n        }) => IncrementalRequest<Chunk, TData>;\n    }\n    // (undocumented)\n    interface IncrementalRequest<Chunk extends Record<string, unknown>, TData> {\n        // (undocumented)\n        handle: (cacheData: TData | DeepPartial<TData> | undefined | null, chunk: Chunk) => FormattedExecutionResult<TData>;\n        // (undocumented)\n        hasNext: boolean;\n    }\n    // (undocumented)\n    type Path = ReadonlyArray<string | number>;\n    // @internal @deprecated (undocumented)\n    interface StreamFieldInfo {\n        // (undocumented)\n        isFirstChunk: boolean;\n        // (undocumented)\n        isLastChunk: boolean;\n    }\n}\n\n// @public (undocumented)\ntype InferContextValueFromResolvers<TResolvers> = TResolvers extends {\n    [typename: string]: infer TFieldResolvers;\n} ? TFieldResolvers extends ({\n    [field: string]: LocalState.Resolver<any, any, infer TContext, any>;\n}) ? unknown extends TContext ? DefaultContext : TContext : DefaultContext : DefaultContext;\n\n// @public (undocumented)\nexport class InMemoryCache extends ApolloCache {\n    constructor(config?: InMemoryCacheConfig);\n    // (undocumented)\n    readonly assumeImmutableResults = true;\n    batch<TUpdateResult>(options: Cache_2.BatchOptions<InMemoryCache, TUpdateResult>): TUpdateResult;\n    // Warning: (ae-forgotten-export) The symbol \"BroadcastOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    protected broadcastWatches(options?: BroadcastOptions): void;\n    // (undocumented)\n    protected config: InMemoryCacheConfig;\n    // (undocumented)\n    diff<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.DiffOptions<TData, TVariables>): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    evict(options: Cache_2.EvictOptions): boolean;\n    // (undocumented)\n    extract(optimistic?: boolean): NormalizedCacheObject;\n    // (undocumented)\n    fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string): boolean;\n    // (undocumented)\n    gc(options?: {\n        resetResultCache?: boolean;\n    }): string[];\n    // Warning: (ae-forgotten-export) The symbol \"getInMemoryCacheMemoryInternals\" needs to be exported by the entry point index.d.ts\n    //\n    // @internal @deprecated\n    getMemoryInternals?: typeof getInMemoryCacheMemoryInternals;\n    // (undocumented)\n    identify(object: StoreObject | Reference): string | undefined;\n    // (undocumented)\n    lookupFragment(fragmentName: string): FragmentDefinitionNode | null;\n    // (undocumented)\n    readonly makeVar: typeof makeVar;\n    // (undocumented)\n    modify<Entity extends Record<string, any> = Record<string, any>>(options: Cache_2.ModifyOptions<Entity>): boolean;\n    // (undocumented)\n    performTransaction(update: (cache: InMemoryCache) => any, optimisticId?: string | null): any;\n    // (undocumented)\n    readonly policies: Policies;\n    // (undocumented)\n    read<TData = unknown>(options: Cache_2.ReadOptions<TData, OperationVariables> & {\n        returnPartialData: true;\n    }): TData | DeepPartial<TData> | null;\n    // (undocumented)\n    read<TData = unknown>(options: Cache_2.ReadOptions<TData, OperationVariables>): TData | null;\n    // (undocumented)\n    release(rootId: string, optimistic?: boolean): number;\n    // (undocumented)\n    removeOptimistic(idToRemove: string): void;\n    // (undocumented)\n    reset(options?: Cache_2.ResetOptions): Promise<void>;\n    // (undocumented)\n    resolvesClientField(typename: string, fieldName: string): boolean;\n    // (undocumented)\n    restore(data: NormalizedCacheObject): this;\n    // (undocumented)\n    retain(rootId: string, optimistic?: boolean): number;\n    // (undocumented)\n    transformDocument(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    watch<TData = unknown, TVariables extends OperationVariables = OperationVariables>(watch: Cache_2.WatchOptions<TData, TVariables>): () => void;\n    // (undocumented)\n    write<TData = unknown, TVariables extends OperationVariables = OperationVariables>(options: Cache_2.WriteOptions<TData, TVariables>): Reference | undefined;\n}\n\n// @public (undocumented)\nexport interface InMemoryCacheConfig extends ApolloReducerConfig {\n    // Warning: (ae-forgotten-export) The symbol \"FragmentRegistryAPI\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    fragments?: FragmentRegistryAPI;\n    // (undocumented)\n    possibleTypes?: PossibleTypesMap;\n    // (undocumented)\n    resultCaching?: boolean;\n    // (undocumented)\n    typePolicies?: TypePolicies;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"RefetchQueriesIncludeShorthand\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport type InternalRefetchQueriesInclude = InternalRefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// @public (undocumented)\nexport type InternalRefetchQueriesMap<TResult> = Map<ObservableQuery<any>, InternalRefetchQueriesResult<TResult>>;\n\n// @public (undocumented)\nexport interface InternalRefetchQueriesOptions<TCache extends ApolloCache, TResult> extends Omit<ApolloClient.RefetchQueriesOptions<TCache, TResult>, \"include\"> {\n    // (undocumented)\n    include?: InternalRefetchQueriesInclude;\n    // (undocumented)\n    removeOptimistic?: string;\n}\n\n// @public (undocumented)\nexport type InternalRefetchQueriesResult<TResult> = TResult extends boolean ? Promise<ApolloClient.QueryResult<any>> : TResult;\n\n// @public (undocumented)\nexport type InternalRefetchQueryDescriptor = RefetchQueryDescriptor | ApolloClient.QueryOptions;\n\n// @internal @deprecated (undocumented)\nexport namespace InternalTypes {\n    export type { NextFetchPolicyContext, QueryManager };\n}\n\n// @public (undocumented)\ninterface InvalidateModifier {\n    // (undocumented)\n    [_invalidateModifier]: true;\n}\n\n// @public (undocumented)\nconst _invalidateModifier: unique symbol;\n\n// @internal @deprecated (undocumented)\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n\n// @public\nexport function isNetworkRequestSettled(networkStatus?: NetworkStatus): boolean;\n\n// @public\nexport function isReference(obj: any): obj is Reference;\n\n// @public (undocumented)\ntype KeyArgsFunction = (args: Record<string, any> | null, context: {\n    typename: string;\n    fieldName: string;\n    field: FieldNode | null;\n    variables?: Record<string, any>;\n}) => KeySpecifier | false | ReturnType<IdGetter>;\n\n// @public (undocumented)\ntype KeyFieldsContext = {\n    typename: string | undefined;\n    storeObject: StoreObject;\n    readField: ReadFieldFunction;\n    selectionSet?: SelectionSetNode;\n    fragmentMap?: FragmentMap;\n    keyObject?: Record<string, any>;\n};\n\n// @public (undocumented)\ntype KeyFieldsFunction = (object: Readonly<StoreObject>, context: KeyFieldsContext) => KeySpecifier | false | ReturnType<IdGetter>;\n\n// @public (undocumented)\ntype KeySpecifier = ReadonlyArray<string | KeySpecifier>;\n\n// @public (undocumented)\nclass Layer extends EntityStore {\n    constructor(id: string, parent: EntityStore, replay: (layer: EntityStore) => any, group: CacheGroup);\n    // (undocumented)\n    addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // (undocumented)\n    findChildRefIds(dataId: string): Record<string, true>;\n    // (undocumented)\n    getStorage(...args: Parameters<EntityStore[\"getStorage\"]>): StorageType;\n    // (undocumented)\n    readonly group: CacheGroup;\n    // (undocumented)\n    readonly id: string;\n    // (undocumented)\n    readonly parent: EntityStore;\n    // (undocumented)\n    removeLayer(layerId: string): EntityStore;\n    // (undocumented)\n    readonly replay: (layer: EntityStore) => any;\n    // (undocumented)\n    toObject(): NormalizedCacheObject;\n}\n\n// @public\nexport const LinkError: {\n    is: (error: unknown) => boolean;\n};\n\n// @public (undocumented)\nnamespace LocalState {\n    // Warning: (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    type ContextFunction<TContext> = (options: ContextFunctionOptions) => TContext;\n    // (undocumented)\n    interface ContextFunctionOptions {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        document: DocumentNode;\n        // (undocumented)\n        phase: \"exports\" | \"resolve\";\n        // (undocumented)\n        requestContext: DefaultContext;\n        // (undocumented)\n        variables: OperationVariables;\n    }\n    // Warning: (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"MaybeRequireContextFunction\" needs to be exported by the entry point index.d.ts\n    type Options<TResolvers extends Resolvers = Resolvers, TContext = DefaultContext> = {\n        context?: ContextFunction<TContext>;\n        resolvers?: TResolvers;\n    } & MaybeRequireContextFunction<TContext>;\n    // (undocumented)\n    type Path = Array<string | number>;\n    type Resolver<TResult = unknown, TParent = unknown, TContext = DefaultContext, TArgs = Record<string, unknown>> = (rootValue: TParent, args: TArgs, context: {\n        requestContext: TContext;\n        client: ApolloClient;\n        phase: \"exports\" | \"resolve\";\n    }, info: {\n        field: FieldNode;\n        fragmentMap: FragmentMap;\n        path: Path;\n    }) => TResult | Promise<TResult>;\n    interface Resolvers<TContext = any> {\n        // (undocumented)\n        [typename: string]: {\n            [field: string]: Resolver<any, any, TContext, any>;\n        };\n    }\n    // Warning: (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    type RootValueFunction<TRootValue> = (context: RootValueFunctionContext) => TRootValue;\n    // (undocumented)\n    interface RootValueFunctionContext {\n        // (undocumented)\n        client: ApolloClient;\n        // (undocumented)\n        context: DefaultContext;\n        // (undocumented)\n        document: DocumentNode;\n        // (undocumented)\n        phase: \"exports\" | \"resolve\";\n        // (undocumented)\n        variables: OperationVariables;\n    }\n}\n\n// Warning: (ae-forgotten-export) The symbol \"InferContextValueFromResolvers\" needs to be exported by the entry point index.d.ts\n//\n// @public\nclass LocalState<TResolvers extends LocalState.Resolvers = LocalState.Resolvers<DefaultContext>, TContext = InferContextValueFromResolvers<TResolvers>> {\n    constructor(...[options]: {} extends TResolvers ? [\n    options?: LocalState.Options<TResolvers, NoInfer_2<TContext>>\n    ] : [\n    options: LocalState.Options<TResolvers, NoInfer_2<TContext>> & {\n        resolvers: TResolvers;\n    }\n    ]);\n    addResolvers(resolvers: TResolvers): void;\n    // (undocumented)\n    execute<TData = unknown, TVariables extends OperationVariables = OperationVariables>({ document, client, context, remoteResult, variables, onlyRunForcedResolvers, returnPartialData, fetchPolicy, }: {\n        document: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        client: ApolloClient;\n        context: DefaultContext | undefined;\n        remoteResult: FormattedExecutionResult<any> | undefined;\n        variables: TVariables | undefined;\n        onlyRunForcedResolvers?: boolean;\n        returnPartialData?: boolean;\n        fetchPolicy: WatchQueryFetchPolicy;\n    }): Promise<FormattedExecutionResult<TData>>;\n    // (undocumented)\n    getExportedVariables<TVariables extends OperationVariables = OperationVariables>({ document, client, context, variables, }: {\n        document: DocumentNode | TypedDocumentNode<any, TVariables>;\n        client: ApolloClient;\n        context: DefaultContext | undefined;\n        variables: Partial<NoInfer_2<TVariables>>;\n    }): Promise<TVariables>;\n}\n\n// @public (undocumented)\nexport namespace LocalStateError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly path?: Array<string | number>;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        path?: Array<string | number>;\n        // (undocumented)\n        sourceError?: unknown;\n    }\n}\n\n// @public\nexport class LocalStateError extends Error {\n    constructor(message: string, options?: LocalStateError.Options);\n    static is(error: unknown): error is LocalStateError;\n    readonly path?: Array<string | number>;\n}\n\n// @public (undocumented)\nexport function makeVar<T>(value: T): ReactiveVar<T>;\n\n// @public (undocumented)\ninterface MaskFragmentOptions<TData> {\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    fragment: DocumentNode;\n    // (undocumented)\n    fragmentName?: string;\n}\n\n// @public (undocumented)\ninterface MaskOperationOptions<TData> {\n    cause?: object;\n    // (undocumented)\n    data: TData;\n    // (undocumented)\n    document: DocumentNode;\n    // (undocumented)\n    fetchPolicy?: WatchQueryFetchPolicy;\n}\n\n// @public\nexport type MaybeMasked<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"MaybeMasked\", PreserveTypes.TypeOverrides, TData>;\n\n// Warning: (ae-forgotten-export) The symbol \"RemoveIndexSignature\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype MaybeRequireContextFunction<TContext> = {} extends RemoveIndexSignature<TContext> ? {} : {\n    context: LocalState.ContextFunction<TContext>;\n};\n\n// @public (undocumented)\nexport interface MergeInfo {\n    // (undocumented)\n    field: FieldNode;\n    // (undocumented)\n    merge: FieldMergeFunction;\n    // (undocumented)\n    path: Array<string | number>;\n    // (undocumented)\n    typename: string | undefined;\n}\n\n// @public (undocumented)\ntype MergeObjectsFunction = <T extends StoreObject | Reference>(existing: T, incoming: T) => T;\n\n// @public (undocumented)\nexport interface MergeTree {\n    // (undocumented)\n    info?: MergeInfo;\n    // (undocumented)\n    map: Map<string | number, MergeTree>;\n}\n\n// @public (undocumented)\nexport class MissingFieldError extends Error {\n    constructor(message: string, path: MissingTree | Array<string | number>, query: DocumentNode, variables?: Record<string, any> | undefined);\n    // (undocumented)\n    readonly message: string;\n    // (undocumented)\n    readonly missing: MissingTree;\n    // (undocumented)\n    readonly path: MissingTree | Array<string | number>;\n    // (undocumented)\n    readonly query: DocumentNode;\n    // (undocumented)\n    readonly variables?: Record<string, any> | undefined;\n}\n\n// @public (undocumented)\ntype MissingTree = string | {\n    readonly [key: string]: MissingTree;\n};\n\n// Warning: (ae-forgotten-export) The symbol \"ModifierDetails\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"DeleteModifier\" needs to be exported by the entry point index.d.ts\n// Warning: (ae-forgotten-export) The symbol \"InvalidateModifier\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype Modifier<T> = (value: T, details: ModifierDetails) => DeepPartial<T> | DeleteModifier | InvalidateModifier | undefined;\n\n// @public (undocumented)\ntype ModifierDetails = {\n    DELETE: DeleteModifier;\n    INVALIDATE: InvalidateModifier;\n    fieldName: string;\n    storeFieldName: string;\n    readField: ReadFieldFunction;\n    canRead: CanReadFunction;\n    isReference: typeof isReference;\n    toReference: ToReferenceFunction;\n    storage: StorageType;\n};\n\n// @public (undocumented)\ntype Modifiers<T extends Record<string, any> = Record<string, unknown>> = Partial<{\n    [FieldName in keyof T]: Modifier<StoreObjectValueMaybeReference<Exclude<T[FieldName], undefined>>>;\n}>;\n\n// @public @deprecated (undocumented)\nexport type MutateResult<TData = unknown> = ApolloClient.MutateResult<TData>;\n\n// @public (undocumented)\nexport type MutationFetchPolicy = Extract<FetchPolicy, \"network-only\" | \"no-cache\">;\n\n// @public @deprecated (undocumented)\nexport type MutationOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables, TCache extends ApolloCache = ApolloCache> = ApolloClient.MutateOptions<TData, TVariables, TCache>;\n\n// @public (undocumented)\nexport type MutationQueryReducer<T> = (previousResult: Record<string, any>, options: {\n    mutationResult: NormalizedExecutionResult<Unmasked<T>>;\n    queryName: string | undefined;\n    queryVariables: Record<string, any>;\n}) => Record<string, any>;\n\n// @public (undocumented)\nexport type MutationQueryReducersMap<T = {\n    [key: string]: any;\n}> = {\n    [queryName: string]: MutationQueryReducer<T>;\n};\n\n// @public (undocumented)\ninterface MutationStoreValue {\n    // (undocumented)\n    error: Error | null;\n    // (undocumented)\n    loading: boolean;\n    // (undocumented)\n    mutation: DocumentNode;\n    // (undocumented)\n    variables: Record<string, any>;\n}\n\n// @public (undocumented)\nexport type MutationUpdaterFunction<TData, TVariables extends OperationVariables, TCache extends ApolloCache> = (cache: TCache, result: FormattedExecutionResult<Unmasked<TData>>, options: {\n    context?: DefaultContext;\n    variables?: TVariables;\n}) => void;\n\n// @public\nexport enum NetworkStatus {\n    error = 8,\n    fetchMore = 3,\n    loading = 1,\n    poll = 6,\n    ready = 7,\n    refetch = 4,\n    setVariables = 2,\n    streaming = 9\n}\n\n// @public (undocumented)\ninterface NextFetchPolicyContext<TData, TVariables extends OperationVariables> {\n    // (undocumented)\n    initialFetchPolicy: WatchQueryFetchPolicy;\n    // (undocumented)\n    observable: ObservableQuery<TData, TVariables>;\n    // (undocumented)\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n    // (undocumented)\n    reason: \"after-fetch\" | \"variables-changed\";\n}\n\n// @public @deprecated\ntype NoInfer_2<T> = [T][T extends any ? 0 : never];\n\n// @public\nexport interface NormalizedCache {\n    // (undocumented)\n    canRead: CanReadFunction;\n    // (undocumented)\n    clear(): void;\n    // (undocumented)\n    delete(dataId: string, fieldName?: string): boolean;\n    // (undocumented)\n    get(dataId: string, fieldName: string): StoreValue;\n    // Warning: (ae-forgotten-export) The symbol \"FieldValueGetter\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getFieldValue: FieldValueGetter;\n    // (undocumented)\n    getStorage(idOrObj: string | StoreObject, ...storeFieldNames: (string | number)[]): StorageType;\n    // (undocumented)\n    has(dataId: string): boolean;\n    // (undocumented)\n    merge(olderId: string, newerObject: StoreObject): void;\n    // (undocumented)\n    merge(olderObject: StoreObject, newerId: string): void;\n    // (undocumented)\n    modify<Entity extends Record<string, any>>(dataId: string, fields: Modifiers<Entity> | AllFieldsModifier<Entity>, exact: boolean): boolean;\n    // (undocumented)\n    release(rootId: string): number;\n    replace(newData: NormalizedCacheObject): void;\n    retain(rootId: string): number;\n    toObject(): NormalizedCacheObject;\n    // (undocumented)\n    toReference: ToReferenceFunction;\n}\n\n// @public\nexport interface NormalizedCacheObject {\n    // (undocumented)\n    [dataId: string]: StoreObject | undefined;\n    // (undocumented)\n    __META?: {\n        extraRootIds: string[];\n    };\n}\n\n// @public\nexport type NormalizedExecutionResult<TData = Record<string, unknown>, TExtensions = Record<string, unknown>> = Omit<FormattedExecutionResult<TData, TExtensions>, \"data\"> & GetDataState<TData, \"streaming\" | \"complete\">;\n\n// @public (undocumented)\nnamespace NotImplementedHandler {\n    // (undocumented)\n    interface NotImplementedResult extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        arg2: unknown;\n        // (undocumented)\n        return: never;\n    }\n    // (undocumented)\n    interface TypeOverrides {\n        // Warning: (ae-forgotten-export) The symbol \"NotImplementedHandler\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        AdditionalApolloLinkResultTypes: NotImplementedResult;\n    }\n}\n\n// @public (undocumented)\nclass NotImplementedHandler implements Incremental.Handler<never> {\n    // (undocumented)\n    extractErrors(): void;\n    // (undocumented)\n    isIncrementalResult(_: any): _ is never;\n    // (undocumented)\n    prepareRequest(request: ApolloLink.Request): ApolloLink.Request;\n    // (undocumented)\n    startRequest: any;\n}\n\nexport { Observable }\n\n// @public (undocumented)\ninterface ObservableAndInfo<TData> {\n    // (undocumented)\n    fromLink: boolean;\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    observable: Observable<QueryNotification.Value<TData>>;\n}\n\n// @public (undocumented)\nexport namespace ObservableQuery {\n    // @internal @deprecated\n    export interface CacheWatchOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> extends Cache_2.WatchOptions<TData, TVariables> {\n        // @deprecated\n        lastOwnDiff?: Cache_2.DiffResult<TData>;\n    }\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface ObservableMethods<TData, OperatorResult> {\n            pipe(...operators: OperatorFunctionChain<ObservableQuery.Result<TData>, OperatorResult>): Observable<OperatorResult>;\n            subscribe(observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)): Subscription;\n        }\n        // (undocumented)\n        export type OperatorFunctionChain<From, To> = [];\n    }\n    // (undocumented)\n    export type FetchMoreOptions<TData, TVariables extends OperationVariables, TFetchData = TData, TFetchVars extends OperationVariables = TVariables> = {\n        query?: DocumentNode | TypedDocumentNode<TFetchData, TFetchVars>;\n        variables?: Partial<NoInfer<TFetchVars>>;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        updateQuery?: (previousQueryResult: Unmasked<TData>, options: {\n            fetchMoreResult: Unmasked<TFetchData>;\n            variables: TFetchVars;\n        }) => Unmasked<TData>;\n    };\n    // (undocumented)\n    export type Options<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {\n        fetchPolicy: WatchQueryFetchPolicy;\n        nextFetchPolicy?: WatchQueryFetchPolicy | ((this: ApolloClient.WatchQueryOptions<TData, TVariables>, currentFetchPolicy: WatchQueryFetchPolicy, context: NextFetchPolicyContext<TData, TVariables>) => WatchQueryFetchPolicy);\n        initialFetchPolicy: WatchQueryFetchPolicy;\n        refetchWritePolicy?: RefetchWritePolicy;\n        errorPolicy?: ErrorPolicy;\n        context?: DefaultContext;\n        pollInterval?: number;\n        notifyOnNetworkStatusChange?: boolean;\n        returnPartialData?: boolean;\n        skipPollAttempt?: () => boolean;\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        variables: TVariables;\n    };\n    // (undocumented)\n    export type Result<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = {\n        error?: ErrorLike;\n        loading: boolean;\n        networkStatus: NetworkStatus;\n        partial: boolean;\n    } & GetDataState<TData, TStates>;\n    export interface ResultPromise<T> extends Promise<T> {\n        retain(): this;\n    }\n    // (undocumented)\n    export interface SubscribeToMoreOptions<TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> {\n        // (undocumented)\n        context?: DefaultContext;\n        // (undocumented)\n        document: DocumentNode | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;\n        // (undocumented)\n        onError?: (error: ErrorLike) => void;\n        // (undocumented)\n        updateQuery?: SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n        // (undocumented)\n        variables?: TSubscriptionVariables;\n    }\n}\n\n// @public (undocumented)\nexport class ObservableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables> implements Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>, InteropObservable<ObservableQuery.Result<MaybeMasked<TData>>> {\n    // (undocumented)\n    [\"@@observable\"]: () => Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>;\n    // (undocumented)\n    [Symbol.observable]: () => Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>;\n    constructor({ queryManager, options, transformedQuery, }: {\n        queryManager: QueryManager;\n        options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n        transformedQuery?: DocumentNode | TypedDocumentNode<TData, TVariables>;\n        queryId?: string;\n    });\n    // @internal @deprecated (undocumented)\n    applyOptions(newOptions: Partial<ObservableQuery.Options<TData, TVariables>>): void;\n    fetchMore<TFetchData = TData, TFetchVars extends OperationVariables = TVariables>(options: ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>): Promise<ApolloClient.QueryResult<TFetchData>>;\n    // @internal @deprecated (undocumented)\n    getCacheDiff({ optimistic }?: {\n        optimistic?: boolean | undefined;\n    }): Cache_2.DiffResult<TData>;\n    // (undocumented)\n    getCurrentResult(): ObservableQuery.Result<MaybeMasked<TData>>;\n    // (undocumented)\n    hasObservers(): boolean;\n    // @internal @deprecated\n    _lastWrite?: unknown;\n    // @internal @deprecated (undocumented)\n    notify(scheduled?: boolean): void;\n    // (undocumented)\n    readonly options: ObservableQuery.Options<TData, TVariables>;\n    pipe: Observable<ObservableQuery.Result<MaybeMasked<TData>>>[\"pipe\"];\n    // (undocumented)\n    get query(): TypedDocumentNode<TData, TVariables>;\n    // (undocumented)\n    readonly queryName?: string;\n    refetch(variables?: Partial<TVariables>): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;\n    reobserve(newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>): ObservableQuery.ResultPromise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // @internal @deprecated\n    reset(): void;\n    setVariables(variables: TVariables): Promise<ApolloClient.QueryResult<TData>>;\n    startPolling(pollInterval: number): void;\n    stop(): void;\n    stopPolling(): void;\n    subscribe: (observerOrNext: Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>> | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)) => Subscription;\n    subscribeToMore<TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>): () => void;\n    updateQuery(mapFn: UpdateQueryMapFn<TData, TVariables>): void;\n    get variables(): TVariables;\n}\n\n// @public (undocumented)\nexport type OnQueryUpdated<TResult> = (observableQuery: ObservableQuery<any>, diff: Cache_2.DiffResult<any>, lastDiff: Cache_2.DiffResult<any> | undefined) => boolean | TResult;\n\n// @public @deprecated (undocumented)\nexport type Operation = ApolloLink.Operation;\n\n// @public (undocumented)\nexport type OperationVariables = Record<string, any>;\n\n// @public (undocumented)\nexport type OptimisticStoreItem = {\n    id: string;\n    data: NormalizedCacheObject;\n    transaction: Transaction;\n};\n\n// @public (undocumented)\nnamespace OverridableTypes {\n    // (undocumented)\n    interface Complete extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n    // (undocumented)\n    interface Defaults {\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Complete: Complete;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Partial: Partial;\n        // Warning: (ae-forgotten-export) The symbol \"OverridableTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        Streaming: Streaming;\n    }\n    // (undocumented)\n    interface Partial extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: DeepPartial<this[\"arg1\"]>;\n    }\n    // (undocumented)\n    interface Streaming extends HKT {\n        // (undocumented)\n        arg1: unknown;\n        // (undocumented)\n        return: this[\"arg1\"];\n    }\n}\n\n// @public (undocumented)\nexport function parseAndCheckHttpResponse(operations: ApolloLink.Operation | ApolloLink.Operation[]): (response: Response) => Promise<any>;\n\n// @public (undocumented)\nclass Policies {\n    constructor(config: {\n        cache: InMemoryCache;\n        dataIdFromObject?: KeyFieldsFunction;\n        possibleTypes?: PossibleTypesMap;\n        typePolicies?: TypePolicies;\n    });\n    // (undocumented)\n    addPossibleTypes(possibleTypes: PossibleTypesMap): void;\n    // (undocumented)\n    addTypePolicies(typePolicies: TypePolicies): void;\n    // (undocumented)\n    readonly cache: InMemoryCache;\n    // (undocumented)\n    fragmentMatches(fragment: InlineFragmentNode | FragmentDefinitionNode, typename: string | undefined, result?: Record<string, any>, variables?: Record<string, any>): boolean;\n    // (undocumented)\n    getMergeFunction(parentTypename: string | undefined, fieldName: string, childTypename: string | undefined): FieldMergeFunction | undefined;\n    // (undocumented)\n    getReadFunction(typename: string | undefined, fieldName: string): FieldReadFunction | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"FieldSpecifier\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getStoreFieldName(fieldSpec: FieldSpecifier): string;\n    // (undocumented)\n    hasKeyArgs(typename: string | undefined, fieldName: string): boolean;\n    // (undocumented)\n    identify(object: StoreObject, partialContext?: Partial<KeyFieldsContext>): [string?, StoreObject?];\n    // Warning: (ae-forgotten-export) The symbol \"ReadFieldOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readField<V = StoreValue>(options: ReadFieldOptions, context: ReadMergeModifyContext): SafeReadonly<V> | undefined;\n    // (undocumented)\n    readonly rootIdsByTypename: Record<string, string>;\n    // (undocumented)\n    readonly rootTypenamesById: Record<string, string>;\n    // (undocumented)\n    runMergeFunction(existing: StoreValue, incoming: StoreValue, { field, typename, merge, path }: MergeInfo, context: WriteContext, storage?: StorageType): any;\n    // (undocumented)\n    readonly usingPossibleTypes = false;\n}\n\n// @public (undocumented)\nexport type PossibleTypesMap = {\n    [supertype: string]: string[];\n};\n\n// @public (undocumented)\nnamespace PreserveTypes {\n    // (undocumented)\n    type FragmentType<_TData> = never;\n    // (undocumented)\n    namespace HKTImplementation {\n        // (undocumented)\n        interface FragmentType extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: never;\n        }\n        // (undocumented)\n        interface MaybeMasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: this[\"arg1\"];\n        }\n        // (undocumented)\n        interface Unmasked extends HKT {\n            // (undocumented)\n            arg1: unknown;\n            // (undocumented)\n            return: this[\"arg1\"];\n        }\n    }\n    // (undocumented)\n    type MaybeMasked<TData> = TData;\n    // (undocumented)\n    interface TypeOverrides {\n        // Warning: (ae-forgotten-export) The symbol \"PreserveTypes\" needs to be exported by the entry point index.d.ts\n        //\n        // (undocumented)\n        FragmentType: HKTImplementation.FragmentType;\n        // (undocumented)\n        MaybeMasked: HKTImplementation.MaybeMasked;\n        // (undocumented)\n        Unmasked: HKTImplementation.Unmasked;\n    }\n    // (undocumented)\n    type Unmasked<TData> = TData;\n}\n\n// @internal @deprecated (undocumented)\ntype Prettify<T> = {\n    [K in keyof T]: T[K];\n} & {};\n\n// @internal @deprecated (undocumented)\ntype Primitive = null | undefined | string | number | boolean | symbol | bigint;\n\n// @public (undocumented)\nnamespace QueryManager {\n    // (undocumented)\n    type Result<TData, TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"]> = ObservableQuery.Result<TData, TStates> & {\n        [extensionsSymbol]?: ExtensionsWithStreamInfo;\n    };\n}\n\n// @public (undocumented)\nclass QueryManager {\n    // Warning: (ae-forgotten-export) The symbol \"QueryManagerOptions\" needs to be exported by the entry point index.d.ts\n    constructor(options: QueryManagerOptions);\n    // (undocumented)\n    readonly assumeImmutableResults: boolean;\n    // (undocumented)\n    broadcastQueries(): void;\n    // (undocumented)\n    get cache(): ApolloCache;\n    // (undocumented)\n    clearStore(options?: Cache_2.ResetOptions): Promise<void>;\n    // (undocumented)\n    readonly client: ApolloClient;\n    readonly clientOptions: ApolloClient.Options;\n    // (undocumented)\n    readonly dataMasking: boolean;\n    // (undocumented)\n    readonly defaultContext: Partial<DefaultContext>;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    readonly documentTransform: DocumentTransform;\n    // (undocumented)\n    protected fetchCancelFns: Map<string, (error: any) => any>;\n    // Warning: (ae-forgotten-export) The symbol \"ObservableAndInfo\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    fetchObservableWithInfo<TData, TVariables extends OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>, { networkStatus, query, fetchQueryOperator, onCacheHit, observableQuery, exposeExtensions, }: {\n        networkStatus?: NetworkStatus;\n        query?: DocumentNode;\n        fetchQueryOperator?: <T>(source: Observable<T>) => Observable<T>;\n        onCacheHit?: () => void;\n        observableQuery?: ObservableQuery<TData, TVariables> | undefined;\n        exposeExtensions?: boolean;\n    }): ObservableAndInfo<TData>;\n    // (undocumented)\n    fetchQuery<TData, TVariables extends OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>, networkStatus?: NetworkStatus): Promise<ApolloClient.QueryResult<TData>>;\n    // (undocumented)\n    generateRequestId(): number;\n    // Warning: (ae-forgotten-export) The symbol \"TransformCacheEntry\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    getDocumentInfo(document: DocumentNode): TransformCacheEntry;\n    // (undocumented)\n    getObservableQueries(include?: InternalRefetchQueriesInclude): Set<ObservableQuery<any, OperationVariables>>;\n    // (undocumented)\n    getVariables<TVariables extends OperationVariables>(document: DocumentNode, variables?: TVariables): TVariables;\n    // (undocumented)\n    readonly incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    protected inFlightLinkObservables: Trie<{\n        observable?: Observable<ApolloLink.Result<any>>;\n        restart?: () => void;\n    }>;\n    // (undocumented)\n    get link(): ApolloLink;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // Warning: (ae-forgotten-export) The symbol \"MaskFragmentOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    maskFragment<TData = unknown>(options: MaskFragmentOptions<TData>): TData;\n    // Warning: (ae-forgotten-export) The symbol \"MaskOperationOptions\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    maskOperation<TData = unknown>(options: MaskOperationOptions<TData>): MaybeMasked<TData>;\n    // (undocumented)\n    mutate<TData, TVariables extends OperationVariables, TCache extends ApolloCache>({ mutation, variables, optimisticResponse, updateQueries, refetchQueries, awaitRefetchQueries, update: updateWithProxyFn, onQueryUpdated, fetchPolicy, errorPolicy, keepRootFields, context, }: ApolloClient.MutateOptions<TData, TVariables, TCache> & {\n        errorPolicy: ErrorPolicy;\n        fetchPolicy: MutationFetchPolicy;\n    }): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    mutationStore?: {\n        [mutationId: string]: MutationStoreValue;\n    };\n    obsQueries: Set<ObservableQuery<any, any>>;\n    prioritizeCacheValues: boolean;\n    // (undocumented)\n    query<TData, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.QueryOptions<TData, TVariables>): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n    // (undocumented)\n    refetchObservableQueries(includeStandby?: boolean): Promise<ApolloClient.QueryResult<any>[]>;\n    // (undocumented)\n    refetchQueries<TResult>({ updateCache, include, optimistic, removeOptimistic, onQueryUpdated, }: InternalRefetchQueriesOptions<ApolloCache, TResult>): InternalRefetchQueriesMap<TResult>;\n    // (undocumented)\n    readonly ssrMode: boolean;\n    // (undocumented)\n    startGraphQLSubscription<TData = unknown>(options: ApolloClient.SubscribeOptions<TData>): SubscriptionObservable<ApolloClient.SubscribeResult<TData>>;\n    stop(): void;\n    // (undocumented)\n    transform(document: DocumentNode): DocumentNode;\n    // (undocumented)\n    watchQuery<TData, TVariables extends OperationVariables = OperationVariables>(options: ApolloClient.WatchQueryOptions<TData, TVariables>): ObservableQuery<TData, TVariables>;\n}\n\n// @public (undocumented)\ninterface QueryManagerOptions {\n    // (undocumented)\n    assumeImmutableResults: boolean;\n    // (undocumented)\n    client: ApolloClient;\n    // (undocumented)\n    clientOptions: ApolloClient.Options;\n    // (undocumented)\n    dataMasking: boolean;\n    // (undocumented)\n    defaultContext: Partial<DefaultContext> | undefined;\n    // (undocumented)\n    defaultOptions: ApolloClient.DefaultOptions;\n    // (undocumented)\n    documentTransform: DocumentTransform | null | undefined;\n    // (undocumented)\n    incrementalHandler: Incremental.Handler;\n    // (undocumented)\n    localState: LocalState | undefined;\n    // (undocumented)\n    onBroadcast: undefined | (() => void);\n    // (undocumented)\n    queryDeduplication: boolean;\n    // (undocumented)\n    ssrMode: boolean;\n}\n\n// @public (undocumented)\nnamespace QueryNotification {\n    // (undocumented)\n    type FromCache<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n        source: \"cache\";\n    };\n    // (undocumented)\n    type FromNetwork<TData> = ObservableNotification<ObservableQuery.Result<TData>> & {\n        source: \"network\";\n    };\n    // (undocumented)\n    type NewNetworkStatus = NextNotification<{\n        resetError?: boolean;\n    }> & {\n        source: \"newNetworkStatus\";\n    };\n    // (undocumented)\n    type SetResult<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n        source: \"setResult\";\n    };\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    // Warning: (ae-forgotten-export) The symbol \"QueryNotification\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    type Value<TData> = FromCache<TData> | FromNetwork<TData> | NewNetworkStatus | SetResult<TData>;\n}\n\n// @public @deprecated (undocumented)\nexport type QueryOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.QueryOptions<TData, TVariables>;\n\n// @public (undocumented)\ntype ReactiveListener<T> = (value: T) => any;\n\n// @public (undocumented)\nexport interface ReactiveVar<T> {\n    // (undocumented)\n    (newValue?: T): T;\n    // (undocumented)\n    attachCache(cache: ApolloCache): this;\n    // (undocumented)\n    forgetCache(cache: ApolloCache): boolean;\n    // Warning: (ae-forgotten-export) The symbol \"ReactiveListener\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    onNextChange(listener: ReactiveListener<T>): () => void;\n}\n\n// @public (undocumented)\ninterface ReadFieldFunction {\n    // (undocumented)\n    <V = StoreValue>(options: ReadFieldOptions): SafeReadonly<V> | undefined;\n    // (undocumented)\n    <V = StoreValue>(fieldName: string, from?: StoreObject | Reference): SafeReadonly<V> | undefined;\n}\n\n// @public (undocumented)\ninterface ReadFieldOptions extends FieldSpecifier {\n    // (undocumented)\n    from?: StoreObject | Reference;\n}\n\n// @public (undocumented)\nexport interface ReadMergeModifyContext {\n    // (undocumented)\n    extensions?: ExtensionsWithStreamInfo;\n    // (undocumented)\n    store: NormalizedCache;\n    // (undocumented)\n    variables?: OperationVariables;\n    // (undocumented)\n    varString?: string;\n}\n\n// @public (undocumented)\nexport type ReadQueryOptions = {\n    store: NormalizedCache;\n    query: DocumentNode;\n    variables?: Object;\n    previousResult?: any;\n    rootId?: string;\n    config?: ApolloReducerConfig;\n};\n\n// @public\nexport interface Reference {\n    // (undocumented)\n    readonly __ref: string;\n}\n\n// @public (undocumented)\nexport type RefetchQueriesInclude = RefetchQueryDescriptor[] | RefetchQueriesIncludeShorthand;\n\n// @public (undocumented)\ntype RefetchQueriesIncludeShorthand = \"all\" | \"active\";\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesOptions<TCache extends ApolloCache, TResult> = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n\n// @public (undocumented)\nexport type RefetchQueriesPromiseResults<TResult> = IsAny<TResult> extends true ? any[] : TResult extends boolean ? ApolloClient.QueryResult<any>[] : TResult extends PromiseLike<infer U> ? U[] : TResult[];\n\n// @public @deprecated (undocumented)\nexport type RefetchQueriesResult<TResult> = ApolloClient.RefetchQueriesResult<TResult>;\n\n// @public (undocumented)\nexport type RefetchQueryDescriptor = string | DocumentNode;\n\n// @public (undocumented)\nexport type RefetchWritePolicy = \"merge\" | \"overwrite\";\n\n// @internal @deprecated (undocumented)\ntype RemoveIndexSignature<T> = {\n    [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K];\n};\n\n// @public @deprecated (undocumented)\nexport type RequestHandler = ApolloLink.RequestHandler;\n\nexport { resetCaches }\n\n// @public (undocumented)\nexport function rewriteURIForGET(chosenURI: string, body: BaseHttpLink.Body): {\n    parseError: unknown;\n    newURI?: undefined;\n} | {\n    newURI: string;\n    parseError?: undefined;\n};\n\n// @public (undocumented)\nclass Root extends EntityStore {\n    constructor({ policies, resultCaching, seed, }: {\n        policies: Policies;\n        resultCaching?: boolean;\n        seed?: NormalizedCacheObject;\n    });\n    // (undocumented)\n    addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer;\n    // (undocumented)\n    getStorage(): StorageType;\n    // (undocumented)\n    removeLayer(): Root;\n    // (undocumented)\n    readonly storageTrie: Trie<StorageType>;\n    // Warning: (ae-forgotten-export) The symbol \"Stump\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    readonly stump: Stump;\n}\n\n// @public (undocumented)\ntype SafeReadonly<T> = T extends object ? Readonly<T> : T;\n\n// Warning: (ae-forgotten-export) The symbol \"HttpConfig\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function selectHttpOptionsAndBody(operation: ApolloLink.Operation, fallbackConfig: HttpConfig, ...configs: Array<HttpConfig>): {\n    options: HttpConfig & Record<string, any>;\n    body: BaseHttpLink.Body;\n};\n\n// @public (undocumented)\nexport function selectHttpOptionsAndBodyInternal(operation: ApolloLink.Operation, printer: BaseHttpLink.Printer, ...configs: HttpConfig[]): {\n    options: HttpConfig & Record<string, any>;\n    body: BaseHttpLink.Body;\n};\n\n// @public (undocumented)\nexport const selectURI: (operation: ApolloLink.Operation, fallbackURI?: string | ((operation: ApolloLink.Operation) => string)) => any;\n\n// @public (undocumented)\nexport namespace ServerError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly bodyText: string;\n            readonly response: Response;\n            readonly statusCode: number;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        bodyText: string;\n        // (undocumented)\n        response: Response;\n    }\n}\n\n// @public\nexport class ServerError extends Error {\n    constructor(message: string, options: ServerError.Options);\n    readonly bodyText: string;\n    static is(error: unknown): error is ServerError;\n    readonly response: Response;\n    readonly statusCode: number;\n}\n\n// @public (undocumented)\nexport namespace ServerParseError {\n    // (undocumented)\n    export namespace DocumentationTypes {\n        // (undocumented)\n        export interface InstanceProperties {\n            readonly bodyText: string;\n            readonly response: Response;\n            readonly statusCode: number;\n        }\n    }\n    // (undocumented)\n    export interface Options {\n        // (undocumented)\n        bodyText: string;\n        // (undocumented)\n        response: Response;\n    }\n}\n\n// @public\nexport class ServerParseError extends Error {\n    constructor(originalParseError: unknown, options: ServerParseError.Options);\n    readonly bodyText: string;\n    static is(error: unknown): error is ServerParseError;\n    readonly response: Response;\n    readonly statusCode: number;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"VerbosityLevel\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\nexport function setLogVerbosity(level: VerbosityLevel): VerbosityLevel;\n\n// @public @deprecated (undocumented)\nexport const split: typeof ApolloLink.split;\n\n// @public (undocumented)\ntype StorageType = Record<string, any>;\n\n// @public\nexport interface StoreObject {\n    // (undocumented)\n    [storeFieldName: string]: StoreValue;\n    // (undocumented)\n    __typename?: string;\n}\n\n// Warning: (ae-forgotten-export) The symbol \"AsStoreObject\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype StoreObjectValueMaybeReference<StoreVal> = StoreVal extends ReadonlyArray<Record<string, any>> ? StoreVal extends ReadonlyArray<infer Item> ? [\nItem\n] extends [Record<string, any>] ? ReadonlyArray<AsStoreObject<Item> | Reference> : never : never : StoreVal extends Record<string, any> ? AsStoreObject<StoreVal> | Reference : StoreVal;\n\n// @public\nexport type StoreValue = number | string | string[] | Reference | Reference[] | null | undefined | void | Object;\n\n// @public\nconst streamInfoSymbol: unique symbol;\n\n// @internal @deprecated (undocumented)\ntype StreamInfoTrie = Trie<{\n    current: Incremental.StreamFieldInfo;\n    previous?: {\n        incoming: unknown;\n        streamFieldInfo: Incremental.StreamFieldInfo;\n        result: unknown;\n    };\n}>;\n\n// @public (undocumented)\nclass Stump extends Layer {\n    constructor(root: Root);\n    // (undocumented)\n    merge(older: string | StoreObject, newer: string | StoreObject): void;\n    // (undocumented)\n    removeLayer(): this;\n}\n\n// @public (undocumented)\nexport interface SubscribeToMoreFunction<TData, TVariables extends OperationVariables = OperationVariables> {\n    // (undocumented)\n    <TSubscriptionData = TData, TSubscriptionVariables extends OperationVariables = TVariables>(options: ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>): () => void;\n}\n\n// @public @deprecated (undocumented)\nexport type SubscribeToMoreOptions<TData = unknown, TSubscriptionVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData, TVariables extends OperationVariables = TSubscriptionVariables> = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\n// @public (undocumented)\nexport type SubscribeToMoreUpdateQueryFn<TData = unknown, TVariables extends OperationVariables = OperationVariables, TSubscriptionData = TData> = {\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables> & {\n        subscriptionData: {\n            data: Unmasked<TSubscriptionData>;\n        };\n    }): Unmasked<TData> | void;\n};\n\n// @public\nexport interface SubscriptionObservable<T> extends Observable<T> {\n    restart: () => void;\n}\n\n// @public @deprecated (undocumented)\nexport type SubscriptionOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.SubscribeOptions<TData, TVariables>;\n\n// @public (undocumented)\ntype ToReferenceFunction = (objOrIdOrRef: StoreObject | string | Reference, mergeIntoStore?: boolean) => Reference | undefined;\n\n// @public (undocumented)\nexport type Transaction = (c: ApolloCache) => void;\n\n// @public (undocumented)\ninterface TransformCacheEntry {\n    // (undocumented)\n    asQuery: DocumentNode;\n    // (undocumented)\n    clientQuery: DocumentNode | null;\n    // (undocumented)\n    defaultVars: OperationVariables;\n    // (undocumented)\n    hasClientExports: boolean;\n    // (undocumented)\n    hasForcedResolvers: boolean;\n    // (undocumented)\n    hasIncrementalDirective: boolean;\n    // (undocumented)\n    hasNonreactiveDirective: boolean;\n    // (undocumented)\n    nonReactiveQuery: DocumentNode;\n    // (undocumented)\n    operationType: OperationTypeNode | undefined;\n    // (undocumented)\n    serverQuery: DocumentNode | null;\n    // (undocumented)\n    violation?: Error | undefined;\n}\n\n// @public (undocumented)\ntype TransformFn = (document: DocumentNode) => DocumentNode;\n\nexport { TypedDocumentNode }\n\n// @public (undocumented)\nexport interface TypeOverrides {\n}\n\n// @public (undocumented)\nexport type TypePolicies = {\n    [__typename: string]: TypePolicy;\n};\n\n// @public (undocumented)\nexport type TypePolicy = {\n    keyFields?: KeySpecifier | KeyFieldsFunction | false;\n    merge?: FieldMergeFunction | boolean;\n    queryType?: true;\n    mutationType?: true;\n    subscriptionType?: true;\n    fields?: {\n        [fieldName: string]: FieldPolicy<any> | FieldReadFunction<any>;\n    };\n};\n\n// @public\nexport class UnconventionalError extends Error {\n    constructor(errorType: unknown);\n    static is(error: unknown): error is UnconventionalError;\n}\n\n// @public\nexport type Unmasked<TData> = ApplyHKTImplementationWithDefault<TypeOverrides, \"Unmasked\", PreserveTypes.TypeOverrides, TData>;\n\n// @public (undocumented)\nexport interface UpdateQueryMapFn<TData = unknown, TVariables extends OperationVariables = OperationVariables> {\n    // (undocumented)\n    (\n    unsafePreviousData: DeepPartial<Unmasked<TData>>, options: UpdateQueryOptions<TData, TVariables>): Unmasked<TData> | void;\n}\n\n// @public (undocumented)\nexport type UpdateQueryOptions<TData, TVariables extends OperationVariables> = {\n    variables?: TVariables;\n} & ({\n    complete: true;\n    previousData: Unmasked<TData>;\n} | {\n    complete: false;\n    previousData: DeepPartial<Unmasked<TData>> | undefined;\n});\n\n// @internal @deprecated (undocumented)\ntype VariablesOption<TVariables extends OperationVariables> = {} extends TVariables ? {\n    variables?: TVariables;\n} : {\n    variables: TVariables;\n};\n\n// @internal @deprecated\nconst variablesUnknownSymbol: unique symbol;\n\n// Warning: (ae-forgotten-export) The symbol \"verbosityLevels\" needs to be exported by the entry point index.d.ts\n//\n// @public (undocumented)\ntype VerbosityLevel = (typeof verbosityLevels)[number];\n\n// @public (undocumented)\nconst verbosityLevels: readonly [\"debug\", \"log\", \"warn\", \"error\", \"silent\"];\n\n// @public (undocumented)\nexport const version: string;\n\n// @public @deprecated (undocumented)\nexport type WatchFragmentOptions<TData = unknown, TVariables extends OperationVariables = OperationVariables> = ApolloCache.WatchFragmentOptions<TData, TVariables>;\n\n// @public @deprecated (undocumented)\nexport type WatchFragmentResult<TData> = ApolloCache.WatchFragmentResult<TData>;\n\n// @public (undocumented)\nexport type WatchQueryFetchPolicy = FetchPolicy | \"cache-and-network\" | \"standby\";\n\n// @public @deprecated (undocumented)\nexport type WatchQueryOptions<TVariables extends OperationVariables = OperationVariables, TData = unknown> = ApolloClient.WatchQueryOptions<TData, TVariables>;\n\n// @public (undocumented)\ninterface WriteContext extends ReadMergeModifyContext {\n    // (undocumented)\n    clientOnly: boolean;\n    // (undocumented)\n    deferred: boolean;\n    // Warning: (ae-forgotten-export) The symbol \"FlavorableWriteContext\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    flavors: Map<string, FlavorableWriteContext>;\n    // (undocumented)\n    readonly fragmentMap: FragmentMap;\n    // (undocumented)\n    incomingById: Map<string, {\n        storeObject: StoreObject;\n        mergeTree?: MergeTree;\n        fieldNodeSet: Set<FieldNode>;\n    }>;\n    // Warning: (ae-forgotten-export) The symbol \"FragmentMapFunction\" needs to be exported by the entry point index.d.ts\n    //\n    // (undocumented)\n    lookupFragment: FragmentMapFunction;\n    // (undocumented)\n    merge<T>(existing: T, incoming: T): T;\n    // (undocumented)\n    overwrite: boolean;\n    // (undocumented)\n    readonly written: {\n        [dataId: string]: SelectionSetNode[];\n    };\n}\n\n// Warnings were encountered during analysis:\n//\n// src/cache/core/cache.ts:126:11 - (ae-forgotten-export) The symbol \"MissingTree\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/policies.ts:101:3 - (ae-forgotten-export) The symbol \"FragmentMap\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/policies.ts:173:3 - (ae-forgotten-export) The symbol \"KeySpecifier\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/policies.ts:173:3 - (ae-forgotten-export) The symbol \"KeyArgsFunction\" needs to be exported by the entry point index.d.ts\n// src/cache/inmemory/types.ts:135:3 - (ae-forgotten-export) The symbol \"KeyFieldsFunction\" needs to be exported by the entry point index.d.ts\n// src/core/ApolloClient.ts:173:5 - (ae-forgotten-export) The symbol \"IgnoreModifier\" needs to be exported by the entry point index.d.ts\n// src/core/ApolloClient.ts:375:5 - (ae-forgotten-export) The symbol \"NextFetchPolicyContext\" needs to be exported by the entry point index.d.ts\n// src/core/ObservableQuery.ts:371:5 - (ae-forgotten-export) The symbol \"QueryManager\" needs to be exported by the entry point index.d.ts\n// src/core/QueryManager.ts:195:5 - (ae-forgotten-export) The symbol \"MutationStoreValue\" needs to be exported by the entry point index.d.ts\n// src/local-state/LocalState.ts:149:5 - (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n// src/local-state/LocalState.ts:202:7 - (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n// src/local-state/LocalState.ts:245:7 - (ae-forgotten-export) The symbol \"LocalState\" needs to be exported by the entry point index.d.ts\n// src/utilities/internal/types/ExtensionsWithStreamDetails.ts:11:5 - (ae-forgotten-export) The symbol \"StreamInfoTrie\" needs to be exported by the entry point index.d.ts\n\n// (No @packageDocumentation comment for this package)\n\n```\n"
  },
  {
    "path": ".attw.json",
    "content": "{\n  \"ignoreRules\": [\"false-esm\", \"cjs-resolves-to-esm\"]\n}\n"
  },
  {
    "path": ".changeset/README.md",
    "content": "# Changesets\n\nHello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works\nwith multi-package repos, or single-package repos to help you version and publish your code. You can\nfind the full documentation for it [in our repository](https://github.com/changesets/changesets)\n\nWe have a quick list of common questions to get you started engaging with this project in\n[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)\n"
  },
  {
    "path": ".changeset/config.json",
    "content": "{\n  \"$schema\": \"https://unpkg.com/@changesets/config@2.2.0/schema.json\",\n  \"changelog\": [\n    \"@changesets/changelog-github\",\n    { \"repo\": \"apollographql/apollo-client\" }\n  ],\n  \"commit\": false,\n  \"fixed\": [],\n  \"linked\": [],\n  \"access\": \"public\",\n  \"baseBranch\": \"main\",\n  \"updateInternalDependencies\": \"patch\",\n  \"ignore\": []\n}\n"
  },
  {
    "path": ".circleci/config.yml",
    "content": "version: 2.1\n\njobs:\n  # Filesize:\n  #   docker:\n  #     - image: cimg/node:20.2.0\n  #   steps:\n  #     - checkout\n  #     - run: npm version\n  #     - run: npm ci\n  #     - run: npm run bundlesize\n\n  Circularity:\n    docker:\n      - image: cimg/node:23.7.0\n    steps:\n      - checkout\n      - run: npm version\n      - run: npm ci\n      - run: npm run madge\n\n  Publint:\n    docker:\n      - image: cimg/node:23.7.0\n    steps:\n      - checkout\n      - run: npm version\n      - run: npm ci\n      - run: npm run build\n      - run: npm run publint\n\n  Lint:\n    docker:\n      - image: cimg/node:23.9.0\n    steps:\n      - checkout\n      - run: npm version\n      - run: npm ci\n      - run: npm run docmodel\n      - run: npm run build\n      - run: npm run lint\n\n  Formatting:\n    docker:\n      - image: cimg/node:23.9.0\n    steps:\n      - checkout\n      - run: npm ci\n      - run: npm run check:format\n\n  Tests:\n    docker:\n      - image: cimg/node:23.9.0\n    parameters:\n      project:\n        type: string\n    steps:\n      - checkout\n      - run: npm run ci:precheck\n      - run: npm version\n      - run: npm ci\n      - run: npm run build\n      - run: npm run typecheck\n      - run: if test \"<< parameters.project >>\" = \"Core Tests\"; then npm run test:memory; fi\n      - run:\n          name: Jest suite with coverage\n          command: npm run test:ci -- --selectProjects \"<< parameters.project >>\"\n          environment:\n            JEST_JUNIT_OUTPUT_FILE: \"reports/junit/js-test-results-<< parameters.project >>.xml\"\n      - store_test_results:\n          path: reports/junit\n      - store_artifacts:\n          path: reports/junit\n  Attest:\n    docker:\n      - image: cimg/node:23.9.0\n    steps:\n      - checkout\n      - run: npm ci\n      - run: npm run test:type-benches\n\n  BuildTarball:\n    docker:\n      - image: cimg/node:23.9.0\n    steps:\n      - checkout\n      - run: npm run ci:precheck\n      - run: npm version\n      - run: npm ci\n      - run: npm run build && cd dist && mv \"$(npm pack --json | jq --raw-output '.[0].filename')\" apollo-client.tgz\n      - persist_to_workspace:\n          root: dist\n          paths:\n            - apollo-client.tgz\n\n  IntegrationTests:\n    parameters:\n      framework:\n        type: string\n      react:\n        type: string\n    docker:\n      - image: cimg/node:23.9.0-browsers\n    steps:\n      - checkout\n      - attach_workspace:\n          at: /tmp/workspace\n      - run: pnpm version\n      - run:\n          command: pnpm pkg set \"pnpm.overrides[@apollo/client]=/tmp/workspace/apollo-client.tgz\"\n          working_directory: integration-tests\n      - run:\n          command: |\n            export VERSION=$(pnpm view react@<< parameters.react >> version)\n            pnpm pkg set \"pnpm.overrides[react]=${VERSION}\" \"pnpm.overrides[react-dom]=${VERSION}\"\n          working_directory: integration-tests\n      - run:\n          command: pnpm run --if-present --filter << parameters.framework >> ci-preparations\n          working_directory: integration-tests\n      - run:\n          command: pnpm install --no-frozen-lockfile\n          working_directory: integration-tests\n      - run:\n          command: cat pnpm-lock.yaml\n          working_directory: integration-tests\n      - run:\n          command: pnpm exec playwright install-deps\n          working_directory: integration-tests\n      - run:\n          command: pnpm exec playwright install\n          working_directory: integration-tests\n      - run:\n          command: pnpm run --if-present --filter << parameters.framework >> build\n          working_directory: integration-tests\n      - run:\n          command: pnpm run --if-present --filter << parameters.framework >> \"/test(:.*|$)/\"\n          working_directory: integration-tests\n\n  TestPeerDepTypes:\n    parameters:\n      externalPackage:\n        type: string\n    docker:\n      - image: cimg/node:23.9.0\n    steps:\n      - checkout\n      - attach_workspace:\n          at: /tmp/workspace\n      - run:\n          working_directory: integration-tests/peerdeps-tsc\n          command: |\n            npm install\n            npm install @apollo/client@/tmp/workspace/apollo-client.tgz\n            npm install << parameters.externalPackage >>\n            npm test\n\nworkflows:\n  Build and Test:\n    jobs:\n      # - Filesize\n      - Tests:\n          matrix:\n            parameters:\n              project:\n                [\n                  \"Core Tests\",\n                  \"Core Tests - RxJS min version\",\n                  \"ReactDOM 17\",\n                  \"ReactDOM 18\",\n                  \"ReactDOM 19\",\n                ]\n      - Circularity\n      - Publint\n      - Attest\n      - Formatting\n      - Lint\n      - BuildTarball\n      - IntegrationTests:\n          name: Integration Test << matrix.framework >> with React << matrix.react >>\n          requires:\n            - BuildTarball\n          matrix:\n            parameters:\n              framework:\n                - cra5\n                #- next\n                - node\n                - vite\n                - vite-swc\n                - wrapping-library\n                # -browser-esm would need a package publish to npm/CDNs\n              react:\n                - \"18.3.0\"\n                - latest\n                - next\n            exclude:\n              # CRA only works with React 18\n              - framework: cra5\n                react: next\n              - framework: cra5\n                react: latest\n              # next ships it's own React version anyways\n              - framework: next\n                react: next\n              - framework: next\n                react: \"18.3.0\"\n              # node doesn't use React in the tests\n              - framework: node\n                react: next\n              - framework: node\n                react: \"18.3.0\"\n      - TestPeerDepTypes:\n          name: Test external types for << matrix.externalPackage >>\n          requires:\n            - BuildTarball\n          matrix:\n            parameters:\n              externalPackage:\n                - \"graphql@15\"\n                - \"graphql@16\"\n                - \"graphql@^17.0.0-alpha\"\n                - \"@types/react@17 @types/react-dom@17\"\n                - \"@types/react@18 @types/react-dom@18\"\n                - \"@types/react@19 @types/react-dom@19\"\n                - \"typescript@next\"\n"
  },
  {
    "path": ".claude/commands/chores.md",
    "content": "---\nallowed-tools: Bash(git commit:*)\ndescription: Chores\n---\n\n## Context\n\n- Current git status: !`git status`\n- Current git diff (staged and unstaged changes): !`git diff HEAD`\n- Current branch: !`git branch --show-current`\n- Recent commits: !`git log --oneline -10`\n\n## Your task\n\nFetch the latest changes from the remote repository. If the current branch is not up to date, don't do anything, but inform the user about it.\n\nTake a note if the current git status is clean.\n\nRun the npm scripts `format`, `build`, `extract-api:only`, `update-size-limits` after each other in that order.\n\nIf before running the scripts, the git status was clean, create a new commit with the message \"chores\".\n"
  },
  {
    "path": ".claude/documentation.md",
    "content": "# Documentation specific instructions\n\nDocumentation can be found in the `docs/` directory and in the `src/` directory as DocBlocks.\n\n## Data sources\n\nSee @docs/source/\\_sidebar.yaml for the documentation structure.\nDocBlocks can contain comments in the form `{@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member}` to (in this example) include the DocBlock of the `query` member on the `QueryOptionsDocumentation` interface. `@apollo/client!QueryOptionsDocumentation#query:member` is called a \"canonical reference\" and is used to uniquely identify a DocBlock.\nAn accumulation of all DocBlocks and their canonical references can be found in @docs/public/client.api.json. This file is generated from the source code by running `npm run docmodel`.\nAll .json files in the `docs/public/` directory are autogenerated. They can be read, but not modified. Instead, the respective source files in the `src/` directory should be modified, and the JSON file should be regenerated by running `npm run docmodel`.\n\n## DocBlock inheritance\n\nIf possible, DocBlocks should not repeat other DocBlocks in other places, but use `@inheritDoc` annotations. For every DocBlock, before adding text, the existing DocBlocks in @src/react/types/types.documentation.ts and @src/utilities/internal/types/DocumentationTypes.ts should always be checked and if possible referenced.\n\n## Available components\n\nFor components that can be used in `.mdx` files, reference @docs/shared/MdxProvidedComponents.ts\n\n## Documentation Guidelines\n\n### Tone\n\nDocumentation should be written in an approachable, positive, and encouraging tone. It should be helpful and opinionated. The goal is to make the documentation easy to understand and follow, while also providing clear guidance on best practices.\nThe target audience is JavaScript and TypeScript developers of all skill levels with different native language backgrounds, so the documentation should be accessible to non-native English speakers as well. Nested sentences and complex non-domain-specific vocabulary should be avoided where possible.\nAt no point should the documentation be sarcastic, condescending or dismissive of the reader's knowledge or experience.\nSpelling and grammar should follow American English conventions.\nContent should be framed towards the reader in an active voice (e.g. \"You can use the `useQuery` hook to fetch data\" instead of \"The `useQuery` hook can be used to fetch data\"). Passive voice can be used to describe the behavior of the library (e.g. \"The `useQuery` hook returns an object containing the query result\") as a result of userland code usage.\nThe use of \"we\" should be avoided, unless it is used to refer to the Apollo Client team as a whole (e.g. \"We recommend using fragment colocation and data masking.\").\n\n### Change documentation - CRITICAL RULE\n\n**NEVER reference changes, previous versions, or historical behavior in documentation.** Documentation must ONLY describe the current state of the library.\n\nFORBIDDEN phrases and patterns:\n\n- \"previously\" or \"previous behavior\"\n- \"has been restructured\" or \"has been changed\"\n- \"now takes\" or \"now provides\"\n- \"in earlier versions\"\n- \"used to be\" or \"was changed\"\n- Any reference to what something was like before\n\nCORRECT approach:\n\n- Describe how things work today\n- State what the current behavior is\n- Explain the current API without comparing to past versions\n\nIf new features are added to the documentation, they can include a `<MinVersion version=\"3.10.0\">` tag wrapping the headline of the new feature, to indicate that this feature is only available in Apollo Client 3.10.0 and later.\nFor features that are introduced in a major version, the `<MinVersion>` tag should not be used, as for each major version, a separate copy of the documentation is maintained.\nCurrently, this documentation copy is the copy for Apollo Client with the major version 4, so all references to previous versions can be removed.\nNever use phrases like \"since version 4.0, this or that change applied\". Only document the current state of the library, not its history.\n\n### Prefer describing certain APIs over others.\n\n- When having a choice, describe the state of the `dataState` property instead of mentioning `partial`.\n- In many cases, be more specific about the `networkStatus` that can be observed instead of using the `loading` property. In some cases it can make sense to mention both.\n\n### Updating DocBlocks\n\nIf outdated or incorrect documentation is found in `docs/public/client.api.json`, find the closest parent `fileUrlPath` in the JSON structure and update the original DocBlock in that file. Then run `npm run docmodel` to regenerate the JSON file and read the `docs/public/client.api.json` again.\n\n### DocBlock Guidelines\n\n- Use `@template` to document TypeScript generics, not `@param`\n- Example: `@template TData - The type of data returned by the query`\n- Use `@param` only for actual function parameters\n- Use `@returns` to document return values\n- Use `@defaultValue` to document default values for properties in interfaces describing options\n- Use `@example` for code examples\n"
  },
  {
    "path": ".claude/hooks.md",
    "content": "# React Hooks\n\nReact Hooks can be found in the `src/react/hooks` directory.\nThis folder contains React Hooks and their associated types, as well as documentation for each hook in DocBlocks, always colocated in one file per hook.\n\n## Hooks Type Structure\n\nTypes for the React Hooks are held in the same file as the hook itself. They follow this structure:\nIn this example, single-line comments (with `//`) are used to annotate and explain the example\nwhile DocBlocks (with `/** ... */`) are part of the actual structure that is present in the files.\n\n```ts\n// A namespace with the hook's name that contains all types related to the hook\nexport declare namespace useMyHook {\n  // an `Options` interface\n  export interface Options {\n    // ...\n  }\n\n  // a `Result` interface\n  export interface Result {\n    // ...\n  }\n\n  // A namespace for documentation types, which are simplified versions of the hook's types.\n  // This is necessary because we can only reference interfaces and function signatures in the Documentation, not complex types.\n  export namespace DocumentationTypes {\n    // The `DocumentationTypes` namespace always contains a simplified version of the hook for documentation purposes.\n\n    // The function signature for documentation, which inherits documentation from the first signature of the actual hook\n    /** {@inheritDoc @apollo/client!useMyHook:function(1)} */\n    export function useMyHook(options: useMyHook.Options): useMyHook.Result;\n  }\n}\n\n// All overload signatures for the hook\n\n// The first hook signature contains the documentation\n/**\n * Documentation for the hook.\n */\nfunction useMyHook(\n  options: useMyHook.Options & SomeSpecifyingType\n): useMyHook.Result & SomeRestrictingType;\n\n// The second and all subsequent signatures don't contain the full documentation, but only a DocBlock with a `@inheritDoc` tag.\n/** {@inheritDoc @apollo/client!useMyHook:function(1)} */\nfunction useMyHook(\n  options: useMyHook.Options & SomeOtherSpecifyingType\n): useMyHook.Result & SomeOtherRestrictingType;\n\n// The hook implementation at the bottom. This one doesn't have a DocBlock.\nexport function useMyHook(options: useMyHook.Options): useMyHook.Result {\n  // Implementation here\n}\n```\n\nIf the `Options`, `Result` or any other documented type is not an interface, but a more complex type,\ncommon properties are extracted into a `useMyHook.Base` namespace.\nThen, another interface with a simplified version of the non-common properties is created in the `DocumentationTypes`\nnamespace, in a sub-namespace that shares the hook name.\nBoth the \"real\" type in the `useMyHook` namespace and the simplified interface version in the `DocumentationTypes.useMyHook`\nnamespace inherit from the common properties interface in the `useMyHook.Base` namespace.\n\nIf the `Options` type would be more complicated, e.g.\n\n```ts\nexport namespace useMyHook {\n  export type Options<T> = {\n    commonProperty: string;\n  } & (T extends SomeType ? { someProperty: string }\n  : { someProperty?: never });\n}\n```\n\nthe result would look like this:\n\n```ts\nexport namespace useMyHook {\n  export namespace Base {\n    export interface Options<T> {\n      commonProperty: string;\n    }\n  }\n\n  export type Options<T> = useMyHook.Base.Options<T> & SomeComplexType<T>;\n\n  export namespace DocumentationTypes {\n    namespace useMyHook {\n      export interface Options<T> extends Base.Options<T> {\n        someProperty?: string;\n      }\n    }\n  }\n\n  // the rest of the structure continues as before\n  export interface Result {\n    // ...\n  }\n}\n```\n\nWhen types are simple interfaces, the nested namespace structure may not be necessary, and the types can be referenced directly in the function signature by `useMyHook.InterfaceName`. However, when dealing with complex types, the nested namespace pattern as shown above is commonly used.\n\nNote that if this is necessary for multiple types, the nested namespace definition\nshould not be merged in one place, but just repeated for each type.\nSo it could look like this in the end:\n\n```ts\nexport namespace useMyHook {\n  export namespace Base {\n    export interface Options<T> {\n      // ...\n    }\n  }\n\n  export type Options<T> = useMyHook.Base.Options<T> & SomeComplexType<T>;\n\n  export namespace DocumentationTypes {\n    namespace useMyHook {\n      export interface Options<T> extends Base.Options<T> {\n        // ...\n      }\n    }\n  }\n\n  export namespace Base {\n    export interface Result<T> {\n      // ...\n    }\n  }\n\n  export type Result<T> = useMyHook.Base.Result<T> & SomeOtherComplexType<T>;\n\n  export namespace DocumentationTypes {\n    namespace useMyHook {\n      export interface Result<T> extends Base.Result<T> {\n        // ...\n      }\n    }\n  }\n\n  // other types\n\n  export namespace DocumentationTypes {\n    export function useMyHook(options: useMyHook.Options): useMyHook.Result;\n  }\n}\n```\n\n## Additional Implementation Details\n\nSome hooks may have more complex implementations with multiple function overloads that use specific type constraints. For example, a hook might have several overloads with different combinations of options that affect the resulting types. These overloads allow TypeScript to narrow the return type based on the specific options passed. The number and complexity of these overloads varies by hook based on its specific requirements.\n\n## Internal Function Implementation Pattern\n\nSome hooks use a pattern where the exported function is a wrapper around an internal implementation function. For example:\n\n```ts\nexport function useMyHook(...args) {\n  return wrapHook(\n    \"useMyHook\",\n    useMyHook_ // Internal implementation function\n    // ... other setup\n  )(...args);\n}\n\nfunction useMyHook_(...args) {\n  // Actual implementation\n}\n```\n\nThis pattern allows for hook implementations to be overwritten by the `ApolloClient` instance of the `ApolloProvider`, which allows for custom behaviour e.g. during SSR.\nEvery hook using this pattern needs to be added to the `WrappableHooks` interface in `src/react/hooks/internal/wrapHook.ts`.\n\n## Simple Hooks\n\nNot all hooks follow the complex namespace pattern. Simple hooks that take minimal parameters and return straightforward values (like `useApolloClient` or `useReactiveVar`) are implemented as plain functions without namespaces or complex type structures. This is appropriate when:\n\n- The hook has no or minimal configuration options\n- The return type is simple and can be described as a single interface or primitive type\n- There's no need for documentation type simplification\n\n## Additional Type Patterns\n\n### Self-import Pattern\n\nIn some cases, a self-import pattern is allowed to access the outer `useMyHook` namespace within the `DocumentationTypes.useMyHook` namespace. This might be necessary to avoid shadowing of the `useMyHook` identifier.\n\n```ts\nexport declare namespace useMyHook {\n  import _self = useMyHook;\n\n  // Now can use _self.Options instead of useMyHook.Options\n}\n```\n\n### Conditional Parameters\n\nHooks may use conditional types in their parameters to make options required or optional based on generic types:\n\n```ts\nexport function useMyHook<TVariables>(\n  query: DocumentNode,\n  ...[options]: {} extends TVariables ?\n    [options?: useMyHook.Options<TVariables>]\n  : [options: useMyHook.Options<TVariables>]\n): useMyHook.Result;\n```\n\n### Result Tuples\n\nSome hooks (like `useLazyQuery` and `useMutation`) return tuples instead of single objects:\n\n```ts\nexport declare namespace useMyHook {\n  export type Result<TData, TVariables> = [\n    executeFunction: (options?: Options) => Promise<TData>,\n    result: QueryResult<TData, TVariables>,\n  ];\n}\n```\n\n### \"use no memo\" Directive\n\nSome hook implementations include a `\"use no memo\";` directive at the beginning of the function body to indicate React Compiler optimization hints.\n\n### Utility Documentation Types\n\nWhen hooks need to extend or compose with common utility types in their documentation interfaces, they import and use `UtilityDocumentationTypes` from the utilities package:\n\n```ts\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  // ... other imports\n} from \"@apollo/client/utilities/internal\";\n\nexport namespace useMyHook {\n  // ... types ...\n\n  export namespace DocumentationTypes {\n    namespace useMyHook {\n      export interface Options<TVariables>\n        extends Base.Options<TVariables>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n\n      export interface Result<TData, TVariables>\n        extends Base.Result<TData, TVariables>,\n          UtilityDocumentationTypes.DataState<TData> {}\n    }\n  }\n}\n```\n\nCommon utility documentation types include:\n\n- `VariableOptions<TVariables>` - For GraphQL variables options\n- `DataState<TData>` - For data state properties in query results\n- `ApolloQueryResult<TData>` - For complete query result types including loading, error, and data states\n"
  },
  {
    "path": ".claude/settings.json",
    "content": "{\n  \"permissions\": {\n    \"allow\": [\n      \"Bash(git add:*)\",\n      \"Bash(git fetch:*)\",\n      \"Bash(git status:*)\",\n      \"Bash(git diff:*)\",\n      \"Bash(npm run:*)\",\n      \"Edit(docs/**)\",\n      \"Edit(src/**)\"\n    ],\n    \"deny\": []\n  }\n}\n"
  },
  {
    "path": ".git-blame-ignore-revs",
    "content": "# format \"ObservableQuery\" test\n0a67647b73abd94b706242f32b88d21a1400ad50\n# format \"ObservableQuery\" test (in #10597)\n104bf11765b1db50292f9656aa8fe48e2d749a83\n# format changes from ee0b4ae\nf7890ae96a3ba900d3de9bf8b23254bcfba18a25\n# Format \"DisplayClientError.js\" (#10909)\n0cb68364f2c3828badde8c74de44e9c1864fb6d4\n# Format `react` folder, upgrade to prettier 3.0 (#11111)\nba3e7d9fa7d46e4c636148bbf01552833db0ceda\n# Format all non-docs files with prettier (#11170)\n352c4a9ad4d140d58850688bd1b2d5513f62c6cb\n# Format remaining files from #11170 (#11185)\n994ae91f16ea4c8ee28818bd7eaac47e4765c660\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text=auto eol=lf\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "* @apollographql/client-typescript\n\n/docs/ @apollographql/docs\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug.yml",
    "content": "name: Bug\ndescription: File a bug report\nbody:\n  - type: markdown\n    attributes:\n      value: \"Hello from the Apollo Client team! Hopefully we can help resolve your issue. To increase the chances of us being able to help, please take the time to fill out the form as completely as possible. A minimal, runnable reproduction is the best way to get us to help you quickly and in many cases we simply cannot help without one.\"\n  - type: textarea\n    attributes:\n      label: Issue Description\n      description: Describe the issue you are experiencing.\n    validations:\n      required: false\n  - type: input\n    attributes:\n      label: Link to Reproduction\n      description: \"A link with runnable reproduction. For web projects, you can fork our `react-apollo-error-template` to create one via [GitHub repository](https://github.com/apollographql/react-apollo-error-template) or [CodeSandbox](https://codesandbox.io/s/github/apollographql/react-apollo-error-template). For React Native projects, you can fork our `rn-apollo-client-testbed` via [GitHub respository](https://github.com/apollographql/rn-apollo-client-testbed). Make sure this includes everything necessary (`package.json`, `tsconfig.json`, etc.) so we don't have to guess anything! If a minimal reproduction can't be created, please share a [Replay](https://docs.replay.io/workflows/recording-bug-reports) of the bug (note: you don't have to grant Replay access to a private repo to create a recording, but it will contain source maps for your JavaScript code).  Feel free to ask for an email address to send Replays to if they contain sensitive information.\"\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Reproduction Steps\n      description: Please provide any additional non-trivial steps required to reproduce the issue.\n    validations:\n      required: false\n  - type: input\n    attributes:\n      label: \"`@apollo/client` version\"\n      description: \"What version of Apollo Client are you running?\"\n      placeholder: \"ex: 3.8.10\"\n    validations:\n      required: true\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature-request.md",
    "content": "---\nname: 🚀 Feature Request\nabout: Feature requests are managed in the Apollo Feature Request repo (https://github.com/apollographql/apollo-feature-requests).\n---\n\nThanks for your interest in helping make Apollo Client better!\n\nFeature requests and non-bug related discussions are no longer managed in this repo. Feature requests should be opened in https://github.com/apollographql/apollo-feature-requests.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/question-discussion.md",
    "content": "---\nname: 🤗 Question / Discussion\nabout: Questions / discussions are best posted in our community forums or StackOverflow.\n---\n\nNeed help or want to talk all things Apollo Client? Issues here are reserved for bugs, but one of the following resources should help:\n\n- Apollo GraphQL community forums: https://community.apollographql.com\n- StackOverflow (`apollo-client` tag): https://stackoverflow.com/questions/tagged/apollo-client\n- Apollo Feature Request repo: https://github.com/apollographql/apollo-feature-requests\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!--\n  Thanks for filing a pull request on Apollo Client!\n\n  A few automated bots may chime in on your PR. They are here to help\n  with reviewing and ensuring Apollo Client is production ready after each\n  pull request merge.\n\n    - apollo-cla will respond asking you to sign the CLA if this is your first PR.\n      It may also respond with warnings, messages, or fail the build if something is off.\n      Don't worry, it'll help you to fix what is broken!\n\n    - bundlesize is a status check to keep the footprint of Apollo Client as small as possible.\n\n    - circleci will run tests, checking style of code, and generally make\n      sure everything is working as expected\n\n  Please look at the following checklist to ensure that your PR\n  can be accepted quickly:\n\n### Checklist:\n- [ ] If this PR contains changes to the library itself (not necessary for e.g. docs updates), please include a changeset (see [CONTRIBUTING.md](https://github.com/apollographql/apollo-client/blob/main/CONTRIBUTING.md#changesets))\n- [ ] If this PR is a new feature, please reference an issue where a consensus about the design was reached (not necessary for small changes)\n- [ ] Make sure all of the significant new logic is covered by tests\n-->\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# Please see the documentation for all configuration options:\n# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"npm\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    # Disable @dependabot (except for security updates) because we use @renovate instead\n    open-pull-requests-limit: 0\n"
  },
  {
    "path": ".github/instructions/apollo-client.instructions.md",
    "content": "---\napplyTo: \"**\"\n---\n\n# Apollo Client Skill Usage Instructions\n\n## When to Use the Apollo Client Skill\n\nUse the `apollo-client` skill when:\n\n1. **Answering questions about Apollo Client** - Any question related to Apollo Client setup, configuration, usage, or troubleshooting\n2. **Reviewing documentation** - When reviewing documentation PRs or content related to Apollo Client\n3. **Reviewing documentation-like content** - Including:\n   - Markdown files (`.md`, `.mdx`)\n   - JSDoc/TSDoc docblocks (`/** ... */`)\n   - Code comments intended for end users\n   - README files\n   - API documentation\n4. **Integration questions** - Questions about integrating Apollo Client with frameworks like Next.js, TanStack Start, or React Router\n\n## Important Notes\n\n- The skill is trained on Apollo Client 4.x, so it provides current patterns\n- The skill is opinionated, so it is a good guide for best practices, but documentation might show alternative approaches - this is valid\n- Always prefer the skill's guidance over general knowledge for Apollo Client questions\n- The skill includes official Apollo documentation patterns and best practices\n- Use the skill even for seemingly simple questions to ensure accuracy\n"
  },
  {
    "path": ".github/workflows/api-extractor.yml",
    "content": "name: Api Extractor\non: pull_request\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  api-extractor:\n    name: Api-Extractor\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n        # Builds the library and runs the api extractor\n      - name: Run Api-Extractor\n        run: npm run extract-api\n"
  },
  {
    "path": ".github/workflows/arethetypeswrong.yml",
    "content": "name: AreTheTypesWrong\non:\n  pull_request:\n    branches:\n      - main\n      - release-*\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  arethetypeswrong:\n    name: Are the types wrong\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: Run build\n        run: npm run build\n      - name: Run AreTheTypesWrong\n        id: attw\n        run: ./node_modules/.bin/attw --format ascii --pack dist > $GITHUB_STEP_SUMMARY\n"
  },
  {
    "path": ".github/workflows/change-prerelease-tag.yml",
    "content": "name: Change Prerelease Tag\n\non:\n  workflow_dispatch:\n    inputs:\n      branch:\n        description: \"Branch name\"\n        type: string\n        default: \"release-\"\n        required: true\n      tag:\n        description: \"New tag name\"\n        type: string\n        default: \"rc\"\n        required: true\n\njobs:\n  change_prerelease_tag:\n    name: Changesets Update Prerelease Tag\n    runs-on: ubuntu-latest\n    # Allow GITHUB_TOKEN to have write permissions\n    permissions:\n      contents: write\n\n    steps:\n      - uses: actions/create-github-app-token@v1\n        id: github-actions-bot-app-token\n        with:\n          app-id: 819772\n          private-key: ${{ secrets.APOLLO_GITHUB_ACTIONS_BOT_PRIVATE_KEY }}\n\n      # Check out the repository, using the Github Actions Bot app's token so\n      # that we can push later.\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          token: ${{ steps.github-actions-bot-app-token.outputs.token }}\n          # Checkout release branch entered when workflow was kicked off\n          ref: ${{ github.event.inputs.branch }}\n          # Fetch entire git history so  Changesets can generate changelogs\n          # with the correct commits\n          fetch-depth: 0\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Write latest version to package.json and package-lock.json\n        run: |\n          version=$(npm show @apollo/client version)\n          npm pkg set version=\"$version\"\n          npm i\n\n      - name: Update prerelease tag in .changeset/pre.json\n        uses: restackio/update-json-file-action@2.1\n        with:\n          file: .changeset/pre.json\n          fields: '{\"tag\": \"${{github.event.inputs.tag}}\"}'\n\n      - name: Commit and push changes\n        env:\n          TAG: ${{ github.event.inputs.tag }}\n        run: |\n          git config user.email \"41898282+github-actions[bot]@users.noreply.github.com\"\n          git config user.name \"github-actions[bot]\"\n          git add -A\n          git commit -m \"Prepare for \"$TAG\" release\"\n          git push\n"
  },
  {
    "path": ".github/workflows/cleanup-checks.mjs",
    "content": "// @ts-check\n/** @param {import('@actions/github-script').AsyncFunctionArguments} AsyncFunctionArguments */\nexport function setup({ context, github }) {\n  return {\n    async add_cleanup_label() {\n      await github.rest.issues.addLabels({\n        owner: context.repo.owner,\n        repo: context.repo.repo,\n        issue_number: context.issue.number,\n        labels: [\"auto-cleanup\"],\n      });\n    },\n  };\n}\n"
  },
  {
    "path": ".github/workflows/cleanup-checks.yml",
    "content": "name: Clean up Prettier, Size-limit, and Api-Extractor\n\non:\n  pull_request:\n  pull_request_review:\n    types: [submitted, edited]\n\njobs:\n  add_cleanup_label:\n    # https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#running-a-workflow-when-a-pull-request-is-approved\n    if: |\n      github.repository == 'apollographql/apollo-client' &&\n      github.event.review.state == 'APPROVED' &&\n      github.event.review.author_association == 'MEMBER' &&\n      contains(github.event.pull_request.labels.*.name, 'auto-cleanup') == false\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n      - name: add label\n        uses: actions/github-script@v8.0.0\n        with:\n          script: |\n            const script = (await import('${{ github.workspace }}/.github/workflows/cleanup-checks.mjs')).setup({context,core,github,exec,glob,io})\n            await script.add_cleanup_label()\n\n  cleanup:\n    if: |\n      github.repository == 'apollographql/apollo-client' &&\n      contains(github.event.pull_request.labels.*.name, 'auto-cleanup')\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: Run Api-Extractor\n        run: npm run extract-api\n        env:\n          CI: \"false\"\n\n      - name: Run prettier\n        run: npm run format\n\n      - name: Run build\n        run: npm run build\n\n      - name: Update size-limit\n        run: npm run update-size-limits\n\n      - name: Commit changes back\n        uses: stefanzweifel/git-auto-commit-action@v7\n        with:\n          commit_message: \"Clean up Prettier, Size-limit, and Api-Extractor\"\n          push_options: \"\"\n          skip_dirty_check: false\n"
  },
  {
    "path": ".github/workflows/close-stale-issues.yml",
    "content": "# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time.\n#\n# You can adjust the behavior by modifying this file.\n# For more information, see:\n# https://github.com/actions/stale\nname: Mark stale issues and pull requests\n\non:\n  schedule:\n    - cron: \"15 5 * * *\"\n\njobs:\n  stale:\n    # Prevents action from running on forks\n    if: github.repository == 'apollographql/apollo-client'\n    runs-on: ubuntu-latest\n    permissions:\n      issues: write\n      pull-requests: write\n\n    steps:\n      - name: Close Stale Issues\n        uses: actions/stale@v10.1.0\n        with:\n          # # Token for the repository. Can be passed in using `{{ secrets.GITHUB_TOKEN }}`.\n          # repo-token: # optional, default is ${{ github.token }}\n\n          # # The message to post on the issue when tagging it. If none provided, will not mark issues stale.\n          #. stale-issue-message: # optional\n\n          # # The message to post on the pull request when tagging it. If none provided, will not mark pull requests stale.\n          # stale-pr-message: # optional\n\n          # The message to post on the issue when closing it. If none provided, will not comment when closing an issue.\n          close-issue-message: \"We're closing this issue now but feel free to ping the maintainers or open a new issue if you still need support.  Thank you!\"\n\n          # # The message to post on the pull request when closing it. If none provided, will not comment when closing a pull requests.\n          # close-pr-message: # optional\n\n          # The number of days old an issue or a pull request can be before marking it stale. Set to -1 to never mark issues or pull requests as stale automatically.\n          days-before-stale: -1\n\n          # The number of days old an issue can be before marking it stale. Set to -1 to never mark issues as stale automatically. Override \"days-before-stale\" option regarding only the issues.\n          days-before-issue-stale: -1\n\n          # The number of days old a pull request can be before marking it stale. Set to -1 to never mark pull requests as stale automatically. Override \"days-before-stale\" option regarding only the pull requests.\n          days-before-pr-stale: -1\n\n          # The number of days to wait to close an issue or a pull request after it being marked stale. Set to -1 to never close stale issues or pull requests.\n          days-before-close: -1\n\n          # The number of days to wait to close an issue after it being marked stale. Set to -1 to never close stale issues. Override \"days-before-close\" option regarding only the issues.\n          days-before-issue-close: 30\n\n          # The number of days to wait to close a pull request after it being marked stale. Set to -1 to never close stale pull requests. Override \"days-before-close\" option regarding only the pull requests.\n          days-before-pr-close: -1\n\n          # The label to apply when an issue is stale.\n          stale-issue-label: \"🏓 awaiting-contributor-response\"\n\n          # # The label to apply when an issue is closed.\n          # close-issue-label: # optional\n\n          # # The labels that mean an issue is exempt from being marked stale. Separate multiple labels with commas (eg. \"label1,label2\").\n          # exempt-issue-labels: # optional, default is\n\n          # The reason to use when closing an issue.\n          close-issue-reason: not_planned\n\n          # # The label to apply when a pull request is stale.\n          # stale-pr-label: # optional, default is Stale\n\n          # # The label to apply when a pull request is closed.\n          # close-pr-label: # optional\n\n          # # The labels that mean a pull request is exempt from being marked as stale. Separate multiple labels with commas (eg. \"label1,label2\").\n          # exempt-pr-labels: # optional, default is\n\n          # # The milestones that mean an issue or a pull request is exempt from being marked as stale. Separate multiple milestones with commas (eg. \"milestone1,milestone2\").\n          # exempt-milestones: # optional, default is\n\n          # # The milestones that mean an issue is exempt from being marked as stale. Separate multiple milestones with commas (eg. \"milestone1,milestone2\"). Override \"exempt-milestones\" option regarding only the issues.\n          # exempt-issue-milestones: # optional, default is\n\n          # # The milestones that mean a pull request is exempt from being marked as stale. Separate multiple milestones with commas (eg. \"milestone1,milestone2\"). Override \"exempt-milestones\" option regarding only the pull requests.\n          # exempt-pr-milestones: # optional, default is\n\n          # # Exempt all issues and pull requests with milestones from being marked as stale. Default to false.\n          # exempt-all-milestones: # optional, default is false\n\n          # # Exempt all issues with milestones from being marked as stale. Override \"exempt-all-milestones\" option regarding only the issues.\n          # exempt-all-issue-milestones: # optional, default is\n\n          # # Exempt all pull requests with milestones from being marked as stale. Override \"exempt-all-milestones\" option regarding only the pull requests.\n          # exempt-all-pr-milestones: # optional, default is\n\n          # # Only issues or pull requests with all of these labels are checked if stale. Defaults to `` (disabled) and can be a comma-separated list of labels.\n          # only-labels: # optional, default is\n\n          # # Only issues or pull requests with at least one of these labels are checked if stale. Defaults to `` (disabled) and can be a comma-separated list of labels.\n          # any-of-labels: # optional, default is\n\n          # Only issues with at least one of these labels are checked if stale. Defaults to `` (disabled) and can be a comma-separated list of labels. Override \"any-of-labels\" option regarding only the issues.\n          any-of-issue-labels: \"🏓 awaiting-contributor-response\"\n\n          # # Only pull requests with at least one of these labels are checked if stale. Defaults to `` (disabled) and can be a comma-separated list of labels. Override \"any-of-labels\" option regarding only the pull requests.\n          # any-of-pr-labels: # optional, default is\n\n          # # Only issues with all of these labels are checked if stale. Defaults to `[]` (disabled) and can be a comma-separated list of labels. Override \"only-labels\" option regarding only the issues.\n          # only-issue-labels: # optional, default is\n\n          # # Only pull requests with all of these labels are checked if stale. Defaults to `[]` (disabled) and can be a comma-separated list of labels. Override \"only-labels\" option regarding only the pull requests.\n          # only-pr-labels: # optional, default is\n\n          # The maximum number of operations per run, used to control rate limiting (GitHub API CRUD related).\n          operations-per-run: 500 # optional, default is 30\n\n          # Remove stale labels from issues and pull requests when they are updated or commented on.\n          remove-stale-when-updated: false\n\n          # Remove stale labels from issues when they are updated or commented on. Override \"remove-stale-when-updated\" option regarding only the issues.\n          remove-issue-stale-when-updated: true\n\n          # Remove stale labels from pull requests when they are updated or commented on. Override \"remove-stale-when-updated\" option regarding only the pull requests.\n          remove-pr-stale-when-updated: false\n\n          # Run the processor in debug mode without actually performing any operations on live issues.\n          debug-only: false\n\n          # # The order to get issues or pull requests. Defaults to false, which is descending.\n          # ascending: # optional, default is false\n\n          # Delete the git branch after closing a stale pull request.\n          delete-branch: false\n\n          # # The date used to skip the stale action on issue/pull request created before it (ISO 8601 or RFC 2822).\n          # start-date: # optional, default is\n\n          # # The assignees which exempt an issue or a pull request from being marked as stale. Separate multiple assignees with commas (eg. \"user1,user2\").\n          # exempt-assignees: # optional, default is\n\n          # # The assignees which exempt an issue from being marked as stale. Separate multiple assignees with commas (eg. \"user1,user2\"). Override \"exempt-assignees\" option regarding only the issues.\n          # exempt-issue-assignees: # optional, default is\n\n          # # The assignees which exempt a pull request from being marked as stale. Separate multiple assignees with commas (eg. \"user1,user2\"). Override \"exempt-assignees\" option regarding only the pull requests.\n          # exempt-pr-assignees: # optional, default is\n\n          # # Exempt all issues and pull requests with assignees from being marked as stale. Default to false.\n          # exempt-all-assignees: # optional, default is false\n\n          # Exempt all issues with assignees from being marked as stale. Override \"exempt-all-assignees\" option regarding only the issues.\n          exempt-all-issue-assignees: true\n\n          # # Exempt all pull requests with assignees from being marked as stale. Override \"exempt-all-assignees\" option regarding only the pull requests.\n          # exempt-all-pr-assignees: # optional, default is\n\n          # # Exempt draft pull requests from being marked as stale. Default to false.\n          # exempt-draft-pr: # optional, default is false\n\n          # # Display some statistics at the end regarding the stale workflow (only when the logs are enabled).\n          enable-statistics: true\n\n          # # A comma delimited list of labels to add when a stale issue or pull request receives activity and has the stale-issue-label or stale-pr-label removed from it.\n          # labels-to-add-when-unstale: # optional, default is\n\n          # A comma delimited list of labels to remove when a stale issue or pull request receives activity and has the stale-issue-label or stale-pr-label removed from it.\n          labels-to-remove-when-unstale: \"🏓 awaiting-contributor-response\"\n\n          # Any update (update/comment) can reset the stale idle time on the issues and pull requests.\n          ignore-updates: false\n\n          # Any update (update/comment) can reset the stale idle time on the issues. Override \"ignore-updates\" option regarding only the issues.\n          ignore-issue-updates: false\n\n          # Any update (update/comment) can reset the stale idle time on the pull requests. Override \"ignore-updates\" option regarding only the pull requests.\n          ignore-pr-updates: false\n\n          # # Only the issues or the pull requests with an assignee will be marked as stale automatically.\n          # include-only-assigned: # optional, default is false\n"
  },
  {
    "path": ".github/workflows/compare-build-output.yml",
    "content": "name: Compare Build Output\non:\n  pull_request:\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  comparebuildoutput:\n    name: Compare Build Output\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          # Fetch entire git history so we have the parent commit to compare against\n          fetch-depth: 0\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: Run comparison script\n        id: attw\n        run: ./config/compare-build-output-to.sh $(git merge-base HEAD origin/${{ github.base_ref }}) | tee $GITHUB_STEP_SUMMARY\n        env:\n          RUNNER_TEMP: ${{ runner.temp }}\n"
  },
  {
    "path": ".github/workflows/copilot-setup-steps.yml",
    "content": "name: \"Copilot Setup Steps\"\n\n# Automatically run the setup steps when they are changed to allow for easy validation, and\n# allow manual testing through the repository's \"Actions\" tab\non:\n  workflow_dispatch:\n  push:\n    paths:\n      - .github/workflows/copilot-setup-steps.yml\n  pull_request:\n    paths:\n      - .github/workflows/copilot-setup-steps.yml\n\njobs:\n  # The job MUST be called `copilot-setup-steps` or it will not be picked up by Copilot.\n  copilot-setup-steps:\n    runs-on: ubuntu-latest\n\n    # Set the permissions to the lowest permissions possible needed for your steps.\n    # Copilot will be given its own token for its operations.\n    permissions:\n      # If you want to clone the repository as part of your setup steps, for example to install dependencies, you'll need the `contents: read` permission. If you don't clone the repository in your setup steps, Copilot will do this for you automatically after the steps complete.\n      contents: read\n\n    # You can define any steps you want, and they will run before the agent starts.\n    # If you do not check out your code, Copilot will do this for you.\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \"24.x\"\n\n      - name: Get upstream skills repository HEAD\n        id: skills-head\n        run: |\n          SKILLS_SHA=$(git ls-remote https://github.com/apollographql/skills.git HEAD | cut -f1)\n          echo \"sha=${SKILLS_SHA}\" >> $GITHUB_OUTPUT\n          echo \"Upstream skills repository HEAD: ${SKILLS_SHA}\"\n\n      - name: Cache downloaded skills and instructions\n        id: cache-skills\n        uses: actions/cache@v5\n        with:\n          path: |\n            .agents/skills/apollo-client/\n            .github/skills/apollo-client/\n            .github/instructions/docs.instructions.md\n          key: skills-${{ steps.skills-head.outputs.sha }}\n          restore-keys: |\n            skills-\n\n      - name: Install JavaScript dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: Install Apollo Client Skill\n        if: steps.cache-skills.outputs.cache-hit != 'true'\n        run: |\n          echo \"Installing Apollo Client skill using npx skills CLI\"\n          npx --yes skills add apollographql/skills --skill apollo-client --agent github-copilot --scope project --method copy --yes\n          echo \"Apollo Client skill installed successfully\"\n\n      - name: Copy Documentation Instructions\n        if: steps.cache-skills.outputs.cache-hit != 'true'\n        run: |\n          echo \"Copying documentation instructions from apollographql/skills\"\n          mkdir -p .github/instructions\n          # Download the docs instructions from the skills repository\n          curl -fsSL https://raw.githubusercontent.com/apollographql/skills/main/.github/instructions/docs.instructions.md \\\n            -o .github/instructions/docs.instructions.md\n          echo \"Documentation instructions copied to .github/instructions/docs.instructions.md\"\n"
  },
  {
    "path": ".github/workflows/devtools-errorcodes.yml",
    "content": "name: Devtools - Trigger Error Code PR after npm Release\non:\n  workflow_dispatch: # for testing\n  workflow_run:\n    workflows: [\"Prerelease\", \"Release\"]\n    types:\n      - completed\njobs:\n  dispatch:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/create-github-app-token@v1\n        id: github-actions-bot-app-token\n        with:\n          app-id: 819772\n          private-key: ${{ secrets.APOLLO_GITHUB_ACTIONS_BOT_PRIVATE_KEY }}\n          repositories: apollo-client-devtools\n      - uses: benc-uk/workflow-dispatch@v1\n        with:\n          workflow: update-errorcodes.yml\n          repo: apollographql/apollo-client-devtools\n          token: ${{ steps.github-actions-bot-app-token.outputs.token }}\n"
  },
  {
    "path": ".github/workflows/docmodel.yml",
    "content": "name: Generate Documentation Model\n\non:\n  push:\n\njobs:\n  docmodel:\n    name: Generate Documentation Model\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: Generate documentation model\n        run: npm run docmodel\n\n      - name: Upload documentation model artifact\n        uses: actions/upload-artifact@v6\n        with:\n          name: client-api-documentation\n          path: docs/public/client.api.json\n          retention-days: 30\n"
  },
  {
    "path": ".github/workflows/exit-prerelease.yml",
    "content": "name: Exit Prerelease Mode\n\non:\n  workflow_dispatch:\n    inputs:\n      branch:\n        description: \"Exit prerelease mode on release branch\"\n        type: string\n        default: \"release-\"\n        required: true\n\njobs:\n  exit_prerelease:\n    name: Changesets Exit Prerelease\n    runs-on: ubuntu-latest\n    # Allow GITHUB_TOKEN to have write permissions\n    permissions:\n      contents: write\n\n    steps:\n      - uses: actions/create-github-app-token@v1\n        id: github-actions-bot-app-token\n        with:\n          app-id: 819772\n          private-key: ${{ secrets.APOLLO_GITHUB_ACTIONS_BOT_PRIVATE_KEY }}\n\n      # Check out the repository, using the Github Actions Bot app's token so\n      # that we can push later.\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          token: ${{ steps.github-actions-bot-app-token.outputs.token }}\n          # Checkout release branch entered when workflow was kicked off\n          ref: ${{ github.event.inputs.branch }}\n          # Fetch entire git history so  Changesets can generate changelogs\n          # with the correct commits\n          fetch-depth: 0\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Write latest version to package.json and package-lock.json\n        run: |\n          version=$(npm show @apollo/client version)\n          npm pkg set version=\"$version\"\n          npm i\n\n      - name: Remove pre.json\n        run: npx rimraf .changeset/pre.json\n\n      - name: Commit and push changes\n        run: |\n          git config user.email \"41898282+github-actions[bot]@users.noreply.github.com\"\n          git config user.name \"github-actions[bot]\"\n          git add -A\n          git commit -m \"Exit prerelease mode\"\n          git push\n"
  },
  {
    "path": ".github/workflows/issue-close-user-survey.yml",
    "content": "name: Issue Close User Survey\n\non:\n  issues:\n    types: [closed]\n\njobs:\n  user-survey-comment:\n    permissions:\n      issues: write\n    runs-on: ubuntu-latest\n    if: github.repository == 'apollographql/apollo-client'\n    steps:\n      - run: |\n          if [ \"$STATE_REASON\" == \"completed\" ] || [ \"$SENDER\" != \"github-actions\" ]; then\n            gh issue comment \"$NUMBER\" --body \"$BODY\"\n          else\n            echo \"Issue was closed as not planned, skipping comment.\"\n          fi\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          GH_REPO: ${{ github.repository }}\n          NUMBER: ${{ github.event.issue.number }}\n          STATE_REASON: ${{ github.event.issue.state_reason }}\n          SENDER: ${{ github.event.sender.login }}\n          BODY: >\n            Do you have any feedback for the maintainers? Please tell us by taking a [one-minute survey](https://docs.google.com/forms/d/e/1FAIpQLSczNDXfJne3ZUOXjk9Ursm9JYvhTh1_nFTDfdq3XBAFWCzplQ/viewform?usp=pp_url&entry.1170701325=Apollo+Client&entry.204965213=GitHub+Issue). Your responses will help us understand Apollo Client usage and allow us to serve you better.\n"
  },
  {
    "path": ".github/workflows/knip.yml",
    "content": "name: Look for dead code and unused dependencies\n\non: push\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    name: Ubuntu/Node v20\n    steps:\n      - uses: actions/checkout@v6\n      - uses: actions/setup-node@v6\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n      - name: Run knip\n        run: npm run knip\n"
  },
  {
    "path": ".github/workflows/lock.yml",
    "content": "name: \"Lock Threads\"\n\non:\n  schedule:\n    - cron: \"0 0 * * *\"\n\npermissions:\n  issues: write\n  pull-requests: write\n\nconcurrency:\n  group: lock\n\njobs:\n  lock:\n    if: github.repository == 'apollographql/apollo-client'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: dessant/lock-threads@v6\n        with:\n          github-token: ${{ github.token }}\n          log-output: true\n          issue-inactive-days: \"30\"\n          exclude-any-issue-labels: \"discussion\"\n          issue-comment: >\n            This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.\n\n            For general questions, we recommend using our [Community Forum](https://community.apollographql.com/) or [Stack Overflow](https://stackoverflow.com/questions/tagged/apollo-client).\n\n          pr-inactive-days: \"30\"\n          exclude-any-pr-labels: \"discussion\"\n"
  },
  {
    "path": ".github/workflows/prerelease.yml",
    "content": "name: Prerelease\n\non:\n  push:\n    branches:\n      # Target release-x.x branches\n      - \"release-*\"\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  prerelease:\n    name: Changesets Prerelease\n    # Prevents changesets action from creating a PR on forks\n    if: github.repository == 'apollographql/apollo-client'\n    runs-on: ubuntu-latest\n    # Permissions necessary for Changesets to push a new branch and open PRs\n    # (for automated Version Packages PRs), and request the JWT for provenance.\n    # More info: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#adding-permissions-settings\n    permissions:\n      contents: write\n      pull-requests: write\n      id-token: write\n    steps:\n      - uses: actions/create-github-app-token@v1\n        id: github-actions-bot-app-token\n        with:\n          app-id: 819772\n          private-key: ${{ secrets.APOLLO_GITHUB_ACTIONS_BOT_PRIVATE_KEY }}\n\n      # Check out the repository, using the Github Actions Bot app's token so\n      # that we can push later.\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          token: ${{ steps.github-actions-bot-app-token.outputs.token }}\n          # Fetch entire git history so  Changesets can generate changelogs\n          # with the correct commits\n          fetch-depth: 0\n\n      - name: Check for pre.json file existence\n        id: check_files\n        uses: andstor/file-existence-action@v3.0.0\n        with:\n          files: \".changeset/pre.json\"\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \"24.x\"\n\n      - name: Install dependencies with cache\n        uses: bahmutov/npm-install@v1\n\n      - name: Enter prerelease mode (alpha by default)\n        # If .changeset/pre.json does not exist and we did not recently exit\n        # prerelease mode, enter prerelease mode with tag alpha\n        if: steps.check_files.outputs.files_exists == 'false' && !contains(github.event.head_commit.message, 'Exit prerelease')\n        run: |\n          git config user.email \"41898282+github-actions[bot]@users.noreply.github.com\"\n          git config user.name \"github-actions[bot]\"\n          npx changeset pre enter alpha\n          git add -A\n          git commit -m 'Enter prerelease mode'\n          git push\n\n      - name: Create prerelease PR\n        # If .changeset/pre.json exists and we are not currently cutting a\n        # release after merging a Version Packages PR\n        if: steps.check_files.outputs.files_exists == 'true' && !startsWith(github.event.head_commit.message, 'Version Packages')\n        uses: changesets/action@v1\n        with:\n          version: npm run changeset-version\n          publish: echo \"This step should never publish\"\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/publish-pr-releases.yml",
    "content": "name: Pull Request Prerelease\n\non:\n  pull_request:\n  push:\n    branches:\n      - \"**\"\n    tags:\n      - \"!**\"\n\njobs:\n  prerelease:\n    name: Pull Request Prerelease\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n\n      - name: Check if any files in codegen/ changed\n        id: changed-files-codegen\n        uses: karpikpl/list-changed-files-action@1.1.4\n        with:\n          file-filter: \"codegen/**\"\n\n      - name: Check if any files in scripts/codemods/ac3-to-ac4/ changed\n        id: changed-files-codemod\n        uses: karpikpl/list-changed-files-action@1.1.4\n        with:\n          file-filter: \"scripts/codemods/ac3-to-ac4/**\"\n\n      - name: Install dependencies with cache\n        uses: bahmutov/npm-install@v1\n\n      - name: Build AC\n        run: npm run build\n\n      - name: Build Codegen\n        if: steps.changed-files-codegen.outputs.changed_files != ''\n        run: npm run build\n        working-directory: \"./codegen\"\n\n      - name: Build Codemod\n        if: steps.changed-files-codemod.outputs.changed_files != ''\n        run: npm run build\n        working-directory: \"./scripts/codemods/ac3-to-ac4\"\n\n      - name: Build and publish to pkg.pr.new\n        env:\n          PACKAGE_CODEGEN: ${{ steps.changed-files-codegen.outputs.changed_files != '' && './codegen' || '' }}\n          PACKAGE_CODEMOD: ${{ steps.changed-files-codemod.outputs.changed_files != '' && './scripts/codemods/ac3-to-ac4' || '' }}\n        # skipping --compact for a moment as there is an unreleased package\n        run: npx pkg-pr-new publish --no-template ./dist $PACKAGE_CODEGEN $PACKAGE_CODEMOD\n"
  },
  {
    "path": ".github/workflows/release.yml",
    "content": "name: Release\n\non:\n  push:\n    branches:\n      - main\n      - version-3.x\n      - \"release-*\"\n\nconcurrency: ${{ github.workflow }}-${{ github.ref }}\n\njobs:\n  release:\n    name: Changesets Release\n    # Prevents action from creating a PR on forks\n    if: github.repository == 'apollographql/apollo-client'\n    runs-on: ubuntu-latest\n    # Permissions necessary for Changesets to push a new branch and open PRs\n    # (for automated Version Packages PRs), and request the JWT for provenance.\n    # More info: https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect#adding-permissions-settings\n    permissions:\n      contents: write\n      pull-requests: write\n      id-token: write\n    outputs:\n      published: ${{ steps.changesets.outputs.published || steps.changesets-prerelease.outputs.published }}\n      publishedPackages: ${{ steps.changesets.outputs.publishedPackages || steps.changesets-prerelease.outputs.publishedPackages }}\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n        with:\n          # Fetch entire git history so  Changesets can generate changelogs\n          # with the correct commits\n          fetch-depth: 0\n\n      - name: Check for pre.json file existence\n        id: check_files\n        uses: andstor/file-existence-action@v3.0.0\n        with:\n          files: \".changeset/pre.json\"\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \"24.x\"\n          registry-url: \"https://registry.npmjs.org\"\n\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n\n      - name: \"[main] Create release PR or publish to npm + GitHub\"\n        id: changesets\n        if: contains(fromJSON('[\"main\", \"version-3.x\"]'), github.ref_name) && steps.check_files.outputs.files_exists == 'false'\n        uses: changesets/action@v1\n        with:\n          version: npm run changeset-version\n          publish: npm run changeset-publish\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          NPM_TOKEN: \"\"\n\n      - name: \"[prerelease] Publish to npm + GitHub\"\n        id: changesets-prerelease\n        # Only run publish if we're still in pre mode and the last commit was\n        # via an automatically created Version Packages PR\n        if: github.ref_name != 'main' && github.ref_name != 'version-3.x' && steps.check_files.outputs.files_exists == 'true' && startsWith(github.event.head_commit.message, 'Version Packages')\n        uses: changesets/action@v1\n        with:\n          version: echo \"This step should never version\"\n          publish: npm run changeset-publish\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          NPM_TOKEN: \"\"\n\n  slack-notification:\n    name: Postrelease Slack Notification\n    runs-on: ubuntu-latest\n    needs: release\n    if: needs.release.result == 'success' && needs.release.outputs.published == 'true'\n    strategy:\n      matrix:\n        package: ${{ fromJSON(needs.release.outputs.publishedPackages) }}\n    steps:\n      - name: Send a Slack notification on publish\n        id: slack\n        uses: slackapi/slack-github-action@v1.27.0\n        with:\n          # Slack channel id, channel name, or user id to post message\n          # See also: https://api.slack.com/methods/chat.postMessage#channels\n          # You can pass in multiple channels to post to by providing\n          # a comma-delimited list of channel IDs\n          channel-id: \"C01PS0CB41G\"\n          payload: |\n            {\n              \"blocks\": [\n                {\n                  \"type\": \"section\",\n                  \"text\": {\n                    \"type\": \"mrkdwn\",\n                    \"text\": \"A new version of `{{ matrix.package.name }}` was released :rocket:\"\n                  }\n                },\n                {\n                  \"type\": \"section\",\n                  \"fields\": [\n                    {\n                      \"type\": \"mrkdwn\",\n                      \"text\": \"*Version:*\\n`${{ matrix.package.version }}`\"\n                    },\n                    {\n                      \"type\": \"mrkdwn\",\n                      \"text\": \"*Tag:*\\n`${{ github.ref_name == 'main' && 'latest' || 'next' }}`\"\n                    },\n                    {\n                      \"type\": \"mrkdwn\",\n                      \"text\": \"*GitHub release:*\\n<https://github.com/apollographql/apollo-client/releases/tag/${{ matrix.package.name }}@${{ matrix.package.version }}|link>\"\n                    },\n                    {\n                      \"type\": \"mrkdwn\",\n                      \"text\": \"*npm releases:*\\n<https://www.npmjs.com/package/@apollo/client?activeTab=versions|link>\"\n                    }\n                  ]\n                }\n              ]\n            }\n        env:\n          SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}\n\n  tag-next:\n    name: Postrelease Tag Next Release\n    runs-on: ubuntu-latest\n    needs: release\n    if: github.ref_name != 'main' && github.ref_name != 'version-3.x' && needs.release.result == 'success' && needs.release.outputs.published == 'true'\n    permissions:\n      id-token: write\n    strategy:\n      matrix:\n        package: ${{ fromJSON(needs.release.outputs.publishedPackages) }}\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \"24.x\"\n          registry-url: \"https://registry.npmjs.org\"\n\n      - name: Install dependencies with cache\n        uses: bahmutov/npm-install@v1\n\n      - name: Tag release with next on npm\n        run: |\n          if NEXT=$(npm show ${{ matrix.package.name }}@next version) node -e 'process.exit(require(\"semver\").gt(\"${{ matrix.package.version }}\",process.env.NEXT)?0:1)'; then\n            npm dist-tag add ${{ matrix.package.name }}@${{ matrix.package.version }} next;\n          fi\n"
  },
  {
    "path": ".github/workflows/scheduled-test-canary.yml",
    "content": "# a GitHub Action that once a day runs all tests from `main` and `release-*` branches\n# with the latest `canary` and `experimental` release of `react` and `react-dom`\nname: Scheduled React Canary Test\non:\n  schedule:\n    - cron: \"0 0 * * *\"\n  workflow_dispatch:\n    inputs:\n      branches:\n        description: \"Branches to test\"\n        required: true\n        default: '[\"main\", \"release-3.13\", \"release-4.0\"]'\n      tags:\n        description: \"React and React-DOM versions\"\n        required: true\n        default: '[\"canary\", \"experimental\"]'\njobs:\n  test:\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        tag: ${{ fromJson(github.event_name == 'workflow_dispatch' && inputs.tags || '[\"canary\", \"experimental\"]') }}\n        branch: ${{ fromJson(github.event_name == 'workflow_dispatch' && inputs.branches || '[\"main\", \"release-3.13\", \"release-4.0\"]') }}\n    steps:\n      - uses: actions/checkout@v6\n        with:\n          ref: ${{ matrix.branch }}\n      - uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n      - uses: bahmutov/npm-install@v1\n      - run: |\n          npm install react@${{ matrix.tag }} react-dom@${{ matrix.tag }}\n      # tests can be flaky, this runs only once a day and we want to minimize false negatives - retry up to three times\n      - run: |\n          node -e 'console.log(\"\\n\\nReact %s, React-DOM %s\\n\\n\", require(\"react\").version, require(\"react-dom\").version)'\n          parallel --line-buffer -j 1 --retries 3 'npm test -- --logHeapUsage --selectProjects ' ::: 'ReactDOM 19'\n"
  },
  {
    "path": ".github/workflows/size-limit.yml",
    "content": "name: \"size\"\non:\n  pull_request:\n    branches:\n      - main\n      - release-*\n      - pr/*\njobs:\n  size:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v6\n      - name: Setup Node.js\n        uses: actions/setup-node@v6\n        with:\n          node-version: \">=23.6.0\"\n      - name: Install dependencies (with cache)\n        uses: bahmutov/npm-install@v1\n      - name: Run size-limit\n        uses: andresz1/size-limit-action@v1\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "# Installed via Github Copilot Setup Steps, should not be committed\n.agents/skills/apollo-client\n.github/instructions/docs.instructions.md\n.github/skills/apollo-client\n\n# fs\n.DS_Store\n.rpt2_cache\n\n# Logs\nlogs\n*.log\n\n# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Ignore Wallaby.js configuration file\nwallaby.js\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directory\n# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git\nnode_modules\n\n# don't commit compiled files\nlib\nbenchmark_lib\ntest-lib\ndist\nnpm\n!flow-typed/npm\n\n# Unpublished output from @apollo/client build, like bundlesize artifacts\ntemp/\n\n# webstorm\n.idea/\n\n# alm editor\n.alm\n\nyarn.lock\n\n# docs\ndb.json\ndocs.json\n*.log\ndocs/public/*\n.idea/\n\njunit.xml\n\n.rpt2_cache\n\n# Local Netlify folder\n.netlify\n\n# Ignore generated test report output\nreports\n\nesbuild-why-*.html\n\n.yalc\nyalc.lock\n\n.attest\n.ignore\n"
  },
  {
    "path": ".npmrc",
    "content": "legacy-peer-deps=true\n"
  },
  {
    "path": ".prettierignore",
    "content": "##### DISCLAIMER ######\n# We have disabled the use of prettier in this project for a variety of reasons.\n# Because much of this project has not been formatted, we don't want to want to\n# apply formatting to everything and skew `git blame` stats. Instead, we should\n# only format newly created files that we can guarantee have no existing git\n# history. For this reason, we have disabled prettier project-wide except for\n# a handful of files.\n#\n# ONLY ADD NEWLY CREATED FILES/PATHS TO THE LIST BELOW. DO NOT ADD EXISTING\n# PROJECT FILES.\n\n# Ignore all mdx & md files:\n*.har\n*.snap\n\nnode_modules/\n.api-reports/\n.yalc/\n.next/\n.changeset/\npnpm-lock.yaml\nscripts/codemods/ac3-to-ac4/src/__testfixtures__\n"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"bracketSpacing\": true,\n  \"printWidth\": 80,\n  \"semi\": true,\n  \"singleQuote\": false,\n  \"tabWidth\": 2,\n  \"trailingComma\": \"es5\",\n  \"experimentalTernaries\": true,\n  \"plugins\": [\n    \"./config/prettier/format-jsdoc.js\",\n    \"./config/prettier/format-mdx3.js\"\n  ],\n  \"overrides\": [\n    {\n      \"files\": [\"*.ts\", \"*.tsx\"],\n      \"options\": {\n        \"parser\": \"typescript-with-jsdoc\"\n      }\n    },\n    {\n      \"files\": [\"**/__tests__/**/*.ts\", \"**/__tests__/**/*.tsx\"],\n      \"options\": {\n        \"parser\": \"typescript\"\n      }\n    },\n    {\n      \"files\": [\"*.mdx\"],\n      \"options\": {\n        \"parser\": \"mdx3\"\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".semgrepignore",
    "content": "# semgrep defaults\n# https://semgrep.dev/docs/ignoring-files-folders-code#defining-ignored-files-and-folders-in-semgrepignore\nnode_modules/\ndist/\n*.min.js\n.npm/\n.yarn/\n.semgrep\n.semgrep_logs/\n\n# custom paths\n__tests__/\n./docs/source/data/subscriptions.mdx\n./docs/source/development-testing/developer-tooling.mdx"
  },
  {
    "path": ".size-limit.cjs",
    "content": "const limits = require(\"./.size-limits.json\");\n\nconst checks = [\n  {\n    import: { \"@apollo/client\": \"{ ApolloClient, InMemoryCache, HttpLink }\" },\n    conditions: [\"require\"],\n  },\n  {\n    import: { \"@apollo/client\": \"{ ApolloClient, InMemoryCache, HttpLink }\" },\n  },\n  ...[\n    \"ApolloProvider\",\n    \"useQuery\",\n    \"useLazyQuery\",\n    \"useMutation\",\n    \"useSubscription\",\n    \"useSuspenseQuery\",\n    \"useBackgroundQuery\",\n    \"useLoadableQuery\",\n    \"useReadQuery\",\n    \"useFragment\",\n  ].map((name) => ({ import: { \"@apollo/client/react\": `{ ${name} }` } })),\n]\n  .map((config) => ({\n    ...config,\n    name:\n      config.name || config.import ?\n        `import ${Object.values(config.import)[0]} from \"${\n          Object.keys(config.import)[0]\n        }\"`\n      : config.path,\n    brotli: true,\n    ignore: [\n      ...(config.ignore || []),\n      \"react\",\n      \"react-dom\",\n      \"@graphql-typed-document-node/core\",\n      \"@wry/caches\",\n      \"@wry/context\",\n      \"@wry/equality\",\n      \"@wry/trie\",\n      \"graphql-tag\",\n      \"optimism\",\n      \"prop-types\",\n      \"response-iterator\",\n      \"symbol-observable\",\n      \"ts-invariant\",\n      \"tslib\",\n      \"zen-observable-ts\",\n    ],\n  }))\n  .flatMap((value) => [\n    {\n      ...value,\n      conditions: [\"development\"].concat(\n        value.conditions || [\"module\", \"browser\"]\n      ),\n    },\n    {\n      ...value,\n      name: `${value.name} (production)`,\n      conditions: [\"production\"].concat(\n        value.conditions || [\"module\", \"browser\"]\n      ),\n    },\n  ])\n  .map((value) => {\n    const conditions = value.conditions;\n    delete value.conditions;\n    if (conditions.includes(\"require\")) {\n      value.name = `${value.name} (CJS)`;\n    }\n    value.limit = limits[value.name];\n    value.modifyEsbuildConfig = (config) => {\n      config.conditions = conditions;\n      return config;\n    };\n    return value;\n  });\n\n// useful snippet to locally run this with `size-limit --save-bundle /tmp/size --clean-dir` to debug bundle sizes\nmodule.exports = checks; //.filter(  (limit) => limit.name === Object.keys(limits).at(-1));\n"
  },
  {
    "path": ".size-limits.json",
    "content": "{\n  \"import { ApolloClient, InMemoryCache, HttpLink } from \\\"@apollo/client\\\" (CJS)\": 46872,\n  \"import { ApolloClient, InMemoryCache, HttpLink } from \\\"@apollo/client\\\" (production) (CJS)\": 41484,\n  \"import { ApolloClient, InMemoryCache, HttpLink } from \\\"@apollo/client\\\"\": 35505,\n  \"import { ApolloClient, InMemoryCache, HttpLink } from \\\"@apollo/client\\\" (production)\": 29301\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n  \"version\": \"0.2.0\",\n  \"configurations\": [\n    {\n      \"name\": \"NodeJS Attach\",\n      \"port\": 9229,\n      \"request\": \"attach\",\n      \"skipFiles\": [\"<node_internals>/**\"],\n      \"type\": \"node\"\n    },\n    {\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"name\": \"Jest Attach Node Inspector for Current File\",\n      \"cwd\": \"${workspaceFolder}\",\n      \"runtimeArgs\": [\n        \"--inspect-brk\",\n        \"${workspaceRoot}/node_modules/.bin/jest\",\n        \"${relativeFile}\",\n        \"--config\",\n        \"./config/jest.config.ts\",\n        \"--runInBand\",\n        \"--watch\"\n      ],\n      \"console\": \"integratedTerminal\",\n      \"internalConsoleOptions\": \"neverOpen\"\n    }\n  ]\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "// Place your settings in this file to overwrite default and user settings.\n{\n  \"editor.tabSize\": 2,\n  \"editor.rulers\": [80],\n  \"files.trimTrailingWhitespace\": true,\n  \"files.insertFinalNewline\": true,\n  \"typescript.tsdk\": \"node_modules/typescript/lib\",\n  \"mdx.server.enable\": true,\n  \"editor.codeActionsOnSave\": {\n    \"source.organizeImports\": \"never\"\n  },\n  \"cSpell.enableFiletypes\": [\"mdx\"],\n  \"jest.jestCommandLine\": \"node --expose-gc  node_modules/.bin/jest --config ./config/jest.config.ts --ignoreProjects 'ReactDOM 17' --ignoreProjects 'ReactDOM 18' --ignoreProjects 'Core Tests - RxJS min version' --runInBand\"\n}\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# @apollo/client\n\n## 4.1.6\n\n### Patch Changes\n\n- [#13128](https://github.com/apollographql/apollo-client/pull/13128) [`6c0b8e4`](https://github.com/apollographql/apollo-client/commit/6c0b8e4301609b62ed599340589c978e4f51f020) Thanks [@pavelivanov](https://github.com/pavelivanov)! - Fix `useQuery` hydration mismatch when `ssr: false` and `skip: true` are used together\n\n  When both options were combined, the server would return `loading: false` (because `useSSRQuery` checks `skip` first), but the client's `getServerSnapshot` was returning `ssrDisabledResult` with `loading: true`, causing a hydration mismatch.\n\n## 4.1.5\n\n### Patch Changes\n\n- [#13155](https://github.com/apollographql/apollo-client/pull/13155) [`3ba1583`](https://github.com/apollographql/apollo-client/commit/3ba1583f93c40343501acd9d598ce506537d1c9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where `useQuery` would poll with `pollInterval` when `skip` was initialized to `true`.\n\n- [#13135](https://github.com/apollographql/apollo-client/pull/13135) [`fd42142`](https://github.com/apollographql/apollo-client/commit/fd42142495d24859a9bc7145a85bc8f8d857ec88) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where `client.query` would apply options from `defaultOptions.watchQuery`.\n\n## 4.1.4\n\n### Patch Changes\n\n- [#13124](https://github.com/apollographql/apollo-client/pull/13124) [`578081f`](https://github.com/apollographql/apollo-client/commit/578081f2da7f2f54c0dd2711ee4a97530a5c38fc) Thanks [@Re-cool](https://github.com/Re-cool)! - Ensure `PersistedQueryLink` merges `http` and `fetchOptions` context values instead of overwriting them.\n\n## 4.1.3\n\n### Patch Changes\n\n- [#13111](https://github.com/apollographql/apollo-client/pull/13111) [`bf46fe0`](https://github.com/apollographql/apollo-client/commit/bf46fe019b316ea8a87a05981a89fac5411260b4) Thanks [@RogerHYang](https://github.com/RogerHYang)! - Fix `createFetchMultipartSubscription` to support cancellation via `AbortController`\n\n  Previously, calling `dispose()` or `unsubscribe()` on a subscription created by `createFetchMultipartSubscription` had no effect - the underlying fetch request would continue running until completion. This was because no `AbortController` was created or passed to `fetch()`, and no cleanup function was returned from the Observable.\n\n## 4.1.2\n\n### Patch Changes\n\n- [#13105](https://github.com/apollographql/apollo-client/pull/13105) [`8b62263`](https://github.com/apollographql/apollo-client/commit/8b62263e19b3442e20fea822de62074cf4f5cb22) Thanks [@phryneas](https://github.com/phryneas)! - `ssrMode`, `ssrForceFetchDelay` or `prioritizeCacheValues` should not override `fetchPolicy: 'cache-only'`, `fetchPolicy: 'no-cache'`, `fetchPolicy: 'standby'`, `skip: true`, or `skipToken` when reading the initial value of an `ObservableQuery`.\n\n- [#13105](https://github.com/apollographql/apollo-client/pull/13105) [`8b62263`](https://github.com/apollographql/apollo-client/commit/8b62263e19b3442e20fea822de62074cf4f5cb22) Thanks [@phryneas](https://github.com/phryneas)! - Fix `skipToken` in `useQuery` with `prerenderStatic` and related SSR functions.\n\n- [#13105](https://github.com/apollographql/apollo-client/pull/13105) [`8b62263`](https://github.com/apollographql/apollo-client/commit/8b62263e19b3442e20fea822de62074cf4f5cb22) Thanks [@phryneas](https://github.com/phryneas)! - Avoid fetches with `fetchPolicy: no-cache` in `useQuery` with `prerenderStatic` and related SSR functions.\n\n## 4.1.1\n\n### Patch Changes\n\n- [#13103](https://github.com/apollographql/apollo-client/pull/13103) [`dee7dcf`](https://github.com/apollographql/apollo-client/commit/dee7dcff4d4baa26d623d1ecace60be88c684c1a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `@client` fields that are children of aliased server fields are resolved correctly.\n\n## 4.1.0\n\n### Minor Changes\n\n- [#13043](https://github.com/apollographql/apollo-client/pull/13043) [`65e66ca`](https://github.com/apollographql/apollo-client/commit/65e66cafb6828b63d14b64877bbad47af95f66e4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Support `headers` transport for enhanced client awareness.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`785e223`](https://github.com/apollographql/apollo-client/commit/785e2232b4f7d9e561611cd4f45b8fdd1e44319e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - You can now provide a callback function as the `context` option on the `mutate` function returned by `useMutation`. The callback function is called with the value of the `context` option provided to the `useMutation` hook. This is useful if you'd like to merge the context object provided to the `useMutation` hook with a value provided to the `mutate` function.\n\n  ```ts\n  function MyComponent() {\n    const [mutate, result] = useMutation(MUTATION, {\n      context: { foo: true },\n    });\n\n    async function runMutation() {\n      await mutate({\n        // sends context as { foo: true, bar: true }\n        context: (hookContext) => ({ ...hookContext, bar: true }),\n      });\n    }\n\n    // ...\n  }\n  ```\n\n- [#12923](https://github.com/apollographql/apollo-client/pull/12923) [`94ea3e3`](https://github.com/apollographql/apollo-client/commit/94ea3e32c82dd767b62a6907be6c3891864633af) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where deferred payloads that returned arrays with fewer items than the original cached array would retain items from the cached array. This change includes `@stream` arrays where stream arrays replace the cached arrays.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`96b531f`](https://github.com/apollographql/apollo-client/commit/96b531f6b57a158aa2c57da976c6dd22c1a7f4d5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't set the fallback value of a `@client` field to `null` when a `read` function is defined. Instead the `read` function will be called with an `existing` value of `undefined` to allow default arguments to be used to set the returned value.\n\n  When a `read` function is not defined nor is there a defined resolver for the field, warn and set the value to `null` only in that instance.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`45ebb52`](https://github.com/apollographql/apollo-client/commit/45ebb52bcb84b81ce3a066204456c2e20f3d4c98) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `from: null` in `client.watchFragment` and `cache.watchFragment`. When `from` is `null`, the emitted result is:\n\n  ```ts\n  {\n    data: null,\n    dataState: \"complete\",\n    complete: true,\n  }\n  ```\n\n- [#12926](https://github.com/apollographql/apollo-client/pull/12926) [`2b7f2c1`](https://github.com/apollographql/apollo-client/commit/2b7f2c167fc4a94e06457777f0c57b6dac7b2f2f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Support the newer incremental delivery format for the `@defer` directive implemented in `graphql@17.0.0-alpha.9`. Import the `GraphQL17Alpha9Handler` to use the newer incremental delivery format with `@defer`.\n\n  ```ts\n  import { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\n\n  const client = new ApolloClient({\n    // ...\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n  ```\n\n  > [!NOTE]\n  > In order to use the `GraphQL17Alpha9Handler`, the GraphQL server MUST implement the newer incremental delivery format. You may see errors or unusual behavior if you use the wrong handler. If you are using Apollo Router, continue to use the `Defer20220824Handler` because Apollo Router does not yet support the newer incremental delivery format.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`45ebb52`](https://github.com/apollographql/apollo-client/commit/45ebb52bcb84b81ce3a066204456c2e20f3d4c98) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for arrays with `useFragment`, `useSuspenseFragment`, and `client.watchFragment`. This allows the ability to use a fragment to watch multiple entities in the cache. Passing an array to `from` will return `data` as an array where each array index corresponds to the index in the `from` array.\n\n  ```ts\n  function MyComponent() {\n    const result = useFragment({\n      fragment,\n      from: [item1, item2, item3],\n    });\n\n    // `data` is an array with 3 items\n    console.log(result); // { data: [{...}, {...}, {...}], dataState: \"complete\", complete: true }\n  }\n  ```\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`45ebb52`](https://github.com/apollographql/apollo-client/commit/45ebb52bcb84b81ce3a066204456c2e20f3d4c98) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `getCurrentResult` function to the observable returned by `client.watchFragment` and `cache.watchFragment` that returns the current value for the watched fragment.\n\n  ```ts\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  console.log(observable.getCurrentResult());\n  // {\n  //   data: {...},\n  //   dataState: \"complete\",\n  //   complete: true,\n  // }\n  ```\n\n- [#13038](https://github.com/apollographql/apollo-client/pull/13038) [`109efe7`](https://github.com/apollographql/apollo-client/commit/109efe7e4380b579c6a577982bd9a6e8c6a53892) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the `from` option to `readFragment`, `watchFragment`, and `updateFragment`.\n\n- [#12918](https://github.com/apollographql/apollo-client/pull/12918) [`2e224b9`](https://github.com/apollographql/apollo-client/commit/2e224b99894432822f926fdfec36bd46dd73b35e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for the `@stream` directive on both the `Defer20220824Handler` and the `GraphQL17Alpha2Handler`.\n\n  > [!NOTE]\n  > The implementations of `@stream` differ in the delivery of incremental results between the different GraphQL spec versions. If you upgrading from the older format to the newer format, expect the timing of some incremental results to change.\n\n- [#13056](https://github.com/apollographql/apollo-client/pull/13056) [`b224efc`](https://github.com/apollographql/apollo-client/commit/b224efc25515370c68b514405762e68a443e4a4a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `InMemoryCache` no longer filters out explicitly returned `undefined` items from `read` functions for array fields. This now makes it possible to create `read` functions on array fields that return partial data and trigger a fetch for the full list.\n\n- [#13058](https://github.com/apollographql/apollo-client/pull/13058) [`121a2cb`](https://github.com/apollographql/apollo-client/commit/121a2cb68820727186ecd74ce1041ef95284682e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an `extensions` option to `cache.write`, `cache.writeQuery`, and `client.writeQuery`. This makes `extensions` available in cache `merge` functions which can be accessed with the other merge function options.\n\n  As a result of this change, any `extensions` returned in GraphQL operations are now available in `merge` in the cache writes for these operations.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`96b531f`](https://github.com/apollographql/apollo-client/commit/96b531f6b57a158aa2c57da976c6dd22c1a7f4d5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an abstract `resolvesClientField` function to `ApolloCache` that can be used by caches to tell `LocalState` if it can resolve a `@client` field when a local resolver is not defined.\n\n  `LocalState` will emit a warning and set a fallback value of `null` when no local resolver is defined and `resolvesClientField` returns `false`, or isn't defined. Returning `true` from `resolvesClientField` signals that a mechanism in the cache will set the field value. In this case, `LocalState` won't set the field value.\n\n- [#13078](https://github.com/apollographql/apollo-client/pull/13078) [`bf1e0dc`](https://github.com/apollographql/apollo-client/commit/bf1e0dcb2f6c9b94576dc6d049745f1869cd0043) Thanks [@phryneas](https://github.com/phryneas)! - Use the default stream merge function for `@stream` fields only if stream info is present. This change means that using the older `Defer20220824Handler` will not use the default stream merge function and will instead truncate the streamed array on the first chunk.\n\n### Patch Changes\n\n- [#12884](https://github.com/apollographql/apollo-client/pull/12884) [`d329790`](https://github.com/apollographql/apollo-client/commit/d32979070381f1897c90fb276e25a0c8375cc29a) Thanks [@phryneas](https://github.com/phryneas)! - Ensure that `PreloadedQueryRef` instances are unsubscribed when garbage collected\n\n- [#13086](https://github.com/apollographql/apollo-client/pull/13086) [`1a1d408`](https://github.com/apollographql/apollo-client/commit/1a1d4088f549088d4af3ff1f2d08d1c8e9af2a4d) Thanks [@phryneas](https://github.com/phryneas)! - Change the returned value from `null` to `{}` when all fields in a query were skipped.\n\n  This also fixes a bug where `useSuspenseQuery` would suspend indefinitely when all fields were skipped.\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where errors parsed from incremental chunks in `ErrorLink` might throw when using the `GraphQL17Alpha9Handler`.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`45ebb52`](https://github.com/apollographql/apollo-client/commit/45ebb52bcb84b81ce3a066204456c2e20f3d4c98) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deduplicate watches created by `useFragment`, `client.watchFragment`, and `cache.watchFragment` that contain the same fragment, variables, and identifier. This should improve performance in situations where a `useFragment` or a `client.watchFragment` is used to watch the same object in multiple places of an application.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`259ae9b`](https://github.com/apollographql/apollo-client/commit/259ae9bafaa8122996b0a52dd99828b2261087e5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow `FragmentType` not only to be called as `FragmentType<TData>`, but also as `FragmentType<TypedDocumentNode>`.\n\n- [#12925](https://github.com/apollographql/apollo-client/pull/12925) [`5851800`](https://github.com/apollographql/apollo-client/commit/58518000edebb2a4b75c36ed22e9b67b3a254fa0) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where calling `fetchMore` with `@defer` or `@stream` would not rerender incremental results as they were streamed.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`9e55188`](https://github.com/apollographql/apollo-client/commit/9e55188adcb4cf4236b14eb552286a4505650a29) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Truncate `@stream` arrays only on last chunk by default.\n\n- [#13083](https://github.com/apollographql/apollo-client/pull/13083) [`f3c2be1`](https://github.com/apollographql/apollo-client/commit/f3c2be1665d8e2e260a4f55ec803d6e609748390) Thanks [@phryneas](https://github.com/phryneas)! - Expose the `ExtensionsWithStreamInfo` type for `extensions` in `Cache.writeQuery`, `Cache.write` and `Cache.update` so other cache implementations also can correctly access them.\n\n- [#12923](https://github.com/apollographql/apollo-client/pull/12923) [`94ea3e3`](https://github.com/apollographql/apollo-client/commit/94ea3e32c82dd767b62a6907be6c3891864633af) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Improve the cache data loss warning message when `existing` or `incoming` is an array.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`4631175`](https://github.com/apollographql/apollo-client/commit/46311758f703ec7baa9013a49b897e823fd4edb0) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ignore top-level `data` values on subsequent chunks in incremental responses.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`2be8de2`](https://github.com/apollographql/apollo-client/commit/2be8de26f1bb68d2d6cd0d286565d47455332b47) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Create mechanism to add experimental features to Apollo Client\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`96b531f`](https://github.com/apollographql/apollo-client/commit/96b531f6b57a158aa2c57da976c6dd22c1a7f4d5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `LocalState` doesn't try to read from the cache when using a `no-cache` fetch policy.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`bb8ed7b`](https://github.com/apollographql/apollo-client/commit/bb8ed7b6b7e36e313822e44b230e27031d6fcbd9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure an error is thrown when `@stream` is detected and an `incrementalDelivery` handler is not configured.\n\n- [#13053](https://github.com/apollographql/apollo-client/pull/13053) [`23ca0ba`](https://github.com/apollographql/apollo-client/commit/23ca0ba895473b397805e6bcc70e0fcf987547c5) Thanks [@phryneas](https://github.com/phryneas)! - Use memoized observable mapping when using `watchFragment`, `useFragment` or `useSuspenseFragment`.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`44706a2`](https://github.com/apollographql/apollo-client/commit/44706a2e7ae2c977fa917214a1ff5e5fe4a9b3a7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add helper type `QueryRef.ForQuery<TypedDocumentNode>`\n\n- [#13082](https://github.com/apollographql/apollo-client/pull/13082) [`c257418`](https://github.com/apollographql/apollo-client/commit/c2574181f6b0d9ae059dfa3822a7842ec5f8ff1f) Thanks [@phryneas](https://github.com/phryneas)! - Pass `streamInfo` through result extensions as a `WeakRef`.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`4631175`](https://github.com/apollographql/apollo-client/commit/46311758f703ec7baa9013a49b897e823fd4edb0) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the `Defer20220824Handler.SubsequentResult` type to match the `FormattedSubsequentIncrementalExecutionResult` type in `graphql@17.0.0-alpha.2`.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`96b531f`](https://github.com/apollographql/apollo-client/commit/96b531f6b57a158aa2c57da976c6dd22c1a7f4d5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using a `no-cache` fetch policy without a local resolver defined. `no-cache` queries do not read or write to the cache which meant `no-cache` queries are silently incomplete when the `@client` field value was handled by a cache `read` function.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`5776ea0`](https://github.com/apollographql/apollo-client/commit/5776ea0db1f082663dcf470c3b22b9182a3eea28) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update the `accept` header used with the `GraphQL17Alpha9Handler` to `multipart/mixed;incrementalSpec=v0.2` to ensure the newest incremental delivery format is requested.\n\n- [#12927](https://github.com/apollographql/apollo-client/pull/12927) [`45ebb52`](https://github.com/apollographql/apollo-client/commit/45ebb52bcb84b81ce3a066204456c2e20f3d4c98) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `DeepPartial<Array<TData>>` now returns `Array<DeepPartial<TData>>` instead of `Array<DeepPartial<TData | undefined>>`.\n\n- [#13071](https://github.com/apollographql/apollo-client/pull/13071) [`99ffe9a`](https://github.com/apollographql/apollo-client/commit/99ffe9a8ede1683d902101c5371807a8442fcdcb) Thanks [@phryneas](https://github.com/phryneas)! - `prerenderStatic`: Expose return value of `renderFunction` to userland, fix `aborted` property.\n\n  This enables usage of `resumeAndPrerender` with React 19.2.\n\n- [#13026](https://github.com/apollographql/apollo-client/pull/13026) [`05eee67`](https://github.com/apollographql/apollo-client/commit/05eee67e91b480252923879987534e81d2866aba) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reduce the number of observables created by `watchFragment` by reusing existing observables as much as possible. This should improve performance when watching the same item in the cache multiple times after a cache update occurs.\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Handle `@stream` payloads that send multiple items in the same chunk when using the `Defer20220824Handler`.\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Handle an edge case with the `Defer20220824Handler` where an error for a `@stream` item that bubbles to the `@stream` boundary (such as an item returning `null` for a non-null array item) would write items from future chunks to the wrong array index. In these cases, the `@stream` field is no longer processed and future updates to the field are ignored. This prevents runtime errors that TypeScript would otherwise not be able to catch.\n\n- [#13081](https://github.com/apollographql/apollo-client/pull/13081) [`1e06ad7`](https://github.com/apollographql/apollo-client/commit/1e06ad7399716139fcfbec7423697eafc5750f5e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Avoid calling `merge` functions more than once for the same incremental chunk.\n\n## 4.1.0-rc.1\n\n### Patch Changes\n\n- [#13086](https://github.com/apollographql/apollo-client/pull/13086) [`1a1d408`](https://github.com/apollographql/apollo-client/commit/1a1d4088f549088d4af3ff1f2d08d1c8e9af2a4d) Thanks [@phryneas](https://github.com/phryneas)! - Change the returned value from `null` to `{}` when all fields in a query were skipped.\n\n  This also fixes a bug where `useSuspenseQuery` would suspend indefinitely when all fields were skipped.\n\n- [#13071](https://github.com/apollographql/apollo-client/pull/13071) [`99ffe9a`](https://github.com/apollographql/apollo-client/commit/99ffe9a8ede1683d902101c5371807a8442fcdcb) Thanks [@phryneas](https://github.com/phryneas)! - `prerenderStatic`: Expose return value of `renderFunction` to userland, fix `aborted` property.\n\n  This enables usage of `resumeAndPrerender` with React 19.2.\n\n## 4.1.0-rc.0\n\n### Minor Changes\n\n- [#13078](https://github.com/apollographql/apollo-client/pull/13078) [`bf1e0dc`](https://github.com/apollographql/apollo-client/commit/bf1e0dcb2f6c9b94576dc6d049745f1869cd0043) Thanks [@phryneas](https://github.com/phryneas)! - Use the default stream merge function for `@stream` fields only if stream info is present. This change means that using the older `Defer20220824Handler` will not use the default stream merge function and will instead truncate the streamed array on the first chunk.\n\n### Patch Changes\n\n- [#13083](https://github.com/apollographql/apollo-client/pull/13083) [`f3c2be1`](https://github.com/apollographql/apollo-client/commit/f3c2be1665d8e2e260a4f55ec803d6e609748390) Thanks [@phryneas](https://github.com/phryneas)! - Expose the `ExtensionsWithStreamInfo` type for `extensions` in `Cache.writeQuery`, `Cache.write` and `Cache.update` so other cache implementations also can correctly access them.\n\n- [#13082](https://github.com/apollographql/apollo-client/pull/13082) [`c257418`](https://github.com/apollographql/apollo-client/commit/c2574181f6b0d9ae059dfa3822a7842ec5f8ff1f) Thanks [@phryneas](https://github.com/phryneas)! - Pass `streamInfo` through result extensions as a `WeakRef`.\n\n- [#13081](https://github.com/apollographql/apollo-client/pull/13081) [`1e06ad7`](https://github.com/apollographql/apollo-client/commit/1e06ad7399716139fcfbec7423697eafc5750f5e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Avoid calling `merge` functions more than once for the same incremental chunk.\n\n## 4.0.12-beta.0\n\n### Patch Changes\n\n- [#12884](https://github.com/apollographql/apollo-client/pull/12884) [`d329790`](https://github.com/apollographql/apollo-client/commit/d32979070381f1897c90fb276e25a0c8375cc29a) Thanks [@phryneas](https://github.com/phryneas)! - Ensure that `PreloadedQueryRef` instances are unsubscribed when garbage collected\n\n- [#13069](https://github.com/apollographql/apollo-client/pull/13069) [`9cad04a`](https://github.com/apollographql/apollo-client/commit/9cad04a4228a5059ea330ac9d284407a363fc10d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Truncate @stream arrays only on last chunk by default\n\n## 4.1.0-alpha.9\n\n### Minor Changes\n\n- [#13056](https://github.com/apollographql/apollo-client/pull/13056) [`b224efc`](https://github.com/apollographql/apollo-client/commit/b224efc25515370c68b514405762e68a443e4a4a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `InMemoryCache` no longer filters out explicitly returned `undefined` items from `read` functions for array fields. This now makes it possible to create `read` functions on array fields that return partial data and trigger a fetch for the full list.\n\n- [#13058](https://github.com/apollographql/apollo-client/pull/13058) [`121a2cb`](https://github.com/apollographql/apollo-client/commit/121a2cb68820727186ecd74ce1041ef95284682e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an `extensions` option to `cache.write`, `cache.writeQuery`, and `client.writeQuery`. This makes `extensions` available in cache `merge` functions which can be accessed with the other merge function options.\n\n  As a result of this change, any `extensions` returned in GraphQL operations are now available in `merge` in the cache writes for these operations.\n\n### Patch Changes\n\n- [#13053](https://github.com/apollographql/apollo-client/pull/13053) [`23ca0ba`](https://github.com/apollographql/apollo-client/commit/23ca0ba895473b397805e6bcc70e0fcf987547c5) Thanks [@phryneas](https://github.com/phryneas)! - Use memoized observable mapping when using `watchFragment`, `useFragment` or `useSuspenseFragment`.\n\n## 4.1.0-alpha.10\n\n### Patch Changes\n\n- [#13053](https://github.com/apollographql/apollo-client/pull/13053) [`23ca0ba`](https://github.com/apollographql/apollo-client/commit/23ca0ba895473b397805e6bcc70e0fcf987547c5) Thanks [@phryneas](https://github.com/phryneas)! - Use memoized observable mapping when using `watchFragment`, `useFragment` or `useSuspenseFragment`.\n\n## 4.1.0-alpha.9\n\n### Minor Changes\n\n- [#13056](https://github.com/apollographql/apollo-client/pull/13056) [`b224efc`](https://github.com/apollographql/apollo-client/commit/b224efc25515370c68b514405762e68a443e4a4a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `InMemoryCache` no longer filters out explicitly returned `undefined` items from `read` functions for array fields. This now makes it possible to create `read` functions on array fields that return partial data and trigger a fetch for the full list.\n\n## 4.1.0-alpha.8\n\n### Minor Changes\n\n- [#13043](https://github.com/apollographql/apollo-client/pull/13043) [`65e66ca`](https://github.com/apollographql/apollo-client/commit/65e66cafb6828b63d14b64877bbad47af95f66e4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Support `headers` transport for enhanced client awareness.\n\n## 4.1.0-alpha.7\n\n### Minor Changes\n\n- [#13038](https://github.com/apollographql/apollo-client/pull/13038) [`109efe7`](https://github.com/apollographql/apollo-client/commit/109efe7e4380b579c6a577982bd9a6e8c6a53892) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the `from` option to `readFragment`, `watchFragment`, and `updateFragment`.\n\n## 4.1.0-alpha.6\n\n### Patch Changes\n\n- [#13026](https://github.com/apollographql/apollo-client/pull/13026) [`05eee67`](https://github.com/apollographql/apollo-client/commit/05eee67e91b480252923879987534e81d2866aba) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reduce the number of observables created by `watchFragment` by reusing existing observables as much as possible. This should improve performance when watching the same item in the cache multiple times after a cache update occurs.\n\n## 4.1.0-alpha.5\n\n### Patch Changes\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where errors parsed from incremental chunks in `ErrorLink` might throw when using the `GraphQL17Alpha9Handler`.\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Handle `@stream` payloads that send multiple items in the same chunk when using the `Defer20220824Handler`.\n\n- [#13010](https://github.com/apollographql/apollo-client/pull/13010) [`7627000`](https://github.com/apollographql/apollo-client/commit/76270002254b0c6acb18872a39ab180f9f1e4067) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Handle an edge case with the `Defer20220824Handler` where an error for a `@stream` item that bubbles to the `@stream` boundary (such as an item returning `null` for a non-null array item) would write items from future chunks to the wrong array index. In these cases, the `@stream` field is no longer processed and future updates to the field are ignored. This prevents runtime errors that TypeScript would otherwise not be able to catch.\n\n## 4.1.0-alpha.4\n\n### Patch Changes\n\n- [#13009](https://github.com/apollographql/apollo-client/pull/13009) [`259ae9b`](https://github.com/apollographql/apollo-client/commit/259ae9bafaa8122996b0a52dd99828b2261087e5) Thanks [@phryneas](https://github.com/phryneas)! - Allow `FragmentType` not only to be called as `FragmentType<TData>`, but also as `FragmentType<TypedDocumentNode>`.\n\n- [#13012](https://github.com/apollographql/apollo-client/pull/13012) [`44706a2`](https://github.com/apollographql/apollo-client/commit/44706a2e7ae2c977fa917214a1ff5e5fe4a9b3a7) Thanks [@phryneas](https://github.com/phryneas)! - Add helper type `QueryRef.ForQuery<TypedDocumentNode>`\n\n## 4.1.0-alpha.3\n\n### Minor Changes\n\n- [#12971](https://github.com/apollographql/apollo-client/pull/12971) [`d11eb40`](https://github.com/apollographql/apollo-client/commit/d11eb40aa41d90ac664705bac01158d58bf55e9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `from: null` in `client.watchFragment` and `cache.watchFragment`. When `from` is `null`, the emitted result is:\n\n  ```ts\n  {\n    data: null,\n    dataState: \"complete\",\n    complete: true,\n  }\n  ```\n\n- [#12971](https://github.com/apollographql/apollo-client/pull/12971) [`d11eb40`](https://github.com/apollographql/apollo-client/commit/d11eb40aa41d90ac664705bac01158d58bf55e9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for arrays with `useFragment`, `useSuspenseFragment`, and `client.watchFragment`. This allows the ability to use a fragment to watch multiple entities in the cache. Passing an array to `from` will return `data` as an array where each array index corresponds to the index in the `from` array.\n\n  ```ts\n  function MyComponent() {\n    const result = useFragment({\n      fragment,\n      from: [item1, item2, item3],\n    });\n\n    // `data` is an array with 3 items\n    console.log(result); // { data: [{...}, {...}, {...}], dataState: \"complete\", complete: true }\n  }\n  ```\n\n- [#12971](https://github.com/apollographql/apollo-client/pull/12971) [`d11eb40`](https://github.com/apollographql/apollo-client/commit/d11eb40aa41d90ac664705bac01158d58bf55e9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `getCurrentResult` function to the observable returned by `client.watchFragment` and `cache.watchFragment` that returns the current value for the watched fragment.\n\n  ```ts\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  console.log(observable.getCurrentResult());\n  // {\n  //   data: {...},\n  //   dataState: \"complete\",\n  //   complete: true,\n  // }\n  ```\n\n### Patch Changes\n\n- [#12971](https://github.com/apollographql/apollo-client/pull/12971) [`d11eb40`](https://github.com/apollographql/apollo-client/commit/d11eb40aa41d90ac664705bac01158d58bf55e9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deduplicate watches created by `useFragment`, `client.watchFragment`, and `cache.watchFragment` that contain the same fragment, variables, and identifier. This should improve performance in situations where a `useFragment` or a `client.watchFragment` is used to watch the same object in multiple places of an application.\n\n- [#12982](https://github.com/apollographql/apollo-client/pull/12982) [`5c56b32`](https://github.com/apollographql/apollo-client/commit/5c56b3210a2c03e247ec9e600f1e27eb71df5e96) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ignore top-level `data` values on subsequent chunks in incremental responses.\n\n- [#12982](https://github.com/apollographql/apollo-client/pull/12982) [`5c56b32`](https://github.com/apollographql/apollo-client/commit/5c56b3210a2c03e247ec9e600f1e27eb71df5e96) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the `Defer20220824Handler.SubsequentResult` type to match the `FormattedSubsequentIncrementalExecutionResult` type in `graphql@17.0.0-alpha.2`.\n\n- [#12973](https://github.com/apollographql/apollo-client/pull/12973) [`072da24`](https://github.com/apollographql/apollo-client/commit/072da24a8daec3a646ef0cce30de32f95ea0bb23) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update the `accept` header used with the `GraphQL17Alpha9Handler` to `multipart/mixed;incrementalSpec=v0.2` to ensure the newest incremental delivery format is requested.\n\n- [#12971](https://github.com/apollographql/apollo-client/pull/12971) [`d11eb40`](https://github.com/apollographql/apollo-client/commit/d11eb40aa41d90ac664705bac01158d58bf55e9b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `DeepPartial<Array<TData>>` now returns `Array<DeepPartial<TData>>` instead of `Array<DeepPartial<TData | undefined>>`.\n\n## 4.1.0-alpha.2\n\n### Minor Changes\n\n- [#12959](https://github.com/apollographql/apollo-client/pull/12959) [`556e837`](https://github.com/apollographql/apollo-client/commit/556e83781069d925a7e8f99e49023f6f858c6438) Thanks [@jerelmiller](https://github.com/jerelmiller)! - You can now provide a callback function as the `context` option on the `mutate` function returned by `useMutation`. The callback function is called with the value of the `context` option provided to the `useMutation` hook. This is useful if you'd like to merge the context object provided to the `useMutation` hook with a value provided to the `mutate` function.\n\n  ```ts\n  function MyComponent() {\n    const [mutate, result] = useMutation(MUTATION, {\n      context: { foo: true },\n    });\n\n    async function runMutation() {\n      await mutate({\n        // sends context as { foo: true, bar: true }\n        context: (hookContext) => ({ ...hookContext, bar: true }),\n      });\n    }\n\n    // ...\n  }\n  ```\n\n### Patch Changes\n\n- [#12954](https://github.com/apollographql/apollo-client/pull/12954) [`1c82eaf`](https://github.com/apollographql/apollo-client/commit/1c82eafe4921a9e30128202623be6c5a3d4df803) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure an error is thrown when `@stream` is detected and an `incrementalDelivery` handler is not configured.\n\n## 4.1.0-alpha.1\n\n### Minor Changes\n\n- [#12934](https://github.com/apollographql/apollo-client/pull/12934) [`54ab6d9`](https://github.com/apollographql/apollo-client/commit/54ab6d994692dad9f06d3d0b84c84d021d126577) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't set the fallback value of a `@client` field to `null` when a `read` function is defined. Instead the `read` function will be called with an `existing` value of `undefined` to allow default arguments to be used to set the returned value.\n\n  When a `read` function is not defined nor is there a defined resolver for the field, warn and set the value to `null` only in that instance.\n\n- [#12934](https://github.com/apollographql/apollo-client/pull/12934) [`54ab6d9`](https://github.com/apollographql/apollo-client/commit/54ab6d994692dad9f06d3d0b84c84d021d126577) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an abstract `resolvesClientField` function to `ApolloCache` that can be used by caches to tell `LocalState` if it can resolve a `@client` field when a local resolver is not defined.\n\n  `LocalState` will emit a warning and set a fallback value of `null` when no local resolver is defined and `resolvesClientField` returns `false`, or isn't defined. Returning `true` from `resolvesClientField` signals that a mechanism in the cache will set the field value. In this case, `LocalState` won't set the field value.\n\n### Patch Changes\n\n- [#12915](https://github.com/apollographql/apollo-client/pull/12915) [`c97b145`](https://github.com/apollographql/apollo-client/commit/c97b145188d39d754ff098ff399a80cae5b10cc0) Thanks [@phryneas](https://github.com/phryneas)! - Create mechanism to add experimental features to Apollo Client\n\n- [#12934](https://github.com/apollographql/apollo-client/pull/12934) [`54ab6d9`](https://github.com/apollographql/apollo-client/commit/54ab6d994692dad9f06d3d0b84c84d021d126577) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `LocalState` doesn't try to read from the cache when using a `no-cache` fetch policy.\n\n- [#12934](https://github.com/apollographql/apollo-client/pull/12934) [`54ab6d9`](https://github.com/apollographql/apollo-client/commit/54ab6d994692dad9f06d3d0b84c84d021d126577) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using a `no-cache` fetch policy without a local resolver defined. `no-cache` queries do not read or write to the cache which meant `no-cache` queries are silently incomplete when the `@client` field value was handled by a cache `read` function.\n\n## 4.1.0-alpha.0\n\n### Minor Changes\n\n- [#12923](https://github.com/apollographql/apollo-client/pull/12923) [`2aa31c7`](https://github.com/apollographql/apollo-client/commit/2aa31c718155e88814551afb14fd7a0035acc57d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where deferred payloads that reteurned arrays with fewer items than the original cached array would retain items from the cached array. This change includes `@stream` arrays where stream arrays replace the cached arrays.\n\n- [#12926](https://github.com/apollographql/apollo-client/pull/12926) [`c7fba99`](https://github.com/apollographql/apollo-client/commit/c7fba99e16da522fdbc35b9c16cdb8df0dda4c2c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Support the newer incremental delivery format for the `@defer` directive implemented in `graphql@17.0.0-alpha.9`. Import the `GraphQL17Alpha9Handler` to use the newer incremental delivery format with `@defer`.\n\n  ```ts\n  import { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\n\n  const client = new ApolloClient({\n    // ...\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n  ```\n\n  > [!NOTE]\n  > In order to use the `GraphQL17Alpha9Handler`, the GraphQL server MUST implement the newer incremental delivery format. You may see errors or unusual behavior if you use the wrong handler. If you are using Apollo Router, continue to use the `Defer20220824Handler` because Apollo Router does not yet support the newer incremental delivery format.\n\n- [#12918](https://github.com/apollographql/apollo-client/pull/12918) [`562e219`](https://github.com/apollographql/apollo-client/commit/562e2191a4b38e05edb3da9074e2958db3c7b6b9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for the `@stream` directive on both the `Defer20220824Handler` and the `GraphQL17Alpha2Handler`.\n\n  > [!NOTE]\n  > The implementations of `@stream` differ in the delivery of incremental results between the different GraphQL spec versions. If you upgrading from the older format to the newer format, expect the timing of some incremental results to change.\n\n### Patch Changes\n\n- [#12925](https://github.com/apollographql/apollo-client/pull/12925) [`f538a83`](https://github.com/apollographql/apollo-client/commit/f538a83621e1d110286c056dd8e91611dfd9a1d3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where calling `fetchMore` with `@defer` or `@stream` would not rerender incremental results as they were streamed.\n\n- [#12923](https://github.com/apollographql/apollo-client/pull/12923) [`01cace0`](https://github.com/apollographql/apollo-client/commit/01cace0a6d4faf79e8a4188b93c7d13c4b26d6d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Improve the cache data loss warning message when `existing` or `incoming` is an array.\n\n## 4.0.13\n\n### Patch Changes\n\n- [#13094](https://github.com/apollographql/apollo-client/pull/13094) [`9cbe2c2`](https://github.com/apollographql/apollo-client/commit/9cbe2c2dd2282ac861327d3c394578db7706df05) Thanks [@phryneas](https://github.com/phryneas)! - Ensure that `compact` and `mergeOptions` preserve symbol keys.\n\n  This fixes an issue where the change introduced in 4.0.11 via #13049 would not\n  be applied if `defaultOptions` for `watchQuery` were declared.\n\n  Please note that `compact` and `mergeOptions` are considered internal utilities\n  and they might have similar behavior changes in future releases.\n  Do not use them in your application code - a change like this is not considered\n  breaking and will not be announced as such.\n\n## 4.0.12\n\n### Patch Changes\n\n- [#13077](https://github.com/apollographql/apollo-client/pull/13077) [`f322460`](https://github.com/apollographql/apollo-client/commit/f322460fe9baae82c0980dd082c1b6b4956a4951) Thanks [@phryneas](https://github.com/phryneas)! - Fix a potential memory leak where Trie nodes would remain in memory too long.\n\n## 4.0.11\n\n### Patch Changes\n\n- [#13050](https://github.com/apollographql/apollo-client/pull/13050) [`8020829`](https://github.com/apollographql/apollo-client/commit/8020829d8a3bdb3219a37e8d1f7b89179f721037) Thanks [@phryneas](https://github.com/phryneas)! - Replace usage of `findLast` with more backwards-compatible methods.\n\n- [#13049](https://github.com/apollographql/apollo-client/pull/13049) [`05638de`](https://github.com/apollographql/apollo-client/commit/05638deaf598c5bf5d03b82d7deaf57468546229) Thanks [@phryneas](https://github.com/phryneas)! - Fixes an issue where queries starting with `skipToken` or lazy queries from `useLazyQuery` were included in `client.refetchQueries()` before they had been executed for the first time. While generally queries with a `standby` `fetchPolicy` should be included in refetch, these queries never had `variables` passed in, so they should be excluded until they have run once and received their actual variables.\n\n  These queries are now properly excluded from refetch operations until after their initial execution.\n\n  This change adds a new hidden option to `client.watchQuery`, `[variablesUnknownSymbol]`, which may be set `true` for queries starting with a `fetchPolicy` of `standby`. It will only be applied when creating the `ObservableQuery` instance and cannot be changed later. This flag indicates that the query's variables are not yet known, and thus it should be excluded from refetch operations until they are.\n  **This option is not meant for everyday use and is intended for framework integrations only.**\n\n## 4.0.10\n\n### Patch Changes\n\n- [#13045](https://github.com/apollographql/apollo-client/pull/13045) [`af4acdc`](https://github.com/apollographql/apollo-client/commit/af4acdc88bd3bac0d697ab300816241e4065842c) Thanks [@phryneas](https://github.com/phryneas)! - Fix memory leak #13036\n\n## 4.0.9\n\n### Patch Changes\n\n- [#12993](https://github.com/apollographql/apollo-client/pull/12993) [`8f3bc9b`](https://github.com/apollographql/apollo-client/commit/8f3bc9b7253a737062dc0d652cd4f8b354f68ccc) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where switching from options with `variables` to `skipToken` with `useSuspenseQuery` and `useBackgroundQuery` would create a new `ObservableQuery`. This could cause unintended refetches where `variables` were absent in the request when the query was referenced with `refetchQueries`.\n\n## 4.0.8\n\n### Patch Changes\n\n- [#12983](https://github.com/apollographql/apollo-client/pull/12983) [`f6d0efa`](https://github.com/apollographql/apollo-client/commit/f6d0efac4d99375c67255aee6d9b2981753b6f55) Thanks [@CarsonF](https://github.com/CarsonF)! - Fix cache.modify() mapping readonly arrays to singular reference\n\n## 4.0.7\n\n### Patch Changes\n\n- [#12950](https://github.com/apollographql/apollo-client/pull/12950) [`5b4f36a`](https://github.com/apollographql/apollo-client/commit/5b4f36a2b249d15e2e8165bd32d9b2fca7e70217) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't send `operationType` in the payload sent by `GraphQLWsLink`.\n\n## 4.0.6\n\n### Patch Changes\n\n- [#12937](https://github.com/apollographql/apollo-client/pull/12937) [`3b0d89b`](https://github.com/apollographql/apollo-client/commit/3b0d89bc9dde3eaee9ddf0aec387da43fe71abc0) Thanks [@phryneas](https://github.com/phryneas)! - Fix a problem with `fetchMore` where the loading state wouldn't reset if the result wouldn't result in a data update.\n\n## 4.0.5\n\n### Patch Changes\n\n- [#12920](https://github.com/apollographql/apollo-client/pull/12920) [`e2fc385`](https://github.com/apollographql/apollo-client/commit/e2fc3850ddb2aa756fc44420390ae357daf31948) Thanks [@phryneas](https://github.com/phryneas)! - Fix an invariance type error in the `MockedResponse` type.\n\n## 4.0.4\n\n### Patch Changes\n\n- [#12892](https://github.com/apollographql/apollo-client/pull/12892) [`db8a04b`](https://github.com/apollographql/apollo-client/commit/db8a04b193c157d57d6fe0f187b1892afdda1b7d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent unhandled rejections from the promise returned by calling the `mutate` function from the `useMutation` hook.\n\n- [#12899](https://github.com/apollographql/apollo-client/pull/12899) [`5352c12`](https://github.com/apollographql/apollo-client/commit/5352c1208e19c93678fef7860a1a87841653eb64) Thanks [@phryneas](https://github.com/phryneas)! - Fix an issue when `invariant` is called by external libraries when no dev error message handler is loaded.\n\n- [#12895](https://github.com/apollographql/apollo-client/pull/12895) [`71f2517`](https://github.com/apollographql/apollo-client/commit/71f2517132a34563a14934f3971666b3691710f9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Support `skipToken` with `useQuery` to provide a more type-safe way to skip query execution.\n\n  ```ts\n  import { skipToken, useQuery } from \"@apollo/client/react\";\n\n  // Use `skipToken` in place of `skip: true` for better type safety\n  // for required variables\n  const { data } = useQuery(QUERY, id ? { variables: { id } } : skipToken);\n  ```\n\n  Note: this change is provided as a patch within the 4.0 minor version because the changes to TypeScript validation with required variables in version 4.0 made using the `skip` option more difficult.\n\n- [#12900](https://github.com/apollographql/apollo-client/pull/12900) [`c0d5be7`](https://github.com/apollographql/apollo-client/commit/c0d5be7cbbb1b1f7771962eb2ae0e173de743265) Thanks [@phryneas](https://github.com/phryneas)! - Use named export `equal` instead of default from `\"@wry/equality\"`\n\n## 4.0.3\n\n### Patch Changes\n\n- [#12887](https://github.com/apollographql/apollo-client/pull/12887) [`6f6ca47`](https://github.com/apollographql/apollo-client/commit/6f6ca47e9f5e80ee9c98fca2639b5cba6317fbbf) Thanks [@phryneas](https://github.com/phryneas)! - Fix accidental deep re-export from `/react` out of `/react/internals`\n\n- [#12890](https://github.com/apollographql/apollo-client/pull/12890) [`019b422`](https://github.com/apollographql/apollo-client/commit/019b4224147a5a8709de54c4474e126619dd2469) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure the `variables` option for `useMutation` provides proper IntelliSense suggestions.\n\n## 4.0.2\n\n### Patch Changes\n\n- [#12880](https://github.com/apollographql/apollo-client/pull/12880) [`56fac52`](https://github.com/apollographql/apollo-client/commit/56fac522549eaed5494097dc0098ea7a558382a0) Thanks [@phryneas](https://github.com/phryneas)! - restore `getMemoryInternals` access in dev builds\n\n## 4.0.1\n\n### Patch Changes\n\n- [#12876](https://github.com/apollographql/apollo-client/pull/12876) [`b00f231`](https://github.com/apollographql/apollo-client/commit/b00f231e5f10a23178cf7a2c69a4e13cd959ab45) Thanks [@phryneas](https://github.com/phryneas)! - Fix CJS build output for `invariantErrorCodes`\n\n- [#12866](https://github.com/apollographql/apollo-client/pull/12866) [`0d1614a`](https://github.com/apollographql/apollo-client/commit/0d1614a9dfca2b1bcf4ea40095cc9018d6314532) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `isNetworkStatusInFlight` from `@apollo/client/utilities`. Add `isNetworkStatusSettled` to `@apollo/client/utilities` and re-export it from `@apollo/client` with a deprecation.\n\n## 4.0.0\n\n# Apollo Client 4.0 Release Notes\n\nApollo Client 4.0 delivers a more modern, efficient, and type-safe GraphQL client experience through various architectural improvements and API refinements. This release focuses on developer experience, bundle size optimization, and framework flexibility.\n\n## Key Improvements\n\n### 🎯 Framework-Agnostic Core\n\nApollo Client 4.0 separates React functionality from the core library, making `@apollo/client` truly framework-agnostic. React exports now live in `@apollo/client/react`, allowing developers to use Apollo Client with any JavaScript framework without React dependencies.\n\n### 📦 Smaller Bundle Sizes\n\n- **Opt-in Local State Management**: The `@client` directive functionality is now opt-in via the `LocalState` class, reducing bundle size when not using local state\n- **Modern Build Target**: Transpiled to target `since 2023, node >= 20, not dead`, leveraging modern JavaScript features for better performance\n- **Improved Tree-Shaking**: Proper `exports` field in package.json enables better dead code elimination\n\n### 💥 Unified Error Handling\n\nApollo Client 4.0 completely reimagines error handling for better clarity and debugging:\n\n- `ApolloError` removed in favor of specific error classes\n- Unification of errors to a single `error` property\n- Network errors now respect `errorPolicy` settings\n- External errors passed through without wrapping\n- New, more granular error classes with static `.is()` methods for robust type narrowing\n\n### 🔧 Enhanced TypeScript Support\n\n- **Namespaced Types**: Types are now colocated with their APIs (e.g., `useQuery.Options` instead of `QueryHookOptions`)\n- **Precise Return Types**: Return types accurately reflect the options passed (e.g., `returnPartialData` makes `data` type `DeepPartial<TData>`)\n- **Stricter Type Safety**: Required variables are now enforced more consistently throughout the client\n- **New `dataState` Property**: Enables accurate type narrowing of query results\n- **Module Augmentation**: Custom context types via declaration merging instead of fragile generics\n- **Customizable Type Implementations**: Select types can now be customized to provide your own type implementation to seamlessly integrate with external tools such as GraphQL Codegen or `gql.tada`\n\n### ⚡ Modern Observable Implementation\n\nApollo Client 4.0 migrates from `zen-observable` to **RxJS**, providing the industry-standard Observable implementation backed by a rich ecosystem of utilities.\n\n## Major Features\n\n### Unified Error Handling\n\nApollo Client 4.0 completely reimagines error handling for better clarity and debugging:\n\n**Key Changes:**\n\n- `ApolloError` removed in favor of specific error classes\n- Network errors now respect `errorPolicy` settings\n- External errors passed through without wrapping\n- New error classes with static `.is()` methods for type checking\n\n**Error Classes:**\n\n- `CombinedGraphQLErrors` - GraphQL errors from the server\n- `ServerError` - Non-GraphQL server errors\n- `ServerParseError` - Server response parsing errors\n- `UnconventionalError` - Wrapper for non-error thrown values\n- `LinkError` - Errors from the link chain (via `.is()` check)\n\n**Migration Example:**\n\n```typescript\n// Apollo Client 3\nif (error instanceof ApolloError) {\n  console.log(error.graphQLErrors);\n  console.log(error.networkError);\n}\n\n// Apollo Client 4\nimport { CombinedGraphQLErrors } from \"@apollo/client\";\n\nif (CombinedGraphQLErrors.is(error)) {\n  console.log(error.errors); // GraphQL errors\n} else if (error) {\n  console.log(error.message); // Other errors\n}\n```\n\n### The `dataState` Property\n\nA new property that clearly indicates the completeness of query results:\n\n**Values:**\n\n- `empty` - No data available (`data` is `undefined`)\n- `partial` - Incomplete data from cache when `returnPartialData` is `true`\n- `streaming` - Incomplete data from a deferred query still streaming\n- `complete` - Fully satisfied query result\n\n**Benefits:**\n\n- Accurate TypeScript type narrowing\n- Clear loading state distinction\n- Better handling of partial results\n\n```typescript\nconst { data, dataState } = useQuery(MY_QUERY);\n\nif (dataState === \"complete\") {\n  // TypeScript knows data is fully populated\n  console.log(data.allFields);\n} else if (dataState === \"partial\") {\n  // TypeScript knows data might be missing fields\n  console.log(data?.someField);\n}\n```\n\n### Pluggable Incremental Delivery (`@defer` Support)\n\nApollo Client 4.0 makes incremental delivery configurable and future-proof:\n\n```typescript\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\n\nconst client = new ApolloClient({\n  // ...\n  incrementalHandler: new Defer20220824Handler(),\n});\n```\n\n**Available Handlers:**\n\n- `NotImplementedHandler` - Default, throws if `@defer` is used\n- `Defer20220824Handler` - Apollo Router format support (also aliased as `GraphQL17Alpha2Handler`)\n\n### Local State Management Improvements\n\nLocal state is now opt-in via the `LocalState` class:\n\n```typescript\nimport { LocalState } from \"@apollo/client/local-state\";\n\nconst client = new ApolloClient({\n  cache,\n  localState: new LocalState({\n    resolvers: {\n      Query: {\n        myField: () => \"Hello World\",\n      },\n    },\n  }),\n});\n```\n\n**Resolver Context Changes:**\n\n```typescript\n// Apollo Client 3\nconst resolver = (parent, args, context, info) => {\n  const { cache } = context;\n};\n\n// Apollo Client 4\nconst resolver = (parent, args, context, info) => {\n  const { client, requestContext, phase } = context;\n  const cache = client.cache;\n};\n```\n\n## React-Specific Improvements\n\n### More Predictable Hooks\n\n**`useLazyQuery` Overhaul:**\n\n- No longer accepts `variables` or `context` options (pass to `execute` instead)\n- `execute` function only accepts `variables` and `context`\n- Cannot be called during render or SSR\n- Automatic cancellation of in-flight queries when new ones start\n\n**`useMutation` Changes:**\n\n- Removed `ignoreResults` option - use `client.mutate` directly for fire-and-forget mutations\n\n**`useQuery` Changes:**\n\n- `notifyOnNetworkStatusChange` now defaults to `true`\n- Removed deprecated `onCompleted` and `onError` callbacks\n\n### New SSR API\n\nThe new `prerenderStatic` API replaces deprecated SSR functions:\n\n```typescript\nimport { prerenderStatic } from \"@apollo/client/react/ssr\";\n\n// Works with React 19's prerender APIs\nconst html = await prerenderStatic(<App />, {\n  client,\n});\n```\n\n### React Compiler Support\n\nPre-compiled React hooks optimized by the React Compiler:\n\n```typescript\n// Use compiled hooks for potential performance improvements\nimport { useQuery } from \"@apollo/client/react/compiled\";\n```\n\nThe compiled hooks are built with React Compiler v19.1.0-rc.2 and include a runtime polyfill for compatibility with React 17+.\n\n## Link System Evolution\n\n### All Links Now Classes\n\nMigration from creator functions to classes:\n\n```typescript\n// Apollo Client 3\nimport { createHttpLink, setContext } from \"@apollo/client\";\nconst httpLink = createHttpLink({ uri: \"/graphql\" });\nconst authLink = setContext((operation, prevContext) => {\n  /*...*/\n});\n\n// Apollo Client 4\nimport { HttpLink, SetContextLink } from \"@apollo/client\";\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\nconst authLink = new SetContextLink((prevContext, operation) => {\n  /*...*/\n});\n```\n\n### ErrorLink Changes\n\n```typescript\n// Apollo Client 3\nonError(({ graphQLErrors, networkError }) => {\n  // Handle errors separately\n});\n\n// Apollo Client 4\nnew ErrorLink(({ error }) => {\n  if (CombinedGraphQLErrors.is(error)) {\n    // Handle GraphQL errors\n  } else if (error) {\n    // Handle other errors\n  }\n});\n```\n\n## Migration Tools\n\n### Automated Codemod\n\nApollo Client 4.0 provides a comprehensive codemod to automate migration:\n\n```bash\n# Basic usage\nnpx @apollo/client-codemod-migrate-3-to-4 src\n\n# TypeScript projects (run separately)\nnpx @apollo/client-codemod-migrate-3-to-4 --parser ts --extensions ts src\nnpx @apollo/client-codemod-migrate-3-to-4 --parser tsx --extensions tsx src\n```\n\nThe codemod handles:\n\n1. **Import updates** - Moves React imports to `@apollo/client/react`\n2. **Type migrations** - Updates types to new namespaced locations\n3. **Link updates** - Converts creator functions to classes\n4. **Removed exports** - Moves to `@apollo/client/v4-migration` with migration instructions\n\n## Breaking Changes Summary\n\n### Installation\n\n```bash\n# RxJS is now a peer dependency\nnpm install @apollo/client graphql rxjs\n```\n\n### ApolloClient Constructor\n\n- `link` option is now required (no more implicit `HttpLink` creation)\n- `uri`, `headers`, `credentials` removed - use `HttpLink` directly\n- `name` and `version` moved to `clientAwareness` option\n- `resolvers` moved to `LocalState` constructor\n- `connectToDevTools` replaced with `devtools.enabled`\n- `disableNetworkFetches` renamed to `prioritizeCacheValues`\n\n### Type System\n\n- Removed `TContext` and `TCacheShape` generics\n- Types moved to namespaces (see migration guide for full list)\n- Custom context via module augmentation\n\n### Observable Changes\n\n- Requires calling `.pipe()` for transformations\n- Use RxJS operators instead of method chaining\n\n### Testing\n\n- `MockedProvider` now has realistic delays by default (20-50ms)\n- `createMockClient` removed - use `MockLink` directly\n\n## Performance & Build Improvements\n\n- **Modern JavaScript**: No downlevel transpilation for modern features\n- **No Polyfills**: Cleaner bundles, bring your own if needed\n- **Development Mode**: Controlled via export conditions, not global `__DEV__`\n- **ESM Support**: Proper `exports` field for better module resolution\n- **Source Maps**: Fixed and improved for better debugging\n\n## Deprecations & Removals\n\n### Removed Packages/Exports\n\n- React render prop components (`@apollo/client/react/components`)\n- Higher-order components (`@apollo/client/react/hoc`)\n- `@apollo/client/react/parser`\n- `@apollo/client/utilities/globals`\n\n## Upgrade Path\n\n1. **Update to Apollo Client 3.14** first for deprecation warnings\n2. **Install peer dependencies**: `npm install rxjs`\n3. **Run the codemod** to automate import and type updates\n4. **Update ApolloClient initialization** (explicit `HttpLink`, `LocalState` if needed)\n5. **Review error handling** - update to use new error classes\n6. **Test thoroughly** - especially SSR, error handling, and local state\n\n## Resources\n\n- [Migration Guide](https://www.apollographql.com/docs/react/migrating/apollo-client-4-migration)\n- [Changelog](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md)\n\n## Acknowledgments\n\nApollo Client 4.0 represents years of community feedback and contributions. Thank you to all our contributors, early adopters, and the entire GraphQL community for making this release possible.\n\n<details>\n\n<summary>\n\n### Major Changes\n\n</summary>\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Replace the `result` property on `ServerError` with `bodyText`. `bodyText` is set to the raw string body. `HttpLink` and `BatchHttpLink` no longer try and parse the response body as JSON when a `ServerError` is thrown.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - The `includeExtensions` option of `HttpLink` and `BatchHttpLink` now defaults\n  to `true`.\n\n  If `includeExtensions` is `true`, but `extensions` is not set or empty, extensions\n  will not be included in outgoing requests.\n\n- [#12686](https://github.com/apollographql/apollo-client/pull/12686) [`dc4b1d0`](https://github.com/apollographql/apollo-client/commit/dc4b1d0d2479a37067113b7bd161a550fb8e4df6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - A `@defer` query that has not yet finished streaming is now considered loading and thus the `loading` flag will be `true` until the response has completed. A new `NetworkStatus.streaming` value has been introduced and will be set as the `networkStatus` while the response is streaming.\n\n- [#12539](https://github.com/apollographql/apollo-client/pull/12539) [`dd0d6d6`](https://github.com/apollographql/apollo-client/commit/dd0d6d6d96d8b810e30dc2fdee2ac8a2477d0017) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `onError` link now uses a single `error` property to report the error that caused the link callback to be called. This will be an instance of `CombinedGraphQLErrors` in the event GraphQL errors were emitted from the terminating link, `CombinedProtocolErrors` if the terminating link emitted protocol errors, or the unwrapped error type if any other non-GraphQL error was thrown or emitted.\n\n  ```diff\n  - const errorLink = onError(({ graphQLErrors, networkError, protocolErrors }) => {\n  -   graphQLErrors.forEach(error => console.log(error.message));\n  + const errorLink = onError(({ error }) => {\n  +   if (error.name === 'CombinedGraphQLErrors') {\n  +     error.errors.forEach(rawError => console.log(rawError.message));\n  +   }\n  });\n  ```\n\n- [#12586](https://github.com/apollographql/apollo-client/pull/12586) [`605db8e`](https://github.com/apollographql/apollo-client/commit/605db8e94fe2ce74c0a395f38f6873d40f431365) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `typeDefs` option from `ApolloClient`.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `asyncMap` utility function. Instead use one of the RxJS operators that creates Observables from promises, such as `from`.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `isApolloError` utility function to check if the error object is an `ApolloError` instance. Use `instanceof` to check for more specific error types that replace `ApolloError`.\n\n- [#12379](https://github.com/apollographql/apollo-client/pull/12379) [`ef892b4`](https://github.com/apollographql/apollo-client/commit/ef892b4dc505b02049525f9aba32c51f1c00c922) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `addTypename` option from `InMemoryCache` and `MockedProvider`. `__typename` is now always added to the outgoing query document when using `InMemoryCache` and cannot be disabled.\n\n  If you are using `<MockedProvider />` with `addTypename={false}`, ensure that your mocked responses include a `__typename` field. This will ensure cache normalization kicks in and behaves more like production.\n\n- [#12396](https://github.com/apollographql/apollo-client/pull/12396) [`00f3d0a`](https://github.com/apollographql/apollo-client/commit/00f3d0a674eede1f909092283041cf8ac8d1b576) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `errors` property from `useQuery` and `useLazyQuery`. Read errors from the `error` property instead.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.getContext` now returns a `Readonly<OperationContext>` type.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `ApolloLink.Request` (i.e. `GraphQLRequest`) passed to `ApolloLink.execute` no longer accepts `operationName` and `operationType` options. These properties are derived from the `query` and set on the returned `ApolloLink.Operation` type.\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - An error is now thrown when trying to call `fetchMore` on a `cache-only` query.\n\n- [#12222](https://github.com/apollographql/apollo-client/pull/12222) [`d1a9054`](https://github.com/apollographql/apollo-client/commit/d1a905461d4378522c3257de00afba2ae8decd22) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Drop support for React 16.\n\n- [#12787](https://github.com/apollographql/apollo-client/pull/12787) [`8ce31fa`](https://github.com/apollographql/apollo-client/commit/8ce31fae54b1ae76c557f361cc946858cb2ff66b) Thanks [@phryneas](https://github.com/phryneas)! - Remove `DataProxy` namespace and interface.\n\n- [#12450](https://github.com/apollographql/apollo-client/pull/12450) [`876d070`](https://github.com/apollographql/apollo-client/commit/876d07042cf3348b3769b2bb415aa5f70ce9844c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `TSerialized` generic argument to `ApolloCache`. The `ApolloCache` base cache abstraction now returns `unknown` for `cache.extract` which can be overridden by a cache subclass.\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `getCacheKey` function is no longer available from `operation.getContext()` in the link chain. Use `operation.client.cache.identify(obj)` in the link chain instead.\n\n- [#12376](https://github.com/apollographql/apollo-client/pull/12376) [`a0c996a`](https://github.com/apollographql/apollo-client/commit/a0c996a816fbb6a2323231c0422d1c8a3e20cbaf) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `ignoreResults` option from `useMutation`. If you don't want to synchronize component state with the mutation, use `useApolloClient` to access your client instance and use `client.mutate` directly.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - More strictly adhere to the [GraphQL over HTTP spec](https://graphql.github.io/graphql-over-http/draft/). This change adds support for the `application/graphql-response+json` media type and modifies the behavior of the `application/json` media type.\n\n  - The client will parse the response as a well-formed GraphQL response when the server encodes `content-type` using `application/graphql-response+json` with a non-200 status code.\n  - The client will now throw a `ServerError` when the server encodes `content-type` using `application/json` and returns a non-200 status code.\n  - The client will now throw a `ServerError` when the server encodes using any other `content-type` and returns a non-200 status code.\n\n  NOTE: If you use a testing utility to mock requests in your test, you may experience different behavior than production if your testing utility responds as `application/json` but your production server responds as `application/graphql-response+json`. If a `content-type` header is not set, the client interprets the response as `application/json`.\n\n- [#12600](https://github.com/apollographql/apollo-client/pull/12600) [`34ff6aa`](https://github.com/apollographql/apollo-client/commit/34ff6aa25b47c3e84d0b18e2c69bc995814bf2f2) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move most of the utilities in `@apollo/client/utilities` to `@apollo/client/utilities/internal`. Many of the utilities exported from the `@apollo/client/utilities` endpoint were not considered stable.\n\n  As a result of this change, utilities or types exported from `@apollo/client/utilities` are now documented and considered stable and will not undergo breaking changes.\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `@apollo/client/react/context` and `@apollo/client/react/hooks` entry points. Please use `@apollo/client/react` instead.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unusubscribing from `ObservableQuery` while a request is in flight will no longer terminate the request by unsubscribing from the link observable.\n\n- [#12463](https://github.com/apollographql/apollo-client/pull/12463) [`3868df8`](https://github.com/apollographql/apollo-client/commit/3868df81f973dc7b5a79fadf4dc1b0e291003b7f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.setOptions` has been removed as it was an alias of `reobserve`. Prefer using `reobserve` directly instead.\n\n  ```diff\n  const observable = client.watchQuery(options);\n\n  // Use reobserve to set new options and reevaluate the query\n  - observable.setOptions(newOptions);\n  + observable.reobserve(newOptions);\n  ```\n\n  As a result of this change, `reobserve` has been marked for public use and is no longer considered an internal API. The `newNetworkStatus` argument has been removed to facilitate this change.\n\n- [#12478](https://github.com/apollographql/apollo-client/pull/12478) [`5ea6a45`](https://github.com/apollographql/apollo-client/commit/5ea6a45b3ec2f0d526abe78ae03c42bb519f87c7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `variables` from the result returned from `useSubscription`.\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `resultCacheMaxSize` option from `InMemoryCache` options.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - The `ApolloClient` constructor options `name` and `version` that are used to\n  configure the client awareness feature have moved onto a `clientAwareness` key.\n\n  ```diff\n  const client = new ApolloClient({\n    // ..\n  -  name: \"my-app\",\n  -  version: \"1.0.0\",\n  +  clientAwareness: {\n  +    name: \"my-app\",\n  +    version: \"1.0.0\",\n  +  },\n  });\n  ```\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `previousData` property on `useLazyQuery` will now change only when `data` changes. Previously `previousData` would change to the same value as `data` while the query was loading.\n\n- [#12690](https://github.com/apollographql/apollo-client/pull/12690) [`5812759`](https://github.com/apollographql/apollo-client/commit/5812759b6659df49277635e89492c0d72c3b57d6) Thanks [@phryneas](https://github.com/phryneas)! - Aliasing any other field to `__typename` is now forbidden.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` will now keep previous `data` around when emitting a `loading` state, unless `query` or `variables` changed.\n  Note that `@exports` variables are not taken into account for this, so `data` will stay around even if they change.\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Report masked fragments as complete even when a nested masked fragment contains partial data.\n\n- [#12788](https://github.com/apollographql/apollo-client/pull/12788) [`4179446`](https://github.com/apollographql/apollo-client/commit/417944677d2e79606b0f6cabd8d5d8b2063c876b) Thanks [@phryneas](https://github.com/phryneas)! - `TVariables` now always `extends OperationVariables` in all interfaces.\n\n- [#12224](https://github.com/apollographql/apollo-client/pull/12224) [`51e6c0f`](https://github.com/apollographql/apollo-client/commit/51e6c0f8657d20cedc570c6e9a244f877047dd61) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `partialRefetch` option.\n\n- [#12407](https://github.com/apollographql/apollo-client/pull/12407) [`8b1390b`](https://github.com/apollographql/apollo-client/commit/8b1390bf0050c6bd4d5a32b67c3b96369d0552d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Calling `refetch` with new variables will now set the `networkStatus` to `refetch` instead of `setVariables`.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions now emit a `SubscribeResult` instead of a `FetchResult`. As a result, the `errors` field has been removed in favor of `error`.\n\n- [#12457](https://github.com/apollographql/apollo-client/pull/12457) [`32e85ea`](https://github.com/apollographql/apollo-client/commit/32e85ea9eb93c1ffb10d6f70e9e2775e1326e9aa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Network errors triggered by queries now adhere to the `errorPolicy`. This means that GraphQL errors and network errors now behave the same way. Previously promise-based APIs, such as `client.query`, would reject the promise with the network error even if `errorPolicy` was set to `ignore`. The promise is now resolved with the `error` property set to the network error instead.\n\n- [#12840](https://github.com/apollographql/apollo-client/pull/12840) [`83e132a`](https://github.com/apollographql/apollo-client/commit/83e132ab1bacb3293da61dd4519379e36a1fb090) Thanks [@phryneas](https://github.com/phryneas)! - If you use an incremental delivery handler, you now have to explicitly opt into adding the chunk types to the `ApolloLink.Result` type.\n\n  ```ts title=\"apollo-client.d.ts\n  import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n  }\n  ```\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries are no longer refetched when calling `client.reFetchObservableQueries` when `includeStandby` is `true`.\n\n- [#12808](https://github.com/apollographql/apollo-client/pull/12808) [`8e31a23`](https://github.com/apollographql/apollo-client/commit/8e31a2303b18f6fc4d8ec1cf4c01bf26b90f3f0b) Thanks [@phryneas](https://github.com/phryneas)! - HTTP Multipart handling will now throw an error if the connection closed before the final boundary has been received.\n  Data after the final boundary will be ignored.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `iterateObserversSafely` utility function.\n\n- [#12825](https://github.com/apollographql/apollo-client/pull/12825) [`292b949`](https://github.com/apollographql/apollo-client/commit/292b949e9e1d10a715e0fd403737361f91432fbf) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `serializeFetchParameter` helper is no longer exported and `JSON.stringify` is used directly. As such, the `ClientParseError` type has also been removed in favor of throwing any JSON serialize errors directly.\n\n- [#12595](https://github.com/apollographql/apollo-client/pull/12595) [`60bb49c`](https://github.com/apollographql/apollo-client/commit/60bb49ccea9aecf3e6a212b5a1f71907e60af886) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `@apollo/client/testing/experimental` test utilities. Use [GraphQL Testing Library](https://github.com/apollographql/graphql-testing-library) instead.\n\n- [#12718](https://github.com/apollographql/apollo-client/pull/12718) [`ecfc02a`](https://github.com/apollographql/apollo-client/commit/ecfc02a37908b58d1f799f0e817cdeab98482720) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only to release latest as `rc`.\n\n- [#12470](https://github.com/apollographql/apollo-client/pull/12470) [`d32902f`](https://github.com/apollographql/apollo-client/commit/d32902f26a4c5dea30421ee52aeea52df3e5334e) Thanks [@phryneas](https://github.com/phryneas)! - `ssrMode`, `ssrForceFetchDelay` and `disableNetworkFetches` have been reworked:\n\n  Previously, a `ObservableQuery` created by `client.query` or `client.watchQuery`\n  while one of those were active would permanently be changed from a `fetchPolicy`\n  of `\"network-only\"` or `\"cache-and-network\"` to `\"cache-first\"`, and stay that way\n  even long after `disableNetworkFetches` would have been deactivated.\n\n  Now, the `ObservableQuery` will keep their original `fetchPolicy`, but queries\n  made during `disableNetworkFetches` will just apply the `fetchPolicy` replacement\n  at request time, just for that one request.\n\n  `ApolloClient.disableNetworkFetches` has been renamed to `ApolloClient.prioritizeCacheValues` to better reflect this behaviour.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.variables` can now be reset back to empty when calling `reobserve` with `variables: undefined`. Previously the `variables` key would be ignored so `variables` would remain unchanged.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `never` is no longer supported as a valid `TVariables` generic argument for APIs that require `variables` as part of its type. Use `Record<string, never>` instead.\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `connectToDevtools` option from `ApolloClientOptions`. Use `devtools.enabled` instead.\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `cache` and `forceFetch` properties are no longer available on context when calling `operation.getContext()`. `cache` can be accessed through the `operation` with `operation.client.cache` instead. `forceFetch` has been replaced with `queryDeduplication` which specifies whether `queryDeduplication` was enabled for the request or not.\n\n- [#12533](https://github.com/apollographql/apollo-client/pull/12533) [`73221d8`](https://github.com/apollographql/apollo-client/commit/73221d87bd5640986f86fe3ee50c63ed49834cbb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `onError` and `setOnError` methods from `ApolloLink`. `onError` was only used by `MockLink` to rewrite errors if `setOnError` was used.\n\n- [#12485](https://github.com/apollographql/apollo-client/pull/12485) [`d338303`](https://github.com/apollographql/apollo-client/commit/d3383033d306b7d66e90f5f3170c24453cd76464) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Throw an error for queries and mutations if the link chain completes without emitting a value.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Removed `getLastResult`, `getLastError` and `resetLastResults` from `ObservableQuery`\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unsubscribing from an `ObservableQuery` before a value has been emitted will remove the query from the tracked list of queries and will no longer be eligible for query deduplication.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.operationType` is now a non-null `OperationTypeNode`. It is now safe to compare this value without having to check for `undefined`.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apollo Client no longer wraps errors in `ApolloError`. `ApolloError` has been replaced with separate error classes depending on the cause of the error. As such, APIs that return an `error` property have been updated to use the generic `Error` type. Use `instanceof` to check for more specific error types.\n\n  ## Migration guide\n\n  `ApolloError` encapsulated 4 main error properties. The type of error would determine which property was set:\n\n  - `graphqlErrors` - Errors returned from the `errors` field by the GraphQL server\n  - `networkError` - Any non-GraphQL error that caused the query to fail\n  - `protocolErrors` - Transport-level errors that occur during [multipart HTTP subscriptions](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol)\n  - `clientErrors` - A space to define custom errors. Mostly unused.\n\n  These errors were mutally exclusive, meaning both `networkError` and `graphqlErrors` were never set simultaneously. The following replaces each of these fields from `ApolloError`.\n\n  ### `graphqlErrors`\n\n  GraphQL errors are now encapsulated in a `CombinedGraphQLErrors` instance. You can access the raw GraphQL errors via the `errors` property.\n\n  ```js\n  import { CombinedGraphQLErrors } from \"@apollo/client\";\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  if (error && error instanceof CombinedGraphQLErrors) {\n    console.log(error.errors);\n  }\n  ```\n\n  ### `networkError`\n\n  Network errors are no longer wrapped and are instead passed through directly.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error(new Error(\"Test error\"));\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // error is `new Error('Test error')`;\n  ```\n\n  ### `protocolErrors`\n\n  Protocol errors are now encapsulated in a `CombinedProtocolErrors` instance. You can access the raw protocol errors via the `errors` property.\n\n  ```js\n  import { CombinedProtocolErrors } from \"@apollo/client\";\n\n  // ...\n\n  const { error } = useSubscription(subscription);\n\n  if (error && error instanceof CombinedProtocolErrors) {\n    console.log(error.errors);\n  }\n  ```\n\n  ### `clientErrors`\n\n  These were unused by the client and have no replacement. Any non-GraphQL or non-protocol errors are now passed through unwrapped.\n\n  ### Strings as errors\n\n  If the link sends a string error, Apollo Client will wrap this in an `Error` instance. This ensures `error` properties are guaranteed to be of type `Error`.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        // Oops we sent a string instead of wrapping it in an `Error`\n        observer.error(\"Test error\");\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // The error string is wrapped and returned as `new Error('Test error')`;\n  ```\n\n  ### Non-error types\n\n  If the link chain sends any other object type as an error, Apollo Client will wrap this in an `UnknownError` instance with the [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) set to the original object. This ensures `error` properties are guaranteed to be of type `Error`.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error({ message: \"Not a proper error type\" });\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // error is an `UnknownError` instance. error.cause returns the original object.\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.operationName` is now set as `string | undefined` where `undefined` represents an anonymous query. Previously `operationName` would return an empty string as the `operationName` for anonymous queries.\n\n- [#12450](https://github.com/apollographql/apollo-client/pull/12450) [`876d070`](https://github.com/apollographql/apollo-client/commit/876d07042cf3348b3769b2bb415aa5f70ce9844c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `TCacheShape` generic argument to `ApolloClient`. `client.extract()` now returns `unknown` by default. You will either need to type-cast this to the expected serialized shape, or use the `cache.extract()` directly from the subclass to get more specific types.\n\n- [#12774](https://github.com/apollographql/apollo-client/pull/12774) [`511b4f3`](https://github.com/apollographql/apollo-client/commit/511b4f3e792a75aa5aa27b335e8119dbc2a9c254) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apply document transforms before reading data from the cache for `client.readQuery`, `client.readFragment`, `client.watchFragment`, `useFragment`, and `useSuspenseFragment`.\n\n  NOTE: This change does not affect the equivalent `cache.*` APIs. To read data from the cache without first running document transforms, run `cache.readQuery`, `cache.readFragment`, etc.\n\n- [#12705](https://github.com/apollographql/apollo-client/pull/12705) [`a60f411`](https://github.com/apollographql/apollo-client/commit/a60f411e58cc67730d0dc4513e4045f004027ded) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries will now initialize with `loading: false` and `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n  This means `useQuery` will no longer render a short initial loading state before rendering `loading: false` and `ObservableQuery.getCurrentResult()` will now return `loading: false` immediately.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unify error behavior on mutations for GraphQL errors and network errors by ensuring network errors are subject to the `errorPolicy`. Network errors created when using an `errorPolicy` of `all` will now resolve the promise and be returned on the `error` property of the result, or stripped away when the `errorPolicy` is `none`.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `fromError` utility function. Use [`throwError`](https://rxjs.dev/api/index/function/throwError) instead.\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `TData` generic provided to types that return a `dataState` property is now modified by the given `DataState` generic instead of passing a modified `TData` type. For example, a `QueryRef` that could return partial data was defined as `QueryRef<DeepPartial<TData>, TVariables>`. Now `TData` should be provided unmodified and a set of allowed states should be given instead: `QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>`.\n\n  To migrate, use the following guide to replace your type with the right set of states (all types listed below are changed the same way):\n\n  ```diff\n  - QueryRef<TData, TVariables>\n  // `QueryRef`'s default is 'complete' | 'streaming' so this can also be left alone if you prefer\n  // All other types affected by this change default to all states\n  + QueryRef<TData, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming'>\n\n  - QueryRef<TData | undefined, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'empty'>\n\n  - QueryRef<DeepPartial<TData>, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>\n\n  - QueryRef<DeepPartial<TData> | undefined, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial' | 'empty'>\n  ```\n\n  The following types are affected. Provide the allowed `dataState` values to the `TDataState` generic:\n\n  - `ApolloQueryResult`\n  - `QueryRef`\n  - `PreloadedQueryRef`\n  - `useLazyQuery.Result`\n  - `useQuery.Result`\n  - `useReadQuery.Result`\n  - `useSuspenseQuery.Result`\n\n  All `*QueryRef` types default to `complete | streaming` states while the rest of the types default to `'complete' | 'streaming' | 'partial' | 'empty'` states. You shouldn't need to provide the states unless you need to either allow for partial data/empty values (`*QueryRef`) or a restricted set of states.\n\n- [#12850](https://github.com/apollographql/apollo-client/pull/12850) [`268cd80`](https://github.com/apollographql/apollo-client/commit/268cd800a2d73305c0df8dd38b6bd1cee98f0fec) Thanks [@phryneas](https://github.com/phryneas)! - Introduce a versioning policy.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `concat`, `from`, and `split` functions on `ApollLink` no longer support a plain request handler function. Please wrap the request handler with `new ApolloLink`.\n\n  ```diff\n  const link = new ApolloLink(/* ... */);\n\n  link.concat(\n  - (operation, forward) => forward(operation),\n  + new ApolloLink((operation, forward) => forward(operation)),\n  );\n  ```\n\n- [#12802](https://github.com/apollographql/apollo-client/pull/12802) [`e2b51b3`](https://github.com/apollographql/apollo-client/commit/e2b51b30acbd360253100f9d2a91fe7e0c57be4c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Disallow the `mutation` option for the `mutate` function returned from `useMutation`.\n\n- [#12211](https://github.com/apollographql/apollo-client/pull/12211) [`c2736db`](https://github.com/apollographql/apollo-client/commit/c2736db3ad6f8b6e56f065682d5b76614f41bfd4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `graphql`, `withQuery`, `withMutation`, `withSubscription`, and `withApollo` hoc components. Use the provided React hooks instead.\n\n- [#12690](https://github.com/apollographql/apollo-client/pull/12690) [`5812759`](https://github.com/apollographql/apollo-client/commit/5812759b6659df49277635e89492c0d72c3b57d6) Thanks [@phryneas](https://github.com/phryneas)! - Aliasing a field to an alias beginning with `__ac_` is now forbidden - this namespace is now reserved for internal use.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - When passing a `variables` key with the value `undefined`, the value will be replaced by the default value in the query, if it is provided, rather than leave it as `undefined`.\n\n  ```ts\n  // given this query\n  const query = gql`\n    query PaginatedQuery($limit: Int! = 10, $offset: Int) {\n      list(limit: $limit, offset: $offset) {\n        id\n      }\n    }\n  `;\n\n  const observable = client.query({\n    query,\n    variables: { limit: 5, offset: 0 },\n  });\n  console.log(observable.variables); // => { limit: 5, offset: 0 }\n\n  observable.reobserve({ variables: { limit: undefined, offset: 10 } });\n  // limit is now `10`. This would previously be `undefined`\n  console.log(observable.variables); // => { limit: 10, offset: 10 }\n  ```\n\n- [#12262](https://github.com/apollographql/apollo-client/pull/12262) [`10ef733`](https://github.com/apollographql/apollo-client/commit/10ef7338cdcbbaf75d806f426e9708c9e095c2da) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `itAsync` test utility.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Adds enhanced client awareness to the client.\n\n  `HttpLink` and `BatchHttpLink` will now per default send information about the\n  client library you are using in `extensions`.\n\n  This could look like this:\n\n  ```json\n  {\n    \"query\": \"query GetUser($id: ID!) { user(id: $id) { __typename id name } }\",\n    \"variables\": {\n      \"id\": 5\n    },\n    \"extensions\": {\n      \"clientLibrary\": {\n        \"name\": \"@apollo/client\",\n        \"version\": \"4.0.0\"\n      }\n    }\n  }\n  ```\n\n  This feature can be disabled by passing `enhancedClientAwareness: { transport: false }` to your\n  `ApolloClient`, `HttpLink` or `BatchHttpLink` constructor options.\n\n- [#12742](https://github.com/apollographql/apollo-client/pull/12742) [`575bf3e`](https://github.com/apollographql/apollo-client/commit/575bf3ed5885efb09c1eec497af4d2690c6b87d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The new `SetContextLink` flips the `prevContext` and `operation` arguments in the callback. The `setContext` function has remained unchanged.\n\n  ```diff\n  - new SetContextLink((operation, prevContext) => {\n  + new SetContextLink((prevContext, operation) => {\n    // ...\n  })\n  ```\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - An initial loading state is now emitted from `ObservableQuery` when subscribing if `notifyOnNetworkStatusChange` is set to `true`.\n\n- [#12465](https://github.com/apollographql/apollo-client/pull/12465) [`a132163`](https://github.com/apollographql/apollo-client/commit/a1321637cafb4023d6df416e9467294114d8346b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Flatten out React hook types. As a result, the base types have been removed. Prefer using the hook types instead. Removed types include:\n\n  - `BaseMutationOptions`\n  - `BaseQueryOptions`\n  - `BaseSubscriptionOptions`\n  - `ObservableQueryFields`\n  - `MutationSharedOptions`\n  - `QueryFunctionOptions`\n\n- [#12675](https://github.com/apollographql/apollo-client/pull/12675) [`8f1d974`](https://github.com/apollographql/apollo-client/commit/8f1d974881ff54339b6b6593a219ba6d5fd013c0) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` no longer has a `queryId` property.\n  `ApolloClient.getObservableQueries` no longer returns a `Map<string, ObservableQuery>`, but a `Set<ObservableQuery>`.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Updates the `ServerError` and `ServerParseError` types to be proper `Error` subclasses. Perviously these were plain `Error` intances with additional properties added at runtime. All properties are retained, but `instanceof` checks now work correctly.\n\n  ```js\n  import { ServerError, ServerParseError } from \"@apollo/client\";\n\n  if (error instanceof ServerError) {\n    // ...\n  }\n\n  if (error instanceof ServerParseError) {\n    // ...\n  }\n  ```\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries are now excluded from `client.refetchQueries` in all situations. `cache-only` queries affected by `updateCache` are also excluded from `refetchQueries` when `onQueryUpdated` is not provided.\n\n- [#12463](https://github.com/apollographql/apollo-client/pull/12463) [`3868df8`](https://github.com/apollographql/apollo-client/commit/3868df81f973dc7b5a79fadf4dc1b0e291003b7f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useQuery` no longer returns `reobserve` as part of its result. It was possible to use `reobserve` to set new options on the underlying `ObservableQuery` instance which differed from the options passed to the hook. This could result in unexpected results. Instead prefer to rerender the hook with new options.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports SSR environments and will now throw if the `execute` function is called in SSR. If you need to run a query in an SSR environment, use `useQuery` instead.\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `resolvers` option from `ApolloClient`. Local resolvers have instead been moved to the new `LocalState` instance which is assigned to the `localState` option in `ApolloClient`. To migrate, move the `resolvers` values into a `LocalState` instance and assign that instance to `localState`.\n\n  ```diff\n  new ApolloClient({\n  - resolvers: { /* ... */ }\n  + localState: new LocalState({\n  +   resolvers: { /* ... */ }\n  + }),\n  });\n  ```\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.mutate` now returns a `MutateResult` instead of `FetchResult`. As a result, the `errors` property has been removed in favor of `error` which is set if either a network error occured or GraphQL errors are returned from the server.\n\n  `useMutation` now also returns a `MutateResult` instead of a `FetchResult`.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The execute function returned from `useLazyQuery` now only supports the `context` and `variables` options. This means that passing options supported by the hook no longer override the hook value.\n\n  To change options, rerender the component with new options. These options will take effect with the next query execution.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery` will no longer terminate on errors and will instead emit a `next` value with an `error` property. This ensures that `ObservableQuery` instances can continue to receive updates after errors are returned in requests without the need to resubscribe to the observable.\n\n- [#12681](https://github.com/apollographql/apollo-client/pull/12681) [`b181f98`](https://github.com/apollographql/apollo-client/commit/b181f98476e635ba3eccab170c09d91f5408060c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changing most options when rerendering `useQuery` will no longer trigger a `reobserve` which may cause network fetches. Instead, the changed options will be applied to the next cache update or fetch.\n\n  Options that now trigger a `reobserve` when changed between renders are:\n\n  - `query`\n  - `variables`\n  - `skip`\n  - Changing `fetchPolicy` to or from `standby`\n\n- [#12787](https://github.com/apollographql/apollo-client/pull/12787) [`8ce31fa`](https://github.com/apollographql/apollo-client/commit/8ce31fae54b1ae76c557f361cc946858cb2ff66b) Thanks [@phryneas](https://github.com/phryneas)! - Generic arguments for `Cache.ReadOptions` were flipped from `TVariables, TData` to `TData, TVariables`.\n\n- [#12837](https://github.com/apollographql/apollo-client/pull/12837) [`7c49fdc`](https://github.com/apollographql/apollo-client/commit/7c49fdce2f40571d92c83602bbb1b5bd891f626b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - You must now opt in to use GraphQL Codegen data masking types when using Apollo Client's data masking feature. By default, Apollo Client now uses an identity type to apply to masked/unmasked types.\n\n  If you're using GraphQL Codegen to generate masked types, opt into the GraphQL Codegen masked types using declaration merging on the `TypeOverides` interface.\n\n  ```ts title=\"apollo-client.d.ts\n  import { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides\n      extends GraphQLCodegenDataMasking.TypeOverrides {}\n  }\n  ```\n\n- [#12824](https://github.com/apollographql/apollo-client/pull/12824) [`0506f12`](https://github.com/apollographql/apollo-client/commit/0506f12936d3fe7c840e5d56a5efa20bbce1525e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure the `error` argument for the `delay` and `attempts` functions on `RetryLink` are an `ErrorLike`.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `throwServerError` utility function. Now that `ServerError` is an\n  `Error` subclass, you can throw these errors directly:\n\n  ```js\n  import { ServerError } from \"@apollo/client\";\n\n  // instead of\n  throwServerError(response, result, \"error message\");\n\n  // Use\n  throw new ServerError(\"error message\", { response, result });\n  ```\n\n- [#12837](https://github.com/apollographql/apollo-client/pull/12837) [`7c49fdc`](https://github.com/apollographql/apollo-client/commit/7c49fdce2f40571d92c83602bbb1b5bd891f626b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The types mode for data masking has been removed. Adding a types mode to the `DataMasking` interface has no effect. Remove the `mode` key in the module where you declare the `DataMasking` type for the `@apollo/client` module.\n\n  As a result, the `Masked` and `MaskedDocumentNode` types have also been removed since these have no effect when types are preserved.\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `Cache.DiffResult<T>` type is now a union type with better type safety for both complete and partial results. Checking `diff.complete` will now narrow the type of `result` depending on whether the value is `true` or `false`.\n\n  When `true`, `diff.result` will be a non-null value equal to the `T` generic type. When `false`, `diff.result` now reports `result` as `DeepPartial<T> | null` indicating that fields in the result may be missing (`DeepPartial<T>`) or empty entirely (`null`).\n\n- [#12731](https://github.com/apollographql/apollo-client/pull/12731) [`0198870`](https://github.com/apollographql/apollo-client/commit/0198870107eab7ad0bc69a549cb069fa41b3280f) Thanks [@phryneas](https://github.com/phryneas)! - Ship React Compiler compiled React hooks in `@apollo/client/react/compiled`.\n\n  We now ship a React-Compiler compiled version of the React hooks in\n  `@apollo/client/react/compiled`.\n\n  This entry point contains everything that `@apollo/client/react` does,\n  so you can use it as a drop-in replacement in your whole application\n  if you choose to use the compiled hooks.\n\n- [#12446](https://github.com/apollographql/apollo-client/pull/12446) [`ab920d2`](https://github.com/apollographql/apollo-client/commit/ab920d2701aa276482dbc78b44a1c25c76467bc9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `defaultOptions` option from `useQuery`. Use options directly or use the global `ApolloClient` `defaultOptions`.\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `QueryReference` type. Please use `QueryRef` instead.\n\n- [#12396](https://github.com/apollographql/apollo-client/pull/12396) [`00f3d0a`](https://github.com/apollographql/apollo-client/commit/00f3d0a674eede1f909092283041cf8ac8d1b576) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `errors` property from the results emitted from `ObservableQuery` or returned from `client.query`. Read errors from the `error` property instead.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The result resolved from the promise returned from the execute function in `useLazyQuery` is now an `ApolloQueryResult` type and no longer includes all the fields returned from the `useLazyQuery` hook tuple.\n\n  If you need access to the additional properties such as `called`, `refetch`, etc. not included in `ApolloQueryResult`, read them from the hook instead.\n\n- [#12531](https://github.com/apollographql/apollo-client/pull/12531) [`7784b46`](https://github.com/apollographql/apollo-client/commit/7784b46117a4f91a270a020ed1a24f042cb9ee17) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Mocked responses passed to `MockLink` now accept a callback for the `request.variables` option. This is used to determine if the mock should be matched for a set of request variables. With this change, the `variableMatcher` option has been removed in favor of passing a callback to `variables`. Update by moving the callback function from `variableMatcher` to `request.variables`.\n\n  ```diff\n  new MockLink([\n    {\n      request: {\n        query,\n  +     variables: (requestVariables) => true\n      },\n  -   variableMatcher: (requestVariables) => true\n    }\n  ]);\n  ```\n\n- [#12793](https://github.com/apollographql/apollo-client/pull/12793) [`24e98a1`](https://github.com/apollographql/apollo-client/commit/24e98a16648d4c21f37ba51a678a8849f88174ea) Thanks [@phryneas](https://github.com/phryneas)! - `ApolloConsumer` has been removed - please use `useApolloClient` instead.\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - Rework option handling for `fetchMore`.\n\n  - Previously, if the `query` option was specified, no options would be inherited\n    from the underlying `ObservableQuery`.\n    Now, even if `query` is specified, all unspecified options except for `variables` will be inherited from the underlying `ObservableQuery`.\n  - If `query` is not specified, `variables` will still be shallowly merged with the `variables` of the underlying `ObservableQuery`. If a `query` option is specified, the `variables` passed to `fetchMore` are used instead.\n  - `errorPolicy` of `fetchMore` will now always default to `\"none\"` instead of inherited from the `ObservableQuery` options. This can prevent accidental cache writes of partial data for a paginated query. To opt into receive partial data that may be written to the cache, pass an `errorPolicy` to `fetchMore` to override the default.\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove local resolvers APIs from `ApolloClient` in favor of `localState`. Methods removed are:\n\n  - `addResolvers`\n  - `getResolvers`\n  - `setResolvers`\n  - `setLocalStateFragmentMatcher`\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ApolloLink.execute` now requires a third argument which provides the `client` that initiated the request to the link chain. If you use `execute` directly, add a third argument with a `client` property:\n\n  ```ts\n  ApolloLink.execute(link, operation, { client });\n\n  // or if you import the `execute` function directly:\n  execute(link, operation, { client });\n  ```\n\n- [#12526](https://github.com/apollographql/apollo-client/pull/12526) [`391af1d`](https://github.com/apollographql/apollo-client/commit/391af1dd733219b7e1e14cfff9d5e3ce3967242f) Thanks [@phryneas](https://github.com/phryneas)! - The `@apollo/client` and `@apollo/client/core` entry points are now equal.\n  In the next major, the `@apollo/client/core` entry point will be removed.\n  Please change imports over from `@apollo/client/core` to `@apollo/client`.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - Added a new `Streaming` type that will mark `data` in results while `dataState`\n  is `\"streaming\"`.\n\n  `Streaming<TData>` defaults to `TData`, but can be overwritten in userland to\n  integrate with different codegen dialects.\n\n  You can override this type globally - this example shows how to override it\n  with `DeepPartial<TData>`:\n\n  ```ts\n  import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n  type StreamingOverride<TData> = DeepPartial<TData>;\n\n  interface StreamingOverrideHKT extends HKT {\n    return: StreamingOverride<this[\"arg1\"]>;\n  }\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides {\n      Streaming: StreamingOverrideHKT;\n    }\n  }\n  ```\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` will no longer rerender with the loading state when calling the execute function the first time unless the `notifyOnNetworkStatusChange` option is set to `true` (which is the new default).\n\n  If you prefer the behavior from 3.x, rerender the component with\n  `notifyOnNetworkStatusChange` set to `false` after the execute function is\n  called the first time.\n\n  ```ts\n  function MyComponent() {\n    const [notifyOnNetworkStatusChange, setNotifyOnNetworkStatusChange] =\n      useState(true);\n    const [execute] = useLazyQuery(query, { notifyOnNetworkStatusChange });\n\n    async function runExecute() {\n      await execute();\n\n      // Set to false after the initial fetch to stop receiving notifications\n      // about changes to the loading states.\n      setNotifyOnNetworkStatusChange(false);\n    }\n\n    // ...\n  }\n  ```\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Mutations no longer report errors if the GraphQL result from the server contains an empty array of errors.\n\n- [#12254](https://github.com/apollographql/apollo-client/pull/12254) [`0028ac0`](https://github.com/apollographql/apollo-client/commit/0028ac0147aaea9ab559f15630200a132b43da42) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changes the default `Accept` header to `application/graphql-response+json`.\n\n- [#12633](https://github.com/apollographql/apollo-client/pull/12633) [`9bfb51f`](https://github.com/apollographql/apollo-client/commit/9bfb51fdbca69560da71f9012c74ee172b6c2b69) Thanks [@phryneas](https://github.com/phryneas)! - If the `execute` function of `useLazyQuery` is executed, previously started queries\n  from the same `useLazyQuery` usage will be rejected with an `AbortError` unless\n  `.retain()` is called on the promise returned by previous `execute` calls.\n\n  Please keep in mind that `useLazyQuery` is primarily meant as a means to synchronize\n  your component to the status of a query and that it's purpose it not to make a\n  series of network calls.\n  If you plan on making a series of network calls without the need to synchronize\n  the result with your component, consider using `ApolloClient.query` instead.\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `@apollo/client/react/parser` entry point. There is no replacement.\n\n- [#12430](https://github.com/apollographql/apollo-client/pull/12430) [`2ff66d0`](https://github.com/apollographql/apollo-client/commit/2ff66d06b6d444fbcb46e580ac40e673e695740f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.setVariables` will now resolve with the last emitted result instead of `undefined` when either the variables match the current variables or there are no subscribers to the query.\n\n- [#12685](https://github.com/apollographql/apollo-client/pull/12685) [`3b74800`](https://github.com/apollographql/apollo-client/commit/3b748003df89ec69a6ad045fb47bbe9c3e62104c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the check and warning for `cache.fragmentMatches` when applying data masking. `cache.fragmentMatches` is a required API and data masking may crash when `cache.fragmentMatches` does not exist.\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - Apollo Client now defaults to production mode, not development mode, if the\n  environment cannot be determined.\n\n  In modern bundlers, this should automatically be handled by the bundler loading\n  the bundler with the `development` export condition.\n\n  If neither the `production` nor the `development` export condition are\n  used by the bundler/runtime, Apollo Client will fall back to `globalThis.__DEV__`\n  to determine if it should run in production or development mode.\n\n  Unlike Apollo Client 3 though, if `globalThis.__DEV__` is not set to `true`,\n  Apollo Client will now default to `production`, not to `development`, behaviour.\n\n  This switch to _explicilty_ requiring `true` also resolves a situation where\n  an HTML element with `id=\"__DEV__\"` would create a global `__DEV__` variable\n  with a referent to the DOM element, which in the past was picked up as \"truthy\" and\n  would have triggered development mode.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Change the default `Accept` header to `application/graphql-response+json,application/json;q=0.9`.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unify error behavior on subscriptions for GraphQL errors and network errors by ensuring network errors are subject to the `errorPolicy`. Network errors that terminate the connection will now be emitted on the `error` property passed to the `next` callback followed by a call to the `complete` callback.\n\n- [#12499](https://github.com/apollographql/apollo-client/pull/12499) [`ce35ea2`](https://github.com/apollographql/apollo-client/commit/ce35ea2b3a87d6dd6757e9be50ecc42837bebe56) Thanks [@phryneas](https://github.com/phryneas)! - Enable React compiler for hooks in ESM builds.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `reobserve` option is no longer available in the result returned from `useLazyQuery`. This was considered an internal API and should not be used directly.\n\n- [#12333](https://github.com/apollographql/apollo-client/pull/12333) [`3e4beaa`](https://github.com/apollographql/apollo-client/commit/3e4beaa8b768a893da80aae0428f79ee01d6aa38) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `data` property on `ApolloQueryResult`. Previously this field was non-optional, non-null `TData`, however at runtime this value could be set to `undefined`. This field is now reported as `TData | undefined`.\n\n  This will affect you in a handful of places:\n\n  - The `data` property emitted from the result passed to the `next` callback from `client.watchQuery`\n  - Fetch-based APIs that return an `ApolloQueryResult` type such as `observableQuery.refetch`, `observableQuery.fetchMore`, etc.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `HttpLink` and `BatchHttpLink` no longer emit a `next` notification with the JSON-parsed response body when a well-formed GraphQL response is returned and a `ServerError` is thrown.\n\n- [#12742](https://github.com/apollographql/apollo-client/pull/12742) [`575bf3e`](https://github.com/apollographql/apollo-client/commit/575bf3ed5885efb09c1eec497af4d2690c6b87d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `operation` argument to the callback passed to `SetContextLink` is now of type `SetContextLink.SetContextOperation` which is an `Operation` without the `getContext` or `setContext` functions. Previously the type of `operation` was `GraphQLRequest` which had access to a `context` property. The `context` property was always `undefined` and could result in bugs when using it instead of the `prevContext` argument.\n\n  This change means the `operation` argument now contains an accessible `client` property.\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move internal testing utilities in `@apollo/client/testing` to `@apollo/client/testing/internal` and remove deprecated testing utilities. Some of the testing utilities exported from the `@apollo/client/testing` endpoint were not considered stable. As a result of this change, testing utilities or types exported from `@apollo/client/testing` are now considered stable and will not undergo breaking changes.\n\n  The following APIs were removed. To migrate, update usages of the following APIs as such:\n\n  **`createMockClient`**\n\n  ```diff\n  - const client = createMockClient(data, query, variables);\n  + const client = new ApolloClient({\n  +   cache: new InMemoryCache(),\n  +   link: new MockLink([\n  +     {\n  +       request: { query, variables },\n  +       result: { data },\n  +     }\n  +   ]),\n  + });\n  ```\n\n  **`mockObservableLink`**\n\n  ```diff\n  - const link = mockObservableLink();\n  + const link = new MockSubscriptionLink();\n  ```\n\n  **`mockSingleLink`**\n\n  ```diff\n  - const link = mockSingleLink({\n  -   request: { query, variables },\n  -   result: { data },\n  - });\n  + const link = new MockLink([\n  +   {\n  +     request: { query, variables },\n  +     result: { data },\n  +   }\n  + ]);\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Third-party caches must now implement the `fragmentMatches` API. Additionally `fragmentMatches` must be able to handle both `InlineFragmentNode` and `FragmentDefinitionNode` nodes.\n\n  ```ts\n  class MyCache extends ApolloCache {\n    // This is now required\n    public fragmentMatches(\n      fragment: InlineFragmentNode | FragmentDefinitionNode,\n      typename: string\n    ): boolean {\n      return; // ... logic to determine if typename matches fragment\n    }\n  }\n  ```\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The promise returned when calling the execute function from `useLazyQuery` will now reject when using an `errorPolicy` of `none` when GraphQL errors are returned from the result.\n\n- [#12684](https://github.com/apollographql/apollo-client/pull/12684) [`e697431`](https://github.com/apollographql/apollo-client/commit/e697431a9995fd1900e625c30a9065edd71111d9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `context` from `useLazyQuery` hook options. If used, `context` must now be provided to the `execute` function. `context` will reset to `{}` if not provided as an option to `execute`.\n\n- [#12704](https://github.com/apollographql/apollo-client/pull/12704) [`45dba43`](https://github.com/apollographql/apollo-client/commit/45dba43b6ba0c306aad8cfbcfd4029265f5e9106) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `ErrorResponse` object passed to the `disable` and `retry` callback options provided to `createPersistedQueryLink` no longer provides separate `graphQLErrors` and `networkError` properties and instead have been combined to a single `error` property of type `ErrorLike`.\n\n  ```diff\n  // The following also applies to the `retry` function since it has the same signature\n  createPersistedQueryLink({\n  - disable: ({ graphQLErrors, networkError }) => {\n  + disable: ({ error }) => {\n  -   if (graphQLErrors) {\n  +   if (CombinedGraphQLErrors.is(error)) {\n        // ... handle GraphQL errors\n      }\n\n  -   if (networkError) {\n  +   if (error) {\n        // ... handle link errors\n      }\n\n      // optionally check for a specific kind of error\n  -   if (networkError) {\n  +   if (ServerError.is(error)) {\n        // ... handle a server error\n      }\n  });\n  ```\n\n  The `response` property has also been renamed to `result`.\n\n  ```diff\n  createPersistedQueryLink({\n  -  disable: ({ response }) => {\n  +  disable: ({ result }) => {\n        // ... handle GraphQL errors\n      }\n    }\n  });\n  ```\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move all 1st party link types into a namespace.\n\n- [#12223](https://github.com/apollographql/apollo-client/pull/12223) [`69c1cb6`](https://github.com/apollographql/apollo-client/commit/69c1cb6f831941598987185238a299b050a364bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `subscribeAndCount` testing utility from `@apollo/client/testing`.\n\n- [#12300](https://github.com/apollographql/apollo-client/pull/12300) [`4d581e4`](https://github.com/apollographql/apollo-client/commit/4d581e4f5a3c5409e5f06a5f164beabdada150f1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Moves all React-related exports to the `@apollo/client/react` entrypoint and out of the main `@apollo/client` entrypoint. This prevents the need to install React in order to use the core client.\n\n  The following is a list of exports available in `@apollo/client` that should now import from `@apollo/client/react`.\n\n  - `ApolloConsumer`\n  - `ApolloProvider`\n  - `createQueryPreloader`\n  - `getApolloContext`\n  - `skipToken`\n  - `useApolloClient`\n  - `useBackgroundQuery`\n  - `useFragment`\n  - `useLazyQuery`\n  - `useLoadableQuery`\n  - `useMutation`\n  - `useQuery`\n  - `useQueryRefHandlers`\n  - `useReactiveVar`\n  - `useReadQuery`\n  - `useSubscription`\n  - `useSuspenseQuery`\n\n  The following is a list of exports available in `@apollo/client/testing` that should now import from `@apollo/client/testing/react`:\n\n  - `MockedProvider`\n\n- [#12525](https://github.com/apollographql/apollo-client/pull/12525) [`8785186`](https://github.com/apollographql/apollo-client/commit/87851863b94eebbc208671b17aeca73748ac41f6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Throw an error when a client-only query is used in a mocked response passed to `MockLink`.\n\n- [#12588](https://github.com/apollographql/apollo-client/pull/12588) [`eed825a`](https://github.com/apollographql/apollo-client/commit/eed825a2549f1d21fff2ec179815206b3baf0fcb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `TContext` generic argument from all types that use it. `TContext` is replaced with `DefaultContext` which can be modified using declaration merging.\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery`s will now only be registered with the `ApolloClient` while they\n  have subscribers.\n\n  That means that `ApolloClient.getObservableQueries` and `ApolloClient.refetchQueries`\n  will only be able to return/refetch queries that have at least one subscriber.\n\n  This changes the previous meaning of `active` and `inactive` queries:\n\n  - `inactive` queries are queries with a subscriber that are skipped from a\n    React hook or have a `fetchPolicy` of `standby`\n  - `active` queries are queries with at least one subscriber that are not skipped or in `standby`.\n\n  `ObservableQuery`s without subscribers but with an active ongoing network request\n  (e.g. caused by calling `reobserve`) will be handled as if they had a subscriber\n  for the duration of the query.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `transformOperation` and `validateOperation` have been removed and are no longer exported from `@apollo/client/link/utils`. These utilities have been merged into the implementation of `createOperation`. As a result, `createOperation` now returns a well-formed `Operation` object. Previously `createOperation` relied on an external call to `transformOperation` to provide a well-formed `Operation` type. If you use `createOperation` directly, remove the calls to `transformOperation` and `validateOperation` and pass the request directly.\n\n- [#12428](https://github.com/apollographql/apollo-client/pull/12428) [`abed922`](https://github.com/apollographql/apollo-client/commit/abed92225fd2a5d2a0a2298893a1170df1cd7400) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `urql` multipart subscriptions utilities. Use the native multipart subscriptions support in `urql` instead.\n\n- [#12590](https://github.com/apollographql/apollo-client/pull/12590) [`a005e82`](https://github.com/apollographql/apollo-client/commit/a005e822de7b24783f85be45df142ffbb9bc561b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Drop `graphql` v15 as a valid peer dependency.\n\n- [#12678](https://github.com/apollographql/apollo-client/pull/12678) [`91a876b`](https://github.com/apollographql/apollo-client/commit/91a876b059042828e431931e7a3c2e0365c387b8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `queryRef`s created by `preloadQuery` no longer have a `.toPromise()` function. Instead `preloadQuery` now has a `toPromise` function that accepts a queryRef and will resolve when the underlying promise has been resolved.\n\n  ```diff\n  const queryRef = preloadQuery(query, options);\n\n  - await queryRef.toPromise();\n  + await preloadQuery.toPromise(queryRef);\n  ```\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Reworked the logic for then a loading state is triggered. If the link chain responds synchronously, a loading state will be omitted, otherwise it will be triggered.\n  If local resolvers are used, the time window for \"sync vs async\" starts as soon as `@exports` variables are resolved.\n\n- [#12637](https://github.com/apollographql/apollo-client/pull/12637) [`d2a60d4`](https://github.com/apollographql/apollo-client/commit/d2a60d45e734a2518dad2443f85d82553cd6456a) Thanks [@phryneas](https://github.com/phryneas)! - `useQuery`: only advance `previousData` if `data` actually changed\n\n- [#12478](https://github.com/apollographql/apollo-client/pull/12478) [`5ea6a45`](https://github.com/apollographql/apollo-client/commit/5ea6a45b3ec2f0d526abe78ae03c42bb519f87c7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `onSubscriptionData` and `onSubscriptionComplete` callbacks from `useSubscription`. Use `onData` and `onComplete` instead.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Switch to [RxJS](https://rxjs.dev/) as the observable implementation. `rxjs` is now a peer dependency of Apollo Client which means you will now need to install `rxjs` in addition to `@apollo/client`.\n\n  This change is mostly transparent, however transforming values on observables, common in link implementations, differs in RxJS vs `zen-observable`. For example, you could modify values in the link chain emitted from a downstream link by using the `.map` function. In RxJS, this is done with the `.pipe` function and passing a `map` operator instead.\n\n  ```ts\n  import { map } from \"rxjs\";\n\n  const link new ApolloLink((operation, forward) => {\n    return forward(operation).pipe(\n      map((result) => performTransform(result))\n    );\n  });\n  ```\n\n  For a full list of operators and comprehensive documentation on the capabilities of RxJS, check out the [documentation](https://rxjs.dev/).\n\n- [#12442](https://github.com/apollographql/apollo-client/pull/12442) [`c5ead08`](https://github.com/apollographql/apollo-client/commit/c5ead08d0f10ddd6232b742defe9620533bf41e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `canonizeResults` option. It was prone to memory leaks. As such, some results that were referentially equal when `canonizeResults` option was set to `true` no longer retain the same object identity.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The request handler provided to `ApolloLink` must now return an `Observable`. `null` is no longer supported as a valid return value. If you rely on `null` so that `ApolloLink` provides an empty observable, use the `EMPTY` observable from RxJS instead:\n\n  ```diff\n  import { ApolloLink } from \"@apollo/client\";\n  + import { EMPTY } from \"rxjs\";\n\n  const link = new ApolloLink((operation, forward) => {\n  - return null;\n  + return EMPTY;\n  });\n  ```\n\n  If you have a custom link that overrides the `request` method, remove `null` from the return signature:\n\n  ```diff\n  class MyCustomLink extends ApolloLink {\n    request(\n      operation: ApolloLink.Operation,\n      forward: ApolloLink.ForwardFunction,\n  - ): Observable<ApolloLink.Result> | null {\n  + ): Observable<ApolloLink.Result> {\n      // implementation\n    }\n  }\n  ```\n\n- [#12329](https://github.com/apollographql/apollo-client/pull/12329) [`61febe4`](https://github.com/apollographql/apollo-client/commit/61febe4ef8712a2035d7ac89ea7283138db5229d) Thanks [@phryneas](https://github.com/phryneas)! - Rework package publish format (#12329, #12382)\n\n  We have reworked the way Apollo Client is packaged.\n\n  - shipping ESM and CJS\n  - fixing up source maps\n  - the build targets a modern runtime environment (browserslist query: `\"since 2023, node >= 20, not dead\"`)\n  - removed the \"proxy directory\" `package.json` files, e.g. `cache/core/package.json` and `react/package.json`. While these helped with older build tools, modern build tooling uses the `exports` field in the root `package.json` instead and the presence of these files can confuse modern build tooling. If your build tooling still relies on those, please update your imports to import from e.g. `@apollo/client/cache/core/index.js` instead of `@apollo/client/cache/core` - but generally, this should not be necessary.\n  - added an `exports` field to `package.json` to expose entry points\n  - instead of `globalThis.__DEV__`, Apollo Client now primarily relies on the `development` and `production` exports conditions. It falls back to `globalThis.__DEV__` if the bundler doesn't know these, though.\n\n- [#12566](https://github.com/apollographql/apollo-client/pull/12566) [`ce4b488`](https://github.com/apollographql/apollo-client/commit/ce4b488bef13f2f5ce1b348d8c3196e198165dd6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't `broadcastQueries` when a query is torn down.\n\n- [#12397](https://github.com/apollographql/apollo-client/pull/12397) [`2545a54`](https://github.com/apollographql/apollo-client/commit/2545a5415b06283be83eb9c4a03a3a8a39b8bcde) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `ObservableQuery.resetQueryStoreErrors` method. This method reset some internal state that was not consumed elsewhere in the client and resulted in a no-op.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `fromPromise` utility function. Use [`from`](https://rxjs.dev/api/index/function/from) instead.\n\n- [#12388](https://github.com/apollographql/apollo-client/pull/12388) [`0d825be`](https://github.com/apollographql/apollo-client/commit/0d825bef533b41f2e99ef22e620d9f9472825057) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Require environments that support `WeakMap`, `WeakSet` and symbols. Apollo Client would fallback to `Map` and `Set` if the weak versions were not available. This has been removed and expects that these features are available in the source environment.\n\n  If you are running in an environment without `WeakMap`, `WeakSet` or symbols, you will need to find appropriate polyfills.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports calling the execute function in render and will now throw. If you need to execute the query immediately, use `useQuery` instead or move the call to a `useEffect`.\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` will now return a `loading: false` state for `fetchPolicy` `standby`, even before subscription\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `@apollo/client/testing/core` entrypoint in favor of `@apollo/client/testing`.\n\n- [#12591](https://github.com/apollographql/apollo-client/pull/12591) [`a7e7383`](https://github.com/apollographql/apollo-client/commit/a7e738328951f5dac25a5fe48d28b3640a3e0eb9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Rename the `@apollo/client/link/core` entrypoint to `@apollo/client/link`.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `defaultOptions` and `initialFetchPolicy` options are no longer supported with `useLazyQuery`.\n\n  If you use `defaultOptions`, pass those options directly to the hook instead. If you use `initialFetchPolicy`, use `fetchPolicy` instead.\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `OperationBatcher` class is no longer exported from `@apollo/client/link/batch`. It is an implementation detail of `BatchLink` and should not be relied on directly.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `createOperation` no longer accepts `context` as the first argument. Instead make sure `context` is set as the `context` property on the request passed to `createOperation`.\n\n  ```diff\n  createOperation(\n  - startingContext,\n  - { query },\n  + { query, context: startingContext },\n    { client }\n  );\n  ```\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Dropped the `saveAsLastResult` argument from `ObservableQuery.getCurrentResult`\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports `variables` in the hook options and therefore no longer performs variable merging. The execute function must now be called with `variables` instead.\n\n  ```ts\n  function MyComponent() {\n    const [execute] = useLazyQuery(query);\n\n    function runExecute() {\n      execute({ variables: { ... }});\n    }\n  }\n  ```\n\n  This change means the execute function returned from `useLazyQuery` is more type-safe. The execute function will require you to pass a `variables` option if the query type includes required variables.\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The resolver function's `context` argument (the 3rd argument) has changed to provide additional information without the possibility of name clashes. Previously the `context` argument would spread request context and override the `client` and `cache` properties to give access to both inside of a resolver. The `context` argument takes now takes the following shape:\n\n  ```ts\n  {\n    // the request context. By default `TContextValue` is of type `DefaultContext`,\n    // but can be changed if a `context` function is provided.\n    requestContext: TContextValue,\n    // The client instance making the request\n    client: ApolloClient,\n    // Whether the resolver is run as a result of gathering exported variables\n    // or resolving the value as part of the result\n    phase: \"exports\" | \"resolve\"\n  }\n  ```\n\n  To migrate, pull any request context from `requestContext` and the `cache` from the `client` property:\n\n  ```diff\n  new LocalState({\n    resolvers: {\n      Query: {\n  -     myResolver: (parent, args, { someValue, cache }) => {\n  +     myResolver: (parent, args, { requestContext, client }) => {\n  +       const someValue = requestContext.someValue;\n  +       const cache = client.cache;\n        }\n      }\n    }\n  });\n  ```\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries no longer poll when a `pollInterval` is set. Instead a warning is now emitted that polling has no effect. If the `fetchPolicy` is changed to `cache-only` after polling is already active, polling is stopped.\n\n- [#12704](https://github.com/apollographql/apollo-client/pull/12704) [`45dba43`](https://github.com/apollographql/apollo-client/commit/45dba43b6ba0c306aad8cfbcfd4029265f5e9106) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `response` property in `onError` link has been renamed to `result`.\n\n  ```diff\n  - onError(({ response }) => {\n  + onError(({ result }) => {\n      // ...\n  });\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apollo Client no longer ships with support for `@client` fields out-of-the-box and now must be opt-in. To opt in to use `@client` fields, pass an instantiated `LocalState` instance to the `localState` option. If a query contains `@client` and local state hasn't been configured, an error will be thrown.\n\n  ```ts\n  import { LocalState } from \"@apollo/client/local-state\";\n\n  new ApolloClient({\n    localState: new LocalState(),\n  });\n  ```\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default the `delay` for all mocked responses passed to `MockLink` using `realisticDelay`. This ensures your test handles loading states by default and is not reliant on a specific timing.\n\n  If you would like to restore the old behavior, use a global default delay of `0`.\n\n  ```ts\n  MockLink.defaultOptions = {\n    delay: 0,\n  };\n  ```\n\n- [#12442](https://github.com/apollographql/apollo-client/pull/12442) [`c5ead08`](https://github.com/apollographql/apollo-client/commit/c5ead08d0f10ddd6232b742defe9620533bf41e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `resetResultIdentities` option from `InMemoryCache.gc()`. This affected object canonization which has been removed.\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - ### Changes for users of `InMemoryCache`\n\n  `cache.diff` now returns `null` instead of an empty object (`{}`) when `returnPartialData` is `true` and the result is empty.\n\n  If you use `cache.diff` directly with `returnPartialData: true`, you will need to check for `null` before accessing any other fields on the `result` property. A non-null value indicates that at least one field was present in the cache for the given query document.\n\n  ### Changes for third-party cache implementations\n\n  The client now expects `cache.diff` to return `null` instead of an empty object when there is no data that can be fulfilled from the cache and `returnPartialData` is `true`. If your cache implementation returns an empty object, please update this to return `null`.\n\n- [#12433](https://github.com/apollographql/apollo-client/pull/12433) [`b86e50b`](https://github.com/apollographql/apollo-client/commit/b86e50b1dc121cd67fe73655256b6c61afc18cb4) Thanks [@phryneas](https://github.com/phryneas)! - Remove workarounds for streaming with non-WhatWG response bodies to reduce bundle size.\n\n  This removes support for `fetch` implementations that return Node Streams, Async Iterators or Blob instances as `Response.body`.\n\n  In the WhatWG Fetch specification, [`Response.body`](https://fetch.spec.whatwg.org/#body) is specified as a WhatWG [ReadableStream](https://streams.spec.whatwg.org/#readablestream).\n\n  At this point in time, this is natively supported in browsers, `node` and React Native (via [react-native-fetch-api](https://www.npmjs.com/package/react-native-fetch-api), see our [setup instructions for React Native](https://www.apollographql.com/docs/react/integrations/react-native#consuming-multipart-http-via-text-streaming)).\n\n  If you are using an older `fetch` polyfill that deviates from the spec, this might not be compatible - for example, [node-fetch](https://github.com/node-fetch/node-fetch?tab=readme-ov-file#interface-body) returns a node `Readable` instead of a `ReadableStream`.\n  In those cases, please switch to a compatible alternative such as the `node`-native `fetch`, or `undici`.\n\n- [#12484](https://github.com/apollographql/apollo-client/pull/12484) [`9a8b9ce`](https://github.com/apollographql/apollo-client/commit/9a8b9cebbcf290984a4f154f261a4090e636e50e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `loading`, `networkStatus`, and `partial` properties on all promise-based query APIs. These properties were mostly static and were unnecessary since promise resolution guaranteed that the query was not longer loading.\n\n  This affects the following APIs:\n\n  - `client.query`\n  - `client.refetchQueries`\n  - `client.reFetchObservableQueries`\n  - `client.resetStore`\n  - `observableQuery.fetchMore`\n  - `observableQuery.refetch`\n  - `observableQuery.reobserve`\n  - `observableQuery.setVariables`\n  - The `useLazyQuery` `execute` function\n\n- [#12512](https://github.com/apollographql/apollo-client/pull/12512) [`e809b71`](https://github.com/apollographql/apollo-client/commit/e809b71aa9a02917a286afdbb03d5be8e5947c53) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `notifyOnNetworkStatusChange` now defaults to `true`. This means that loading states will be emitted (core API) or rendered (React) by default when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n  ```ts\n  new ApolloClient({\n    defaultOptions: {\n      watchQuery: {\n        // Use the v3 default\n        notifyOnNetworkStatusChange: false,\n      },\n    },\n  });\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `fragmentMatcher` option from `ApolloClient`. Custom fragment matchers used with local state are no longer supported. Fragment matching is now performed by the configured `cache` via the `cache.fragmentMatches` API.\n\n- [#12430](https://github.com/apollographql/apollo-client/pull/12430) [`2ff66d0`](https://github.com/apollographql/apollo-client/commit/2ff66d06b6d444fbcb46e580ac40e673e695740f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes `ObservableQuery.result()` method. If you use this method and need similar functionality, use the `firstValueFrom` helper in RxJS.\n\n  ```ts\n  import { firstValueFrom, from } from \"rxjs\";\n\n  // The `from` is necessary to turn `observableQuery` into an RxJS observable\n  const result = await firstValueFrom(from(observableQuery));\n  ```\n\n- [#12359](https://github.com/apollographql/apollo-client/pull/12359) [`ebb4d96`](https://github.com/apollographql/apollo-client/commit/ebb4d9644104244fb066b93a32df778928f2f8a9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `onCompleted` and `onError` callbacks from `useQuery` and `useLazyQuery`.\n\n  See [#12352](https://github.com/apollographql/apollo-client/issues/12352) for more context on this change.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions are no longer eagerly started after calling `client.subscribe`. To kick off the subscription, you will now need to subscribe to the returned observable.\n\n  ```ts\n  // Subscriptions are no longer started when calling subscribe on its own.\n  const subscriptionObservable = client.subscribe(...);\n\n  // Instead, subscribe to the returned observable to kick off the subscription.\n  subscriptionObservable.subscribe({\n    next: (value) => console.log(value)\n  });\n  ```\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - GraphQL errors or network errors emitted while using an `errorPolicy` of `ignore` in subscriptions will no longer emit a result if there is no `data` emitted along with the error.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` will now only execute the query when the execute function is called. Previously `useLazyQuery` would behave like `useQuery` after the first call to the execute function which means changes to options might perform network requests.\n\n  You can now safely rerender `useLazyQuery` with new options which will take effect the next time you manually trigger the query.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `TVariables` generic argument on the `GraphQLRequest` type.\n\n- [#12464](https://github.com/apollographql/apollo-client/pull/12464) [`0595f39`](https://github.com/apollographql/apollo-client/commit/0595f39deba52ac43fa0780b742564134ec7ab89) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `called` property from `useQuery`.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `toPromise` utility function. Use [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom) instead.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions no longer emit errors in the `error` callback and instead provide errors on the `error` property on the result passed to the `next` callback. As a result, errors will no longer automatically terminate the connection allowing additional results to be emitted when the connection stays open.\n\n  When an error terminates the downstream connection, a `next` event will be emitted with an `error` property followed by a `complete` event instead.\n\n- [#12841](https://github.com/apollographql/apollo-client/pull/12841) [`65b503f`](https://github.com/apollographql/apollo-client/commit/65b503fe4bfcf942e8f66f36f622f5f6448d6731) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `DataMasking` interface exported from `@apollo/client` and `@apollo/client/masking`.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The context object returned from `operation.getContext()` is now frozen to prevent mutable changes to the object which could result in subtle bugs. This applies to the `previousContext` object passed to the `operation.setContext()` callback as well.\n\n- [#12715](https://github.com/apollographql/apollo-client/pull/12715) [`0be0b3f`](https://github.com/apollographql/apollo-client/commit/0be0b3f54a1b533c95c69d3698c5c3bdbd6279fe) Thanks [@phryneas](https://github.com/phryneas)! - All links are now available as classes. The old creator functions have been deprecated.\n\n  Please migrate these function calls to class creations:\n\n  ```diff\n  import {\n  - setContext\n  + SetContextLink\n  } from \"@apollo/client/link/context\"\n\n  -const link = setContext(...)\n  +const link = new SetContextLink(...)\n  ```\n\n  ```diff\n  import {\n  - createHttpLink\n  + HttpLink\n  } from \"@apollo/client/link/http\"\n\n  -const link = createHttpLink(...)\n  +const link = new HttpLink(...)\n  ```\n\n  ```diff\n  import {\n  - createPersistedQueryLink\n  + PersistedQueryLink\n  } from \"@apollo/client/link/persisted-queries\"\n\n  -const link = createPersistedQueryLink(...)\n  +const link = new PersistedQueryLink(...)\n  ```\n\n  ```diff\n  import {\n  - removeTypenameFromVariables\n  + RemoveTypenameFromVariablesLink\n  } from \"@apollo/client/link/remove-typename\"\n\n  -const link = removeTypenameFromVariables(...)\n  +const link = new RemoveTypenameFromVariablesLink(...)\n  ```\n\n- [#12530](https://github.com/apollographql/apollo-client/pull/12530) [`2973e2a`](https://github.com/apollographql/apollo-client/commit/2973e2a6e6fd81fa59b769d84c252c98ca69440d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `newData` option for mocked responses passed to `MockLink` or the `mocks` option on `MockedProvider`. This option was undocumented and was nearly identical to using the `result` option as a callback.\n\n  To replicate the old behavior of `newData`, use `result` as a callback and add the `maxUsageCount` option with a value set to `Number.POSITIVE_INFINITY`.\n\n  **with `MockLink`**\n\n  ```diff\n  new MockLink([\n    {\n      request: { query, variables },\n  -   newData: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +   result: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +   maxUsageCount: Number.POSITIVE_INFINITY,\n    }\n  ])\n  ```\n\n  **with `MockedProvider`**\n\n  ```diff\n  <MockedProvider\n    mocks={[\n      {\n        request: { query, variables },\n  -     newData: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +     result: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +     maxUsageCount: Number.POSITIVE_INFINITY,\n      }\n    ]}\n  />\n  ```\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - A call to `ObservableQuery.setVariables` with different variables or a `ObservableQuery.refetch` call will always now guarantee that a value will be emitted from the observable, even if it is deep equal to the previous value.\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - `ApolloClient.stop()` now cleans up more agressively to prevent memory leaks:\n\n  - It will now unsubscribe all active `ObservableQuery` instances by emitting a `completed` event.\n  - It will now reject all currently running queries with `\"QueryManager stopped while query was in flight\"`.\n  - It will remove all queryRefs from the suspense cache.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `forward` function passed to the request handler is now always provided to `request` and no longer optional. If you create custom links by subclassing `ApolloLink`, the `forward` function no longer needs to be optional:\n\n  ```ts\n  class CustomLink extends ApolloLink {\n    request(\n      operation: ApolloLink.Operation,\n      // This no longer needs to be typed as optional\n      forward: ApolloLink.ForwardFunction\n    ) {\n      // ...\n    }\n  }\n  ```\n\n  As a result of this change, `ApolloLink` no longer detects terminating links by checking function arity on the request handler. This means using methods such as `concat` on a terminating link no longer emit a warning. On the flip side, if the terminating link calls the `forward` function, a warning is emitted and an observable that immediately completes is returned which will result in an error from Apollo Client.\n\n- [#12589](https://github.com/apollographql/apollo-client/pull/12589) [`15f5a1c`](https://github.com/apollographql/apollo-client/commit/15f5a1c29ac05015387a7bbc2dbe9a91d09fedfa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Require the `link` option when instantiating `ApolloClient`. This removes the `uri`, `credentials` and `headers` options from `ApolloClient` in favor of passing an instantiated `HttpLink` directly. To migrate:\n\n  **If using `uri`, `credentials`, or `headers` options**\n\n  ```diff\n  new ApolloClient({\n    // ...\n  - uri,\n  - credentials,\n  - headers,\n  + link: new HttpLink({ uri, credentials, headers }),\n  // or if you prefer the function call approach:\n  + link: createHttpLink({ uri, credentials, headers }),\n  });\n  ```\n\n  **If creating a client without the `link` option**\n\n  ```diff\n  new ApolloClient({\n    // ...\n  + link: ApolloLink.empty()\n  });\n  ```\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - ### Changes for users of `InMemoryCache`\n\n  `cache.diff` no longer throws when `returnPartialData` is set to `false` without a complete result. Instead, `cache.diff` will return `null` when it is unable to read a full cache result.\n\n  If you use `cache.diff` directly with `returnPartialData: false`, remove the `try`/`catch` block and replace with a check for `null`.\n\n  ### Changes for third-party cache implementations\n\n  The client now expects `cache.diff` to return `null` instead of throwing when the cache returns an incomplete result and `returnPartialData` is `false`. The internal `try`/`catch` blocks have been removed around `cache.diff`. If your cache implementation throws for incomplete results, please update this to return `null`.\n\n- [#12451](https://github.com/apollographql/apollo-client/pull/12451) [`77e1b13`](https://github.com/apollographql/apollo-client/commit/77e1b133bdba32c67b5a840090dbacb16282dee9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default the `TData` generic type to `unknown` in all APIs that use a `TData` generic argument such as `useQuery`, `client.query`, etc.\n\n- [#12562](https://github.com/apollographql/apollo-client/pull/12562) [`90bf0e6`](https://github.com/apollographql/apollo-client/commit/90bf0e61516a382182f212ac8ab891099e2eb009) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.query` no longer supports a `fetchPolicy` of `standby`. `standby` does not fetch and did not return `data`. `standby` is meant for watched queries where fetching should be on hold.\n\n- [#12211](https://github.com/apollographql/apollo-client/pull/12211) [`c2736db`](https://github.com/apollographql/apollo-client/commit/c2736db3ad6f8b6e56f065682d5b76614f41bfd4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `Query`, `Mutation`, and `Subscription` components. Use the provided React hooks instead.\n\n</details>\n\n<details>\n\n<summary>\n\n### Minor Changes\n\n</summary>\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow mocked responses passed to `MockLink` to accept a callback for the `delay` option. The `delay` callback will be given the current operation which can be used to determine what delay should be used for the mock.\n\n- [#12711](https://github.com/apollographql/apollo-client/pull/12711) [`f730f83`](https://github.com/apollographql/apollo-client/commit/f730f83346d4e3c20116da6f55fdd1381114416c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an `extensions` property to `CombinedGraphQLErrors` to capture any extensions from the original response.\n\n- [#12438](https://github.com/apollographql/apollo-client/pull/12438) [`5089516`](https://github.com/apollographql/apollo-client/commit/5089516aa3ad140df22bb8a458faeeb884ed0388) Thanks [@phryneas](https://github.com/phryneas)! - Drop `rehackt` dependency.\n  We can now directly import from `react` without causing build errors in RSC.\n\n- [#12437](https://github.com/apollographql/apollo-client/pull/12437) [`4779dc7`](https://github.com/apollographql/apollo-client/commit/4779dc7badaba10d8c7a271eb0da6a079049b65d) Thanks [@phryneas](https://github.com/phryneas)! - Remove polyfills for Object.freeze,seal and preventExtensions in React Native\n\n  These polyfills were only necessary until React Native 0.59, which\n  [patched the problem](https://github.com/facebook/react-native/pull/21492) on\n  the React Native side.\n\n  With React Native 0.61, the `Map` function was [completely replaced](https://github.com/facebook/react-native/commit/93b9ac74e59bbe84ea388d7c1879857b4acab114)\n  with a native implementation that never had the problems we guarded against.\n\n- [#12557](https://github.com/apollographql/apollo-client/pull/12557) [`51d26ae`](https://github.com/apollographql/apollo-client/commit/51d26ae631c6631a189c98ea9357b18e77a9a876) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add ability to specify message formatter for `CombinedGraphQLErrors` and `CombinedProtocolErrors`. To provide your own message formatter, override the static `formatMessage` property on these classes.\n\n  ```ts\n  CombinedGraphQLErrors.formatMessage = (\n    errors,\n    { result, defaultFormatMessage }\n  ) => {\n    return \"Some formatted message\";\n  };\n\n  CombinedProtocolErrors.formatMessage = (errors, { defaultFormatMessage }) => {\n    return \"Some formatted message\";\n  };\n  ```\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `dataState` to the value emitted from `client.watchFragment`.\n\n- [#12670](https://github.com/apollographql/apollo-client/pull/12670) [`0a880ea`](https://github.com/apollographql/apollo-client/commit/0a880ea4c2360a985fdd2edadb94fcc4b82bad73) Thanks [@phryneas](https://github.com/phryneas)! - Provide a mechanism to override the DataMasking types.\n\n  Up until now, our types `Masked`, `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked` would assume that you are stictly using the type output format of GraphQL Codegen.\n\n  With this change, you can now modify the behaviour of those types if you use a different form of codegen that produces different types for your queries.\n\n  A simple implementation that would override the `Masked` type to remove all fields starting with `_` from a type would look like this:\n\n  ```ts\n  // your actual implementation of `Masked`\n  type CustomMaskedImplementation<TData> = {\n    [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n  };\n\n  import { HKT } from \"@apollo/client/utilities\";\n  // transform this type into a higher kinded type that can be evaulated at a later time\n  interface CustomMaskedType extends HKT {\n    arg1: unknown; // TData\n    return: CustomMaskedImplementation<this[\"arg1\"]>;\n  }\n\n  // create an \"implementation interface\" for the types you want to override\n  export interface CustomDataMaskingImplementation {\n    Masked: CustomMaskedType;\n    // other possible keys: `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked`\n  }\n  ```\n\n  then you would use that `CustomDataMaskingImplementation` interface in your project to extend the `TypeOverrides` interface exported by `@apollo/client` with it's functionality:\n\n  ```ts\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides extends CustomDataMaskingImplementation {}\n  }\n  ```\n\n  After that, all internal usage of `Masked` in Apollo Client as well as all usage in your code base will use the new `CustomMaskedType` implementation.\n\n  If you don't specify overrides, Apollo Client will still default to the GraphQL Codegen data masking implementation.\n  The types for that are also explicitly exported as the `GraphQLCodegenDataMasking` namespace in `@apollo/client/masking`.\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduce a new `realisticDelay` helper function for use with the `delay` callback for mocked responses used with `MockLink`. `realisticDelay` will generate a random value between 20 and 50ms to provide an experience closer to unpredictable network latency. `realisticDelay` can be configured with a `min` and `max` to set different thresholds if the defaults are not sufficient.\n\n  ```ts\n  import { realisticDelay } from \"@apollo/client/testing\";\n\n  new MockLink([\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: realisticDelay(),\n    },\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: realisticDelay({ min: 10, max: 100 }),\n    },\n  ]);\n  ```\n\n- [#12844](https://github.com/apollographql/apollo-client/pull/12844) [`18a0cad`](https://github.com/apollographql/apollo-client/commit/18a0cad773257e540ec8dc8e90f7a875a0ccf99f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an entrypoint at `@apollo/client/v4-migration` that includes removed values and types. Each export includes doc blocks on how to migrate away from the removed type.\n\n- [#12546](https://github.com/apollographql/apollo-client/pull/12546) [`5dffbbe`](https://github.com/apollographql/apollo-client/commit/5dffbbe407eb1d9adbcb0fff89f2d3a75dc1ad2b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a static `is` method to error types defined by Apollo Client. `is` makes it simpler to determine whether an error is a specific type, which can be helpful in cases where you'd like to narrow the error type in order to use specific properties from that error.\n\n  This change applies to the following error types:\n\n  - `CombinedGraphQLErrors`\n  - `CombinedProtocolErrors`\n  - `ServerError`\n  - `ServerParseError`\n  - `UnconventionalError`\n\n  **Example**\n\n  ```ts\n  import { CombinedGraphQLErrors } from \"@apollo/client\";\n\n  if (CombinedGraphQLErrors.is(error)) {\n    console.log(error.message);\n    error.errors.forEach((graphQLError) => console.log(graphQLError.message));\n  }\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Revamp local resolvers and fix several issues from the existing `resolvers` option.\n\n  - Throwing errors in a resolver will set the field value as `null` and add an error to the response's `errors` array.\n  - Remote results are dealiased before they are passed as the parent object to a resolver so that you can access fields by their field name.\n  - You can now specify a `context` function that you can use to customize the `requestContext` given to resolvers.\n  - The `LocalState` class accepts a `Resolvers` generic that provides autocompletion and type checking against your resolver types to ensure your resolvers are type-safe.\n  - `data: null` is now handled correctly and does not call your local resolvers when the server does not provide a result.\n  - Additional warnings have been added to provide hints when resolvers behave unexpectedly.\n\n  ```ts\n  import { LocalState } from \"@apollo/client/local-state\";\n\n  import { Resolvers } from \"./path/to/local-resolvers-types.ts\";\n\n  // LocalState now accepts a `Resolvers` generic.\n  const localState = new LocalState<Resolvers>({\n    // The return value of this funciton\n    context: (options) => ({\n      // ...\n    }),\n    resolvers: {\n      // ...\n    },\n  });\n\n  // You may also pass a `ContextValue` generic used to ensure the `context`\n  // function returns the correct type. This type is inferred from your resolvers\n  // if not provided.\n  new LocalState<Resolvers, ContextValue>({\n    // ...\n  });\n  ```\n\n- [#12828](https://github.com/apollographql/apollo-client/pull/12828) [`81b03d8`](https://github.com/apollographql/apollo-client/commit/81b03d86ad7e7384124708477829bcbf63d4fa2c) Thanks [@phryneas](https://github.com/phryneas)! - `invariant.error` will now also log in production builds, not only dev builds\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The callback function that can be passed to the `ApolloClient.mutate`\n  `refetchQueries` option will now receive a `FormattedExecutionResult` with an\n  additional `dataState` option that describes if the result is `\"streaming\"`\n  or `\"complete\"`.\n  This indicates whether the `data` value is of type\n\n  - `Unmasked<TData>` (if `\"complete\"`)\n  - `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - Apollo Client is no longer using `ts-invariant`, but ships with a modified variant of it.\n\n  The existing export `setLogVerbosity` from `@apollo/client` is still available and\n  now points to this new integration.\n  **In most cases, you should be using this export.**\n  It will no longer adjust the verbosity of `ts-invariant` and as such no longer\n  influence other packages relying on `ts-invariant`.\n\n  The new entry point `@apollo/client/utilities/invariant` now exports `invariant`,\n  `InvariantError` and `setVerbosity`.\n  (Note that these tools are mostly meant to be used by Apollo Client and libraries directly\n  based on Apollo Client like the `@apollo/client-integration-*` packages.)\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Provide an extension to define types for `context` passed to the link chain. To define your own types, use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to add properties to the `DefaultContext` type.\n\n  ```ts\n  // @apollo-client.d.ts\n  // This import is necessary to ensure all Apollo Client imports\n  // are still available to the rest of the application.\n  import \"@apollo/client\";\n\n  declare module \"@apollo/client\" {\n    interface DefaultContext extends Record<string, any> {\n      myProperty: string;\n    }\n  }\n  ```\n\n  Links that provide context options can be used with this type to add those context types to `DefaultContext`. For example, to add context options from `HttpLink`, add the following code:\n\n  ```ts\n  import { HttpLink } from \"@apollo/client\";\n\n  declare module \"@apollo/client\" {\n    interface DefaultContext extends HttpLink.ContextOptions {\n      myProperty: string;\n    }\n  }\n  ```\n\n  At this time, the following built-in links support context options:\n\n  - `HttpLink.ContextOptions`\n  - `BatchHttpLink.ContextOptions`\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - Allow passing `errorPolicy` option to `fetchMore` and change default value to \"none\".\n\n- [#12497](https://github.com/apollographql/apollo-client/pull/12497) [`ff2cbe1`](https://github.com/apollographql/apollo-client/commit/ff2cbe1db1815c30f5fda7f6c07091663e065582) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `data` property to `CombinedGraphQLErrors` that captures any partial data returned by the GraphQL response when `errors` are also returned.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ApolloLink`'s `concat` method now accepts multiple links to concatenate together.\n\n  ```ts\n  const first = new ApolloLink();\n\n  const link = first.concat(second, third, fouth);\n  ```\n\n- [#12753](https://github.com/apollographql/apollo-client/pull/12753) [`b85818d`](https://github.com/apollographql/apollo-client/commit/b85818dcc66d3ed8b1c3a7e5e37b2875d6bf9d03) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Renamed `client.reFetchObservableQueries` to `client.refetchObservableQueries`.\n  `client.reFetchObservableQueries` is still available as an alias, but is now\n  deprecated and will be removed in a future major version.\n\n- [#12561](https://github.com/apollographql/apollo-client/pull/12561) [`99d72bf`](https://github.com/apollographql/apollo-client/commit/99d72bfdb38e3d9679f60b9acb065a84e3b42fd6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to detect if an error was an error was emitted from the link chain. This is useful if your application throws custom errors in other areas of the application and you'd like to differentiate them from errors emitted by the link chain itself.\n\n  To detect if an error was emitted from the link chain, use `LinkError.is`.\n\n  ```ts\n  import { LinkError } from \"@apollo/client\";\n\n  client.query({ query }).catch((error) => {\n    if (LinkError.is(error)) {\n      // This error originated from the link chain\n    }\n  });\n  ```\n\n- [#12698](https://github.com/apollographql/apollo-client/pull/12698) [`be77d1a`](https://github.com/apollographql/apollo-client/commit/be77d1a6ddf719cab4780a0679fcd98556ac7f22) Thanks [@phryneas](https://github.com/phryneas)! - Adjusted the accept header for multipart requests according to the new GraphQL over HTTP spec with these changes:\n\n  ```diff\n  -multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json\n  +multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/graphql-response+json,application/json;q=0.9\n  ```\n\n  ```diff\n  -multipart/mixed;deferSpec=20220824,application/json\n  +multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\n  ```\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions created by `client.subscribe()` can now be restarted. Restarting a subscription will terminate the connection with the link chain and recreate the request. Restarts also work across deduplicated subscriptions so calling `restart` on an `observable` who's request is deduplicated will restart the connection for each observable.\n\n  ```ts\n  const observable = client.subscribe({ query: subscription });\n\n  // Restart the connection to the link\n  observable.restart();\n  ```\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move `MockLink` types to `MockLink` namespace. This affects the `MockedResponse`, `MockLinkOptions`, and `ResultFunction` types. These types are still exported but are deprecated in favor of the namespace. To migrate, use the types on the `MockLink` namespace instead.\n\n  ```diff\n  import {\n  - MockedResponse,\n  - MockLinkOptions,\n  - ResultFunction,\n  + MockLink\n  } from \"@apollo/client/testing\";\n\n  - const mocks: MockedResponse = [];\n  + const mocks: MockLink.MockedResponse = [];\n\n  - const result: ResultFunction = () => {/* ... */ }\n  + const result: MockLink.ResultFunction = () => {/* ... */ }\n\n  - const options: MockLinkOptions = {}\n  + const options: MockLink.Options = {}\n  ```\n\n- [#12201](https://github.com/apollographql/apollo-client/pull/12201) [`1c6e03c`](https://github.com/apollographql/apollo-client/commit/1c6e03c9c74a9fad2a1c2e1c3ae61a9560038238) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Overridable types for `dataState: \"complete\"`, `dataState: \"streaming\"` and\n  `dataState: \"partial\"` responses.\n\n  This adds the `DataValue` namespace exported from Apollo Client with the three\n  types `DataValue.Complete`, `DataValue.Streaming` and `DataValue.Partial`.\n\n  These types will be used to mark `TData` in the respective states.\n\n  - `Complete` defaults to `TData`\n  - `Streaming` defaults to `TData`\n  - `Partial` defaults to `DeepPartial<TData>`\n\n  All three can be overwritten, e.g. to be `DeepReadonly` using higher kinded types\n  by following this pattern:\n\n  ```ts\n  import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n  import { DeepReadonly } from \"some-type-helper-library\";\n\n  interface CompleteOverride extends HKT {\n    return: DeepReadonly<this[\"arg1\"]>;\n  }\n\n  interface StreamingOverride extends HKT {\n    return: DeepReadonly<this[\"arg1\"]>;\n  }\n\n  interface PartialOverride extends HKT {\n    return: DeepReadonly<DeepPartial<this[\"arg1\"]>>;\n  }\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides {\n      Complete: CompleteOverride;\n      Streaming: StreamingOverride;\n      Partial: PartialOverride;\n    }\n  }\n  ```\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deduplicating subscription operations is now supported. Previously it was possible to deduplicate a subscription only if the new subscription was created before a previously subscribed subscription emitted any values. As soon as a value was emitted from a subscription, new subscriptions would create new connections. Deduplication is now active for as long as a subscription connection is open (i.e. the source observable hasn't emitted a `complete` or `error` notification yet.)\n\n  To disable deduplication and force a new connection, use the `queryDeduplication` option in `context` like you would a query operation.\n\n  As a result of this change, calling the `restart` function returned from `useSubscription` will now restart the connection on deduplicated subscriptions.\n\n- [#12438](https://github.com/apollographql/apollo-client/pull/12438) [`5089516`](https://github.com/apollographql/apollo-client/commit/5089516aa3ad140df22bb8a458faeeb884ed0388) Thanks [@phryneas](https://github.com/phryneas)! - Add `react-server` entry point with stubs for normal exports.\n\n- [#12333](https://github.com/apollographql/apollo-client/pull/12333) [`3e4beaa`](https://github.com/apollographql/apollo-client/commit/3e4beaa8b768a893da80aae0428f79ee01d6aa38) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deprecate the `partial` flag on `ApolloQueryResult` and make it a non-optional property. Previously `partial` was only set conditionally if the result emitted was partial. This value is now available with all results that return an `ApolloQueryResult`.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Add the new `ClientAwarenessLink`.\n\n  This link is already included in `HttpLink` and `BatchHttpLink` to enable the\n  \"client awareness\" and \"enhanced client awareness\" features, but you can also use\n  `ClientAwarenessLink` directly in your link chain to combine it with other\n  terminating links.\n\n  If you want to save the bundle size that `ClientAwarenessLink` adds to `HttpLink`\n  and `BatchHttpLink`, you can use `BaseHttpLink` or `BaseBatchHttpLink` instead.\n  These links come without the `ClientAwarenessLink` included.\n\n  For example:\n\n  ```diff\n  import {\n    ApolloClient,\n  -  HttpLink,\n  } from \"@apollo/client\";\n  +import { BaseHttpLink } from \"@apollo/client/link/http\";\n\n  const client = new ApolloClient({\n  -  link: new HttpLink({\n  +  link: new BaseHttpLink({\n      uri,\n    }),\n    cache: new InMemoryCache(),\n  });\n  ```\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - Added a new `.stop` function on `ObservableQuery`.\n  Calling this method will unsubscribe all current subscribers by sending a `complete` event from the observable and tear down the `ObservableQuery`.\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `client` property to the `operation` passed to the link chain. This `client` is set as the `client` making the request to the link chain.\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add ability to specify a default `delay` for all mocked responses passed to `MockLink`. This `delay` can be configured globally (all instances of `MockLink` will use the global defaults), or per-instance (all mocks in a single instance will use the defaults). A `delay` defined on a single mock will supercede all default delays. Per-instance defaults supercede global defaults.\n\n  **Global defaults**\n\n  ```ts\n  MockLink.defaultOptions = {\n    // Use a default delay of 20ms for all mocks in all instances without a specified delay\n    delay: 20,\n\n    // altenatively use a callback which will be executed for each mock\n    delay: () => getRandomNumber(),\n\n    // or use the built-in `realisticDelay`. This is the default\n    delay: realisticDelay(),\n  };\n  ```\n\n  **Per-instance defaults**\n\n  ```ts\n  new MockLink(\n    [\n      // Use the default delay\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello\" } },\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello\" } },\n        // Override the default for this mock\n        delay: 10,\n      },\n    ],\n    {\n      defaultOptions: {\n        // Use a default delay of 20ms for all mocks without a specified delay\n        delay: 20,\n\n        // altenatively use a callback which will be executed for each mock\n        delay: () => getRandomNumber(),\n\n        // or use the built-in `realisticDelay`. This is the default\n        delay: realisticDelay(),\n      },\n    }\n  );\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Many of the types exported from `@apollo/client/link` now live on the `ApolloLink` namespace. The old types are now deprecated in favor of the namespaced types.\n\n  - `FetchResult` -> `ApolloLink.Result`\n  - `GraphQLRequest` -> `ApolloLink.Request`\n  - `NextLink` -> `ApolloLink.ForwardFunction`\n  - `Operation` -> `ApolloLink.Operation`\n  - `RequestHandler` -> `ApolloLink.RequestHandler`\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - The `FetchMoreQueryOptions` type has been inlined into `FetchMoreOptions`, and\n  `FetchMoreQueryOptions` has been removed.\n\n- [#12757](https://github.com/apollographql/apollo-client/pull/12757) [`5fd2e7c`](https://github.com/apollographql/apollo-client/commit/5fd2e7c15eecc6469ecf5f4fb116633b056ad103) Thanks [@phryneas](https://github.com/phryneas)! - Add `dataState` and overridable `DataValue` types to `useFragment`\n\n- [#12757](https://github.com/apollographql/apollo-client/pull/12757) [`5fd2e7c`](https://github.com/apollographql/apollo-client/commit/5fd2e7c15eecc6469ecf5f4fb116633b056ad103) Thanks [@phryneas](https://github.com/phryneas)! - Add overridable `DataValue` types to `useSuspenseFragment`\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - Prioritize usage of `FormattedExecutionResult` over `FetchResult` where applicable.\n\n  Many APIs used `FetchResult` in place of `FormattedExecutionResult`, which could\n  cause inconsistencies.\n\n  - `FetchResult` is now used to refer to an unhandled \"raw\" result as returned from\n    a link.\n    This can also include incremental results that use a different format.\n  - `FormattedExecutionResult` from the `graphql` package is now used to represent\n    the execution of a standard GraphQL request without incremental results.\n\n  If your custom links access the `data` property, you might need to first check if\n  the result is a standard GraphQL result by using the `isFormattedExecutionResult`\n  helper from `@apollo/client/utilities`.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The static `ApolloLink.concat` method is now deprecated in favor of `ApolloLink.from`. `ApolloLink.concat` is now an alias for `ApolloLink.from` so prefer `ApolloLink.from` instead.\n\n- [#12488](https://github.com/apollographql/apollo-client/pull/12488) [`c98b633`](https://github.com/apollographql/apollo-client/commit/c98b6335de5b15e546aa5db79a8cf2dc9d914dcf) Thanks [@phryneas](https://github.com/phryneas)! - Add a new method for static SSR of React components, `prerenderStatic`.\n  The old methods, `getDataFromTree`, `getMarkupFromTree` and `renderToStringWithData`\n  have been deprecated in favor of `prerenderStatic`.\n\n  If used with React 19 and the `prerender` or `prerenderToNodeStream` apis from\n  `react-dom/static`, this method can now be used to SSR-prerender suspense-enabled\n  hook APIs.\n\n- [#12698](https://github.com/apollographql/apollo-client/pull/12698) [`be77d1a`](https://github.com/apollographql/apollo-client/commit/be77d1a6ddf719cab4780a0679fcd98556ac7f22) Thanks [@phryneas](https://github.com/phryneas)! - Adds an `accept` option to `HttpOptions` that allows to add additional `Accept` headers to be merged in without overriding user-specified or default accept headers.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The `mutationResult` option passed to the `updateQueries` callback now has an\n  additional property, `dataState` with possible values of `\"complete\"` and `\"streaming\"`.\n  This indicates whether the `data` value is of type\n\n  - `Unmasked<TData>` (if `\"complete\"`)\n  - `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n\n- [#12487](https://github.com/apollographql/apollo-client/pull/12487) [`b695e5e`](https://github.com/apollographql/apollo-client/commit/b695e5e10ab0eb47948e914b610f67c40267349e) Thanks [@phryneas](https://github.com/phryneas)! - Split out SSR-specific code from useQuery hook, remove RenderPromises\n\n- [#12725](https://github.com/apollographql/apollo-client/pull/12725) [`89ac725`](https://github.com/apollographql/apollo-client/commit/89ac7256a34b3b04fe2cf83937b5494b375ce36d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `operationType` to `operation` in `ApolloLink`. This means that determining whether a `query` is a specific operation type can now be compared with this property instead of using `getMainDefinition`.\n\n  ```diff\n  - import { getMainDefinition } from \"@apollo/client/utilities\";\n  + import { OperationTypeNode } from \"graphql\";\n\n  ApolloLink.split(\n  - ({ query }) => {\n  -   const definition = getMainDefinition(query);\n  -   return (\n  -     definition.kind === 'OperationDefinition' &&\n  -     definition.operation === 'subscription'\n  -   );\n  -   return\n  - },\n  + ({ operationType }) => {\n  +   return operationType === OperationTypeNode.SUBSCRIPTION;\n  + },\n    conditionTrueLink,\n    conditionFalseLink,\n  );\n  ```\n\n- [#12633](https://github.com/apollographql/apollo-client/pull/12633) [`9bfb51f`](https://github.com/apollographql/apollo-client/commit/9bfb51fdbca69560da71f9012c74ee172b6c2b69) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery.refetch` and `ObservableQuery.reobserve` and the `execute` function of `useLazyQuery` now return a\n  `ResultPromise` with an additional `.retain` method.\n  If this method is called, the underlying network operation will be kept running even if the `ObservableQuery` itself does\n  not require the result anymore, and the Promise will resolve with the final result instead of resolving with an intermediate\n  result in the case of early cancellation.\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a new `dataState` property that determines the completeness of the `data` property. `dataState` helps narrow the type of `data`. `dataState` is now emitted from `ObservableQuery` and returned from all React hooks that return a `data` property.\n\n  The `dataState` values are:\n\n  - `empty`: No data could be fulfilled from the cache or the result is incomplete. `data` is `undefined`.\n  - `partial`: Some data could be fulfilled from the cache but `data` is incomplete. This is only possible when `returnPartialData` is `true`.\n  - `streaming`: `data` is incomplete as a result of a deferred query and the result is still streaming in.\n  - `complete`: `data` is a fully satisfied query result fulfilled either from the cache or network.\n\n  Example:\n\n  ```ts\n  const { data, dataState } = useQuery<TData>(query);\n\n  if (dataState === \"empty\") {\n    expectTypeOf(data).toEqualTypeOf<undefined>();\n  }\n\n  if (dataState === \"partial\") {\n    expectTypeOf(data).toEqualTypeOf<DeepPartial<TData>>();\n  }\n\n  if (dataState === \"streaming\") {\n    expectTypeOf(data).toEqualTypeOf<TData>();\n  }\n\n  if (dataState === \"complete\") {\n    expectTypeOf(data).toEqualTypeOf<TData>();\n  }\n  ```\n\n</details>\n<details>\n\n<summary>\n\n### Patch Changes\n\n</summary>\n\n- [#12574](https://github.com/apollographql/apollo-client/pull/12574) [`0098ec9`](https://github.com/apollographql/apollo-client/commit/0098ec9f860e4e08a2070823f723dce401ae588a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `gql` from the `@apollo/client/react` entrypoint.\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - When updating `skip` from `false` to `true` in `useQuery`, retain `data` if it is available rather than setting it to `undefined`.\n\n- [#12822](https://github.com/apollographql/apollo-client/pull/12822) [`103664d`](https://github.com/apollographql/apollo-client/commit/103664dc93c0a7097eaec1a5144e769eb4fb7a31) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `HttpLink.ContextOptions` and `BatchHttpLink.ContextOptions` include `ClientAwarenessLink.ContextOptions`.\n\n- [#12291](https://github.com/apollographql/apollo-client/pull/12291) [`ae5d06a`](https://github.com/apollographql/apollo-client/commit/ae5d06ac45ca6584d3c79aa417dae22f37a7d3b6) Thanks [@phryneas](https://github.com/phryneas)! - Remove deprecated `resetApolloContext` export\n\n- [#12728](https://github.com/apollographql/apollo-client/pull/12728) [`07a0c8c`](https://github.com/apollographql/apollo-client/commit/07a0c8c52774793b254ecc91e5d4632bfdf48093) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export the `IgnoreModifier` type from `@apollo/client/cache`.\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache.watchFragment` now returns an `Unmasked<TData>` result since `cache.watchFragment` does not mask fragment spreads.\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Change the `unsafePreviousData` argument on `UpdateQueryMapFn` and `SubscribeToMoreQueryFn` to a `DeepPartial` since the result may contain partial data.\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The returned `networkStatus` in `useLazyQuery` is now set to `setVariables` when calling the `useLazyQuery` `execute` function for the first time with variables.\n\n- [#12748](https://github.com/apollographql/apollo-client/pull/12748) [`e1ca85e`](https://github.com/apollographql/apollo-client/commit/e1ca85eab181d8e16d945e849dfb13352902f197) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where the new `operationType` property wasn't passed into `operation`.\n\n- [#12709](https://github.com/apollographql/apollo-client/pull/12709) [`9d42e2a`](https://github.com/apollographql/apollo-client/commit/9d42e2a08d3ddfdfdfc7ac65bd66985da5642e7d) Thanks [@phryneas](https://github.com/phryneas)! - Remove these incremental-format-specific types:\n\n  - `ExecutionPatchIncrementalResult`\n  - `ExecutionPatchInitialResult`\n  - `ExecutionPatchResult`\n  - `IncrementalPayload`\n  - `Path`\n\n- [#12618](https://github.com/apollographql/apollo-client/pull/12618) [`e4a3ecf`](https://github.com/apollographql/apollo-client/commit/e4a3ecfe50bc5b462067574a0ffb1951549fb60f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove code that strips `@client` fields in `HttpLink` and `BatchHttpLink`. This was unused code since core handles removing `@client` fields and should have no observable change.\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `ObservableQuery` stops polling if switching to a `standby` `fetchPolicy`. When switching back to a non-`standby` `fetchPolicy`, polling will resume.\n\n- [#12677](https://github.com/apollographql/apollo-client/pull/12677) [`94e58ed`](https://github.com/apollographql/apollo-client/commit/94e58ed75fc547ff037d9efeeba929fd61b20c4c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Downgrade minimum supported `rxjs` peer dependency version to 7.3.0.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `variables` option used with various APIs are now enforced more consistently across the client when `TVariables` contains required variables. If required `variables` are not provided, TypeScript will now complain that it requires a `variables` option.\n\n  This change affects the following APIs:\n\n  - `client.query`\n  - `client.mutate`\n  - `client.subscribe`\n  - `client.watchQuery`\n  - `useBackgroundQuery`\n  - `useQuery`\n  - `useSubscription`\n  - `useSuspenseQuery`\n\n- [#12451](https://github.com/apollographql/apollo-client/pull/12451) [`77e1b13`](https://github.com/apollographql/apollo-client/commit/77e1b133bdba32c67b5a840090dbacb16282dee9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default `TVariables` generic type to `OperationVariables` instead of `any` throughout the client in areas that did not yet have the default as such.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `variables` returned from `useLazyQuery`. When `called` is `false`, `variables` is now `Partial<TVariables>` instead of `TVariables`.\n\n- [#12402](https://github.com/apollographql/apollo-client/pull/12402) [`903c3ef`](https://github.com/apollographql/apollo-client/commit/903c3ef9f77280492c298b4d8e5f96f110e3cda1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Use an an empty object (`{}`) rather than an object with `null` prototype (`Object.create(null)`) in all areas that instantiate objects.\n\n- [#12734](https://github.com/apollographql/apollo-client/pull/12734) [`037979d`](https://github.com/apollographql/apollo-client/commit/037979dc47ffb7125429707471d901a08db49283) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't warn about a missing resolver if a `@client` does not have a configured resolver. It is possible the cache contains a `read` function for the field and the warning added confusion.\n\n  Note that `read` functions without a defined resolver will receive the `existing` argument as `null` instead of `undefined` even when data hasn't been written to the cache. This is because `LocalState` sets a default value of `null` when a resolver is not defined to ensure that the field contains a value in case a `read` function is not defined rather than omitting the field entirely.\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure a loading state is emitted when calling the `execute` function after changing clients in `useLazyQuery`.\n\n- [#12370](https://github.com/apollographql/apollo-client/pull/12370) [`0517163`](https://github.com/apollographql/apollo-client/commit/05171634404a44231329bf63eee960db52d08b25) Thanks [@phryneas](https://github.com/phryneas)! - `InMemoryCache`: Fields with an empty argument object are now saved the same way as fields without arguments.\n\n  Previously, it was possible that the reponses for these two queries would be stored differently in the cache:\n\n  ```gql\n  query PlainAccess {\n    myField\n  }\n  ```\n\n  would be stored as `myField`\n  and\n\n  ```gql\n  query AccessWithoutOptionalArgument($optional: String) {\n    myField(optional: $optional)\n  }\n  ```\n\n  would be stored as `myField({\"optional\":\"Foo\"})` if called with `{optional: \"Foo\"}` and as `myField({})` if called without the optional argument.\n\n  The cases `myField` and `myField({})` are equivalent from the perspective of a GraphQL server, and so in the future both of these will be stored as `myField` in the cache.\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - \\* dropped the deprecated `DEV` export from `@apollo/client/utilities` and `@apollo/client/utilities/globals`\n\n  - moved the `__DEV__` export from `@apollo/client/utilities/globals` to `@apollo/client/utilities/environment`\n  - moved the `invariant`, `newInvariantError` and `InvariantError` exports from `@apollo/client/utilities/globals` to `@apollo/client/utilities/invariant`\n\n- [#12709](https://github.com/apollographql/apollo-client/pull/12709) [`9d42e2a`](https://github.com/apollographql/apollo-client/commit/9d42e2a08d3ddfdfdfc7ac65bd66985da5642e7d) Thanks [@phryneas](https://github.com/phryneas)! - Slightly rework multipart response parsing.\n\n  This removes last incremental-protocol-specific details from `HttpLink` and `BatchHttpLink`.\n\n- [#12824](https://github.com/apollographql/apollo-client/pull/12824) [`0506f12`](https://github.com/apollographql/apollo-client/commit/0506f12936d3fe7c840e5d56a5efa20bbce1525e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `RetryLink` now emits a `next` event instead of an `error` event when encountering a protocol errors for multipart subscriptions when the operation is not retried. This ensures the observable notification remains the same as when `RetryLink` is not used.\n\n- [#12487](https://github.com/apollographql/apollo-client/pull/12487) [`b695e5e`](https://github.com/apollographql/apollo-client/commit/b695e5e10ab0eb47948e914b610f67c40267349e) Thanks [@phryneas](https://github.com/phryneas)! - `useQuery` with `ssr: false` - previously, `skip` had a higher priortity than `ssr: false` while `ssr: false` had a higher priority than `fetchPolicy: \"standby\"` (which is roughly equivalent to `skip`).\n\n  This priority has been adjusted so now both `skip` and `fetchPolicy: \"standby\"` have a higher priority than `ssr: false` and will return `loading: false`, while `ssr: false` will only come after those and will return `loading: true` if those are not set.\n\n- [#12725](https://github.com/apollographql/apollo-client/pull/12725) [`89ac725`](https://github.com/apollographql/apollo-client/commit/89ac7256a34b3b04fe2cf83937b5494b375ce36d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `getMainDefinition` from `@apollo/client/utilities`.\n\n- [#12716](https://github.com/apollographql/apollo-client/pull/12716) [`ad88976`](https://github.com/apollographql/apollo-client/commit/ad889766882b4817e50e8e819044bc5ed772173b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only to release latest as `rc`.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where passing `onError` to `useMutation` would resolve the promise returned by the `mutate` function instead of rejecting when using an `errorPolicy` of `none`.\n\n- [#12542](https://github.com/apollographql/apollo-client/pull/12542) [`afb4fce`](https://github.com/apollographql/apollo-client/commit/afb4fce08859b2c6eebf288230a7c35b7acf2da6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `useLazyQuery` does not return a `partial` property which is not specified by the result type.\n\n- [#12432](https://github.com/apollographql/apollo-client/pull/12432) [`c7c2f61`](https://github.com/apollographql/apollo-client/commit/c7c2f6122c874eed16d5621be26992f86d9756eb) Thanks [@phryneas](https://github.com/phryneas)! - ObservableQuery: implement the `rxjs` `InteropObservable` interface to ensure `from(observableQuery)` stays possible\n\n- [#12775](https://github.com/apollographql/apollo-client/pull/12775) [`454ec78`](https://github.com/apollographql/apollo-client/commit/454ec78b751853da07243174a6f9bdc4535e7e8f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't export `gql` from `@apollo/client/react` entrypoint. Import from `@apollo/client` instead.\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - `@apollo/client`, `@apollo/client/core` and `@apollo/client/cache` no longer export an empty `Cache` runtime object. This is meant to be a type-only namespace.\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `parser` cache. The functionality has been replaced in a way that doesn't need caching.\n\n- [#12465](https://github.com/apollographql/apollo-client/pull/12465) [`a132163`](https://github.com/apollographql/apollo-client/commit/a1321637cafb4023d6df416e9467294114d8346b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Rename all React hook result types and options. These types have all moved under a namespace that matches the hook name. For example, `useQuery` exports `useQuery.Options` and `useQuery.Result` types. As such, the old hook types have been deprecated and will be removed in v5.\n\n- [#12739](https://github.com/apollographql/apollo-client/pull/12739) [`b184754`](https://github.com/apollographql/apollo-client/commit/b184754d08810df9a7838615990e90a960966037) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `error` argument on the `onError` option for `subscribeToMore` to `ErrorLike`.\n\n- [#12572](https://github.com/apollographql/apollo-client/pull/12572) [`3dc50e6`](https://github.com/apollographql/apollo-client/commit/3dc50e6476dcedf82ed3856bf9f4571a32a760a6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Adjust `useMutation` types to better handle required variables. When required variables are missing, TypeScript will now complain if they are not provided either to the hook or the returned `mutate` function. Providing required variables to `useMutation` will make them optional in the returned `mutate` function.\n\n- [#12819](https://github.com/apollographql/apollo-client/pull/12819) [`7ff548d`](https://github.com/apollographql/apollo-client/commit/7ff548dab0f38bfe315fce6cc51105c93d112271) Thanks [@jerelmiller](https://github.com/jerelmiller)! - update type of `HttpLink.Options.fetchOptions` to `RequestInit`\n\n- [#12761](https://github.com/apollographql/apollo-client/pull/12761) [`db6f7c3`](https://github.com/apollographql/apollo-client/commit/db6f7c3823aaf58ee403ef45f0e817241b1c56a2) Thanks [@phryneas](https://github.com/phryneas)! - Deprecate second argument to `readFragment` and `readQuery` - `optimistic` should be passed as part of the object in the first argument instead.\n\n- [#12820](https://github.com/apollographql/apollo-client/pull/12820) [`fba3d9e`](https://github.com/apollographql/apollo-client/commit/fba3d9ec96cce9f1a89908e4f33361e27d1f52b4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `fetchOptions` option provided to `HttpLink` and `BatchHttpLink` is now `RequestInit` instead of `any`. The `credentials` option is now a `RequestCredentials` type instead of a `string`.\n\n- [#12650](https://github.com/apollographql/apollo-client/pull/12650) [`2a32ac6`](https://github.com/apollographql/apollo-client/commit/2a32ac6d38de2be0be6891a969ee4f5e3bbca629) Thanks [@phryneas](https://github.com/phryneas)! - Fix a situation where a passed-in `AbortSignal` would override internal unsubscription cancellation behaviour.\n\n- [#12562](https://github.com/apollographql/apollo-client/pull/12562) [`90bf0e6`](https://github.com/apollographql/apollo-client/commit/90bf0e61516a382182f212ac8ab891099e2eb009) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.query` no longer supports `notifyOnNetworkStatusChange` in options. An error will be thrown if this option is set. The effects of this option were not observable by `client.query` since `client.query` emits a single result.\n\n- [#12557](https://github.com/apollographql/apollo-client/pull/12557) [`51d26ae`](https://github.com/apollographql/apollo-client/commit/51d26ae631c6631a189c98ea9357b18e77a9a876) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update format of the error message for `CombinedGraphQLErrors` and `CombinedProtocolErrors` to be more like v3.x.\n\n  ```diff\n  console.log(error.message);\n  - `The GraphQL server returned with errors:\n  - - Email not found\n  - - Username already in use`\n  + `Email not found\n  + Username already in use`\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The individual `empty`, `concat`, `from` and `split` functions exported from `@apollo/client/link` are now deprecated in favor of using the static functions instead.\n\n  ```diff\n  import {\n    ApolloLink,\n  - concat,\n  - empty,\n  - from,\n  - split,\n  } from \"@apollo/client/link\";\n\n  - concat(first, second);\n  + ApolloLink.concat(first, second);\n\n  - empty();\n  + ApolloLink.empty();\n\n  - from([first, second]);\n  + ApolloLink.from([first, second]);\n\n  - split(\n  + ApolloLink.split(\n    (operation) => /* */,\n    first,\n    second\n  );\n  ```\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The incremental delivery (`@defer` support) implementation is now pluggable.\n\n  `ApolloClient` now per default ships without an incremental format implementation\n  and allows you to swap in the format that you want to use.\n\n  Usage looks like this:\n\n  ```ts\n  import {\n    // this is the default\n    NotImplementedHandler,\n    // this implements the `@defer` transport format that ships with Apollo Router\n    Defer20220824Handler,\n    // this implements the `@defer` transport format that ships with GraphQL 17.0.0-alpha.2\n    GraphQL17Alpha2Handler,\n  } from \"@apollo/client/incremental\";\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      /*...*/\n    }),\n    link: new HttpLink({\n      /*...*/\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n  ```\n\n  We will add handlers for other response formats that can be swapped this way\n  during the lifetime of Apollo Client 4.0.\n\n- [#12454](https://github.com/apollographql/apollo-client/pull/12454) [`925548a`](https://github.com/apollographql/apollo-client/commit/925548a9baadb19b7bb78ee84c6f9e64b55c39e9) Thanks [@phryneas](https://github.com/phryneas)! - Fix up the 4.0 CommonJS build\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't emit a partial cache result from `cache-only` queries when `returnPartialData` is `false`.\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - The `error` property is no longer present when `skip` is `true` in `useQuery`.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.variables` has been updated to return `TVariables` rather than `TVariables | undefined`. This is more consistent with the runtime value where an empty object (`{}`) will be returned when the `variables` option is not provided.\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the type of the argument for the `sha256` function for `PersistedQueryLink` from `...any[]` to `string`.\n\n- [#12729](https://github.com/apollographql/apollo-client/pull/12729) [`699c830`](https://github.com/apollographql/apollo-client/commit/699c8305639ff69bab36fd2214defbe1ac6f0b18) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `useQuery` rerenders when `notifyOnNetworkStatusChange` is `false` and a `refetch` that changes variables returns a result deeply equal to previous variables.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where additional response properties were returned on the result returned from `client.mutate`, such as `@defer` payload fields. These properties are now stripped out to correspond to the TypeScript type.\n\n- [#12821](https://github.com/apollographql/apollo-client/pull/12821) [`223a409`](https://github.com/apollographql/apollo-client/commit/223a4094f401bbe7fd3e4c249fa405843b63ba2e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a deprecation warning to `WebSocketLink`.\n\n- [#12782](https://github.com/apollographql/apollo-client/pull/12782) [`742b3a0`](https://github.com/apollographql/apollo-client/commit/742b3a0ed65d28818974e56225c86ab7e350e677) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move `ApolloClient`, `ObservableQuery`, and `ApolloCache.watchFragment` method options and result types into namespaces. The old types are now exported as deprecated.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Fixed a bug in `PersistedQueryLink` where the `persistedQuery` extension would still be sent after a `PersistedQueryNotSupported` if `includeExtensions` was enabled on `HttpLink`.\n\n</details>\n\n## 4.0.0-rc.13\n\n### Major Changes\n\n- [#12850](https://github.com/apollographql/apollo-client/pull/12850) [`268cd80`](https://github.com/apollographql/apollo-client/commit/268cd800a2d73305c0df8dd38b6bd1cee98f0fec) Thanks [@phryneas](https://github.com/phryneas)! - Introduce a versioning policy.\n\n## 4.0.0-rc.12\n\n### Minor Changes\n\n- [#12838](https://github.com/apollographql/apollo-client/pull/12838) [`b005561`](https://github.com/apollographql/apollo-client/commit/b0055613c1f4837e994d2d0756348d553e2f302f) Thanks [@phryneas](https://github.com/phryneas)! - Add an entrypoint at `@apollo/client/v4-migration` that includes removed values and types. Each export includes doc blocks on how to migrate away from the removed type.\n\n## 4.0.0-rc.11\n\n### Major Changes\n\n- [#12840](https://github.com/apollographql/apollo-client/pull/12840) [`83e132a`](https://github.com/apollographql/apollo-client/commit/83e132ab1bacb3293da61dd4519379e36a1fb090) Thanks [@phryneas](https://github.com/phryneas)! - If you use an incremental delivery handler, you now have to explicitly opt into adding the chunk types to the `ApolloLink.Result` type.\n\n  ```ts title=\"apollo-client.d.ts\n  import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n  }\n  ```\n\n- [#12841](https://github.com/apollographql/apollo-client/pull/12841) [`65b503f`](https://github.com/apollographql/apollo-client/commit/65b503fe4bfcf942e8f66f36f622f5f6448d6731) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `DataMasking` interface exported from `@apollo/client` and `@apollo/client/masking`.\n\n## 4.0.0-rc.10\n\n### Major Changes\n\n- [#12837](https://github.com/apollographql/apollo-client/pull/12837) [`7c49fdc`](https://github.com/apollographql/apollo-client/commit/7c49fdce2f40571d92c83602bbb1b5bd891f626b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - You must now opt in to use GraphQL Codegen data masking types when using Apollo Client's data masking feature. By default, Apollo Client now uses an identity type to apply to masked/unmasked types.\n\n  If you're using GraphQL Codegen to generate masked types, opt into the GraphQL Codegen masked types using declaration merging on the `TypeOverides` interface.\n\n  ```ts title=\"apollo-client.d.ts\n  import { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides\n      extends GraphQLCodegenDataMasking.TypeOverrides {}\n  }\n  ```\n\n- [#12837](https://github.com/apollographql/apollo-client/pull/12837) [`7c49fdc`](https://github.com/apollographql/apollo-client/commit/7c49fdce2f40571d92c83602bbb1b5bd891f626b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The types mode for data masking has been removed. Adding a types mode to the `DataMasking` interface has no effect. Remove the `mode` key in the module where you declare the `DataMasking` type for the `@apollo/client` module.\n\n  As a result, the `Masked` and `MaskedDocumentNode` types have also been removed since these have no effect when types are preserved.\n\n## 4.0.0-rc.9\n\n### Minor Changes\n\n- [#12828](https://github.com/apollographql/apollo-client/pull/12828) [`81b03d8`](https://github.com/apollographql/apollo-client/commit/81b03d86ad7e7384124708477829bcbf63d4fa2c) Thanks [@phryneas](https://github.com/phryneas)! - `invariant.error` will now also log in production builds, not only dev builds\n\n### Patch Changes\n\n- [#12822](https://github.com/apollographql/apollo-client/pull/12822) [`103664d`](https://github.com/apollographql/apollo-client/commit/103664dc93c0a7097eaec1a5144e769eb4fb7a31) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `HttpLink.ContextOptions` and `BatchHttpLink.ContextOptions` include `ClientAwarenessLink.ContextOptions`.\n\n- [#12650](https://github.com/apollographql/apollo-client/pull/12650) [`2a32ac6`](https://github.com/apollographql/apollo-client/commit/2a32ac6d38de2be0be6891a969ee4f5e3bbca629) Thanks [@phryneas](https://github.com/phryneas)! - Fix a situation where a passed-in `AbortSignal` would override internal unsubscription cancellation behaviour.\n\n## 4.0.0-rc.8\n\n### Major Changes\n\n- [#12825](https://github.com/apollographql/apollo-client/pull/12825) [`292b949`](https://github.com/apollographql/apollo-client/commit/292b949e9e1d10a715e0fd403737361f91432fbf) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `serializeFetchParameter` helper is no longer exported and `JSON.stringify` is used directly. As such, the `ClientParseError` type has also been removed in favor of throwing any JSON serialize errors directly.\n\n- [#12824](https://github.com/apollographql/apollo-client/pull/12824) [`0506f12`](https://github.com/apollographql/apollo-client/commit/0506f12936d3fe7c840e5d56a5efa20bbce1525e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure the `error` argument for the `delay` and `attempts` functions on `RetryLink` are an `ErrorLike`.\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move all 1st party link types into a namespace.\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `OperationBatcher` class is no longer exported from `@apollo/client/link/batch`. It is an implementation detail of `BatchLink` and should not be relied on directly.\n\n### Patch Changes\n\n- [#12824](https://github.com/apollographql/apollo-client/pull/12824) [`0506f12`](https://github.com/apollographql/apollo-client/commit/0506f12936d3fe7c840e5d56a5efa20bbce1525e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `RetryLink` now emits a `next` event instead of an `error` event when encountering a protocol errors for multipart subscriptions when the operation is not retried. This ensures the observable notification remains the same as when `RetryLink` is not used.\n\n- [#12819](https://github.com/apollographql/apollo-client/pull/12819) [`7ff548d`](https://github.com/apollographql/apollo-client/commit/7ff548dab0f38bfe315fce6cc51105c93d112271) Thanks [@jerelmiller](https://github.com/jerelmiller)! - update type of `HttpLink.Options.fetchOptions` to `RequestInit`\n\n- [#12820](https://github.com/apollographql/apollo-client/pull/12820) [`fba3d9e`](https://github.com/apollographql/apollo-client/commit/fba3d9ec96cce9f1a89908e4f33361e27d1f52b4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `fetchOptions` option provided to `HttpLink` and `BatchHttpLink` is now `RequestInit` instead of `any`. The `credentials` option is now a `RequestCredentials` type instead of a `string`.\n\n- [#12823](https://github.com/apollographql/apollo-client/pull/12823) [`19e315e`](https://github.com/apollographql/apollo-client/commit/19e315e316ae458913f4d11961b0a2a365df0a19) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the type of the argument for the `sha256` function for `PersistedQueryLink` from `...any[]` to `string`.\n\n- [#12821](https://github.com/apollographql/apollo-client/pull/12821) [`223a409`](https://github.com/apollographql/apollo-client/commit/223a4094f401bbe7fd3e4c249fa405843b63ba2e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a deprecation warning to `WebSocketLink`.\n\n## 4.0.0-rc.7\n\n### Major Changes\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.getContext` now returns a `Readonly<OperationContext>` type.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `ApolloLink.Request` (i.e. `GraphQLRequest`) passed to `ApolloLink.execute` no longer accepts `operationName` and `operationType` options. These properties are derived from the `query` and set on the returned `ApolloLink.Operation` type.\n\n- [#12808](https://github.com/apollographql/apollo-client/pull/12808) [`8e31a23`](https://github.com/apollographql/apollo-client/commit/8e31a2303b18f6fc4d8ec1cf4c01bf26b90f3f0b) Thanks [@phryneas](https://github.com/phryneas)! - HTTP Multipart handling will now throw an error if the connection closed before the final boundary has been received.\n  Data after the final boundary will be ignored.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.operationType` is now a non-null `OperationTypeNode`. It is now safe to compare this value without having to check for `undefined`.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `operation.operationName` is now set as `string | undefined` where `undefined` represents an anonymous query. Previously `operationName` would return an empty string as the `operationName` for anonymous queries.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `concat`, `from`, and `split` functions on `ApollLink` no longer support a plain request handler function. Please wrap the request handler with `new ApolloLink`.\n\n  ```diff\n  const link = new ApolloLink(/* ... */);\n\n  link.concat(\n  - (operation, forward) => forward(operation),\n  + new ApolloLink((operation, forward) => forward(operation)),\n  );\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `transformOperation` and `validateOperation` have been removed and are no longer exported from `@apollo/client/link/utils`. These utilities have been merged into the implementation of `createOperation`. As a result, `createOperation` now returns a well-formed `Operation` object. Previously `createOperation` relied on an external call to `transformOperation` to provide a well-formed `Operation` type. If you use `createOperation` directly, remove the calls to `transformOperation` and `validateOperation` and pass the request directly.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The request handler provided to `ApolloLink` must now return an `Observable`. `null` is no longer supported as a valid return value. If you rely on `null` so that `ApolloLink` provides an empty observable, use the `EMPTY` observable from RxJS instead:\n\n  ```diff\n  import { ApolloLink } from \"@apollo/client\";\n  + import { EMPTY } from \"rxjs\";\n\n  const link = new ApolloLink((operation, forward) => {\n  - return null;\n  + return EMPTY;\n  });\n  ```\n\n  If you have a custom link that overrides the `request` method, remove `null` from the return signature:\n\n  ```diff\n  class MyCustomLink extends ApolloLink {\n    request(\n      operation: ApolloLink.Operation,\n      forward: ApolloLink.ForwardFunction,\n  - ): Observable<ApolloLink.Result> | null {\n  + ): Observable<ApolloLink.Result> {\n      // implementation\n    }\n  }\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `createOperation` no longer accepts `context` as the first argument. Instead make sure `context` is set as the `context` property on the request passed to `createOperation`.\n\n  ```diff\n  createOperation(\n  - startingContext,\n  - { query },\n  + { query, context: startingContext },\n    { client }\n  );\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `TVariables` generic argument on the `GraphQLRequest` type.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The context object returned from `operation.getContext()` is now frozen to prevent mutable changes to the object which could result in subtle bugs. This applies to the `previousContext` object passed to the `operation.setContext()` callback as well.\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `forward` function passed to the request handler is now always provided to `request` and no longer optional. If you create custom links by subclassing `ApolloLink`, the `forward` function no longer needs to be optional:\n\n  ```ts\n  class CustomLink extends ApolloLink {\n    request(\n      operation: ApolloLink.Operation,\n      // This no longer needs to be typed as optional\n      forward: ApolloLink.ForwardFunction\n    ) {\n      // ...\n    }\n  }\n  ```\n\n  As a result of this change, `ApolloLink` no longer detects terminating links by checking function arity on the request handler. This means using methods such as `concat` on a terminating link no longer emit a warning. On the flip side, if the terminating link calls the `forward` function, a warning is emitted and an observable that immediately completes is returned which will result in an error from Apollo Client.\n\n### Minor Changes\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ApolloLink`'s `concat` method now accepts multiple links to concatenate together.\n\n  ```ts\n  const first = new ApolloLink();\n\n  const link = first.concat(second, third, fouth);\n  ```\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Many of the types exported from `@apollo/client/link` now live on the `ApolloLink` namespace. The old types are now deprecated in favor of the namespaced types.\n\n  - `FetchResult` -> `ApolloLink.Result`\n  - `GraphQLRequest` -> `ApolloLink.Request`\n  - `NextLink` -> `ApolloLink.ForwardFunction`\n  - `Operation` -> `ApolloLink.Operation`\n  - `RequestHandler` -> `ApolloLink.RequestHandler`\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The static `ApolloLink.concat` method is now deprecated in favor of `ApolloLink.from`. `ApolloLink.concat` is now an alias for `ApolloLink.from` so prefer `ApolloLink.from` instead.\n\n### Patch Changes\n\n- [#12809](https://github.com/apollographql/apollo-client/pull/12809) [`e2a0be8`](https://github.com/apollographql/apollo-client/commit/e2a0be8c3f8b242706f90e0dcc022628992a8ae8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The individual `empty`, `concat`, `from` and `split` functions exported from `@apollo/client/link` are now deprecated in favor of using the static functions instead.\n\n  ```diff\n  import {\n    ApolloLink,\n  - concat,\n  - empty,\n  - from,\n  - split,\n  } from \"@apollo/client/link\";\n\n  - concat(first, second);\n  + ApolloLink.concat(first, second);\n\n  - empty();\n  + ApolloLink.empty();\n\n  - from([first, second]);\n  + ApolloLink.from([first, second]);\n\n  - split(\n  + ApolloLink.split(\n    (operation) => /* */,\n    first,\n    second\n  );\n  ```\n\n## 4.0.0-rc.6\n\n### Major Changes\n\n- [#12787](https://github.com/apollographql/apollo-client/pull/12787) [`8ce31fa`](https://github.com/apollographql/apollo-client/commit/8ce31fae54b1ae76c557f361cc946858cb2ff66b) Thanks [@phryneas](https://github.com/phryneas)! - Remove `DataProxy` namespace and interface.\n\n- [#12788](https://github.com/apollographql/apollo-client/pull/12788) [`4179446`](https://github.com/apollographql/apollo-client/commit/417944677d2e79606b0f6cabd8d5d8b2063c876b) Thanks [@phryneas](https://github.com/phryneas)! - `TVariables` now always `extends OperationVariables` in all interfaces.\n\n- [#12802](https://github.com/apollographql/apollo-client/pull/12802) [`e2b51b3`](https://github.com/apollographql/apollo-client/commit/e2b51b30acbd360253100f9d2a91fe7e0c57be4c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Disallow the `mutation` option for the `mutate` function returned from `useMutation`.\n\n- [#12787](https://github.com/apollographql/apollo-client/pull/12787) [`8ce31fa`](https://github.com/apollographql/apollo-client/commit/8ce31fae54b1ae76c557f361cc946858cb2ff66b) Thanks [@phryneas](https://github.com/phryneas)! - Generic arguments for `Cache.ReadOptions` were flipped from `TVariables, TData` to `TData, TVariables`.\n\n- [#12793](https://github.com/apollographql/apollo-client/pull/12793) [`24e98a1`](https://github.com/apollographql/apollo-client/commit/24e98a16648d4c21f37ba51a678a8849f88174ea) Thanks [@phryneas](https://github.com/phryneas)! - `ApolloConsumer` has been removed - please use `useApolloClient` instead.\n\n### Patch Changes\n\n- [#12782](https://github.com/apollographql/apollo-client/pull/12782) [`742b3a0`](https://github.com/apollographql/apollo-client/commit/742b3a0ed65d28818974e56225c86ab7e350e677) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move `ApolloClient`, `ObservableQuery`, and `ApolloCache.watchFragment` method options and result types into namespaces. The old types are now exported as deprecated.\n\n## 4.0.0-rc.5\n\n### Major Changes\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Report masked fragments as complete even when a nested masked fragment contains partial data.\n\n- [#12774](https://github.com/apollographql/apollo-client/pull/12774) [`511b4f3`](https://github.com/apollographql/apollo-client/commit/511b4f3e792a75aa5aa27b335e8119dbc2a9c254) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apply document transforms before reading data from the cache for `client.readQuery`, `client.readFragment`, `client.watchFragment`, `useFragment`, and `useSuspenseFragment`.\n\n  NOTE: This change does not affect the equivalent `cache.*` APIs. To read data from the cache without first running document transforms, run `cache.readQuery`, `cache.readFragment`, etc.\n\n### Minor Changes\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `dataState` to the value emitted from `client.watchFragment`.\n\n### Patch Changes\n\n- [#12776](https://github.com/apollographql/apollo-client/pull/12776) [`bce9b74`](https://github.com/apollographql/apollo-client/commit/bce9b7448a226b109cbe8f14911503fb09f37825) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache.watchFragment` now returns an `Unmasked<TData>` result since `cache.watchFragment` does not mask fragment spreads.\n\n- [#12370](https://github.com/apollographql/apollo-client/pull/12370) [`0517163`](https://github.com/apollographql/apollo-client/commit/05171634404a44231329bf63eee960db52d08b25) Thanks [@phryneas](https://github.com/phryneas)! - `InMemoryCache`: Fields with an empty argument object are now saved the same way as fields without arguments.\n\n  Previously, it was possible that the reponses for these two queries would be stored differently in the cache:\n\n  ```gql\n  query PlainAccess {\n    myField\n  }\n  ```\n\n  would be stored as `myField`\n  and\n\n  ```gql\n  query AccessWithoutOptionalArgument($optional: String) {\n    myField(optional: $optional)\n  }\n  ```\n\n  would be stored as `myField({\"optional\":\"Foo\"})` if called with `{optional: \"Foo\"}` and as `myField({})` if called without the optional argument.\n\n  The cases `myField` and `myField({})` are equivalent from the perspective of a GraphQL server, and so in the future both of these will be stored as `myField` in the cache.\n\n- [#12775](https://github.com/apollographql/apollo-client/pull/12775) [`454ec78`](https://github.com/apollographql/apollo-client/commit/454ec78b751853da07243174a6f9bdc4535e7e8f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't export `gql` from `@apollo/client/react` entrypoint. Import from `@apollo/client` instead.\n\n- [#12761](https://github.com/apollographql/apollo-client/pull/12761) [`db6f7c3`](https://github.com/apollographql/apollo-client/commit/db6f7c3823aaf58ee403ef45f0e817241b1c56a2) Thanks [@phryneas](https://github.com/phryneas)! - Deprecate second argument to `readFragment` and `readQuery` - `optimistic` should be passed as part of the object in the first argument instead.\n\n## 4.0.0-rc.4\n\n### Minor Changes\n\n- [#12757](https://github.com/apollographql/apollo-client/pull/12757) [`5fd2e7c`](https://github.com/apollographql/apollo-client/commit/5fd2e7c15eecc6469ecf5f4fb116633b056ad103) Thanks [@phryneas](https://github.com/phryneas)! - Add `dataState` and overridable `DataValue` types to `useFragment`\n\n- [#12757](https://github.com/apollographql/apollo-client/pull/12757) [`5fd2e7c`](https://github.com/apollographql/apollo-client/commit/5fd2e7c15eecc6469ecf5f4fb116633b056ad103) Thanks [@phryneas](https://github.com/phryneas)! - Add overridable `DataValue` types to `useSuspenseFragment`\n\n## 4.0.0-rc.3\n\n### Major Changes\n\n- [#12731](https://github.com/apollographql/apollo-client/pull/12731) [`0198870`](https://github.com/apollographql/apollo-client/commit/0198870107eab7ad0bc69a549cb069fa41b3280f) Thanks [@phryneas](https://github.com/phryneas)! - Ship React Compiler compiled React hooks in `@apollo/client/react/compiled`.\n\n  We now ship a React-Compiler compiled version of the React hooks in\n  `@apollo/client/react/compiled`.\n\n  This entry point contains everything that `@apollo/client/react` does,\n  so you can use it as a drop-in replacement in your whole application\n  if you choose to use the compiled hooks.\n\n### Minor Changes\n\n- [#12753](https://github.com/apollographql/apollo-client/pull/12753) [`b85818d`](https://github.com/apollographql/apollo-client/commit/b85818dcc66d3ed8b1c3a7e5e37b2875d6bf9d03) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Renamed `client.reFetchObservableQueries` to `client.refetchObservableQueries`.\n  `client.reFetchObservableQueries` is still available as an alias, but is now\n  deprecated and will be removed in a future major version.\n\n## 4.0.0-rc.2\n\n### Major Changes\n\n- [#12742](https://github.com/apollographql/apollo-client/pull/12742) [`575bf3e`](https://github.com/apollographql/apollo-client/commit/575bf3ed5885efb09c1eec497af4d2690c6b87d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The new `SetContextLink` flips the `prevContext` and `operation` arguments in the callback. The `setContext` function has remained unchanged.\n\n  ```diff\n  - new SetContextLink((operation, prevContext) => {\n  + new SetContextLink((prevContext, operation) => {\n    // ...\n  })\n  ```\n\n- [#12742](https://github.com/apollographql/apollo-client/pull/12742) [`575bf3e`](https://github.com/apollographql/apollo-client/commit/575bf3ed5885efb09c1eec497af4d2690c6b87d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `operation` argument to the callback passed to `SetContextLink` is now of type `SetContextLink.SetContextOperation` which is an `Operation` without the `getContext` or `setContext` functions. Previously the type of `operation` was `GraphQLRequest` which had access to a `context` property. The `context` property was always `undefined` and could result in bugs when using it instead of the `prevContext` argument.\n\n  This change means the `operation` argument now contains an accessible `client` property.\n\n### Minor Changes\n\n- [#12740](https://github.com/apollographql/apollo-client/pull/12740) [`1c6e03c`](https://github.com/apollographql/apollo-client/commit/1c6e03c9c74a9fad2a1c2e1c3ae61a9560038238) Thanks [@phryneas](https://github.com/phryneas)! - Overridable types for `dataState: \"complete\"`, `dataState: \"streaming\"` and\n  `dataState: \"partial\"` responses.\n\n  This adds the `DataValue` namespace exported from Apollo Client with the three\n  types `DataValue.Complete`, `DataValue.Streaming` and `DataValue.Partial`.\n\n  These types will be used to mark `TData` in the respective states.\n\n  - `Complete` defaults to `TData`\n  - `Streaming` defaults to `TData`\n  - `Partial` defaults to `DeepPartial<TData>`\n\n  All three can be overwritten, e.g. to be `DeepReadonly` using higher kinded types\n  by following this pattern:\n\n  ```ts\n  import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n  import { DeepReadonly } from \"some-type-helper-library\";\n\n  interface CompleteOverride extends HKT {\n    return: DeepReadonly<this[\"arg1\"]>;\n  }\n\n  interface StreamingOverride extends HKT {\n    return: DeepReadonly<this[\"arg1\"]>;\n  }\n\n  interface PartialOverride extends HKT {\n    return: DeepReadonly<DeepPartial<this[\"arg1\"]>>;\n  }\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides {\n      Complete: CompleteOverride;\n      Streaming: StreamingOverride;\n      Partial: PartialOverride;\n    }\n  }\n  ```\n\n### Patch Changes\n\n- [#12748](https://github.com/apollographql/apollo-client/pull/12748) [`e1ca85e`](https://github.com/apollographql/apollo-client/commit/e1ca85eab181d8e16d945e849dfb13352902f197) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where the new `operationType` property wasn't passed into `operation`.\n\n- [#12739](https://github.com/apollographql/apollo-client/pull/12739) [`b184754`](https://github.com/apollographql/apollo-client/commit/b184754d08810df9a7838615990e90a960966037) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `error` argument on the `onError` option for `subscribeToMore` to `ErrorLike`.\n\n## 4.0.0-rc.1\n\n### Major Changes\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `resultCacheMaxSize` option from `InMemoryCache` options.\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `connectToDevtools` option from `ApolloClientOptions`. Use `devtools.enabled` instead.\n\n### Minor Changes\n\n- [#12725](https://github.com/apollographql/apollo-client/pull/12725) [`89ac725`](https://github.com/apollographql/apollo-client/commit/89ac7256a34b3b04fe2cf83937b5494b375ce36d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `operationType` to `operation` in `ApolloLink`. This means that determining whether a `query` is a specific operation type can now be compared with this property instead of using `getMainDefinition`.\n\n  ```diff\n  - import { getMainDefinition } from \"@apollo/client/utilities\";\n  + import { OperationTypeNode } from \"graphql\";\n\n  ApolloLink.split(\n  - ({ query }) => {\n  -   const definition = getMainDefinition(query);\n  -   return (\n  -     definition.kind === 'OperationDefinition' &&\n  -     definition.operation === 'subscription'\n  -   );\n  -   return\n  - },\n  + ({ operationType }) => {\n  +   return operationType === OperationTypeNode.SUBSCRIPTION;\n  + },\n    conditionTrueLink,\n    conditionFalseLink,\n  );\n  ```\n\n### Patch Changes\n\n- [#12728](https://github.com/apollographql/apollo-client/pull/12728) [`07a0c8c`](https://github.com/apollographql/apollo-client/commit/07a0c8c52774793b254ecc91e5d4632bfdf48093) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export the `IgnoreModifier` type from `@apollo/client/cache`.\n\n- [#12735](https://github.com/apollographql/apollo-client/pull/12735) [`5159880`](https://github.com/apollographql/apollo-client/commit/51598808851e16af722baaefbd1f90534332e07a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Change the `unsafePreviousData` argument on `UpdateQueryMapFn` and `SubscribeToMoreQueryFn` to a `DeepPartial` since the result may contain partial data.\n\n- [#12734](https://github.com/apollographql/apollo-client/pull/12734) [`037979d`](https://github.com/apollographql/apollo-client/commit/037979dc47ffb7125429707471d901a08db49283) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't warn about a missing resolver if a `@client` does not have a configured resolver. It is possible the cache contains a `read` function for the field and the warning added confusion.\n\n  Note that `read` functions without a defined resolver will receive the `existing` argument as `null` instead of `undefined` even when data hasn't been written to the cache. This is because `LocalState` sets a default value of `null` when a resolver is not defined to ensure that the field contains a value in case a `read` function is not defined rather than omitting the field entirely.\n\n- [#12725](https://github.com/apollographql/apollo-client/pull/12725) [`89ac725`](https://github.com/apollographql/apollo-client/commit/89ac7256a34b3b04fe2cf83937b5494b375ce36d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `getMainDefinition` from `@apollo/client/utilities`.\n\n- [#12729](https://github.com/apollographql/apollo-client/pull/12729) [`699c830`](https://github.com/apollographql/apollo-client/commit/699c8305639ff69bab36fd2214defbe1ac6f0b18) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `useQuery` rerenders when `notifyOnNetworkStatusChange` is `false` and a `refetch` that changes variables returns a result deeply equal to previous variables.\n\n## 4.0.0-rc.0\n\n### Major Changes\n\n- [#12718](https://github.com/apollographql/apollo-client/pull/12718) [`ecfc02a`](https://github.com/apollographql/apollo-client/commit/ecfc02a37908b58d1f799f0e817cdeab98482720) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only to release latest as `rc`.\n\n## 4.0.0-alpha.23\n\n### Major Changes\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - An error is now thrown when trying to call `fetchMore` on a `cache-only` query.\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries are no longer refetched when calling `client.reFetchObservableQueries` when `includeStandby` is `true`.\n\n- [#12705](https://github.com/apollographql/apollo-client/pull/12705) [`a60f411`](https://github.com/apollographql/apollo-client/commit/a60f411e58cc67730d0dc4513e4045f004027ded) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries will now initialize with `loading: false` and `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n  This means `useQuery` will no longer render a short initial loading state before rendering `loading: false` and `ObservableQuery.getCurrentResult()` will now return `loading: false` immediately.\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries are now excluded from `client.refetchQueries` in all situations. `cache-only` queries affected by `updateCache` are also excluded from `refetchQueries` when `onQueryUpdated` is not provided.\n\n- [#12681](https://github.com/apollographql/apollo-client/pull/12681) [`b181f98`](https://github.com/apollographql/apollo-client/commit/b181f98476e635ba3eccab170c09d91f5408060c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changing most options when rerendering `useQuery` will no longer trigger a `reobserve` which may cause network fetches. Instead, the changed options will be applied to the next cache update or fetch.\n\n  Options that now trigger a `reobserve` when changed between renders are:\n\n  - `query`\n  - `variables`\n  - `skip`\n  - Changing `fetchPolicy` to or from `standby`\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - Rework option handling for `fetchMore`.\n\n  - Previously, if the `query` option was specified, no options would be inherited\n    from the underlying `ObservableQuery`.\n    Now, even if `query` is specified, all unspecified options except for `variables` will be inherited from the underlying `ObservableQuery`.\n  - If `query` is not specified, `variables` will still be shallowly merged with the `variables` of the underlying `ObservableQuery`. If a `query` option is specified, the `variables` passed to `fetchMore` are used instead.\n  - `errorPolicy` of `fetchMore` will now always default to `\"none\"` instead of inherited from the `ObservableQuery` options. This can prevent accidental cache writes of partial data for a paginated query. To opt into receive partial data that may be written to the cache, pass an `errorPolicy` to `fetchMore` to override the default.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - Added a new `Streaming` type that will mark `data` in results while `dataStatus`\n  is `\"streaming\"`.\n\n  `Streaming<TData>` defaults to `TData`, but can be overwritten in userland to\n  integrate with different codegen dialects.\n\n  You can override this type globally - this example shows how to override it\n  with `DeepPartial<TData>`:\n\n  ```ts\n  import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n  type StreamingOverride<TData> = DeepPartial<TData>;\n\n  interface StreamingOverrideHKT extends HKT {\n    return: StreamingOverride<this[\"arg1\"]>;\n  }\n\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides {\n      Streaming: StreamingOverrideHKT;\n    }\n  }\n  ```\n\n- [#12499](https://github.com/apollographql/apollo-client/pull/12499) [`ce35ea2`](https://github.com/apollographql/apollo-client/commit/ce35ea2b3a87d6dd6757e9be50ecc42837bebe56) Thanks [@phryneas](https://github.com/phryneas)! - Enable React compiler for hooks in ESM builds.\n\n- [#12704](https://github.com/apollographql/apollo-client/pull/12704) [`45dba43`](https://github.com/apollographql/apollo-client/commit/45dba43b6ba0c306aad8cfbcfd4029265f5e9106) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `ErrorResponse` object passed to the `disable` and `retry` callback options provided to `createPersistedQueryLink` no longer provides separate `graphQLErrors` and `networkError` properties and instead have been combined to a single `error` property of type `ErrorLike`.\n\n  ```diff\n  // The following also applies to the `retry` function since it has the same signature\n  createPersistedQueryLink({\n  - disable: ({ graphQLErrors, networkError }) => {\n  + disable: ({ error }) => {\n  -   if (graphQLErrors) {\n  +   if (CombinedGraphQLErrors.is(error)) {\n        // ... handle GraphQL errors\n      }\n\n  -   if (networkError) {\n  +   if (error) {\n        // ... handle link errors\n      }\n\n      // optionally check for a specific kind of error\n  -   if (networkError) {\n  +   if (ServerError.is(error)) {\n        // ... handle a server error\n      }\n  });\n  ```\n\n  The `response` property has also been renamed to `result`.\n\n  ```diff\n  createPersistedQueryLink({\n  -  disable: ({ response }) => {\n  +  disable: ({ result }) => {\n        // ... handle GraphQL errors\n      }\n    }\n  });\n  ```\n\n- [#12712](https://github.com/apollographql/apollo-client/pull/12712) [`bbb2b61`](https://github.com/apollographql/apollo-client/commit/bbb2b61d259da54560a79813b130a977dae10523) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `cache-only` queries no longer poll when a `pollInterval` is set. Instead a warning is now emitted that polling has no effect. If the `fetchPolicy` is changed to `cache-only` after polling is already active, polling is stopped.\n\n- [#12704](https://github.com/apollographql/apollo-client/pull/12704) [`45dba43`](https://github.com/apollographql/apollo-client/commit/45dba43b6ba0c306aad8cfbcfd4029265f5e9106) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `response` property in `onError` link has been renamed to `result`.\n\n  ```diff\n  - onError(({ response }) => {\n  + onError(({ result }) => {\n      // ...\n  });\n  ```\n\n- [#12715](https://github.com/apollographql/apollo-client/pull/12715) [`0be0b3f`](https://github.com/apollographql/apollo-client/commit/0be0b3f54a1b533c95c69d3698c5c3bdbd6279fe) Thanks [@phryneas](https://github.com/phryneas)! - All links are now available as classes. The old creator functions have been deprecated.\n\n  Please migrate these function calls to class creations:\n\n  ```diff\n  import {\n  - setContext\n  + SetContextLink\n  } from \"@apollo/client/link/context\"\n\n  -const link = setContext(...)\n  +const link = new SetContextLink(...)\n  ```\n\n  ```diff\n  import {\n  - createHttpLink\n  + HttpLink\n  } from \"@apollo/client/link/http\"\n\n  -const link = createHttpLink(...)\n  +const link = new HttpLink(...)\n  ```\n\n  ```diff\n  import {\n  - createPersistedQueryLink\n  + PersistedQueryLink\n  } from \"@apollo/client/link/persisted-queries\"\n\n  -const link = createPersistedQueryLink(...)\n  +const link = new PersistedQueryLink(...)\n  ```\n\n  ```diff\n  import {\n  - removeTypenameFromVariables\n  + RemoveTypenameFromVariablesLink\n  } from \"@apollo/client/link/remove-typename\"\n\n  -const link = removeTypenameFromVariables(...)\n  +const link = new RemoveTypenameFromVariablesLink(...)\n  ```\n\n### Minor Changes\n\n- [#12711](https://github.com/apollographql/apollo-client/pull/12711) [`f730f83`](https://github.com/apollographql/apollo-client/commit/f730f83346d4e3c20116da6f55fdd1381114416c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an `extensions` property to `CombinedGraphQLErrors` to capture any extensions from the original response.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The callback function that can be passed to the `ApolloClient.mutate`\n  `refetchQueries` option will now receive a `FormattedExecutionResult` with an\n  additional `dataState` option that describes if the result is `\"streaming\"`\n  or `\"complete\"`.\n  This indicates whether the `data` value is of type\n\n  - `Unmasked<TData>` (if `\"complete\"`)\n  - `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - Allow passing `errorPolicy` option to `fetchMore` and change default value to \"none\".\n\n- [#12714](https://github.com/apollographql/apollo-client/pull/12714) [`0e39469`](https://github.com/apollographql/apollo-client/commit/0e394692eaf0f8d8e506d8304935deafa952accf) Thanks [@phryneas](https://github.com/phryneas)! - The `FetchMoreQueryOptions` type has been inlined into `FetchMoreOptions`, and\n  `FetchMoreQueryOptions` has been removed.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - Prioritize usage of `FormattedExecutionResult` over `FetchResult` where applicable.\n\n  Many APIs used `FetchResult` in place of `FormattedExecutionResult`, which could\n  cause inconsistencies.\n\n  - `FetchResult` is now used to refer to an unhandled \"raw\" result as returned from\n    a link.\n    This can also include incremental results that use a different format.\n  - `FormattedExecutionResult` from the `graphql` package is now used to represent\n    the execution of a standard GraphQL request without incremental results.\n\n  If your custom links access the `data` property, you might need to first check if\n  the result is a standard GraphQL result by using the `isFormattedExecutionResult`\n  helper from `@apollo/client/utilities`.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The `mutationResult` option passed to the `updateQueries` callback now has an\n  additional property, `dataState` with possible values of `\"complete\"` and `\"streaming\"`.\n  This indicates whether the `data` value is of type\n  - `Unmasked<TData>` (if `\"complete\"`)\n  - `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n\n### Patch Changes\n\n- [#12709](https://github.com/apollographql/apollo-client/pull/12709) [`9d42e2a`](https://github.com/apollographql/apollo-client/commit/9d42e2a08d3ddfdfdfc7ac65bd66985da5642e7d) Thanks [@phryneas](https://github.com/phryneas)! - Remove these incremental-format-specific types:\n\n  - `ExecutionPatchIncrementalResult`\n  - `ExecutionPatchInitialResult`\n  - `ExecutionPatchResult`\n  - `IncrementalPayload`\n  - `Path`\n\n- [#12677](https://github.com/apollographql/apollo-client/pull/12677) [`94e58ed`](https://github.com/apollographql/apollo-client/commit/94e58ed75fc547ff037d9efeeba929fd61b20c4c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Downgrade minimum supported `rxjs` peer dependency version to 7.3.0.\n\n- [#12709](https://github.com/apollographql/apollo-client/pull/12709) [`9d42e2a`](https://github.com/apollographql/apollo-client/commit/9d42e2a08d3ddfdfdfc7ac65bd66985da5642e7d) Thanks [@phryneas](https://github.com/phryneas)! - Slightly rework multipart response parsing.\n\n  This removes last incremental-protocol-specific details from `HttpLink` and `BatchHttpLink`.\n\n- [#12700](https://github.com/apollographql/apollo-client/pull/12700) [`8e96e08`](https://github.com/apollographql/apollo-client/commit/8e96e0862c306df17c09c232704041196a72a466) Thanks [@phryneas](https://github.com/phryneas)! - The incremental delivery (`@defer` support) implementation is now pluggable.\n\n  `ApolloClient` now per default ships without an incremental format implementation\n  and allows you to swap in the format that you want to use.\n\n  Usage looks like this:\n\n  ```ts\n  import {\n    // this is the default\n    NotImplementedHandler,\n    // this implements the `@defer` transport format that ships with Apollo Router\n    Defer20220824Handler,\n    // this implements the `@defer` transport format that ships with GraphQL 17.0.0-alpha.2\n    GraphQL17Alpha2Handler,\n  } from \"@apollo/client/incremental\";\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      /*...*/\n    }),\n    link: new HttpLink({\n      /*...*/\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n  ```\n\n  We will add handlers for other response formats that can be swapped this way\n  during the lifetime of Apollo Client 4.0.\n\n## 4.0.0-alpha.22\n\n### Major Changes\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - The `includeExtensions` option of `HttpLink` and `BatchHttpLink` now defaults\n  to `true`.\n\n  If `includeExtensions` is `true`, but `extensions` is not set or empty, extensions\n  will not be included in outgoing requests.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - The `ApolloClient` constructor options `name` and `version` that are used to\n  configure the client awareness feature have moved onto a `clientAwareness` key.\n\n  ```diff\n  const client = new ApolloClient({\n    // ..\n  -  name: \"my-app\",\n  -  version: \"1.0.0\",\n  +  clientAwareness: {\n  +    name: \"my-app\",\n  +    version: \"1.0.0\",\n  +  },\n  });\n  ```\n\n- [#12690](https://github.com/apollographql/apollo-client/pull/12690) [`5812759`](https://github.com/apollographql/apollo-client/commit/5812759b6659df49277635e89492c0d72c3b57d6) Thanks [@phryneas](https://github.com/phryneas)! - Aliasing any other field to `__typename` is now forbidden.\n\n- [#12690](https://github.com/apollographql/apollo-client/pull/12690) [`5812759`](https://github.com/apollographql/apollo-client/commit/5812759b6659df49277635e89492c0d72c3b57d6) Thanks [@phryneas](https://github.com/phryneas)! - Aliasing a field to an alias beginning with `__ac_` is now forbidden - this namespace is now reserved for internal use.\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Adds enhanced client awareness to the client.\n\n  `HttpLink` and `BatchHttpLink` will now per default send information about the\n  client library you are using in `extensions`.\n\n  This could look like this:\n\n  ```json\n  {\n    \"query\": \"query GetUser($id: ID!) { user(id: $id) { __typename id name } }\",\n    \"variables\": {\n      \"id\": 5\n    },\n    \"extensions\": {\n      \"clientLibrary\": {\n        \"name\": \"@apollo/client\",\n        \"version\": \"4.0.0\"\n      }\n    }\n  }\n  ```\n\n  This feature can be disabled by passing `enhancedClientAwareness: { transport: false }` to your\n  `ApolloClient`, `HttpLink` or `BatchHttpLink` constructor options.\n\n### Minor Changes\n\n- [#12698](https://github.com/apollographql/apollo-client/pull/12698) [`be77d1a`](https://github.com/apollographql/apollo-client/commit/be77d1a6ddf719cab4780a0679fcd98556ac7f22) Thanks [@phryneas](https://github.com/phryneas)! - Adjusted the accept header for multipart requests according to the new GraphQL over HTTP spec with these changes:\n\n  ```diff\n  -multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json\n  +multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/graphql-response+json,application/json;q=0.9\n  ```\n\n  ```diff\n  -multipart/mixed;deferSpec=20220824,application/json\n  +multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\n  ```\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Add the new `ClientAwarenessLink`.\n\n  This link is already included in `HttpLink` and `BatchHttpLink` to enable the\n  \"client awareness\" and \"enhanced client awareness\" features, but you can also use\n  `ClientAwarenessLink` directly in your link chain to combine it with other\n  terminating links.\n\n  If you want to save the bundle size that `ClientAwarenessLink` adds to `HttpLink`\n  and `BatchHttpLink`, you can use `BaseHttpLink` or `BaseBatchHttpLink` instead.\n  These links come without the `ClientAwarenessLink` included.\n\n  For example:\n\n  ```diff\n  import {\n    ApolloClient,\n  -  HttpLink,\n  } from \"@apollo/client\";\n  +import { BaseHttpLink } from \"@apollo/client/link/http\";\n\n  const client = new ApolloClient({\n  -  link: new HttpLink({\n  +  link: new BaseHttpLink({\n      uri,\n    }),\n    cache: new InMemoryCache(),\n  });\n  ```\n\n- [#12698](https://github.com/apollographql/apollo-client/pull/12698) [`be77d1a`](https://github.com/apollographql/apollo-client/commit/be77d1a6ddf719cab4780a0679fcd98556ac7f22) Thanks [@phryneas](https://github.com/phryneas)! - Adds an `accept` option to `HttpOptions` that allows to add additional `Accept` headers to be merged in without overriding user-specified or default accept headers.\n\n### Patch Changes\n\n- [#12673](https://github.com/apollographql/apollo-client/pull/12673) [`cee90ab`](https://github.com/apollographql/apollo-client/commit/cee90abcd2a9c91c5fdf872cf2d1c12deaa6593e) Thanks [@phryneas](https://github.com/phryneas)! - Fixed a bug in `PersistedQueryLink` where the `persistedQuery` extension would still be sent after a `PersistedQueryNotSupported` if `includeExtensions` was enabled on `HttpLink`.\n\n## 4.0.0-alpha.21\n\n### Major Changes\n\n- [#12686](https://github.com/apollographql/apollo-client/pull/12686) [`dc4b1d0`](https://github.com/apollographql/apollo-client/commit/dc4b1d0d2479a37067113b7bd161a550fb8e4df6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - A `@defer` query that has not yet finished streaming is now considered loading and thus the `loading` flag will be `true` until the response has completed. A new `NetworkStatus.streaming` value has been introduced and will be set as the `networkStatus` while the response is streaming.\n\n- [#12685](https://github.com/apollographql/apollo-client/pull/12685) [`3b74800`](https://github.com/apollographql/apollo-client/commit/3b748003df89ec69a6ad045fb47bbe9c3e62104c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the check and warning for `cache.fragmentMatches` when applying data masking. `cache.fragmentMatches` is a required API and data masking may crash when `cache.fragmentMatches` does not exist.\n\n- [#12684](https://github.com/apollographql/apollo-client/pull/12684) [`e697431`](https://github.com/apollographql/apollo-client/commit/e697431a9995fd1900e625c30a9065edd71111d9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `context` from `useLazyQuery` hook options. If used, `context` must now be provided to the `execute` function. `context` will reset to `{}` if not provided as an option to `execute`.\n\n## 4.0.0-alpha.20\n\n### Major Changes\n\n- [#12675](https://github.com/apollographql/apollo-client/pull/12675) [`8f1d974`](https://github.com/apollographql/apollo-client/commit/8f1d974881ff54339b6b6593a219ba6d5fd013c0) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` no longer has a `queryId` property.\n  `ApolloClient.getObservableQueries` no longer returns a `Map<string, ObservableQuery>`, but a `Set<ObservableQuery>`.\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery`s will now only be registered with the `ApolloClient` while they\n  have subscribers.\n\n  That means that `ApolloClient.getObservableQueries` and `ApolloClient.refetchQueries`\n  will only be able to return/refetch queries that have at least one subscriber.\n\n  This changes the previous meaning of `active` and `inactive` queries:\n\n  - `inactive` queries are queries with a subscriber that are skipped from a\n    React hook or have a `fetchPolicy` of `standby`\n  - `active` queries are queries with at least one subscriber that are not skipped or in `standby`.\n\n  `ObservableQuery`s without subscribers but with an active ongoing network request\n  (e.g. caused by calling `reobserve`) will be handled as if they had a subscriber\n  for the duration of the query.\n\n- [#12678](https://github.com/apollographql/apollo-client/pull/12678) [`91a876b`](https://github.com/apollographql/apollo-client/commit/91a876b059042828e431931e7a3c2e0365c387b8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `queryRef`s created by `preloadQuery` no longer have a `.toPromise()` function. Instead `preloadQuery` now has a `toPromise` function that accepts a queryRef and will resolve when the underlying promise has been resolved.\n\n  ```diff\n  const queryRef = preloadQuery(query, options);\n\n  - await queryRef.toPromise();\n  + await preloadQuery.toPromise(queryRef);\n  ```\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - `ApolloClient.stop()` now cleans up more agressively to prevent memory leaks:\n\n  - It will now unsubscribe all active `ObservableQuery` instances by emitting a `completed` event.\n  - It will now reject all currently running queries with `\"QueryManager stopped while query was in flight\"`.\n  - It will remove all queryRefs from the suspense cache.\n\n### Minor Changes\n\n- [#12647](https://github.com/apollographql/apollo-client/pull/12647) [`a70fac6`](https://github.com/apollographql/apollo-client/commit/a70fac6dd8f26b46c813723a7206e55bfb677690) Thanks [@phryneas](https://github.com/phryneas)! - Added a new `.stop` function on `ObservableQuery`.\n  Calling this method will unsubscribe all current subscribers by sending a `complete` event from the observable and tear down the `ObservableQuery`.\n\n## 4.0.0-alpha.19\n\n### Major Changes\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unsubscribing from an `ObservableQuery` before a value has been emitted will remove the query from the tracked list of queries and will no longer be eligible for query deduplication.\n\n### Minor Changes\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions created by `client.subscribe()` can now be restarted. Restarting a subscription will terminate the connection with the link chain and recreate the request. Restarts also work across deduplicated subscriptions so calling `restart` on an `observable` who's request is deduplicated will restart the connection for each observable.\n\n  ```ts\n  const observable = client.subscribe({ query: subscription });\n\n  // Restart the connection to the link\n  observable.restart();\n  ```\n\n- [#12663](https://github.com/apollographql/apollo-client/pull/12663) [`01512f2`](https://github.com/apollographql/apollo-client/commit/01512f2429dd394fb72b8ba9284047a09ade666f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deduplicating subscription operations is now supported. Previously it was possible to deduplicate a subscription only if the new subscription was created before a previously subscribed subscription emitted any values. As soon as a value was emitted from a subscription, new subscriptions would create new connections. Deduplication is now active for as long as a subscription connection is open (i.e. the source observable hasn't emitted a `complete` or `error` notification yet.)\n\n  To disable deduplication and force a new connection, use the `queryDeduplication` option in `context` like you would a query operation.\n\n  As a result of this change, calling the `restart` function returned from `useSubscription` will now restart the connection on deduplicated subscriptions.\n\n## 4.0.0-alpha.18\n\n### Minor Changes\n\n- [#12670](https://github.com/apollographql/apollo-client/pull/12670) [`0a880ea`](https://github.com/apollographql/apollo-client/commit/0a880ea4c2360a985fdd2edadb94fcc4b82bad73) Thanks [@phryneas](https://github.com/phryneas)! - Provide a mechanism to override the DataMasking types.\n\n  Up until now, our types `Masked`, `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked` would assume that you are stictly using the type output format of GraphQL Codegen.\n\n  With this change, you can now modify the behaviour of those types if you use a different form of codegen that produces different types for your queries.\n\n  A simple implementation that would override the `Masked` type to remove all fields starting with `_` from a type would look like this:\n\n  ```ts\n  // your actual implementation of `Masked`\n  type CustomMaskedImplementation<TData> = {\n    [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n  };\n\n  import { HKT } from \"@apollo/client/utilities\";\n  // transform this type into a higher kinded type that can be evaulated at a later time\n  interface CustomMaskedType extends HKT {\n    arg1: unknown; // TData\n    return: CustomMaskedImplementation<this[\"arg1\"]>;\n  }\n\n  // create an \"implementation interface\" for the types you want to override\n  export interface CustomDataMaskingImplementation {\n    Masked: CustomMaskedType;\n    // other possible keys: `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked`\n  }\n  ```\n\n  then you would use that `CustomDataMaskingImplementation` interface in your project to extend the `TypeOverrides` interface exported by `@apollo/client` with it's functionality:\n\n  ```ts\n  declare module \"@apollo/client\" {\n    export interface TypeOverrides extends CustomDataMaskingImplementation {}\n  }\n  ```\n\n  After that, all internal usage of `Masked` in Apollo Client as well as all usage in your code base will use the new `CustomMaskedType` implementation.\n\n  If you don't specify overrides, Apollo Client will still default to the GraphQL Codegen data masking implementation.\n  The types for that are also explicitly exported as the `GraphQLCodegenDataMasking` namespace in `@apollo/client/masking`.\n\n## 4.0.0-alpha.17\n\n### Major Changes\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `TData` generic provided to types that return a `dataState` property is now modified by the given `DataState` generic instead of passing a modified `TData` type. For example, a `QueryRef` that could return partial data was defined as `QueryRef<DeepPartial<TData>, TVariables>`. Now `TData` should be provided unmodified and a set of allowed states should be given instead: `QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>`.\n\n  To migrate, use the following guide to replace your type with the right set of states (all types listed below are changed the same way):\n\n  ```diff\n  - QueryRef<TData, TVariables>\n  // `QueryRef`'s default is 'complete' | 'streaming' so this can also be left alone if you prefer\n  // All other types affected by this change default to all states\n  + QueryRef<TData, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming'>\n\n  - QueryRef<TData | undefined, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'empty'>\n\n  - QueryRef<DeepPartial<TData>, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>\n\n  - QueryRef<DeepPartial<TData> | undefined, TVariables>\n  + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial' | 'empty'>\n  ```\n\n  The following types are affected. Provide the allowed `dataState` values to the `TDataState` generic:\n\n  - `ApolloQueryResult`\n  - `QueryRef`\n  - `PreloadedQueryRef`\n  - `useLazyQuery.Result`\n  - `useQuery.Result`\n  - `useReadQuery.Result`\n  - `useSuspenseQuery.Result`\n\n  All `*QueryRef` types default to `complete | streaming` states while the rest of the types default to `'complete' | 'streaming' | 'partial' | 'empty'` states. You shouldn't need to provide the states unless you need to either allow for partial data/empty values (`*QueryRef`) or a restricted set of states.\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `QueryReference` type. Please use `QueryRef` instead.\n\n- [#12633](https://github.com/apollographql/apollo-client/pull/12633) [`9bfb51f`](https://github.com/apollographql/apollo-client/commit/9bfb51fdbca69560da71f9012c74ee172b6c2b69) Thanks [@phryneas](https://github.com/phryneas)! - If the `execute` function of `useLazyQuery` is executed, previously started queries\n  from the same `useLazyQuery` usage will be rejected with an `AbortError` unless\n  `.retain()` is called on the promise returned by previous `execute` calls.\n\n  Please keep in mind that `useLazyQuery` is primarily meant as a means to synchronize\n  your component to the status of a query and that it's purpose it not to make a\n  series of network calls.\n  If you plan on making a series of network calls without the need to synchronize\n  the result with your component, consider using `ApolloClient.query` instead.\n\n### Minor Changes\n\n- [#12633](https://github.com/apollographql/apollo-client/pull/12633) [`9bfb51f`](https://github.com/apollographql/apollo-client/commit/9bfb51fdbca69560da71f9012c74ee172b6c2b69) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery.refetch` and `ObservableQuery.reobserve` and the `execute` function of `useLazyQuery` now return a\n  `ResultPromise` with an additional `.retain` method.\n  If this method is called, the underlying network operation will be kept running even if the `ObservableQuery` itself does\n  not require the result anymore, and the Promise will resolve with the final result instead of resolving with an intermediate\n  result in the case of early cancellation.\n\n- [#12649](https://github.com/apollographql/apollo-client/pull/12649) [`0be92ad`](https://github.com/apollographql/apollo-client/commit/0be92ad51cf8de444fa1cc507bab2c21d230a44e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a new `dataState` property that determines the completeness of the `data` property. `dataState` helps narrow the type of `data`. `dataState` is now emitted from `ObservableQuery` and returned from all React hooks that return a `data` property.\n\n  The `dataState` values are:\n\n  - `empty`: No data could be fulfilled from the cache or the result is incomplete. `data` is `undefined`.\n  - `partial`: Some data could be fulfilled from the cache but `data` is incomplete. This is only possible when `returnPartialData` is `true`.\n  - `streaming`: `data` is incomplete as a result of a deferred query and the result is still streaming in.\n  - `complete`: `data` is a fully satisfied query result fulfilled either from the cache or network.\n\n  Example:\n\n  ```ts\n  const { data, dataState } = useQuery<TData>(query);\n\n  if (dataState === \"empty\") {\n    expectTypeOf(data).toEqualTypeOf<undefined>();\n  }\n\n  if (dataState === \"partial\") {\n    expectTypeOf(data).toEqualTypeOf<DeepPartial<TData>>();\n  }\n\n  if (dataState === \"streaming\") {\n    expectTypeOf(data).toEqualTypeOf<TData>();\n  }\n\n  if (dataState === \"complete\") {\n    expectTypeOf(data).toEqualTypeOf<TData>();\n  }\n  ```\n\n## 4.0.0-alpha.16\n\n### Major Changes\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Replace the `result` property on `ServerError` with `bodyText`. `bodyText` is set to the raw string body. `HttpLink` and `BatchHttpLink` no longer try and parse the response body as JSON when a `ServerError` is thrown.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - More strictly adhere to the [GraphQL over HTTP spec](https://graphql.github.io/graphql-over-http/draft/). This change adds support for the `application/graphql-response+json` media type and modifies the behavior of the `application/json` media type.\n\n  - The client will parse the response as a well-formed GraphQL response when the server encodes `content-type` using `application/graphql-response+json` with a non-200 status code.\n  - The client will now throw a `ServerError` when the server encodes `content-type` using `application/json` and returns a non-200 status code.\n  - The client will now throw a `ServerError` when the server encodes using any other `content-type` and returns a non-200 status code.\n\n  NOTE: If you use a testing utility to mock requests in your test, you may experience different behavior than production if your testing utility responds as `application/json` but your production server responds as `application/graphql-response+json`. If a `content-type` header is not set, the client interprets the response as `application/json`.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Change the default `Accept` header to `application/graphql-response+json,application/json;q=0.9`.\n\n- [#12644](https://github.com/apollographql/apollo-client/pull/12644) [`fe2f005`](https://github.com/apollographql/apollo-client/commit/fe2f005c34913ae082b96a807dc240e2785d50bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `HttpLink` and `BatchHttpLink` no longer emit a `next` notification with the JSON-parsed response body when a well-formed GraphQL response is returned and a `ServerError` is thrown.\n\n## 4.0.0-alpha.15\n\n### Major Changes\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move internal testing utilities in `@apollo/client/testing` to `@apollo/client/testing/internal` and remove deprecated testing utilities. Some of the testing utilities exported from the `@apollo/client/testing` endpoint were not considered stable. As a result of this change, testing utilities or types exported from `@apollo/client/testing` are now considered stable and will not undergo breaking changes.\n\n  The following APIs were removed. To migrate, update usages of the following APIs as such:\n\n  **`createMockClient`**\n\n  ```diff\n  - const client = createMockClient(data, query, variables);\n  + const client = new ApolloClient({\n  +   cache: new InMemoryCache(),\n  +   link: new MockLink([\n  +     {\n  +       request: { query, variables },\n  +       result: { data },\n  +     }\n  +   ]),\n  + });\n  ```\n\n  **`mockObservableLink`**\n\n  ```diff\n  - const link = mockObservableLink();\n  + const link = new MockSubscriptionLink();\n  ```\n\n  **`mockSingleLink`**\n\n  ```diff\n  - const link = mockSingleLink({\n  -   request: { query, variables },\n  -   result: { data },\n  - });\n  + const link = new MockLink([\n  +   {\n  +     request: { query, variables },\n  +     result: { data },\n  +   }\n  + ]);\n  ```\n\n- [#12637](https://github.com/apollographql/apollo-client/pull/12637) [`d2a60d4`](https://github.com/apollographql/apollo-client/commit/d2a60d45e734a2518dad2443f85d82553cd6456a) Thanks [@phryneas](https://github.com/phryneas)! - `useQuery`: only advance `previousData` if `data` actually changed\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` will now return a `loading: false` state for `fetchPolicy` `standby`, even before subscription\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `@apollo/client/testing/core` entrypoint in favor of `@apollo/client/testing`.\n\n### Minor Changes\n\n- [#12639](https://github.com/apollographql/apollo-client/pull/12639) [`1bdf489`](https://github.com/apollographql/apollo-client/commit/1bdf4893abb173c97877c71012afa15f9d3da8e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move `MockLink` types to `MockLink` namespace. This affects the `MockedResponse`, `MockLinkOptions`, and `ResultFunction` types. These types are still exported but are deprecated in favor of the namespace. To migrate, use the types on the `MockLink` namespace instead.\n\n  ```diff\n  import {\n  - MockedResponse,\n  - MockLinkOptions,\n  - ResultFunction,\n  + MockLink\n  } from \"@apollo/client/testing\";\n\n  - const mocks: MockedResponse = [];\n  + const mocks: MockLink.MockedResponse = [];\n\n  - const result: ResultFunction = () => {/* ... */ }\n  + const result: MockLink.ResultFunction = () => {/* ... */ }\n\n  - const options: MockLinkOptions = {}\n  + const options: MockLink.Options = {}\n  ```\n\n### Patch Changes\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - When updating `skip` from `false` to `true` in `useQuery`, retain `data` if it is available rather than setting it to `undefined`.\n\n- [#12631](https://github.com/apollographql/apollo-client/pull/12631) [`b147cac`](https://github.com/apollographql/apollo-client/commit/b147cac5c96c44bfc3deb72c12c7521981584c12) Thanks [@phryneas](https://github.com/phryneas)! - The `error` property is no longer present when `skip` is `true` in `useQuery`.\n\n## 4.0.0-alpha.14\n\n### Major Changes\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `getCacheKey` function is no longer available from `operation.getContext()` in the link chain. Use `operation.client.cache.identify(obj)` in the link chain instead.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - `ObservableQuery` will now keep previous `data` around when emitting a `loading` state, unless `query` or `variables` changed.\n  Note that `@exports` variables are not taken into account for this, so `data` will stay around even if they change.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Removed `getLastResult`, `getLastError` and `resetLastResults` from `ObservableQuery`\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `resolvers` option from `ApolloClient`. Local resolvers have instead been moved to the new `LocalState` instance which is assigned to the `localState` option in `ApolloClient`. To migrate, move the `resolvers` values into a `LocalState` instance and assign that instance to `localState`.\n\n  ```diff\n  new ApolloClient({\n  - resolvers: { /* ... */ }\n  + localState: new LocalState({\n  +   resolvers: { /* ... */ }\n  + }),\n  });\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove local resolvers APIs from `ApolloClient` in favor of `localState`. Methods removed are:\n\n  - `addResolvers`\n  - `getResolvers`\n  - `setResolvers`\n  - `setLocalStateFragmentMatcher`\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Third-party caches must now implement the `fragmentMatches` API. Additionally `fragmentMatches` must be able to handle both `InlineFragmentNode` and `FragmentDefinitionNode` nodes.\n\n  ```ts\n  class MyCache extends ApolloCache {\n    // This is now required\n    public fragmentMatches(\n      fragment: InlineFragmentNode | FragmentDefinitionNode,\n      typename: string\n    ): boolean {\n      return; // ... logic to determine if typename matches fragment\n    }\n  }\n  ```\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Reworked the logic for then a loading state is triggered. If the link chain responds synchronously, a loading state will be omitted, otherwise it will be triggered.\n  If local resolvers are used, the time window for \"sync vs async\" starts as soon as `@exports` variables are resolved.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - Dropped the `saveAsLastResult` argument from `ObservableQuery.getCurrentResult`\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The resolver function's `context` argument (the 3rd argument) has changed to provide additional information without the possibility of name clashes. Previously the `context` argument would spread request context and override the `client` and `cache` properties to give access to both inside of a resolver. The `context` argument takes now takes the following shape:\n\n  ```ts\n  {\n    // the request context. By default `TContextValue` is of type `DefaultContext`,\n    // but can be changed if a `context` function is provided.\n    requestContext: TContextValue,\n    // The client instance making the request\n    client: ApolloClient,\n    // Whether the resolver is run as a result of gathering exported variables\n    // or resolving the value as part of the result\n    phase: \"exports\" | \"resolve\"\n  }\n  ```\n\n  To migrate, pull any request context from `requestContext` and the `cache` from the `client` property:\n\n  ```diff\n  new LocalState({\n    resolvers: {\n      Query: {\n  -     myResolver: (parent, args, { someValue, cache }) => {\n  +     myResolver: (parent, args, { requestContext, client }) => {\n  +       const someValue = requestContext.someValue;\n  +       const cache = client.cache;\n        }\n      }\n    }\n  });\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apollo Client no longer ships with support for `@client` fields out-of-the-box and now must be opt-in. To opt in to use `@client` fields, pass an instantiated `LocalState` instance to the `localState` option. If a query contains `@client` and local state hasn't been configured, an error will be thrown.\n\n  ```ts\n  import { LocalState } from \"@apollo/client/local-state\";\n\n  new ApolloClient({\n    localState: new LocalState(),\n  });\n  ```\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `fragmentMatcher` option from `ApolloClient`. Custom fragment matchers used with local state are no longer supported. Fragment matching is now performed by the configured `cache` via the `cache.fragmentMatches` API.\n\n- [#12556](https://github.com/apollographql/apollo-client/pull/12556) [`c3fceda`](https://github.com/apollographql/apollo-client/commit/c3fceda86c5e0f499d0b5fa54ea7dc4c4391ae2c) Thanks [@phryneas](https://github.com/phryneas)! - A call to `ObservableQuery.setVariables` with different variables or a `ObservableQuery.refetch` call will always now guarantee that a value will be emitted from the observable, even if it is deep equal to the previous value.\n\n### Minor Changes\n\n- [#12614](https://github.com/apollographql/apollo-client/pull/12614) [`d2851e2`](https://github.com/apollographql/apollo-client/commit/d2851e2c74541995760a86904b1e3ab4bd736e62) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Revamp local resolvers and fix several issues from the existing `resolvers` option.\n\n  - Throwing errors in a resolver will set the field value as `null` and add an error to the response's `errors` array.\n  - Remote results are dealiased before they are passed as the parent object to a resolver so that you can access fields by their field name.\n  - You can now specify a `context` function that you can use to customize the `requestContext` given to resolvers.\n  - The `LocalState` class accepts a `Resolvers` generic that provides autocompletion and type checking against your resolver types to ensure your resolvers are type-safe.\n  - `data: null` is now handled correctly and does not call your local resolvers when the server does not provide a result.\n  - Additional warnings have been added to provide hints when resolvers behave unexpectedly.\n\n  ```ts\n  import { LocalState } from \"@apollo/client/local-state\";\n\n  import { Resolvers } from \"./path/to/local-resolvers-types.ts\";\n\n  // LocalState now accepts a `Resolvers` generic.\n  const localState = new LocalState<Resolvers>({\n    // The return value of this funciton\n    context: (options) => ({\n      // ...\n    }),\n    resolvers: {\n      // ...\n    },\n  });\n\n  // You may also pass a `ContextValue` generic used to ensure the `context`\n  // function returns the correct type. This type is inferred from your resolvers\n  // if not provided.\n  new LocalState<Resolvers, ContextValue>({\n    // ...\n  });\n  ```\n\n## 4.0.0-alpha.13\n\n### Major Changes\n\n- [#12600](https://github.com/apollographql/apollo-client/pull/12600) [`34ff6aa`](https://github.com/apollographql/apollo-client/commit/34ff6aa25b47c3e84d0b18e2c69bc995814bf2f2) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Move most of the utilities in `@apollo/client/utilities` to `@apollo/client/utilities/internal`. Many of the utilities exported from the `@apollo/client/utilities` endpoint were not considered stable.\n\n  As a result of this change, utilities or types exported from `@apollo/client/utilities` are now documented and considered stable and will not undergo breaking changes.\n\n- [#12595](https://github.com/apollographql/apollo-client/pull/12595) [`60bb49c`](https://github.com/apollographql/apollo-client/commit/60bb49ccea9aecf3e6a212b5a1f71907e60af886) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `@apollo/client/testing/experimental` test utilities. Use [GraphQL Testing Library](https://github.com/apollographql/graphql-testing-library) instead.\n\n### Patch Changes\n\n- [#12618](https://github.com/apollographql/apollo-client/pull/12618) [`e4a3ecf`](https://github.com/apollographql/apollo-client/commit/e4a3ecfe50bc5b462067574a0ffb1951549fb60f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove code that strips `@client` fields in `HttpLink` and `BatchHttpLink`. This was unused code since core handles removing `@client` fields and should have no observable change.\n\n## 4.0.0-alpha.12\n\n### Major Changes\n\n- [#12586](https://github.com/apollographql/apollo-client/pull/12586) [`605db8e`](https://github.com/apollographql/apollo-client/commit/605db8e94fe2ce74c0a395f38f6873d40f431365) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `typeDefs` option from `ApolloClient`.\n\n- [#12588](https://github.com/apollographql/apollo-client/pull/12588) [`eed825a`](https://github.com/apollographql/apollo-client/commit/eed825a2549f1d21fff2ec179815206b3baf0fcb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `TContext` generic argument from all types that use it. `TContext` is replaced with `DefaultContext` which can be modified using declaration merging.\n\n- [#12590](https://github.com/apollographql/apollo-client/pull/12590) [`a005e82`](https://github.com/apollographql/apollo-client/commit/a005e822de7b24783f85be45df142ffbb9bc561b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Drop `graphql` v15 as a valid peer dependency.\n\n- [#12591](https://github.com/apollographql/apollo-client/pull/12591) [`a7e7383`](https://github.com/apollographql/apollo-client/commit/a7e738328951f5dac25a5fe48d28b3640a3e0eb9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Rename the `@apollo/client/link/core` entrypoint to `@apollo/client/link`.\n\n- [#12589](https://github.com/apollographql/apollo-client/pull/12589) [`15f5a1c`](https://github.com/apollographql/apollo-client/commit/15f5a1c29ac05015387a7bbc2dbe9a91d09fedfa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Require the `link` option when instantiating `ApolloClient`. This removes the `uri`, `credentials` and `headers` options from `ApolloClient` in favor of passing an instantiated `HttpLink` directly. To migrate:\n\n  **If using `uri`, `credentials`, or `headers` options**\n\n  ```diff\n  new ApolloClient({\n    // ...\n  - uri,\n  - credentials,\n  - headers,\n  + link: new HttpLink({ uri, credentials, headers }),\n  // or if you prefer the function call approach:\n  + link: createHttpLink({ uri, credentials, headers }),\n  });\n  ```\n\n  **If creating a client without the `link` option**\n\n  ```diff\n  new ApolloClient({\n    // ...\n  + link: ApolloLink.empty()\n  });\n  ```\n\n## 4.0.0-alpha.11\n\n### Major Changes\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `cache` and `forceFetch` properties are no longer available on context when calling `operation.getContext()`. `cache` can be accessed through the `operation` with `operation.client.cache` instead. `forceFetch` has been replaced with `queryDeduplication` which specifies whether `queryDeduplication` was enabled for the request or not.\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ApolloLink.execute` now requires a third argument which provides the `client` that initiated the request to the link chain. If you use `execute` directly, add a third argument with a `client` property:\n\n  ```ts\n  ApolloLink.execute(link, operation, { client });\n\n  // or if you import the `execute` function directly:\n  execute(link, operation, { client });\n  ```\n\n- [#12566](https://github.com/apollographql/apollo-client/pull/12566) [`ce4b488`](https://github.com/apollographql/apollo-client/commit/ce4b488bef13f2f5ce1b348d8c3196e198165dd6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't `broadcastQueries` when a query is torn down.\n\n### Minor Changes\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Provide an extension to define types for `context` passed to the link chain. To define your own types, use [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to add properties to the `DefaultContext` type.\n\n  ```ts\n  // @apollo-client.d.ts\n  // This import is necessary to ensure all Apollo Client imports\n  // are still available to the rest of the application.\n  import \"@apollo/client\";\n\n  declare module \"@apollo/client\" {\n    interface DefaultContext extends Record<string, any> {\n      myProperty: string;\n    }\n  }\n  ```\n\n  Links that provide context options can be used with this type to add those context types to `DefaultContext`. For example, to add context options from `HttpLink`, add the following code:\n\n  ```ts\n  import { HttpLink } from \"@apollo/client\";\n\n  declare module \"@apollo/client\" {\n    interface DefaultContext extends HttpLink.ContextOptions {\n      myProperty: string;\n    }\n  }\n  ```\n\n  At this time, the following built-in links support context options:\n\n  - `HttpLink.ContextOptions`\n  - `BatchHttpLink.ContextOptions`\n\n- [#12576](https://github.com/apollographql/apollo-client/pull/12576) [`a92ff78`](https://github.com/apollographql/apollo-client/commit/a92ff780abee60896bb9632867e90c82d0829255) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `client` property to the `operation` passed to the link chain. This `client` is set as the `client` making the request to the link chain.\n\n### Patch Changes\n\n- [#12574](https://github.com/apollographql/apollo-client/pull/12574) [`0098ec9`](https://github.com/apollographql/apollo-client/commit/0098ec9f860e4e08a2070823f723dce401ae588a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `gql` from the `@apollo/client/react` entrypoint.\n\n- [#12572](https://github.com/apollographql/apollo-client/pull/12572) [`3dc50e6`](https://github.com/apollographql/apollo-client/commit/3dc50e6476dcedf82ed3856bf9f4571a32a760a6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Adjust `useMutation` types to better handle required variables. When required variables are missing, TypeScript will now complain if they are not provided either to the hook or the returned `mutate` function. Providing required variables to `useMutation` will make them optional in the returned `mutate` function.\n\n## 4.0.0-alpha.10\n\n### Major Changes\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.variables` can now be reset back to empty when calling `reobserve` with `variables: undefined`. Previously the `variables` key would be ignored so `variables` would remain unchanged.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `never` is no longer supported as a valid `TVariables` generic argument for APIs that require `variables` as part of its type. Use `Record<string, never>` instead.\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - When passing a `variables` key with the value `undefined`, the value will be replaced by the default value in the query, if it is provided, rather than leave it as `undefined`.\n\n  ```ts\n  // given this query\n  const query = gql`\n    query PaginatedQuery($limit: Int! = 10, $offset: Int) {\n      list(limit: $limit, offset: $offset) {\n        id\n      }\n    }\n  `;\n\n  const observable = client.query({\n    query,\n    variables: { limit: 5, offset: 0 },\n  });\n  console.log(observable.variables); // => { limit: 5, offset: 0 }\n\n  observable.reobserve({ variables: { limit: undefined, offset: 10 } });\n  // limit is now `10`. This would previously be `undefined`\n  console.log(observable.variables); // => { limit: 10, offset: 10 }\n  ```\n\n- [#12562](https://github.com/apollographql/apollo-client/pull/12562) [`90bf0e6`](https://github.com/apollographql/apollo-client/commit/90bf0e61516a382182f212ac8ab891099e2eb009) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.query` no longer supports a `fetchPolicy` of `standby`. `standby` does not fetch and did not return `data`. `standby` is meant for watched queries where fetching should be on hold.\n\n### Minor Changes\n\n- [#12557](https://github.com/apollographql/apollo-client/pull/12557) [`51d26ae`](https://github.com/apollographql/apollo-client/commit/51d26ae631c6631a189c98ea9357b18e77a9a876) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add ability to specify message formatter for `CombinedGraphQLErrors` and `CombinedProtocolErrors`. To provide your own message formatter, override the static `formatMessage` property on these classes.\n\n  ```ts\n  CombinedGraphQLErrors.formatMessage = (\n    errors,\n    { result, defaultFormatMessage }\n  ) => {\n    return \"Some formatted message\";\n  };\n\n  CombinedProtocolErrors.formatMessage = (errors, { defaultFormatMessage }) => {\n    return \"Some formatted message\";\n  };\n  ```\n\n- [#12546](https://github.com/apollographql/apollo-client/pull/12546) [`5dffbbe`](https://github.com/apollographql/apollo-client/commit/5dffbbe407eb1d9adbcb0fff89f2d3a75dc1ad2b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a static `is` method to error types defined by Apollo Client. `is` makes it simpler to determine whether an error is a specific type, which can be helpful in cases where you'd like to narrow the error type in order to use specific properties from that error.\n\n  This change applies to the following error types:\n\n  - `CombinedGraphQLErrors`\n  - `CombinedProtocolErrors`\n  - `ServerError`\n  - `ServerParseError`\n  - `UnconventionalError`\n\n  **Example**\n\n  ```ts\n  import { CombinedGraphQLErrors } from \"@apollo/client\";\n\n  if (CombinedGraphQLErrors.is(error)) {\n    console.log(error.message);\n    error.errors.forEach((graphQLError) => console.log(graphQLError.message));\n  }\n  ```\n\n- [#12561](https://github.com/apollographql/apollo-client/pull/12561) [`99d72bf`](https://github.com/apollographql/apollo-client/commit/99d72bfdb38e3d9679f60b9acb065a84e3b42fd6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to detect if an error was an error was emitted from the link chain. This is useful if your application throws custom errors in other areas of the application and you'd like to differentiate them from errors emitted by the link chain itself.\n\n  To detect if an error was emitted from the link chain, use `LinkError.is`.\n\n  ```ts\n  import { LinkError } from \"@apollo/client\";\n\n  client.query({ query }).catch((error) => {\n    if (LinkError.is(error)) {\n      // This error originated from the link chain\n    }\n  });\n  ```\n\n### Patch Changes\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `variables` option used with various APIs are now enforced more consistently across the client when `TVariables` contains required variables. If required `variables` are not provided, TypeScript will now complain that it requires a `variables` option.\n\n  This change affects the following APIs:\n\n  - `client.query`\n  - `client.mutate`\n  - `client.subscribe`\n  - `client.watchQuery`\n  - `useBackgroundQuery`\n  - `useQuery`\n  - `useSubscription`\n  - `useSuspenseQuery`\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `variables` returned from `useLazyQuery`. When `called` is `false`, `variables` is now `Partial<TVariables>` instead of `TVariables`.\n\n- [#12562](https://github.com/apollographql/apollo-client/pull/12562) [`90bf0e6`](https://github.com/apollographql/apollo-client/commit/90bf0e61516a382182f212ac8ab891099e2eb009) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.query` no longer supports `notifyOnNetworkStatusChange` in options. An error will be thrown if this option is set. The effects of this option were not observable by `client.query` since `client.query` emits a single result.\n\n- [#12557](https://github.com/apollographql/apollo-client/pull/12557) [`51d26ae`](https://github.com/apollographql/apollo-client/commit/51d26ae631c6631a189c98ea9357b18e77a9a876) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update format of the error message for `CombinedGraphQLErrors` and `CombinedProtocolErrors` to be more like v3.x.\n\n  ```diff\n  console.log(error.message);\n  - `The GraphQL server returned with errors:\n  - - Email not found\n  - - Username already in use`\n  + `Email not found\n  + Username already in use`\n  ```\n\n- [#12559](https://github.com/apollographql/apollo-client/pull/12559) [`49ace0e`](https://github.com/apollographql/apollo-client/commit/49ace0e2119b7fd5997dcf051002ebd4ba2e0bc4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.variables` has been updated to return `TVariables` rather than `TVariables | undefined`. This is more consistent with the runtime value where an empty object (`{}`) will be returned when the `variables` option is not provided.\n\n## 4.0.0-alpha.9\n\n### Major Changes\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - An initial loading state is now emitted from `ObservableQuery` when subscribing if `notifyOnNetworkStatusChange` is set to `true`.\n\n- [#12512](https://github.com/apollographql/apollo-client/pull/12512) [`e809b71`](https://github.com/apollographql/apollo-client/commit/e809b71aa9a02917a286afdbb03d5be8e5947c53) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `notifyOnNetworkStatusChange` now defaults to `true`. This means that loading states will be emitted (core API) or rendered (React) by default when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n  ```ts\n  new ApolloClient({\n    defaultOptions: {\n      watchQuery: {\n        // Use the v3 default\n        notifyOnNetworkStatusChange: false,\n      },\n    },\n  });\n  ```\n\n### Patch Changes\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The returned `networkStatus` in `useLazyQuery` is now set to `setVariables` when calling the `useLazyQuery` `execute` function for the first time with variables.\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `ObservableQuery` stops polling if switching to a `standby` `fetchPolicy`. When switching back to a non-`standby` `fetchPolicy`, polling will resume.\n\n- [#12536](https://github.com/apollographql/apollo-client/pull/12536) [`e14205a`](https://github.com/apollographql/apollo-client/commit/e14205ad5909f95aa04684acd0ca2f25956ee50c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure a loading state is emitted when calling the `execute` function after changing clients in `useLazyQuery`.\n\n- [#12542](https://github.com/apollographql/apollo-client/pull/12542) [`afb4fce`](https://github.com/apollographql/apollo-client/commit/afb4fce08859b2c6eebf288230a7c35b7acf2da6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `useLazyQuery` does not return a `partial` property which is not specified by the result type.\n\n## 4.0.0-alpha.8\n\n### Major Changes\n\n- [#12539](https://github.com/apollographql/apollo-client/pull/12539) [`dd0d6d6`](https://github.com/apollographql/apollo-client/commit/dd0d6d6d96d8b810e30dc2fdee2ac8a2477d0017) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `onError` link now uses a single `error` property to report the error that caused the link callback to be called. This will be an instance of `CombinedGraphQLErrors` in the event GraphQL errors were emitted from the terminating link, `CombinedProtocolErrors` if the terminating link emitted protocol errors, or the unwrapped error type if any other non-GraphQL error was thrown or emitted.\n\n  ```diff\n  - const errorLink = onError(({ graphQLErrors, networkError, protocolErrors }) => {\n  -   graphQLErrors.forEach(error => console.log(error.message));\n  + const errorLink = onError(({ error }) => {\n  +   if (error.name === 'CombinedGraphQLErrors') {\n  +     error.errors.forEach(rawError => console.log(rawError.message));\n  +   }\n  });\n  ```\n\n- [#12533](https://github.com/apollographql/apollo-client/pull/12533) [`73221d8`](https://github.com/apollographql/apollo-client/commit/73221d87bd5640986f86fe3ee50c63ed49834cbb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `onError` and `setOnError` methods from `ApolloLink`. `onError` was only used by `MockLink` to rewrite errors if `setOnError` was used.\n\n- [#12531](https://github.com/apollographql/apollo-client/pull/12531) [`7784b46`](https://github.com/apollographql/apollo-client/commit/7784b46117a4f91a270a020ed1a24f042cb9ee17) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Mocked responses passed to `MockLink` now accept a callback for the `request.variables` option. This is used to determine if the mock should be matched for a set of request variables. With this change, the `variableMatcher` option has been removed in favor of passing a callback to `variables`. Update by moving the callback function from `variableMatcher` to `request.variables`.\n\n  ```diff\n  new MockLink([\n    {\n      request: {\n        query,\n  +     variables: (requestVariables) => true\n      },\n  -   variableMatcher: (requestVariables) => true\n    }\n  ]);\n  ```\n\n- [#12526](https://github.com/apollographql/apollo-client/pull/12526) [`391af1d`](https://github.com/apollographql/apollo-client/commit/391af1dd733219b7e1e14cfff9d5e3ce3967242f) Thanks [@phryneas](https://github.com/phryneas)! - The `@apollo/client` and `@apollo/client/core` entry points are now equal.\n  In the next major, the `@apollo/client/core` entry point will be removed.\n  Please change imports over from `@apollo/client/core` to `@apollo/client`.\n\n- [#12525](https://github.com/apollographql/apollo-client/pull/12525) [`8785186`](https://github.com/apollographql/apollo-client/commit/87851863b94eebbc208671b17aeca73748ac41f6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Throw an error when a client-only query is used in a mocked response passed to `MockLink`.\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default the `delay` for all mocked responses passed to `MockLink` using `realisticDelay`. This ensures your test handles loading states by default and is not reliant on a specific timing.\n\n  If you would like to restore the old behavior, use a global default delay of `0`.\n\n  ```ts\n  MockLink.defaultOptions = {\n    delay: 0,\n  };\n  ```\n\n- [#12530](https://github.com/apollographql/apollo-client/pull/12530) [`2973e2a`](https://github.com/apollographql/apollo-client/commit/2973e2a6e6fd81fa59b769d84c252c98ca69440d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `newData` option for mocked responses passed to `MockLink` or the `mocks` option on `MockedProvider`. This option was undocumented and was nearly identical to using the `result` option as a callback.\n\n  To replicate the old behavior of `newData`, use `result` as a callback and add the `maxUsageCount` option with a value set to `Number.POSITIVE_INFINITY`.\n\n  **with `MockLink`**\n\n  ```diff\n  new MockLink([\n    {\n      request: { query, variables },\n  -   newData: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +   result: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +   maxUsageCount: Number.POSITIVE_INFINITY,\n    }\n  ])\n  ```\n\n  **with `MockedProvider`**\n\n  ```diff\n  <MockedProvider\n    mocks={[\n      {\n        request: { query, variables },\n  -     newData: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +     result: (variables) => ({ data: { greeting: \"Hello \" + variables.greeting } }),\n  +     maxUsageCount: Number.POSITIVE_INFINITY,\n      }\n    ]}\n  />\n  ```\n\n### Minor Changes\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow mocked responses passed to `MockLink` to accept a callback for the `delay` option. The `delay` callback will be given the current operation which can be used to determine what delay should be used for the mock.\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduce a new `realisticDelay` helper function for use with the `delay` callback for mocked responses used with `MockLink`. `realisticDelay` will generate a random value between 20 and 50ms to provide an experience closer to unpredictable network latency. `realisticDelay` can be configured with a `min` and `max` to set different thresholds if the defaults are not sufficient.\n\n  ```ts\n  import { realisticDelay } from \"@apollo/client/testing\";\n\n  new MockLink([\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: realisticDelay(),\n    },\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: realisticDelay({ min: 10, max: 100 }),\n    },\n  ]);\n  ```\n\n- [#12532](https://github.com/apollographql/apollo-client/pull/12532) [`ae0dcad`](https://github.com/apollographql/apollo-client/commit/ae0dcad89924e6b8090ca3182df30e528589b562) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add ability to specify a default `delay` for all mocked responses passed to `MockLink`. This `delay` can be configured globally (all instances of `MockLink` will use the global defaults), or per-instance (all mocks in a single instance will use the defaults). A `delay` defined on a single mock will supercede all default delays. Per-instance defaults supercede global defaults.\n\n  **Global defaults**\n\n  ```ts\n  MockLink.defaultOptions = {\n    // Use a default delay of 20ms for all mocks in all instances without a specified delay\n    delay: 20,\n\n    // altenatively use a callback which will be executed for each mock\n    delay: () => getRandomNumber(),\n\n    // or use the built-in `realisticDelay`. This is the default\n    delay: realisticDelay(),\n  };\n  ```\n\n  **Per-instance defaults**\n\n  ```ts\n  new MockLink(\n    [\n      // Use the default delay\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello\" } },\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello\" } },\n        // Override the default for this mock\n        delay: 10,\n      },\n    ],\n    {\n      defaultOptions: {\n        // Use a default delay of 20ms for all mocks without a specified delay\n        delay: 20,\n\n        // altenatively use a callback which will be executed for each mock\n        delay: () => getRandomNumber(),\n\n        // or use the built-in `realisticDelay`. This is the default\n        delay: realisticDelay(),\n      },\n    }\n  );\n  ```\n\n## 4.0.0-alpha.7\n\n### Major Changes\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `@apollo/client/react/context` and `@apollo/client/react/hooks` entry points. Please use `@apollo/client/react` instead.\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `@apollo/client/react/parser` entry point. There is no replacement.\n\n### Patch Changes\n\n- [#12513](https://github.com/apollographql/apollo-client/pull/12513) [`9c3207c`](https://github.com/apollographql/apollo-client/commit/9c3207c44ddad1f8b845c09495d6c070ace8de7b) Thanks [@phryneas](https://github.com/phryneas)! - Removed the `parser` cache. The functionality has been replaced in a way that doesn't need caching.\n\n## 4.0.0-alpha.6\n\n### Major Changes\n\n- [#12485](https://github.com/apollographql/apollo-client/pull/12485) [`d338303`](https://github.com/apollographql/apollo-client/commit/d3383033d306b7d66e90f5f3170c24453cd76464) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Throw an error for queries and mutations if the link chain completes without emitting a value.\n\n- [#12484](https://github.com/apollographql/apollo-client/pull/12484) [`9a8b9ce`](https://github.com/apollographql/apollo-client/commit/9a8b9cebbcf290984a4f154f261a4090e636e50e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `loading`, `networkStatus`, and `partial` properties on all promise-based query APIs. These properties were mostly static and were unnecessary since promise resolution guaranteed that the query was not longer loading.\n\n  This affects the following APIs:\n\n  - `client.query`\n  - `client.refetchQueries`\n  - `client.reFetchObservableQueries`\n  - `client.resetStore`\n  - `observableQuery.fetchMore`\n  - `observableQuery.refetch`\n  - `observableQuery.reobserve`\n  - `observableQuery.setVariables`\n  - The `useLazyQuery` `execute` function\n\n### Minor Changes\n\n- [#12497](https://github.com/apollographql/apollo-client/pull/12497) [`ff2cbe1`](https://github.com/apollographql/apollo-client/commit/ff2cbe1db1815c30f5fda7f6c07091663e065582) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `data` property to `CombinedGraphQLErrors` that captures any partial data returned by the GraphQL response when `errors` are also returned.\n\n- [#12488](https://github.com/apollographql/apollo-client/pull/12488) [`c98b633`](https://github.com/apollographql/apollo-client/commit/c98b6335de5b15e546aa5db79a8cf2dc9d914dcf) Thanks [@phryneas](https://github.com/phryneas)! - Add a new method for static SSR of React components, `prerenderStatic`.\n  The old methods, `getDataFromTree`, `getMarkupFromTree` and `renderToStringWithData`\n  have been deprecated in favor of `prerenderStatic`.\n\n  If used with React 19 and the `prerender` or `prerenderToNodeStream` apis from\n  `react-dom/static`, this method can now be used to SSR-prerender suspense-enabled\n  hook APIs.\n\n## 4.0.0-alpha.5\n\n### Major Changes\n\n- [#12478](https://github.com/apollographql/apollo-client/pull/12478) [`5ea6a45`](https://github.com/apollographql/apollo-client/commit/5ea6a45b3ec2f0d526abe78ae03c42bb519f87c7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `variables` from the result returned from `useSubscription`.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions now emit a `SubscribeResult` instead of a `FetchResult`. As a result, the `errors` field has been removed in favor of `error`.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unify error behavior on mutations for GraphQL errors and network errors by ensuring network errors are subject to the `errorPolicy`. Network errors created when using an `errorPolicy` of `all` will now resolve the promise and be returned on the `error` property of the result, or stripped away when the `errorPolicy` is `none`.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `client.mutate` now returns a `MutateResult` instead of `FetchResult`. As a result, the `errors` property has been removed in favor of `error` which is set if either a network error occured or GraphQL errors are returned from the server.\n\n  `useMutation` now also returns a `MutateResult` instead of a `FetchResult`.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Mutations no longer report errors if the GraphQL result from the server contains an empty array of errors.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unify error behavior on subscriptions for GraphQL errors and network errors by ensuring network errors are subject to the `errorPolicy`. Network errors that terminate the connection will now be emitted on the `error` property passed to the `next` callback followed by a call to the `complete` callback.\n\n- [#12478](https://github.com/apollographql/apollo-client/pull/12478) [`5ea6a45`](https://github.com/apollographql/apollo-client/commit/5ea6a45b3ec2f0d526abe78ae03c42bb519f87c7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `onSubscriptionData` and `onSubscriptionComplete` callbacks from `useSubscription`. Use `onData` and `onComplete` instead.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - GraphQL errors or network errors emitted while using an `errorPolicy` of `ignore` in subscriptions will no longer emit a result if there is no `data` emitted along with the error.\n\n- [#12476](https://github.com/apollographql/apollo-client/pull/12476) [`6afff60`](https://github.com/apollographql/apollo-client/commit/6afff60beece953406af2cbe07f7ccbf973cadaa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions no longer emit errors in the `error` callback and instead provide errors on the `error` property on the result passed to the `next` callback. As a result, errors will no longer automatically terminate the connection allowing additional results to be emitted when the connection stays open.\n\n  When an error terminates the downstream connection, a `next` event will be emitted with an `error` property followed by a `complete` event instead.\n\n### Minor Changes\n\n- [#12487](https://github.com/apollographql/apollo-client/pull/12487) [`b695e5e`](https://github.com/apollographql/apollo-client/commit/b695e5e10ab0eb47948e914b610f67c40267349e) Thanks [@phryneas](https://github.com/phryneas)! - Split out SSR-specific code from useQuery hook, remove RenderPromises\n\n### Patch Changes\n\n- [#12487](https://github.com/apollographql/apollo-client/pull/12487) [`b695e5e`](https://github.com/apollographql/apollo-client/commit/b695e5e10ab0eb47948e914b610f67c40267349e) Thanks [@phryneas](https://github.com/phryneas)! - `useQuery` with `ssr: false` - previously, `skip` had a higher priortity than `ssr: false` while `ssr: false` had a higher priority than `fetchPolicy: \"standby\"` (which is roughly equivalent to `skip`).\n\n  This priority has been adjusted so now both `skip` and `fetchPolicy: \"standby\"` have a higher priority than `ssr: false` and will return `loading: false`, while `ssr: false` will only come after those and will return `loading: true` if those are not set.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where passing `onError` to `useMutation` would resolve the promise returned by the `mutate` function instead of rejecting when using an `errorPolicy` of `none`.\n\n- [#12475](https://github.com/apollographql/apollo-client/pull/12475) [`3de63eb`](https://github.com/apollographql/apollo-client/commit/3de63ebcdf95a87adc31e6b4a39cae5391ed945a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where additional response properties were returned on the result returned from `client.mutate`, such as `@defer` payload fields. These properties are now stripped out to correspond to the TypeScript type.\n\n## 4.0.0-alpha.4\n\n### Major Changes\n\n- [#12463](https://github.com/apollographql/apollo-client/pull/12463) [`3868df8`](https://github.com/apollographql/apollo-client/commit/3868df81f973dc7b5a79fadf4dc1b0e291003b7f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.setOptions` has been removed as it was an alias of `reobserve`. Prefer using `reobserve` directly instead.\n\n  ```diff\n  const observable = client.watchQuery(options);\n\n  // Use reobserve to set new options and reevaluate the query\n  - observable.setOptions(newOptions);\n  + observable.reobserve(newOptions);\n  ```\n\n  As a result of this change, `reobserve` has been marked for public use and is no longer considered an internal API. The `newNetworkStatus` argument has been removed to facilitate this change.\n\n- [#12470](https://github.com/apollographql/apollo-client/pull/12470) [`d32902f`](https://github.com/apollographql/apollo-client/commit/d32902f26a4c5dea30421ee52aeea52df3e5334e) Thanks [@phryneas](https://github.com/phryneas)! - `ssrMode`, `ssrForceFetchDelay` and `disableNetworkFetches` have been reworked:\n\n  Previously, a `ObservableQuery` created by `client.query` or `client.watchQuery`\n  while one of those were active would permanently be changed from a `fetchPolicy`\n  of `\"network-only\"` or `\"cache-and-network\"` to `\"cache-first\"`, and stay that way\n  even long after `disableNetworkFetches` would have been deactivated.\n\n  Now, the `ObservableQuery` will keep their original `fetchPolicy`, but queries\n  made during `disableNetworkFetches` will just apply the `fetchPolicy` replacement\n  at request time, just for that one request.\n\n  `ApolloClient.disableNetworkFetches` has been renamed to `ApolloClient.prioritizeCacheValues` to better reflect this behaviour.\n\n- [#12465](https://github.com/apollographql/apollo-client/pull/12465) [`a132163`](https://github.com/apollographql/apollo-client/commit/a1321637cafb4023d6df416e9467294114d8346b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Flatten out React hook types. As a result, the base types have been removed. Prefer using the hook types instead. Removed types include:\n\n  - `BaseMutationOptions`\n  - `BaseQueryOptions`\n  - `BaseSubscriptionOptions`\n  - `ObservableQueryFields`\n  - `MutationSharedOptions`\n  - `QueryFunctionOptions`\n\n- [#12463](https://github.com/apollographql/apollo-client/pull/12463) [`3868df8`](https://github.com/apollographql/apollo-client/commit/3868df81f973dc7b5a79fadf4dc1b0e291003b7f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useQuery` no longer returns `reobserve` as part of its result. It was possible to use `reobserve` to set new options on the underlying `ObservableQuery` instance which differed from the options passed to the hook. This could result in unexpected results. Instead prefer to rerender the hook with new options.\n\n### Patch Changes\n\n- [#12465](https://github.com/apollographql/apollo-client/pull/12465) [`a132163`](https://github.com/apollographql/apollo-client/commit/a1321637cafb4023d6df416e9467294114d8346b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Rename all React hook result types and options. These types have all moved under a namespace that matches the hook name. For example, `useQuery` exports `useQuery.Options` and `useQuery.Result` types. As such, the old hook types have been deprecated and will be removed in v5.\n\n## 4.0.0-alpha.3\n\n### Major Changes\n\n- [#12457](https://github.com/apollographql/apollo-client/pull/12457) [`32e85ea`](https://github.com/apollographql/apollo-client/commit/32e85ea9eb93c1ffb10d6f70e9e2775e1326e9aa) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Network errors triggered by queries now adhere to the `errorPolicy`. This means that GraphQL errors and network errors now behave the same way. Previously promise-based APIs, such as `client.query`, would reject the promise with the network error even if `errorPolicy` was set to `ignore`. The promise is now resolved with the `error` property set to the network error instead.\n\n- [#12464](https://github.com/apollographql/apollo-client/pull/12464) [`0595f39`](https://github.com/apollographql/apollo-client/commit/0595f39deba52ac43fa0780b742564134ec7ab89) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `called` property from `useQuery`.\n\n## 4.0.0-alpha.2\n\n### Major Changes\n\n- [#12450](https://github.com/apollographql/apollo-client/pull/12450) [`876d070`](https://github.com/apollographql/apollo-client/commit/876d07042cf3348b3769b2bb415aa5f70ce9844c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `TSerialized` generic argument to `ApolloCache`. The `ApolloCache` base cache abstraction now returns `unknown` for `cache.extract` which can be overridden by a cache subclass.\n\n- [#12450](https://github.com/apollographql/apollo-client/pull/12450) [`876d070`](https://github.com/apollographql/apollo-client/commit/876d07042cf3348b3769b2bb415aa5f70ce9844c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `TCacheShape` generic argument to `ApolloClient`. `client.extract()` now returns `unknown` by default. You will either need to type-cast this to the expected serialized shape, or use the `cache.extract()` directly from the subclass to get more specific types.\n\n- [#12446](https://github.com/apollographql/apollo-client/pull/12446) [`ab920d2`](https://github.com/apollographql/apollo-client/commit/ab920d2701aa276482dbc78b44a1c25c76467bc9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `defaultOptions` option from `useQuery`. Use options directly or use the global `ApolloClient` `defaultOptions`.\n\n- [#12442](https://github.com/apollographql/apollo-client/pull/12442) [`c5ead08`](https://github.com/apollographql/apollo-client/commit/c5ead08d0f10ddd6232b742defe9620533bf41e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `canonizeResults` option. It was prone to memory leaks. As such, some results that were referentially equal when `canonizeResults` option was set to `true` no longer retain the same object identity.\n\n- [#12442](https://github.com/apollographql/apollo-client/pull/12442) [`c5ead08`](https://github.com/apollographql/apollo-client/commit/c5ead08d0f10ddd6232b742defe9620533bf41e6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `resetResultIdentities` option from `InMemoryCache.gc()`. This affected object canonization which has been removed.\n\n- [#12451](https://github.com/apollographql/apollo-client/pull/12451) [`77e1b13`](https://github.com/apollographql/apollo-client/commit/77e1b133bdba32c67b5a840090dbacb16282dee9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default the `TData` generic type to `unknown` in all APIs that use a `TData` generic argument such as `useQuery`, `client.query`, etc.\n\n### Patch Changes\n\n- [#12451](https://github.com/apollographql/apollo-client/pull/12451) [`77e1b13`](https://github.com/apollographql/apollo-client/commit/77e1b133bdba32c67b5a840090dbacb16282dee9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Default `TVariables` generic type to `OperationVariables` instead of `any` throughout the client in areas that did not yet have the default as such.\n\n- [#12454](https://github.com/apollographql/apollo-client/pull/12454) [`925548a`](https://github.com/apollographql/apollo-client/commit/925548a9baadb19b7bb78ee84c6f9e64b55c39e9) Thanks [@phryneas](https://github.com/phryneas)! - Fix up the 4.0 CommonJS build\n\n## 4.0.0-alpha.1\n\n### Major Changes\n\n- [#12433](https://github.com/apollographql/apollo-client/pull/12433) [`b86e50b`](https://github.com/apollographql/apollo-client/commit/b86e50b1dc121cd67fe73655256b6c61afc18cb4) Thanks [@phryneas](https://github.com/phryneas)! - Remove workarounds for streaming with non-WhatWG response bodies to reduce bundle size.\n\n  This removes support for `fetch` implementations that return Node Streams, Async Iterators or Blob instances as `Response.body`.\n\n  In the WhatWG Fetch specification, [`Response.body`](https://fetch.spec.whatwg.org/#body) is specified as a WhatWG [ReadableStream](https://streams.spec.whatwg.org/#readablestream).\n\n  At this point in time, this is natively supported in browsers, `node` and React Native (via [react-native-fetch-api](https://www.npmjs.com/package/react-native-fetch-api), see our [setup instructions for React Native](https://www.apollographql.com/docs/react/integrations/react-native#consuming-multipart-http-via-text-streaming)).\n\n  If you are using an older `fetch` polyfill that deviates from the spec, this might not be compatible - for example, [node-fetch](https://github.com/node-fetch/node-fetch?tab=readme-ov-file#interface-body) returns a node `Readable` instead of a `ReadableStream`.\n  In those cases, please switch to a compatible alternative such as the `node`-native `fetch`, or `undici`.\n\n### Minor Changes\n\n- [#12438](https://github.com/apollographql/apollo-client/pull/12438) [`5089516`](https://github.com/apollographql/apollo-client/commit/5089516aa3ad140df22bb8a458faeeb884ed0388) Thanks [@phryneas](https://github.com/phryneas)! - Drop `rehackt` dependency.\n  We can now directly import from `react` without causing build errors in RSC.\n\n- [#12437](https://github.com/apollographql/apollo-client/pull/12437) [`4779dc7`](https://github.com/apollographql/apollo-client/commit/4779dc7badaba10d8c7a271eb0da6a079049b65d) Thanks [@phryneas](https://github.com/phryneas)! - Remove polyfills for Object.freeze,seal and preventExtensions in React Native\n\n  These polyfills were only necessary until React Native 0.59, which\n  [patched the problem](https://github.com/facebook/react-native/pull/21492) on\n  the React Native side.\n\n  With React Native 0.61, the `Map` function was [completely replaced](https://github.com/facebook/react-native/commit/93b9ac74e59bbe84ea388d7c1879857b4acab114)\n  with a native implementation that never had the problems we guarded against.\n\n- [#12438](https://github.com/apollographql/apollo-client/pull/12438) [`5089516`](https://github.com/apollographql/apollo-client/commit/5089516aa3ad140df22bb8a458faeeb884ed0388) Thanks [@phryneas](https://github.com/phryneas)! - Add `react-server` entry point with stubs for normal exports.\n\n## 4.0.0-alpha.0\n\n### Major Changes\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `asyncMap` utility function. Instead use one of the RxJS operators that creates Observables from promises, such as `from`.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `isApolloError` utility function to check if the error object is an `ApolloError` instance. Use `instanceof` to check for more specific error types that replace `ApolloError`.\n\n- [#12379](https://github.com/apollographql/apollo-client/pull/12379) [`ef892b4`](https://github.com/apollographql/apollo-client/commit/ef892b4dc505b02049525f9aba32c51f1c00c922) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `addTypename` option from `InMemoryCache` and `MockedProvider`. `__typename` is now always added to the outgoing query document when using `InMemoryCache` and cannot be disabled.\n\n  If you are using `<MockedProvider />` with `addTypename={false}`, ensure that your mocked responses include a `__typename` field. This will ensure cache normalization kicks in and behaves more like production.\n\n- [#12396](https://github.com/apollographql/apollo-client/pull/12396) [`00f3d0a`](https://github.com/apollographql/apollo-client/commit/00f3d0a674eede1f909092283041cf8ac8d1b576) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `errors` property from `useQuery` and `useLazyQuery`. Read errors from the `error` property instead.\n\n- [#12222](https://github.com/apollographql/apollo-client/pull/12222) [`d1a9054`](https://github.com/apollographql/apollo-client/commit/d1a905461d4378522c3257de00afba2ae8decd22) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Drop support for React 16.\n\n- [#12376](https://github.com/apollographql/apollo-client/pull/12376) [`a0c996a`](https://github.com/apollographql/apollo-client/commit/a0c996a816fbb6a2323231c0422d1c8a3e20cbaf) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `ignoreResults` option from `useMutation`. If you don't want to synchronize component state with the mutation, use `useApolloClient` to access your client instance and use `client.mutate` directly.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Unusubscribing from `ObservableQuery` while a request is in flight will no longer terminate the request by unsubscribing from the link observable.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `previousData` property on `useLazyQuery` will now change only when `data` changes. Previously `previousData` would change to the same value as `data` while the query was loading.\n\n- [#12224](https://github.com/apollographql/apollo-client/pull/12224) [`51e6c0f`](https://github.com/apollographql/apollo-client/commit/51e6c0f8657d20cedc570c6e9a244f877047dd61) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove deprecated `partialRefetch` option.\n\n- [#12407](https://github.com/apollographql/apollo-client/pull/12407) [`8b1390b`](https://github.com/apollographql/apollo-client/commit/8b1390bf0050c6bd4d5a32b67c3b96369d0552d4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Calling `refetch` with new variables will now set the `networkStatus` to `refetch` instead of `setVariables`.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `iterateObserversSafely` utility function.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Apollo Client no longer wraps errors in `ApolloError`. `ApolloError` has been replaced with separate error classes depending on the cause of the error. As such, APIs that return an `error` property have been updated to use the generic `Error` type. Use `instanceof` to check for more specific error types.\n\n  ## Migration guide\n\n  `ApolloError` encapsulated 4 main error properties. The type of error would determine which property was set:\n\n  - `graphqlErrors` - Errors returned from the `errors` field by the GraphQL server\n  - `networkError` - Any non-GraphQL error that caused the query to fail\n  - `protocolErrors` - Transport-level errors that occur during [multipart HTTP subscriptions](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol)\n  - `clientErrors` - A space to define custom errors. Mostly unused.\n\n  These errors were mutally exclusive, meaning both `networkError` and `graphqlErrors` were never set simultaneously. The following replaces each of these fields from `ApolloError`.\n\n  ### `graphqlErrors`\n\n  GraphQL errors are now encapsulated in a `CombinedGraphQLErrors` instance. You can access the raw GraphQL errors via the `errors` property.\n\n  ```js\n  import { CombinedGraphQLErrors } from \"@apollo/client\";\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  if (error && error instanceof CombinedGraphQLErrors) {\n    console.log(error.errors);\n  }\n  ```\n\n  ### `networkError`\n\n  Network errors are no longer wrapped and are instead passed through directly.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error(new Error(\"Test error\"));\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // error is `new Error('Test error')`;\n  ```\n\n  ### `protocolErrors`\n\n  Protocol errors are now encapsulated in a `CombinedProtocolErrors` instance. You can access the raw protocol errors via the `errors` property.\n\n  ```js\n  import { CombinedProtocolErrors } from \"@apollo/client\";\n\n  // ...\n\n  const { error } = useSubscription(subscription);\n\n  if (error && error instanceof CombinedProtocolErrors) {\n    console.log(error.errors);\n  }\n  ```\n\n  ### `clientErrors`\n\n  These were unused by the client and have no replacement. Any non-GraphQL or non-protocol errors are now passed through unwrapped.\n\n  ### Strings as errors\n\n  If the link sends a string error, Apollo Client will wrap this in an `Error` instance. This ensures `error` properties are guaranteed to be of type `Error`.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        // Oops we sent a string instead of wrapping it in an `Error`\n        observer.error(\"Test error\");\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // The error string is wrapped and returned as `new Error('Test error')`;\n  ```\n\n  ### Non-error types\n\n  If the link chain sends any other object type as an error, Apollo Client will wrap this in an `UnknownError` instance with the [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) set to the original object. This ensures `error` properties are guaranteed to be of type `Error`.\n\n  ```js\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error({ message: \"Not a proper error type\" });\n      });\n    }),\n  });\n\n  // ...\n\n  const { error } = useQuery(query);\n\n  // error is an `UnknownError` instance. error.cause returns the original object.\n  ```\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `fromError` utility function. Use [`throwError`](https://rxjs.dev/api/index/function/throwError) instead.\n\n- [#12211](https://github.com/apollographql/apollo-client/pull/12211) [`c2736db`](https://github.com/apollographql/apollo-client/commit/c2736db3ad6f8b6e56f065682d5b76614f41bfd4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `graphql`, `withQuery`, `withMutation`, `withSubscription`, and `withApollo` hoc components. Use the provided React hooks instead.\n\n- [#12262](https://github.com/apollographql/apollo-client/pull/12262) [`10ef733`](https://github.com/apollographql/apollo-client/commit/10ef7338cdcbbaf75d806f426e9708c9e095c2da) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `itAsync` test utility.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Updates the `ServerError` and `ServerParseError` types to be proper `Error` subclasses. Perviously these were plain `Error` intances with additional properties added at runtime. All properties are retained, but `instanceof` checks now work correctly.\n\n  ```js\n  import { ServerError, ServerParseError } from \"@apollo/client\";\n\n  if (error instanceof ServerError) {\n    // ...\n  }\n\n  if (error instanceof ServerParseError) {\n    // ...\n  }\n  ```\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports SSR environments and will now throw if the `execute` function is called in SSR. If you need to run a query in an SSR environment, use `useQuery` instead.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The execute function returned from `useLazyQuery` now only supports the `context` and `variables` options. This means that passing options supported by the hook no longer override the hook value.\n\n  To change options, rerender the component with new options. These options will take effect with the next query execution.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery` will no longer terminate on errors and will instead emit a `next` value with an `error` property. This ensures that `ObservableQuery` instances can continue to receive updates after errors are returned in requests without the need to resubscribe to the observable.\n\n- [#12398](https://github.com/apollographql/apollo-client/pull/12398) [`8cf5077`](https://github.com/apollographql/apollo-client/commit/8cf5077bed1ab46fdd32c5e253071506c0076064) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `throwServerError` utility function. Now that `ServerError` is an\n  `Error` subclass, you can throw these errors directly:\n\n  ```js\n  import { ServerError } from \"@apollo/client\";\n\n  // instead of\n  throwServerError(response, result, \"error message\");\n\n  // Use\n  throw new ServerError(\"error message\", { response, result });\n  ```\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `Cache.DiffResult<T>` type is now a union type with better type safety for both complete and partial results. Checking `diff.complete` will now narrow the type of `result` depending on whether the value is `true` or `false`.\n\n  When `true`, `diff.result` will be a non-null value equal to the `T` generic type. When `false`, `diff.result` now reports `result` as `DeepPartial<T> | null` indicating that fields in the result may be missing (`DeepPartial<T>`) or empty entirely (`null`).\n\n- [#12396](https://github.com/apollographql/apollo-client/pull/12396) [`00f3d0a`](https://github.com/apollographql/apollo-client/commit/00f3d0a674eede1f909092283041cf8ac8d1b576) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `errors` property from the results emitted from `ObservableQuery` or returned from `client.query`. Read errors from the `error` property instead.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The result resolved from the promise returned from the execute function in `useLazyQuery` is now an `ApolloQueryResult` type and no longer includes all the fields returned from the `useLazyQuery` hook tuple.\n\n  If you need access to the additional properties such as `called`, `refetch`, etc. not included in `ApolloQueryResult`, read them from the hook instead.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` will no longer rerender with the loading state when calling the execute function the first time unless the `notifyOnNetworkStatusChange` option is set to `true` (which is the new default).\n\n  If you prefer the behavior from 3.x, rerender the component with\n  `notifyOnNetworkStatusChange` set to `false` after the execute function is\n  called the first time.\n\n  ```ts\n  function MyComponent() {\n    const [notifyOnNetworkStatusChange, setNotifyOnNetworkStatusChange] =\n      useState(true);\n    const [execute] = useLazyQuery(query, { notifyOnNetworkStatusChange });\n\n    async function runExecute() {\n      await execute();\n\n      // Set to false after the initial fetch to stop receiving notifications\n      // about changes to the loading states.\n      setNotifyOnNetworkStatusChange(false);\n    }\n\n    // ...\n  }\n  ```\n\n- [#12254](https://github.com/apollographql/apollo-client/pull/12254) [`0028ac0`](https://github.com/apollographql/apollo-client/commit/0028ac0147aaea9ab559f15630200a132b43da42) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changes the default `Accept` header to `application/graphql-response+json`.\n\n- [#12430](https://github.com/apollographql/apollo-client/pull/12430) [`2ff66d0`](https://github.com/apollographql/apollo-client/commit/2ff66d06b6d444fbcb46e580ac40e673e695740f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `ObservableQuery.setVariables` will now resolve with the last emitted result instead of `undefined` when either the variables match the current variables or there are no subscribers to the query.\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - Apollo Client now defaults to production mode, not development mode, if the\n  environment cannot be determined.\n\n  In modern bundlers, this should automatically be handled by the bundler loading\n  the bundler with the `development` export condition.\n\n  If neither the `production` nor the `development` export condition are\n  used by the bundler/runtime, Apollo Client will fall back to `globalThis.__DEV__`\n  to determine if it should run in production or development mode.\n\n  Unlike Apollo Client 3 though, if `globalThis.__DEV__` is not set to `true`,\n  Apollo Client will now default to `production`, not to `development`, behaviour.\n\n  This switch to _explicilty_ requiring `true` also resolves a situation where\n  an HTML element with `id=\"__DEV__\"` would create a global `__DEV__` variable\n  with a referent to the DOM element, which in the past was picked up as \"truthy\" and\n  would have triggered development mode.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `reobserve` option is no longer available in the result returned from `useLazyQuery`. This was considered an internal API and should not be used directly.\n\n- [#12333](https://github.com/apollographql/apollo-client/pull/12333) [`3e4beaa`](https://github.com/apollographql/apollo-client/commit/3e4beaa8b768a893da80aae0428f79ee01d6aa38) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `data` property on `ApolloQueryResult`. Previously this field was non-optional, non-null `TData`, however at runtime this value could be set to `undefined`. This field is now reported as `TData | undefined`.\n\n  This will affect you in a handful of places:\n\n  - The `data` property emitted from the result passed to the `next` callback from `client.watchQuery`\n  - Fetch-based APIs that return an `ApolloQueryResult` type such as `observableQuery.refetch`, `observableQuery.fetchMore`, etc.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The promise returned when calling the execute function from `useLazyQuery` will now reject when using an `errorPolicy` of `none` when GraphQL errors are returned from the result.\n\n- [#12223](https://github.com/apollographql/apollo-client/pull/12223) [`69c1cb6`](https://github.com/apollographql/apollo-client/commit/69c1cb6f831941598987185238a299b050a364bd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `subscribeAndCount` testing utility from `@apollo/client/testing`.\n\n- [#12300](https://github.com/apollographql/apollo-client/pull/12300) [`4d581e4`](https://github.com/apollographql/apollo-client/commit/4d581e4f5a3c5409e5f06a5f164beabdada150f1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Moves all React-related exports to the `@apollo/client/react` entrypoint and out of the main `@apollo/client` entrypoint. This prevents the need to install React in order to use the core client.\n\n  The following is a list of exports available in `@apollo/client` that should now import from `@apollo/client/react`.\n\n  - `ApolloConsumer`\n  - `ApolloProvider`\n  - `createQueryPreloader`\n  - `getApolloContext`\n  - `skipToken`\n  - `useApolloClient`\n  - `useBackgroundQuery`\n  - `useFragment`\n  - `useLazyQuery`\n  - `useLoadableQuery`\n  - `useMutation`\n  - `useQuery`\n  - `useQueryRefHandlers`\n  - `useReactiveVar`\n  - `useReadQuery`\n  - `useSubscription`\n  - `useSuspenseQuery`\n\n  The following is a list of exports available in `@apollo/client/testing` that should now import from `@apollo/client/testing/react`:\n\n  - `MockedProvider`\n\n- [#12428](https://github.com/apollographql/apollo-client/pull/12428) [`abed922`](https://github.com/apollographql/apollo-client/commit/abed92225fd2a5d2a0a2298893a1170df1cd7400) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes the `urql` multipart subscriptions utilities. Use the native multipart subscriptions support in `urql` instead.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Switch to [RxJS](https://rxjs.dev/) as the observable implementation. `rxjs` is now a peer dependency of Apollo Client which means you will now need to install `rxjs` in addition to `@apollo/client`.\n\n  This change is mostly transparent, however transforming values on observables, common in link implementations, differs in RxJS vs `zen-observable`. For example, you could modify values in the link chain emitted from a downstream link by using the `.map` function. In RxJS, this is done with the `.pipe` function and passing a `map` operator instead.\n\n  ```ts\n  import { map } from \"rxjs\";\n\n  const link new ApolloLink((operation, forward) => {\n    return forward(operation).pipe(\n      map((result) => performTransform(result))\n    );\n  });\n  ```\n\n  For a full list of operators and comprehensive documentation on the capabilities of RxJS, check out the [documentation](https://rxjs.dev/).\n\n- [#12329](https://github.com/apollographql/apollo-client/pull/12329) [`61febe4`](https://github.com/apollographql/apollo-client/commit/61febe4ef8712a2035d7ac89ea7283138db5229d) Thanks [@phryneas](https://github.com/phryneas)! - Rework package publish format (#12329, #12382)\n\n  We have reworked the way Apollo Client is packaged.\n\n  - shipping ESM and CJS\n  - fixing up source maps\n  - the build targets a modern runtime environment (browserslist query: `\"since 2023, node >= 20, not dead\"`)\n  - removed the \"proxy directory\" `package.json` files, e.g. `cache/core/package.json` and `react/package.json`. While these helped with older build tools, modern build tooling uses the `exports` field in the root `package.json` instead and the presence of these files can confuse modern build tooling. If your build tooling still relies on those, please update your imports to import from e.g. `@apollo/client/cache/core/index.js` instead of `@apollo/client/cache/core` - but generally, this should not be necessary.\n  - added an `exports` field to `package.json` to expose entry points\n  - instead of `globalThis.__DEV__`, Apollo Client now primarily relies on the `development` and `production` exports conditions. It falls back to `globalThis.__DEV__` if the bundler doesn't know these, though.\n\n- [#12397](https://github.com/apollographql/apollo-client/pull/12397) [`2545a54`](https://github.com/apollographql/apollo-client/commit/2545a5415b06283be83eb9c4a03a3a8a39b8bcde) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `ObservableQuery.resetQueryStoreErrors` method. This method reset some internal state that was not consumed elsewhere in the client and resulted in a no-op.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `fromPromise` utility function. Use [`from`](https://rxjs.dev/api/index/function/from) instead.\n\n- [#12388](https://github.com/apollographql/apollo-client/pull/12388) [`0d825be`](https://github.com/apollographql/apollo-client/commit/0d825bef533b41f2e99ef22e620d9f9472825057) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Require environments that support `WeakMap`, `WeakSet` and symbols. Apollo Client would fallback to `Map` and `Set` if the weak versions were not available. This has been removed and expects that these features are available in the source environment.\n\n  If you are running in an environment without `WeakMap`, `WeakSet` or symbols, you will need to find appropriate polyfills.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports calling the execute function in render and will now throw. If you need to execute the query immediately, use `useQuery` instead or move the call to a `useEffect`.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - The `defaultOptions` and `initialFetchPolicy` options are no longer supported with `useLazyQuery`.\n\n  If you use `defaultOptions`, pass those options directly to the hook instead. If you use `initialFetchPolicy`, use `fetchPolicy` instead.\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` no longer supports `variables` in the hook options and therefore no longer performs variable merging. The execute function must now be called with `variables` instead.\n\n  ```ts\n  function MyComponent() {\n    const [execute] = useLazyQuery(query);\n\n    function runExecute() {\n      execute({ variables: { ... }});\n    }\n  }\n  ```\n\n  This change means the execute function returned from `useLazyQuery` is more type-safe. The execute function will require you to pass a `variables` option if the query type includes required variables.\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - ### Changes for users of `InMemoryCache`\n\n  `cache.diff` now returns `null` instead of an empty object (`{}`) when `returnPartialData` is `true` and the result is empty.\n\n  If you use `cache.diff` directly with `returnPartialData: true`, you will need to check for `null` before accessing any other fields on the `result` property. A non-null value indicates that at least one field was present in the cache for the given query document.\n\n  ### Changes for third-party cache implementations\n\n  The client now expects `cache.diff` to return `null` instead of an empty object when there is no data that can be fulfilled from the cache and `returnPartialData` is `true`. If your cache implementation returns an empty object, please update this to return `null`.\n\n- [#12430](https://github.com/apollographql/apollo-client/pull/12430) [`2ff66d0`](https://github.com/apollographql/apollo-client/commit/2ff66d06b6d444fbcb46e580ac40e673e695740f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Removes `ObservableQuery.result()` method. If you use this method and need similar functionality, use the `firstValueFrom` helper in RxJS.\n\n  ```ts\n  import { firstValueFrom, from } from \"rxjs\";\n\n  // The `from` is necessary to turn `observableQuery` into an RxJS observable\n  const result = await firstValueFrom(from(observableQuery));\n  ```\n\n- [#12359](https://github.com/apollographql/apollo-client/pull/12359) [`ebb4d96`](https://github.com/apollographql/apollo-client/commit/ebb4d9644104244fb066b93a32df778928f2f8a9) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the `onCompleted` and `onError` callbacks from `useQuery` and `useLazyQuery`.\n\n  See [#12352](https://github.com/apollographql/apollo-client/issues/12352) for more context on this change.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Subscriptions are no longer eagerly started after calling `client.subscribe`. To kick off the subscription, you will now need to subscribe to the returned observable.\n\n  ```ts\n  // Subscriptions are no longer started when calling subscribe on its own.\n  const subscriptionObservable = client.subscribe(...);\n\n  // Instead, subscribe to the returned observable to kick off the subscription.\n  subscriptionObservable.subscribe({\n    next: (value) => console.log(value)\n  });\n  ```\n\n- [#12367](https://github.com/apollographql/apollo-client/pull/12367) [`e6af35e`](https://github.com/apollographql/apollo-client/commit/e6af35ed30c732ad834e6c524bc9ce5adbe5f706) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useLazyQuery` will now only execute the query when the execute function is called. Previously `useLazyQuery` would behave like `useQuery` after the first call to the execute function which means changes to options might perform network requests.\n\n  You can now safely rerender `useLazyQuery` with new options which will take effect the next time you manually trigger the query.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `toPromise` utility function. Use [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom) instead.\n\n- [#12304](https://github.com/apollographql/apollo-client/pull/12304) [`86469a2`](https://github.com/apollographql/apollo-client/commit/86469a25abb72dbd68adff3554e3909036e77eee) Thanks [@jerelmiller](https://github.com/jerelmiller)! - ### Changes for users of `InMemoryCache`\n\n  `cache.diff` no longer throws when `returnPartialData` is set to `false` without a complete result. Instead, `cache.diff` will return `null` when it is unable to read a full cache result.\n\n  If you use `cache.diff` directly with `returnPartialData: false`, remove the `try`/`catch` block and replace with a check for `null`.\n\n  ### Changes for third-party cache implementations\n\n  The client now expects `cache.diff` to return `null` instead of throwing when the cache returns an incomplete result and `returnPartialData` is `false`. The internal `try`/`catch` blocks have been removed around `cache.diff`. If your cache implementation throws for incomplete results, please update this to return `null`.\n\n- [#12211](https://github.com/apollographql/apollo-client/pull/12211) [`c2736db`](https://github.com/apollographql/apollo-client/commit/c2736db3ad6f8b6e56f065682d5b76614f41bfd4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the deprecated `Query`, `Mutation`, and `Subscription` components. Use the provided React hooks instead.\n\n### Minor Changes\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - Apollo Client is no longer using `ts-invariant`, but ships with a modified variant of it.\n\n  The existing export `setLogVerbosity` from `@apollo/client` is still available and\n  now points to this new integration.\n  **In most cases, you should be using this export.**\n  It will no longer adjust the verbosity of `ts-invariant` and as such no longer\n  influence other packages relying on `ts-invariant`.\n\n  The new entry point `@apollo/client/utilities/invariant` now exports `invariant`,\n  `InvariantError` and `setVerbosity`.\n  (Note that these tools are mostly meant to be used by Apollo Client and libraries directly\n  based on Apollo Client like the `@apollo/client-integration-*` packages.)\n\n- [#12333](https://github.com/apollographql/apollo-client/pull/12333) [`3e4beaa`](https://github.com/apollographql/apollo-client/commit/3e4beaa8b768a893da80aae0428f79ee01d6aa38) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deprecate the `partial` flag on `ApolloQueryResult` and make it a non-optional property. Previously `partial` was only set conditionally if the result emitted was partial. This value is now available with all results that return an `ApolloQueryResult`.\n\n### Patch Changes\n\n- [#12291](https://github.com/apollographql/apollo-client/pull/12291) [`ae5d06a`](https://github.com/apollographql/apollo-client/commit/ae5d06ac45ca6584d3c79aa417dae22f37a7d3b6) Thanks [@phryneas](https://github.com/phryneas)! - Remove deprecated `resetApolloContext` export\n\n- [#12402](https://github.com/apollographql/apollo-client/pull/12402) [`903c3ef`](https://github.com/apollographql/apollo-client/commit/903c3ef9f77280492c298b4d8e5f96f110e3cda1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Use an an empty object (`{}`) rather than an object with `null` prototype (`Object.create(null)`) in all areas that instantiate objects.\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - \\* dropped the deprecated `DEV` export from `@apollo/client/utilities` and `@apollo/client/utilities/globals`\n\n  - moved the `__DEV__` export from `@apollo/client/utilities/globals` to `@apollo/client/utilities/environment`\n  - moved the `invariant`, `newInvariantError` and `InvariantError` exports from `@apollo/client/utilities/globals` to `@apollo/client/utilities/invariant`\n\n- [#12432](https://github.com/apollographql/apollo-client/pull/12432) [`c7c2f61`](https://github.com/apollographql/apollo-client/commit/c7c2f6122c874eed16d5621be26992f86d9756eb) Thanks [@phryneas](https://github.com/phryneas)! - ObservableQuery: implement the `rxjs` `InteropObservable` interface to ensure `from(observableQuery)` stays possible\n\n- [#12385](https://github.com/apollographql/apollo-client/pull/12385) [`cad5117`](https://github.com/apollographql/apollo-client/commit/cad511723a1b8b0ac2042cf49435f7affb0dc4e4) Thanks [@phryneas](https://github.com/phryneas)! - `@apollo/client`, `@apollo/client/core` and `@apollo/client/cache` no longer export an empty `Cache` runtime object. This is meant to be a type-only namespace.\n\n- [#12384](https://github.com/apollographql/apollo-client/pull/12384) [`6aa6fd3`](https://github.com/apollographql/apollo-client/commit/6aa6fd316cfdb31ebbe3e3133cca2965604e7ca1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't emit a partial cache result from `cache-only` queries when `returnPartialData` is `false`.\n\n## 3.14.0\n\n### Minor Changes\n\n- [#12752](https://github.com/apollographql/apollo-client/pull/12752) [`8b779b4`](https://github.com/apollographql/apollo-client/commit/8b779b428b9dc9dad3e78f02bba6646ff415631d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings to remaining APIs changed in Apollo Client 4.0.\n\n- [#12746](https://github.com/apollographql/apollo-client/pull/12746) [`0bcd2f4`](https://github.com/apollographql/apollo-client/commit/0bcd2f4ead372eb5928bbd5c00b0bd48e497a5e1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add warnings and deprecations for options and methods for all React APIs.\n\n- [#12751](https://github.com/apollographql/apollo-client/pull/12751) [`567cad8`](https://github.com/apollographql/apollo-client/commit/567cad8fcc30ac3b82560abc24970d33f160622e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `@deprecated` tags to all properties returned from any query API (e.g. `client.query`, `observableQuery.refetch`, etc.), `client.mutate`, and `client.subscribe` that are no longer available in Apollo Client 4.0.\n\n- [#12746](https://github.com/apollographql/apollo-client/pull/12746) [`0bcd2f4`](https://github.com/apollographql/apollo-client/commit/0bcd2f4ead372eb5928bbd5c00b0bd48e497a5e1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `preloadQuery.toPromise(queryRef)` as a replacement for `queryRef.toPromise()`. `queryRef.toPromise()` has been removed in Apollo Client 4.0 in favor of `preloadQuery.toPromise` and is now considered deprecated.\n\n- [#12736](https://github.com/apollographql/apollo-client/pull/12736) [`ea89440`](https://github.com/apollographql/apollo-client/commit/ea8944013278060ef87dfa4de6663a21b5204880) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and deprecation warnings for `ApolloClient` options and methods.\n\n- [#12763](https://github.com/apollographql/apollo-client/pull/12763) [`5de6a3d`](https://github.com/apollographql/apollo-client/commit/5de6a3d3189afa2a7c3bb2eb08d3c4394ae4a16d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only to release latest as `rc`.\n\n- [#12459](https://github.com/apollographql/apollo-client/pull/12459) [`1c5a031`](https://github.com/apollographql/apollo-client/commit/1c5a0313d388945aeda93b2c1992ad77f4416fa1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reset `addTypenameTransform` and `fragments` caches when calling `cache.gc()` only when `resetResultCache` is `true`.\n\n- [#12743](https://github.com/apollographql/apollo-client/pull/12743) [`92ad409`](https://github.com/apollographql/apollo-client/commit/92ad4097e5c83e0a780ede20db34e9e63fb98e8b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings for `addTypename` in `InMemoryCache` and `MockedProvider`.\n\n- [#12743](https://github.com/apollographql/apollo-client/pull/12743) [`92ad409`](https://github.com/apollographql/apollo-client/commit/92ad4097e5c83e0a780ede20db34e9e63fb98e8b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings for `canonizeResults`.\n\n- [#12751](https://github.com/apollographql/apollo-client/pull/12751) [`567cad8`](https://github.com/apollographql/apollo-client/commit/567cad8fcc30ac3b82560abc24970d33f160622e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using a `standby` fetch policy with `client.query`.\n\n### Patch Changes\n\n- [#12750](https://github.com/apollographql/apollo-client/pull/12750) [`ecf3de1`](https://github.com/apollographql/apollo-client/commit/ecf3de1cc9a2cf3aaeba0c945909324b9e4b478a) Thanks [@phryneas](https://github.com/phryneas)! - Prevent field policies from overwriting/merging into supertype field policies.\n\n## 3.14.0-rc.0\n\n### Minor Changes\n\n- [#12763](https://github.com/apollographql/apollo-client/pull/12763) [`5de6a3d`](https://github.com/apollographql/apollo-client/commit/5de6a3d3189afa2a7c3bb2eb08d3c4394ae4a16d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only to release latest as `rc`.\n\n## 3.14.0-alpha.1\n\n### Minor Changes\n\n- [#12752](https://github.com/apollographql/apollo-client/pull/12752) [`8b779b4`](https://github.com/apollographql/apollo-client/commit/8b779b428b9dc9dad3e78f02bba6646ff415631d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings to remaining APIs changed in Apollo Client 4.0.\n\n- [#12751](https://github.com/apollographql/apollo-client/pull/12751) [`567cad8`](https://github.com/apollographql/apollo-client/commit/567cad8fcc30ac3b82560abc24970d33f160622e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `@deprecated` tags to all properties returned from any query API (e.g. `client.query`, `observableQuery.refetch`, etc.), `client.mutate`, and `client.subscribe` that are no longer available in Apollo Client 4.0.\n\n- [#12751](https://github.com/apollographql/apollo-client/pull/12751) [`567cad8`](https://github.com/apollographql/apollo-client/commit/567cad8fcc30ac3b82560abc24970d33f160622e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using a `standby` fetch policy with `client.query`.\n\n## 3.14.0-alpha.0\n\n### Minor Changes\n\n- [#12746](https://github.com/apollographql/apollo-client/pull/12746) [`0bcd2f4`](https://github.com/apollographql/apollo-client/commit/0bcd2f4ead372eb5928bbd5c00b0bd48e497a5e1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add warnings and deprecations for options and methods for all React APIs.\n\n- [#12746](https://github.com/apollographql/apollo-client/pull/12746) [`0bcd2f4`](https://github.com/apollographql/apollo-client/commit/0bcd2f4ead372eb5928bbd5c00b0bd48e497a5e1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `preloadQuery.toPromise(queryRef)` as a replacement for `queryRef.toPromise()`. `queryRef.toPromise()` has been removed in Apollo Client 4.0 in favor of `preloadQuery.toPromise` and is now considered deprecated.\n\n- [#12736](https://github.com/apollographql/apollo-client/pull/12736) [`ea89440`](https://github.com/apollographql/apollo-client/commit/ea8944013278060ef87dfa4de6663a21b5204880) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and deprecation warnings for `ApolloClient` options and methods.\n\n- [#12459](https://github.com/apollographql/apollo-client/pull/12459) [`1c5a031`](https://github.com/apollographql/apollo-client/commit/1c5a0313d388945aeda93b2c1992ad77f4416fa1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reset `addTypenameTransform` and `fragments` caches when calling `cache.gc()` only when `resetResultCache` is `true`.\n\n- [#12743](https://github.com/apollographql/apollo-client/pull/12743) [`92ad409`](https://github.com/apollographql/apollo-client/commit/92ad4097e5c83e0a780ede20db34e9e63fb98e8b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings for `addTypename` in `InMemoryCache` and `MockedProvider`.\n\n- [#12743](https://github.com/apollographql/apollo-client/pull/12743) [`92ad409`](https://github.com/apollographql/apollo-client/commit/92ad4097e5c83e0a780ede20db34e9e63fb98e8b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add deprecations and warnings for `canonizeResults`.\n\n### Patch Changes\n\n- [#12750](https://github.com/apollographql/apollo-client/pull/12750) [`ecf3de1`](https://github.com/apollographql/apollo-client/commit/ecf3de1cc9a2cf3aaeba0c945909324b9e4b478a) Thanks [@phryneas](https://github.com/phryneas)! - Prevent field policies from overwriting/merging into supertype field policies.\n\n## 3.13.9\n\n### Patch Changes\n\n- [#12804](https://github.com/apollographql/apollo-client/pull/12804) [`32c9aa9`](https://github.com/apollographql/apollo-client/commit/32c9aa9215fab72e9ab68ee71198ce242157f855) Thanks [@phryneas](https://github.com/phryneas)! - Fix a possible race condition on queries that were reobserved before they were subscribed to the first time.\n\n## 3.13.8\n\n### Patch Changes\n\n- [#12567](https://github.com/apollographql/apollo-client/pull/12567) [`c19d415`](https://github.com/apollographql/apollo-client/commit/c19d41513cac0cc143aa7358f26c89c9408da102) Thanks [@thearchitector](https://github.com/thearchitector)! - Fix in-flight multipart urql subscription cancellation\n\n## 3.13.7\n\n### Patch Changes\n\n- [#12540](https://github.com/apollographql/apollo-client/pull/12540) [`0098932`](https://github.com/apollographql/apollo-client/commit/009893220934081f6e5733bff5863c768a597117) Thanks [@phryneas](https://github.com/phryneas)! - Refactor: Move notification scheduling logic from `QueryInfo` to `ObservableQuery`\n\n- [#12540](https://github.com/apollographql/apollo-client/pull/12540) [`0098932`](https://github.com/apollographql/apollo-client/commit/009893220934081f6e5733bff5863c768a597117) Thanks [@phryneas](https://github.com/phryneas)! - Refactored cache emit logic for ObservableQuery. This should be an invisible change.\n\n## 3.13.6\n\n### Patch Changes\n\n- [#12285](https://github.com/apollographql/apollo-client/pull/12285) [`cdc55ff`](https://github.com/apollographql/apollo-client/commit/cdc55ff54bf4c83ec8571508ec4bf8156af1bc97) Thanks [@phryneas](https://github.com/phryneas)! - keep ObservableQuery created by useQuery non-active before it is first subscribed\n\n## 3.13.5\n\n### Patch Changes\n\n- [#12461](https://github.com/apollographql/apollo-client/pull/12461) [`12c8d06`](https://github.com/apollographql/apollo-client/commit/12c8d06f1ef7cfbece8e3a63b7ad09d91334f663) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where a `cache-first` query would return the result for previous variables when a cache update is issued after simultaneously changing variables and skipping the query.\n\n## 3.13.4\n\n### Patch Changes\n\n- [#12420](https://github.com/apollographql/apollo-client/pull/12420) [`fee9368`](https://github.com/apollographql/apollo-client/commit/fee9368750e242ea03dea8d1557683506d411d8d) Thanks [@jorenbroekema](https://github.com/jorenbroekema)! - Use import star from `rehackt` to prevent issues with importing named exports from external CJS modules.\n\n## 3.13.3\n\n### Patch Changes\n\n- [#12362](https://github.com/apollographql/apollo-client/pull/12362) [`f6d387c`](https://github.com/apollographql/apollo-client/commit/f6d387c166cc76f08135966fb6d74fd8fe808c21) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixes an issue where calling `observableQuery.getCurrentResult()` when the `errorPolicy` was set to `all` would return the `networkStatus` as `NetworkStatus.ready` when there were errors returned in the result. This has been corrected to report `NetworkStatus.error`.\n\n  This bug also affected the `useQuery` and `useLazyQuery` hooks and may affect you if you check for `networkStatus` in your component.\n\n## 3.13.2\n\n### Patch Changes\n\n- [#12409](https://github.com/apollographql/apollo-client/pull/12409) [`6aa2f3e`](https://github.com/apollographql/apollo-client/commit/6aa2f3e81ee0ae59da7ae0b12000bb5a55ec5c6d) Thanks [@phryneas](https://github.com/phryneas)! - To mitigate problems when Apollo Client ends up more than once in the bundle, some unique symbols were converted into `Symbol.for` calls.\n\n- [#12392](https://github.com/apollographql/apollo-client/pull/12392) [`644bb26`](https://github.com/apollographql/apollo-client/commit/644bb2662168a9bac0519be6979f0db38b0febc4) Thanks [@Joja81](https://github.com/Joja81)! - Fixes an issue where the DeepOmit type would turn optional properties into required properties. This should only affect you if you were using the omitDeep or stripTypename utilities exported by Apollo Client.\n\n- [#12404](https://github.com/apollographql/apollo-client/pull/12404) [`4332b88`](https://github.com/apollographql/apollo-client/commit/4332b886f0409145af57f26d334f86e5a1b465c5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Show `NaN` rather than converting to `null` in debug messages from `MockLink` for unmatched `variables` values.\n\n## 3.13.1\n\n### Patch Changes\n\n- [#12369](https://github.com/apollographql/apollo-client/pull/12369) [`bdfc5b2`](https://github.com/apollographql/apollo-client/commit/bdfc5b2e386ed5f835716a542de0cf17da37f7fc) Thanks [@phryneas](https://github.com/phryneas)! - `ObervableQuery.refetch`: don't refetch with `cache-and-network`, swich to `network-only` instead\n\n- [#12375](https://github.com/apollographql/apollo-client/pull/12375) [`d3f8f13`](https://github.com/apollographql/apollo-client/commit/d3f8f130718ef50531ca0079192c2672a513814a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export the `UseSuspenseFragmentOptions` type.\n\n## 3.13.0\n\n### Minor Changes\n\n- [#12066](https://github.com/apollographql/apollo-client/pull/12066) [`c01da5d`](https://github.com/apollographql/apollo-client/commit/c01da5da639d4d9e882d380573b7876df4a1d65b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Adds a new `useSuspenseFragment` hook.\n\n  `useSuspenseFragment` suspends until `data` is complete. It is a drop-in replacement for `useFragment` when you prefer to use Suspense to control the loading state of a fragment. See the [documentation](https://www.apollographql.com/docs/react/data/fragments#usesuspensefragment) for more details.\n\n- [#12174](https://github.com/apollographql/apollo-client/pull/12174) [`ba5cc33`](https://github.com/apollographql/apollo-client/commit/ba5cc330f8734a989eef71e883861f848388ac0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure errors thrown in the `onCompleted` callback from `useMutation` don't call `onError`.\n\n- [#12340](https://github.com/apollographql/apollo-client/pull/12340) [`716d02e`](https://github.com/apollographql/apollo-client/commit/716d02ec9c5b1448f50cb50a0306a345310a2342) Thanks [@phryneas](https://github.com/phryneas)! - Deprecate the `onCompleted` and `onError` callbacks of `useQuery` and `useLazyQuery`.\n  For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Provide a more type-safe option for the previous data value passed to `observableQuery.updateQuery`. Using it could result in crashes at runtime as this callback could be called with partial data even though its type reported the value as a complete result.\n\n  The `updateQuery` callback function is now called with a new type-safe `previousData` property and a new `complete` property in the 2nd argument that determines whether `previousData` is a complete or partial result.\n\n  As a result of this change, it is recommended to use the `previousData` property passed to the 2nd argument of the callback rather than using the previous data value from the first argument since that value is not type-safe. The first argument is now deprecated and will be removed in a future version of Apollo Client.\n\n  ```ts\n  observableQuery.updateQuery(\n    (unsafePreviousData, { previousData, complete }) => {\n      previousData;\n      // ^? TData | DeepPartial<TData> | undefined\n\n      if (complete) {\n        previousData;\n        // ^? TData\n      } else {\n        previousData;\n        // ^? DeepPartial<TData> | undefined\n      }\n    }\n  );\n  ```\n\n- [#12174](https://github.com/apollographql/apollo-client/pull/12174) [`ba5cc33`](https://github.com/apollographql/apollo-client/commit/ba5cc330f8734a989eef71e883861f848388ac0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reject the mutation promise if errors are thrown in the `onCompleted` callback of `useMutation`.\n\n### Patch Changes\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Fix the return type of the `updateQuery` function to allow for `undefined`. `updateQuery` had the ability to bail out of the update by returning a falsey value, but the return type enforced a query value.\n\n  ```ts\n  observableQuery.updateQuery(\n    (unsafePreviousData, { previousData, complete }) => {\n      if (!complete) {\n        // Bail out of the update by returning early\n        return;\n      }\n\n      // ...\n    }\n  );\n  ```\n\n- [#12296](https://github.com/apollographql/apollo-client/pull/12296) [`2422df2`](https://github.com/apollographql/apollo-client/commit/2422df202a7ec71365d5a8ab5b3b554fcf60e4af) Thanks [@Cellule](https://github.com/Cellule)! - Deprecate option `ignoreResults` in `useMutation`.\n  Once this option is removed, existing code still using it might see increase in re-renders.\n  If you don't want to synchronize your component state with the mutation, please use `useApolloClient` to get your ApolloClient instance and call `client.mutate` directly.\n\n- [#12338](https://github.com/apollographql/apollo-client/pull/12338) [`67c16c9`](https://github.com/apollographql/apollo-client/commit/67c16c93897e36be980ba2139ee8bd3f24ab8558) Thanks [@phryneas](https://github.com/phryneas)! - In case of a multipart response (e.g. with `@defer`), query deduplication will\n  now keep going until the final chunk has been received.\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Fix the type of the `variables` property passed as the 2nd argument to the `subscribeToMore` callback. This was previously reported as the `variables` type for the subscription itself, but is now properly typed as the query `variables`.\n\n## 3.13.0-rc.0\n\n### Minor Changes\n\n- [#12066](https://github.com/apollographql/apollo-client/pull/12066) [`c01da5d`](https://github.com/apollographql/apollo-client/commit/c01da5da639d4d9e882d380573b7876df4a1d65b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Adds a new `useSuspenseFragment` hook.\n\n  `useSuspenseFragment` suspends until `data` is complete. It is a drop-in replacement for `useFragment` when you prefer to use Suspense to control the loading state of a fragment.\n\n- [#12174](https://github.com/apollographql/apollo-client/pull/12174) [`ba5cc33`](https://github.com/apollographql/apollo-client/commit/ba5cc330f8734a989eef71e883861f848388ac0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure errors thrown in the `onCompleted` callback from `useMutation` don't call `onError`.\n\n- [#12340](https://github.com/apollographql/apollo-client/pull/12340) [`716d02e`](https://github.com/apollographql/apollo-client/commit/716d02ec9c5b1448f50cb50a0306a345310a2342) Thanks [@phryneas](https://github.com/phryneas)! - Deprecate the `onCompleted` and `onError` callbacks of `useQuery` and `useLazyQuery`.\n  For more context, please see the [related issue](https://github.com/apollographql/apollo-client/issues/12352) on GitHub.\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Provide a more type-safe option for the previous data value passed to `observableQuery.updateQuery`. Using it could result in crashes at runtime as this callback could be called with partial data even though its type reported the value as a complete result.\n\n  The `updateQuery` callback function is now called with a new type-safe `previousData` property and a new `complete` property in the 2nd argument that determines whether `previousData` is a complete or partial result.\n\n  As a result of this change, it is recommended to use the `previousData` property passed to the 2nd argument of the callback rather than using the previous data value from the first argument since that value is not type-safe. The first argument is now deprecated and will be removed in a future version of Apollo Client.\n\n  ```ts\n  observableQuery.updateQuery(\n    (unsafePreviousData, { previousData, complete }) => {\n      previousData;\n      // ^? TData | DeepPartial<TData> | undefined\n\n      if (complete) {\n        previousData;\n        // ^? TData\n      } else {\n        previousData;\n        // ^? DeepPartial<TData> | undefined\n      }\n    }\n  );\n  ```\n\n- [#12174](https://github.com/apollographql/apollo-client/pull/12174) [`ba5cc33`](https://github.com/apollographql/apollo-client/commit/ba5cc330f8734a989eef71e883861f848388ac0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Reject the mutation promise if errors are thrown in the `onCompleted` callback of `useMutation`.\n\n### Patch Changes\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Fix the return type of the `updateQuery` function to allow for `undefined`. `updateQuery` had the ability to bail out of the update by returning a falsey value, but the return type enforced a query value.\n\n  ```ts\n  observableQuery.updateQuery(\n    (unsafePreviousData, { previousData, complete }) => {\n      if (!complete) {\n        // Bail out of the update by returning early\n        return;\n      }\n\n      // ...\n    }\n  );\n  ```\n\n- [#12296](https://github.com/apollographql/apollo-client/pull/12296) [`2422df2`](https://github.com/apollographql/apollo-client/commit/2422df202a7ec71365d5a8ab5b3b554fcf60e4af) Thanks [@Cellule](https://github.com/Cellule)! - Deprecate option `ignoreResults` in `useMutation`.\n  Once this option is removed, existing code still using it might see increase in re-renders.\n  If you don't want to synchronize your component state with the mutation, please use `useApolloClient` to get your ApolloClient instance and call `client.mutate` directly.\n\n- [#12338](https://github.com/apollographql/apollo-client/pull/12338) [`67c16c9`](https://github.com/apollographql/apollo-client/commit/67c16c93897e36be980ba2139ee8bd3f24ab8558) Thanks [@phryneas](https://github.com/phryneas)! - In case of a multipart response (e.g. with `@defer`), query deduplication will\n  now keep going until the final chunk has been received.\n\n- [#12276](https://github.com/apollographql/apollo-client/pull/12276) [`670f112`](https://github.com/apollographql/apollo-client/commit/670f112a7d9d85cb357eb279a488ac2c6d0137a9) Thanks [@Cellule](https://github.com/Cellule)! - Fix the type of the `variables` property passed as the 2nd argument to the `subscribeToMore` `updateQuery` callback. This was previously reported as the `variables` type for the subscription itself, but is now properly typed as the query `variables`.\n\n## 3.12.11\n\n### Patch Changes\n\n- [#12351](https://github.com/apollographql/apollo-client/pull/12351) [`3da908b`](https://github.com/apollographql/apollo-client/commit/3da908b1dde73847805a41c287a83700b2b88887) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixes an issue where the wrong `networkStatus` and `loading` value was emitted from `observableQuery` when calling `fetchMore` with a `no-cache` fetch policy. The `networkStatus` now properly reports as `ready` and `loading` as `false` after the result is returned.\n\n- [#12354](https://github.com/apollographql/apollo-client/pull/12354) [`a24ef94`](https://github.com/apollographql/apollo-client/commit/a24ef9474f8f7a864f8b866563f8f7e661d2533f) Thanks [@phryneas](https://github.com/phryneas)! - Fix missing `main.d.cts` file\n\n## 3.12.10\n\n### Patch Changes\n\n- [#12341](https://github.com/apollographql/apollo-client/pull/12341) [`f2bb0b9`](https://github.com/apollographql/apollo-client/commit/f2bb0b9955564e432345ee8bd431290e698d092c) Thanks [@phryneas](https://github.com/phryneas)! - `useReadQuery`/`useQueryRefHandlers`: Fix a \"hook order\" warning that might be emitted in React 19 dev mode.\n\n- [#12342](https://github.com/apollographql/apollo-client/pull/12342) [`219b26b`](https://github.com/apollographql/apollo-client/commit/219b26ba5a697981ad700e05b926d42db0fb8e59) Thanks [@phryneas](https://github.com/phryneas)! - Add `graphql-ws` `^6.0.3` as a valid `peerDependency`\n\n## 3.12.9\n\n### Patch Changes\n\n- [#12321](https://github.com/apollographql/apollo-client/pull/12321) [`daa4f33`](https://github.com/apollographql/apollo-client/commit/daa4f3303cfb81e8dca66c21ce3f3dc24946cafb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix type of `extensions` in `protocolErrors` for `ApolloError` and the `onError` link. According to the [multipart HTTP subscription protocol](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol), fatal tranport errors follow the [GraphQL error format](https://spec.graphql.org/draft/#sec-Errors.Error-Result-Format) which require `extensions` to be a map as its value instead of an array.\n\n- [#12318](https://github.com/apollographql/apollo-client/pull/12318) [`b17968b`](https://github.com/apollographql/apollo-client/commit/b17968b61f0e35b1ba20d081dacee66af8225491) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow `RetryLink` to retry an operation when fatal [transport-level errors](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol#message-and-error-format) are emitted from multipart subscriptions.\n\n  ```js\n  const retryLink = new RetryLink({\n    attempts: (count, operation, error) => {\n      if (error instanceof ApolloError) {\n        // errors available on the `protocolErrors` field in `ApolloError`\n        console.log(error.protocolErrors);\n      }\n\n      return true;\n    },\n  });\n  ```\n\n## 3.12.8\n\n### Patch Changes\n\n- [#12292](https://github.com/apollographql/apollo-client/pull/12292) [`3abd944`](https://github.com/apollographql/apollo-client/commit/3abd944e4adde5d94d91133f2bf6ed1c7744f8c5) Thanks [@phryneas](https://github.com/phryneas)! - Remove unused dependency `response-iterator`\n\n- [#12287](https://github.com/apollographql/apollo-client/pull/12287) [`bf313a3`](https://github.com/apollographql/apollo-client/commit/bf313a39d342a73dc3e9b3db9415c71c2573db3f) Thanks [@phryneas](https://github.com/phryneas)! - Fixes an issue where `client.watchFragment`/`useFragment` with `@includes` crashes when a separate cache update writes to the conditionally included fields.\n\n## 3.12.7\n\n### Patch Changes\n\n- [#12281](https://github.com/apollographql/apollo-client/pull/12281) [`d638ec3`](https://github.com/apollographql/apollo-client/commit/d638ec317b7d21c2246251ef1b9d773588277b39) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Make fatal [tranport-level errors](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol#message-and-error-format) from multipart subscriptions available to the error link with the `protocolErrors` property.\n\n  ```js\n  const errorLink = onError(({ protocolErrors }) => {\n    if (protocolErrors) {\n      console.log(protocolErrors);\n    }\n  });\n  ```\n\n- [#12281](https://github.com/apollographql/apollo-client/pull/12281) [`d638ec3`](https://github.com/apollographql/apollo-client/commit/d638ec317b7d21c2246251ef1b9d773588277b39) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the array type for the `errors` field on the `ApolloPayloadResult` type. This type was always in the shape of the GraphQL error format, per the [multipart subscriptions protocol](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol#message-and-error-format) and never a plain string or a JavaScript error object.\n\n## 3.12.6\n\n### Patch Changes\n\n- [#12267](https://github.com/apollographql/apollo-client/pull/12267) [`d57429d`](https://github.com/apollographql/apollo-client/commit/d57429df336412bfdce5fc92b8299360c522d121) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Maintain the `TData` type when used with `Unmasked` when `TData` is not a masked type generated from GraphQL Codegen.\n\n- [#12270](https://github.com/apollographql/apollo-client/pull/12270) [`3601246`](https://github.com/apollographql/apollo-client/commit/3601246f6e7b4f8b2937e0d431e6b5a6964f9066) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix handling of tagged/branded primitive types when used as scalar values with `Unmasked`.\n\n## 3.12.5\n\n### Patch Changes\n\n- [#12252](https://github.com/apollographql/apollo-client/pull/12252) [`cb9cd4e`](https://github.com/apollographql/apollo-client/commit/cb9cd4ea251aab225adf5e4e4f3f69e1bbacee52) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changes the default behavior of the `MaybeMasked` type to preserve types unless otherwise specified. This change makes it easier to upgrade from older versions of the client where types could have unexpectedly changed in the application due to the default of trying to unwrap types into unmasked types. This change also fixes the compilation performance regression experienced when simply upgrading the client since types are now preserved by default.\n\n  A new `mode` option has now been introduced to allow for the old behavior. See the next section on migrating if you wish to maintain the old default behavior after upgrading to this version.\n\n  ### Migrating from <= v3.12.4\n\n  If you've adopted data masking and have opted in to using masked types by setting the `enabled` property to `true`, you can remove this configuration entirely:\n\n  ```diff\n  -declare module \"@apollo/client\" {\n  -  interface DataMasking {\n  -    mode: \"unmask\"\n  -  }\n  -}\n  ```\n\n  If you prefer to specify the behavior explicitly, change the property from `enabled: true`, to `mode: \"preserveTypes\"`:\n\n  ```diff\n  declare module \"@apollo/client\" {\n    interface DataMasking {\n  -    enabled: true\n  +    mode: \"preserveTypes\"\n    }\n  }\n  ```\n\n  If you rely on the default behavior in 3.12.4 or below and would like to continue to use unmasked types by default, set the `mode` to `unmask`:\n\n  ```ts\n  declare module \"@apollo/client\" {\n    interface DataMasking {\n      mode: \"unmask\";\n    }\n  }\n  ```\n\n## 3.12.4\n\n### Patch Changes\n\n- [#12236](https://github.com/apollographql/apollo-client/pull/12236) [`4334d30`](https://github.com/apollographql/apollo-client/commit/4334d30cc3fbedb4f736eff196c49a9f20a46704) Thanks [@charpeni](https://github.com/charpeni)! - Fix an issue with `refetchQueries` where comparing `DocumentNode`s internally by references could lead to an unknown query, even though the `DocumentNode` was indeed an active query—with a different reference.\n\n## 3.12.3\n\n### Patch Changes\n\n- [#12214](https://github.com/apollographql/apollo-client/pull/12214) [`8bfee88`](https://github.com/apollographql/apollo-client/commit/8bfee88102dd071ea5836f7267f30ca082671b2b) Thanks [@phryneas](https://github.com/phryneas)! - Data masking: prevent infinite recursion of `ContainsFragmentsRefs` type\n\n- [#12204](https://github.com/apollographql/apollo-client/pull/12204) [`851deb0`](https://github.com/apollographql/apollo-client/commit/851deb06f42eb255b4839c2b88430f991943ae0f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix `Unmasked` unwrapping tuple types into an array of their subtypes.\n\n- [#12204](https://github.com/apollographql/apollo-client/pull/12204) [`851deb0`](https://github.com/apollographql/apollo-client/commit/851deb06f42eb255b4839c2b88430f991943ae0f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `MaybeMasked` does not try and unwrap types that contain index signatures.\n\n- [#12204](https://github.com/apollographql/apollo-client/pull/12204) [`851deb0`](https://github.com/apollographql/apollo-client/commit/851deb06f42eb255b4839c2b88430f991943ae0f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `MaybeMasked` does not try to unwrap the type as `Unmasked` if the type contains `any`.\n\n## 3.12.2\n\n### Patch Changes\n\n- [#12175](https://github.com/apollographql/apollo-client/pull/12175) [`84af347`](https://github.com/apollographql/apollo-client/commit/84af347d53bc31df4a6a90a55e7c98413144376a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update peer deps to allow for React 19 stable release.\n\n## 3.12.1\n\n### Patch Changes\n\n- [#12171](https://github.com/apollographql/apollo-client/pull/12171) [`e1efe74`](https://github.com/apollographql/apollo-client/commit/e1efe74c61b5f31fdd122ff8f4ce01012d0f5398) Thanks [@phryneas](https://github.com/phryneas)! - Fix import extension in masking entry point.\n\n## 3.12.0\n\n### Minor Changes\n\n#### Data masking 🎭\n\n- [#12042](https://github.com/apollographql/apollo-client/pull/12042) [`1c0ecbf`](https://github.com/apollographql/apollo-client/commit/1c0ecbf3c0454056853dd3dcb493dfd5fa1a96b1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduces data masking in Apollo Client.\n\n  Data masking enforces that only the fields requested by the query or fragment is available to that component. Data masking is best paired with [colocated fragments](https://www.apollographql.com/docs/react/data/fragments#colocating-fragments).\n\n  To enable data masking in Apollo Client, set the `dataMasking` option to `true`.\n\n  ```ts\n  new ApolloClient({\n    dataMasking: true,\n    // ... other options\n  });\n  ```\n\n  For detailed information on data masking, including how to incrementally adopt it in an existing applications, see the [data masking documentation](https://www.apollographql.com/docs/react/data/fragments#data-masking).\n\n- [#12131](https://github.com/apollographql/apollo-client/pull/12131) [`21c3f08`](https://github.com/apollographql/apollo-client/commit/21c3f083013445707b7b50ae6390318bc568d0f5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow `null` as a valid `from` value in `useFragment`.\n\n<details open>\n  <summary><h3>More Patch Changes</h3></summary>\n\n- [#12126](https://github.com/apollographql/apollo-client/pull/12126) [`d10d702`](https://github.com/apollographql/apollo-client/commit/d10d702ee9bd4d1d1dee2551821140f2c49d5c0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Maintain the existing document if its unchanged by the codemod and move to more naive whitespace formatting\n\n- [#12150](https://github.com/apollographql/apollo-client/pull/12150) [`9ed1e1e`](https://github.com/apollographql/apollo-client/commit/9ed1e1ef02b28445614fed4f5c141a289ac32d66) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue when using `Unmasked` with older versions of TypeScript when used with array fields.\n\n- [#12116](https://github.com/apollographql/apollo-client/pull/12116) [`8ae6e4e`](https://github.com/apollographql/apollo-client/commit/8ae6e4e5cec296c3910fdffb0ce51a0f5f06c5d3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent field accessor warnings when using `@unmask(mode: \"migrate\")` on objects that are passed into `cache.identify`.\n\n- [#12120](https://github.com/apollographql/apollo-client/pull/12120) [`6a98e76`](https://github.com/apollographql/apollo-client/commit/6a98e76af5c800a91a748c498611b55c33e02c68) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Provide a codemod that applies `@unmask` to all named fragments for all operations and fragments.\n\n  Learn how to use the codemod in the [incremental adoption documentation](https://www.apollographql.com/docs/react/data/fragments#incremental-adoption-in-an-existing-application).\n\n- [#12134](https://github.com/apollographql/apollo-client/pull/12134) [`cfaf4ef`](https://github.com/apollographql/apollo-client/commit/cfaf4efc6dea56ae46a5b5199d8ed9414b0f17d8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where data went missing when an unmasked fragment in migrate mode selected fields that the parent did not.\n\n- [#12154](https://github.com/apollographql/apollo-client/pull/12154) [`d933def`](https://github.com/apollographql/apollo-client/commit/d933def986d476cd64321059299ab15031297f04) Thanks [@phryneas](https://github.com/phryneas)! - Data masking types: handle overlapping nested array types and fragments on interface types.\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue where masked data would sometimes get returned when the field was part of a child fragment from a fragment unmasked by the parent query.\n\n- [#12123](https://github.com/apollographql/apollo-client/pull/12123) [`8422a30`](https://github.com/apollographql/apollo-client/commit/8422a305eff861fc8f953731e92c860f555bd99a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using data masking with \"no-cache\" operations.\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue where the warning emitted by `@unmask(mode: \"migrate\")` would trigger unnecessarily when the fragment was used alongside a masked fragment inside an inline fragment.\n\n- [#12114](https://github.com/apollographql/apollo-client/pull/12114) [`1d4ce00`](https://github.com/apollographql/apollo-client/commit/1d4ce0034395147445165022f7d23f42ff638d8a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix error when combining `@unmask` and `@defer` directives on a fragment spread when data masking is enabled.\n\n- [#12130](https://github.com/apollographql/apollo-client/pull/12130) [`1e7d009`](https://github.com/apollographql/apollo-client/commit/1e7d009e4a52949dab0065f3219dfe148837531e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix error thrown when applying unmask migrate mode warnings on interface types with selection sets that contain inline fragment conditions.\n\n- [#12152](https://github.com/apollographql/apollo-client/pull/12152) [`78137ec`](https://github.com/apollographql/apollo-client/commit/78137eccba90b80dd29bd8e1423b49ebe51ef8df) Thanks [@phryneas](https://github.com/phryneas)! - Add a helper that will skip the TS unmasking alorithm when no fragments are present on type level\n\n- [#12126](https://github.com/apollographql/apollo-client/pull/12126) [`d10d702`](https://github.com/apollographql/apollo-client/commit/d10d702ee9bd4d1d1dee2551821140f2c49d5c0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure documents unchanged by the codemod are left untouched.\n\n- [#12133](https://github.com/apollographql/apollo-client/pull/12133) [`a6ece37`](https://github.com/apollographql/apollo-client/commit/a6ece375119ce12c19749471c55b0059843a7217) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `null` is retained in nullable types when unmasking a type with the `Unmasked` helper type.\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue that threw errors when masking partial data with `@unmask(mode: \"migrate\")`.\n\n</details>\n\n## 3.12.0-rc.4\n\n### Patch Changes\n\n- [#12154](https://github.com/apollographql/apollo-client/pull/12154) [`d933def`](https://github.com/apollographql/apollo-client/commit/d933def986d476cd64321059299ab15031297f04) Thanks [@phryneas](https://github.com/phryneas)! - Data masking types: handle overlapping nested array types and fragments on interface types.\n\n## 3.12.0-rc.3\n\n### Patch Changes\n\n- [#12150](https://github.com/apollographql/apollo-client/pull/12150) [`9ed1e1e`](https://github.com/apollographql/apollo-client/commit/9ed1e1ef02b28445614fed4f5c141a289ac32d66) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue when using `Unmasked` with older versions of TypeScript when used with array fields.\n\n- [#12152](https://github.com/apollographql/apollo-client/pull/12152) [`78137ec`](https://github.com/apollographql/apollo-client/commit/78137eccba90b80dd29bd8e1423b49ebe51ef8df) Thanks [@phryneas](https://github.com/phryneas)! - Add a helper that will skip the TS unmasking alorithm when no fragments are present on type level\n\n## 3.12.0-rc.2\n\n### Patch Changes\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue where masked data would sometimes get returned when the field was part of a child fragment from a fragment unmasked by the parent query.\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue where the warning emitted by `@unmask(mode: \"migrate\")` would trigger unnecessarily when the fragment was used alongside a masked fragment inside an inline fragment.\n\n- [#12139](https://github.com/apollographql/apollo-client/pull/12139) [`5a53e15`](https://github.com/apollographql/apollo-client/commit/5a53e15e713e5eb2ebc9216615ea1a845fad2685) Thanks [@phryneas](https://github.com/phryneas)! - Fix issue that threw errors when masking partial data with `@unmask(mode: \"migrate\")`.\n\n## 3.12.0-rc.1\n\n### Minor Changes\n\n- [#12131](https://github.com/apollographql/apollo-client/pull/12131) [`21c3f08`](https://github.com/apollographql/apollo-client/commit/21c3f083013445707b7b50ae6390318bc568d0f5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow `null` as a valid `from` value in `useFragment`.\n\n### Patch Changes\n\n- [#12126](https://github.com/apollographql/apollo-client/pull/12126) [`d10d702`](https://github.com/apollographql/apollo-client/commit/d10d702ee9bd4d1d1dee2551821140f2c49d5c0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Maintain the existing document if its unchanged by the codemod and move to more naive whitespace formatting\n\n- [#12134](https://github.com/apollographql/apollo-client/pull/12134) [`cfaf4ef`](https://github.com/apollographql/apollo-client/commit/cfaf4efc6dea56ae46a5b5199d8ed9414b0f17d8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where data went missing when an unmasked fragment in migrate mode selected fields that the parent did not.\n\n- [#12130](https://github.com/apollographql/apollo-client/pull/12130) [`1e7d009`](https://github.com/apollographql/apollo-client/commit/1e7d009e4a52949dab0065f3219dfe148837531e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix error thrown when applying unmask migrate mode warnings on interface types with selection sets that contain inline fragment conditions.\n\n- [#12126](https://github.com/apollographql/apollo-client/pull/12126) [`d10d702`](https://github.com/apollographql/apollo-client/commit/d10d702ee9bd4d1d1dee2551821140f2c49d5c0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure documents unchanged by the codemod are left untouched.\n\n- [#12133](https://github.com/apollographql/apollo-client/pull/12133) [`a6ece37`](https://github.com/apollographql/apollo-client/commit/a6ece375119ce12c19749471c55b0059843a7217) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `null` is retained in nullable types when unmasking a type with the `Unmasked` helper type.\n\n## 3.12.0-rc.0\n\n### Patch Changes\n\n- [#12116](https://github.com/apollographql/apollo-client/pull/12116) [`8ae6e4e`](https://github.com/apollographql/apollo-client/commit/8ae6e4e5cec296c3910fdffb0ce51a0f5f06c5d3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent field accessor warnings when using `@unmask(mode: \"migrate\")` on objects that are passed into `cache.identify`.\n\n- [#12120](https://github.com/apollographql/apollo-client/pull/12120) [`6a98e76`](https://github.com/apollographql/apollo-client/commit/6a98e76af5c800a91a748c498611b55c33e02c68) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Provide a codemod that applies `@unmask` to all named fragments for all operations and fragments. To use the codemod, run the following command:\n\n  ```\n  npx jscodeshift -t node_modules/@apollo/client/scripts/codemods/data-masking/unmask.ts --extensions tsx --parser tsx path/to/app/\n  ```\n\n  To customize the tag used to search for GraphQL operations, use the `--tag` option. By default the codemod looks for `gql` and `graphql` tags.\n\n  To apply the directive in migrate mode in order to receive runtime warnings on potentially masked fields, use the `--mode migrate` option.\n\n  For more information on the options that can be used with `jscodeshift`, check out the [`jscodeshift` documentation](https://github.com/facebook/jscodeshift).\n\n- [#12121](https://github.com/apollographql/apollo-client/pull/12121) [`1085a95`](https://github.com/apollographql/apollo-client/commit/1085a95e4430da35d19033613e73f315a0aede9e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Warn when using data masking with \"no-cache\" operations.\n\n- [#12114](https://github.com/apollographql/apollo-client/pull/12114) [`1d4ce00`](https://github.com/apollographql/apollo-client/commit/1d4ce0034395147445165022f7d23f42ff638d8a) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix error when combining `@unmask` and `@defer` directives on a fragment spread when data masking is enabled.\n\n## 3.12.0-alpha.0\n\n### Minor Changes\n\n- [#12042](https://github.com/apollographql/apollo-client/pull/12042) [`1c0ecbf`](https://github.com/apollographql/apollo-client/commit/1c0ecbf3c0454056853dd3dcb493dfd5fa1a96b1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduces data masking into Apollo Client. Data masking allows components to access only the data they asked for through GraphQL fragments. This prevents coupling between components that might otherwise implicitly rely on fields not requested by the component. Data masking also provides the benefit that masked fields only rerender components that ask for the field.\n\n  To enable data masking in Apollo Client, set the `dataMasking` option to `true`.\n\n  ```ts\n  new ApolloClient({\n    dataMasking: true,\n    // ... other options\n  });\n  ```\n\n  You can selectively disable data masking using the `@unmask` directive. Apply this to any named fragment to receive all fields requested by the fragment.\n\n  ```graphql\n  query {\n    user {\n      id\n      ...UserFields @unmask\n    }\n  }\n  ```\n\n  To help with migration, use the `@unmask` migrate mode which will add warnings when accessing fields that would otherwise be masked.\n\n  ```graphql\n  query {\n    user {\n      id\n      ...UserFields @unmask(mode: \"migrate\")\n    }\n  }\n  ```\n\n## 3.11.10\n\n### Patch Changes\n\n- [#12093](https://github.com/apollographql/apollo-client/pull/12093) [`1765668`](https://github.com/apollographql/apollo-client/commit/1765668b7d495ef8a581f697bf9e4b7460455f13) Thanks [@mgmolisani](https://github.com/mgmolisani)! - Fixed a bug when evaluating the devtools flag with the new syntax `devtools.enabled` that could result to `true` when explicitly set to `false`.\n\n## 3.11.9\n\n### Patch Changes\n\n- [#12110](https://github.com/apollographql/apollo-client/pull/12110) [`a3f95c6`](https://github.com/apollographql/apollo-client/commit/a3f95c6f7623060bbf68b418b0ab268fabc0c9b6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where errors returned from a `fetchMore` call from a Suspense hook would cause a Suspense boundary to be shown indefinitely.\n\n## 3.11.8\n\n### Patch Changes\n\n- [#12054](https://github.com/apollographql/apollo-client/pull/12054) [`35cf186`](https://github.com/apollographql/apollo-client/commit/35cf186ed9237e41735f150e0cbf4edd995ab0d9) Thanks [@phryneas](https://github.com/phryneas)! - Fixed a bug where incorrect object access in some Safari extensions could cause a crash.\n\n## 3.11.7\n\n### Patch Changes\n\n- [#12052](https://github.com/apollographql/apollo-client/pull/12052) [`e471cef`](https://github.com/apollographql/apollo-client/commit/e471cef875eadef04f8ee18ef431ee70e7b9bcab) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixes a regression from where passing an invalid identifier to `from` in `useFragment` would result in the warning `TypeError: Cannot read properties of undefined (reading '__typename')`.\n\n## 3.11.6\n\n### Patch Changes\n\n- [#12049](https://github.com/apollographql/apollo-client/pull/12049) [`9c26892`](https://github.com/apollographql/apollo-client/commit/9c268927b1f8e5921b9440a53c9979a37f594e75) Thanks [@phryneas](https://github.com/phryneas) and [@maciesielka](https://github.com/maciesielka)! - Fix a bug where `useFragment` did not re-render as expected\n\n- [#12044](https://github.com/apollographql/apollo-client/pull/12044) [`04462a2`](https://github.com/apollographql/apollo-client/commit/04462a274ad39b392142385a2f052abbf3014749) Thanks [@DoctorJohn](https://github.com/DoctorJohn)! - Cache the `useSubscription` hook's `restart` function definition between re-renders.\n\n## 3.11.5\n\n### Patch Changes\n\n- [#12027](https://github.com/apollographql/apollo-client/pull/12027) [`eb3e21b`](https://github.com/apollographql/apollo-client/commit/eb3e21b9f7fa6a3161705c2c7270129c17b65095) Thanks [@JavaScriptBach](https://github.com/JavaScriptBach)! - Type `MutationResult.reset` as an arrow function\n\n- [#12020](https://github.com/apollographql/apollo-client/pull/12020) [`82d8cb4`](https://github.com/apollographql/apollo-client/commit/82d8cb4255be497748829f12eb25ac87c11ee5e4) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Better conform to Rules of React by avoiding write of ref in render for `useFragment`.\n\n## 3.11.4\n\n### Patch Changes\n\n- [#11994](https://github.com/apollographql/apollo-client/pull/11994) [`41b17e5`](https://github.com/apollographql/apollo-client/commit/41b17e5950f4db5ef9e32ded5bb327b3bf19e6e8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Update the `Modifier` function type to allow `cache.modify` to return deeply partial data.\n\n- [#11989](https://github.com/apollographql/apollo-client/pull/11989) [`e609156`](https://github.com/apollographql/apollo-client/commit/e609156c4989def88ae1a28b2e0f0378077a5528) Thanks [@phryneas](https://github.com/phryneas)! - Fix a potential crash when calling `clearStore` while a query was running.\n\n  Previously, calling `client.clearStore()` while a query was running had one of these results:\n\n  - `useQuery` would stay in a `loading: true` state.\n  - `useLazyQuery` would stay in a `loading: true` state, but also crash with a `\"Cannot read property 'data' of undefined\"` error.\n\n  Now, in both cases, the hook will enter an error state with a `networkError`, and the promise returned by the `useLazyQuery` `execute` function will return a result in an error state.\n\n- [#11994](https://github.com/apollographql/apollo-client/pull/11994) [`41b17e5`](https://github.com/apollographql/apollo-client/commit/41b17e5950f4db5ef9e32ded5bb327b3bf19e6e8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent accidental distribution on `cache.modify` field modifiers when a field is a union type array.\n\n## 3.11.3\n\n### Patch Changes\n\n- [#11984](https://github.com/apollographql/apollo-client/pull/11984) [`5db1659`](https://github.com/apollographql/apollo-client/commit/5db1659dc07e3de697894fc1c6f00a151d068291) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where multiple fetches with results that returned errors would sometimes set the `data` property with an `errorPolicy` of `none`.\n\n- [#11974](https://github.com/apollographql/apollo-client/pull/11974) [`c95848e`](https://github.com/apollographql/apollo-client/commit/c95848e859fb7ce0b3b9439ac71dff880f991450) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where `fetchMore` would write its result data to the cache when using it with a `no-cache` fetch policy.\n\n- [#11974](https://github.com/apollographql/apollo-client/pull/11974) [`c95848e`](https://github.com/apollographql/apollo-client/commit/c95848e859fb7ce0b3b9439ac71dff880f991450) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where executing `fetchMore` with a `no-cache` fetch policy could sometimes result in multiple network requests.\n\n- [#11974](https://github.com/apollographql/apollo-client/pull/11974) [`c95848e`](https://github.com/apollographql/apollo-client/commit/c95848e859fb7ce0b3b9439ac71dff880f991450) Thanks [@jerelmiller](https://github.com/jerelmiller)! -\n\n  #### Potentially disruptive change\n\n  When calling `fetchMore` with a query that has a `no-cache` fetch policy, `fetchMore` will now throw if an `updateQuery` function is not provided. This provides a mechanism to merge the results from the `fetchMore` call with the query's previous result.\n\n## 3.11.2\n\n### Patch Changes\n\n- [#11980](https://github.com/apollographql/apollo-client/pull/11980) [`38c0a2c`](https://github.com/apollographql/apollo-client/commit/38c0a2c43dd28677ee240754cd389c8a08c05738) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix missing `getServerSnapshot` error when using `useSubscription` on the server.\n\n## 3.11.1\n\n### Patch Changes\n\n- [#11969](https://github.com/apollographql/apollo-client/pull/11969) [`061cab6`](https://github.com/apollographql/apollo-client/commit/061cab6627abd4ec81f83c40c1d281c418627c93) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove check for `window.__APOLLO_CLIENT__` when determining whether to connect to Apollo Client Devtools when `connectToDevtools` or `devtools.enabled` is not specified. This now simply checks to see if the application is in development mode.\n\n- [#11971](https://github.com/apollographql/apollo-client/pull/11971) [`ecf77f6`](https://github.com/apollographql/apollo-client/commit/ecf77f6f5b5ccf64cfba51e838e96549fb6c92fe) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent the `setTimeout` for suggesting devtools from running in non-browser environments.\n\n## 3.11.0\n\n### Potentially Breaking Fixes\n\n- [#11789](https://github.com/apollographql/apollo-client/pull/11789) [`5793301`](https://github.com/apollographql/apollo-client/commit/579330147d6bd6f7167a35413a33746103e375cb) Thanks [@phryneas](https://github.com/phryneas)! - Changes usages of the `GraphQLError` type to `GraphQLFormattedError`.\n\n  This was a type bug - these errors were never `GraphQLError` instances\n  to begin with, and the `GraphQLError` class has additional properties that can\n  never be correctly rehydrated from a GraphQL result.\n  The correct type to use here is `GraphQLFormattedError`.\n\n  Similarly, please ensure to use the type `FormattedExecutionResult`\n  instead of `ExecutionResult` - the non-\"Formatted\" versions of these types\n  are for use on the server only, but don't get transported over the network.\n\n- [#11626](https://github.com/apollographql/apollo-client/pull/11626) [`228429a`](https://github.com/apollographql/apollo-client/commit/228429a1d36eae691473b24fb641ec3cd84c8a3d) Thanks [@phryneas](https://github.com/phryneas)! - Call `nextFetchPolicy` with \"variables-changed\" even if there is a `fetchPolicy` specified.\n\n  Previously this would only be called when the current `fetchPolicy` was equal to the `fetchPolicy` option or the option was not specified. If you use `nextFetchPolicy` as a function, expect to see this function called more often.\n\n  Due to this bug, this also meant that the `fetchPolicy` might be reset to the initial `fetchPolicy`, even when you specified a `nextFetchPolicy` function. If you previously relied on this behavior, you will need to update your `nextFetchPolicy` callback function to implement this resetting behavior.\n\n  As an example, if your code looked like the following:\n\n  ```js\n  useQuery(QUERY, {\n    nextFetchPolicy(currentFetchPolicy, info) {\n      // your logic here\n    }\n  );\n  ```\n\n  Update your function to the following to reimplement the resetting behavior:\n\n  ```js\n  useQuery(QUERY, {\n    nextFetchPolicy(currentFetchPolicy, info) {\n      if (info.reason === 'variables-changed') {\n        return info.initialFetchPolicy;\n      }\n      // your logic here\n    }\n  );\n  ```\n\n### Minor Changes\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useQueryRefHandlers`.\n\n- [#11854](https://github.com/apollographql/apollo-client/pull/11854) [`3812800`](https://github.com/apollographql/apollo-client/commit/3812800c6e4e5e3e64f473543babdba35ce100c2) Thanks [@jcostello-atlassian](https://github.com/jcostello-atlassian)! - Support extensions in useSubscription\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useLoadableQuery`.\n\n- [#11863](https://github.com/apollographql/apollo-client/pull/11863) [`98e44f7`](https://github.com/apollographql/apollo-client/commit/98e44f74cb7c7e93a81bdc7492c9218bf4a2dcd4) Thanks [@phryneas](https://github.com/phryneas)! - Reimplement `useSubscription` to fix rules of React violations.\n\n- [#11869](https://github.com/apollographql/apollo-client/pull/11869) [`a69327c`](https://github.com/apollographql/apollo-client/commit/a69327cce1b36e8855258e9b19427511e0af8748) Thanks [@phryneas](https://github.com/phryneas)! - Rewrite big parts of `useQuery` and `useLazyQuery` to be more compliant with the Rules of React and React Compiler\n\n- [#11936](https://github.com/apollographql/apollo-client/pull/11936) [`1b23337`](https://github.com/apollographql/apollo-client/commit/1b23337e5a9eec4ce3ed69531ca4f4afe8e897a6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to specify a name for the client instance for use with Apollo Client Devtools. This is useful when instantiating multiple clients to identify the client instance more easily. This deprecates the `connectToDevtools` option in favor of a new `devtools` configuration.\n\n  ```ts\n  new ApolloClient({\n    devtools: {\n      enabled: true,\n      name: \"Test Client\",\n    },\n  });\n  ```\n\n  This option is backwards-compatible with `connectToDevtools` and will be used in the absense of a `devtools` option.\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useBackgroundQuery`.\n\n- [#11930](https://github.com/apollographql/apollo-client/pull/11930) [`a768575`](https://github.com/apollographql/apollo-client/commit/a768575ac1454587208aad63abc811b6a966fe72) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deprecates experimental schema testing utilities introduced in 3.10 in favor of recommending [`@apollo/graphql-testing-library`](https://github.com/apollographql/graphql-testing-library).\n\n### Patch Changes\n\n- [#11951](https://github.com/apollographql/apollo-client/pull/11951) [`0de03af`](https://github.com/apollographql/apollo-client/commit/0de03af912a76c4e0111f21b4f90a073317b63b6) Thanks [@phryneas](https://github.com/phryneas)! - add React 19 RC to `peerDependencies`\n\n- [#11927](https://github.com/apollographql/apollo-client/pull/11927) [`2941824`](https://github.com/apollographql/apollo-client/commit/2941824dd66cdd20eee5f2293373ad7a9cf991a4) Thanks [@phryneas](https://github.com/phryneas)! - Add `restart` function to `useSubscription`.\n\n- [#11949](https://github.com/apollographql/apollo-client/pull/11949) [`4528918`](https://github.com/apollographql/apollo-client/commit/45289186bcaaa33dfe904913eb6df31e2541c219) Thanks [@alessbell](https://github.com/alessbell)! - Remove deprecated `watchFragment` option, `canonizeResults`\n\n- [#11937](https://github.com/apollographql/apollo-client/pull/11937) [`78332be`](https://github.com/apollographql/apollo-client/commit/78332be32a9af0da33eb3e4100e7a76c3eac2496) Thanks [@phryneas](https://github.com/phryneas)! - `createSchemaFetch`: simulate serialized errors instead of an `ApolloError` instance\n\n- [#11902](https://github.com/apollographql/apollo-client/pull/11902) [`96422ce`](https://github.com/apollographql/apollo-client/commit/96422ce95b923b560321a88acd2eec35cf2a1c18) Thanks [@phryneas](https://github.com/phryneas)! - Add `cause` field to `ApolloError`.\n\n- [#11806](https://github.com/apollographql/apollo-client/pull/11806) [`8df6013`](https://github.com/apollographql/apollo-client/commit/8df6013b6b45452ec058fab3e068b5b6d6c493f7) Thanks [@phryneas](https://github.com/phryneas)! - MockLink: add query default variables if not specified in mock request\n\n- [#11926](https://github.com/apollographql/apollo-client/pull/11926) [`3dd6432`](https://github.com/apollographql/apollo-client/commit/3dd64324dc5156450cead27f8141ea93315ffe65) Thanks [@phryneas](https://github.com/phryneas)! - `watchFragment`: forward additional options to `diffOptions`\n\n- [#11946](https://github.com/apollographql/apollo-client/pull/11946) [`7d833b8`](https://github.com/apollographql/apollo-client/commit/7d833b80119a991e6d2eb58f2c71074d697b8e63) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where mutations were not accessible by Apollo Client Devtools in 3.11.0-rc.0.\n\n- [#11944](https://github.com/apollographql/apollo-client/pull/11944) [`8f3d7eb`](https://github.com/apollographql/apollo-client/commit/8f3d7eb3bc2e0c2d79c5b1856655abe829390742) Thanks [@sneyderdev](https://github.com/sneyderdev)! - Allow `IgnoreModifier` to be returned from a `optimisticResponse` function when inferring from a `TypedDocumentNode` when used with a generic argument.\n\n- [#11954](https://github.com/apollographql/apollo-client/pull/11954) [`4a6e86a`](https://github.com/apollographql/apollo-client/commit/4a6e86aeaf6685abf0dd23110784848c8b085735) Thanks [@phryneas](https://github.com/phryneas)! - Document (and deprecate) the previously undocumented `errors` property on the `useQuery` `QueryResult` type.\n\n- [#11719](https://github.com/apollographql/apollo-client/pull/11719) [`09a6677`](https://github.com/apollographql/apollo-client/commit/09a6677ec1a0cffedeecb2cbac5cd3a3c8aa0fa1) Thanks [@phryneas](https://github.com/phryneas)! - Allow wrapping `createQueryPreloader`\n\n- [#11921](https://github.com/apollographql/apollo-client/pull/11921) [`70406bf`](https://github.com/apollographql/apollo-client/commit/70406bfd2b9a645d781638569853d9b435e047df) Thanks [@phryneas](https://github.com/phryneas)! - add `ignoreResults` option to `useSubscription`\n\n## 3.11.0-rc.2\n\n### Patch Changes\n\n- [#11951](https://github.com/apollographql/apollo-client/pull/11951) [`0de03af`](https://github.com/apollographql/apollo-client/commit/0de03af912a76c4e0111f21b4f90a073317b63b6) Thanks [@phryneas](https://github.com/phryneas)! - add React 19 RC to `peerDependencies`\n\n- [#11937](https://github.com/apollographql/apollo-client/pull/11937) [`78332be`](https://github.com/apollographql/apollo-client/commit/78332be32a9af0da33eb3e4100e7a76c3eac2496) Thanks [@phryneas](https://github.com/phryneas)! - `createSchemaFetch`: simulate serialized errors instead of an `ApolloError` instance\n\n- [#11944](https://github.com/apollographql/apollo-client/pull/11944) [`8f3d7eb`](https://github.com/apollographql/apollo-client/commit/8f3d7eb3bc2e0c2d79c5b1856655abe829390742) Thanks [@sneyderdev](https://github.com/sneyderdev)! - Allow `IgnoreModifier` to be returned from a `optimisticResponse` function when inferring from a `TypedDocumentNode` when used with a generic argument.\n\n- [#11954](https://github.com/apollographql/apollo-client/pull/11954) [`4a6e86a`](https://github.com/apollographql/apollo-client/commit/4a6e86aeaf6685abf0dd23110784848c8b085735) Thanks [@phryneas](https://github.com/phryneas)! - Document (and deprecate) the previously undocumented `errors` property on the `useQuery` `QueryResult` type.\n\n## 3.11.0-rc.1\n\n### Patch Changes\n\n- [#11949](https://github.com/apollographql/apollo-client/pull/11949) [`4528918`](https://github.com/apollographql/apollo-client/commit/45289186bcaaa33dfe904913eb6df31e2541c219) Thanks [@alessbell](https://github.com/alessbell)! - Remove deprecated `watchFragment` option, `canonizeResults`\n\n- [#11926](https://github.com/apollographql/apollo-client/pull/11926) [`3dd6432`](https://github.com/apollographql/apollo-client/commit/3dd64324dc5156450cead27f8141ea93315ffe65) Thanks [@phryneas](https://github.com/phryneas)! - `watchFragment`: forward additional options to `diffOptions`\n\n- [#11946](https://github.com/apollographql/apollo-client/pull/11946) [`7d833b8`](https://github.com/apollographql/apollo-client/commit/7d833b80119a991e6d2eb58f2c71074d697b8e63) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where mutations were not accessible by Apollo Client Devtools in 3.11.0-rc.0.\n\n## 3.11.0-rc.0\n\n### Minor Changes\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useQueryRefHandlers`.\n\n- [#11854](https://github.com/apollographql/apollo-client/pull/11854) [`3812800`](https://github.com/apollographql/apollo-client/commit/3812800c6e4e5e3e64f473543babdba35ce100c2) Thanks [@jcostello-atlassian](https://github.com/jcostello-atlassian)! - Support extensions in useSubscription\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useLoadableQuery`.\n\n- [#11863](https://github.com/apollographql/apollo-client/pull/11863) [`98e44f7`](https://github.com/apollographql/apollo-client/commit/98e44f74cb7c7e93a81bdc7492c9218bf4a2dcd4) Thanks [@phryneas](https://github.com/phryneas)! - Reimplement `useSubscription` to fix rules of React violations.\n\n- [#11869](https://github.com/apollographql/apollo-client/pull/11869) [`a69327c`](https://github.com/apollographql/apollo-client/commit/a69327cce1b36e8855258e9b19427511e0af8748) Thanks [@phryneas](https://github.com/phryneas)! - Rewrite big parts of `useQuery` and `useLazyQuery` to be more compliant with the Rules of React and React Compiler\n\n- [#11936](https://github.com/apollographql/apollo-client/pull/11936) [`1b23337`](https://github.com/apollographql/apollo-client/commit/1b23337e5a9eec4ce3ed69531ca4f4afe8e897a6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to specify a name for the client instance for use with Apollo Client Devtools. This is useful when instantiating multiple clients to identify the client instance more easily. This deprecates the `connectToDevtools` option in favor of a new `devtools` configuration.\n\n  ```ts\n  new ApolloClient({\n    devtools: {\n      enabled: true,\n      name: \"Test Client\",\n    },\n  });\n  ```\n\n  This option is backwards-compatible with `connectToDevtools` and will be used in the absense of a `devtools` option.\n\n- [#11923](https://github.com/apollographql/apollo-client/pull/11923) [`d88c7f8`](https://github.com/apollographql/apollo-client/commit/d88c7f8909e3cb31532e8b1fc7dd06be12f35591) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for `subscribeToMore` function to `useBackgroundQuery`.\n\n- [#11789](https://github.com/apollographql/apollo-client/pull/11789) [`5793301`](https://github.com/apollographql/apollo-client/commit/579330147d6bd6f7167a35413a33746103e375cb) Thanks [@phryneas](https://github.com/phryneas)! - Changes usages of the `GraphQLError` type to `GraphQLFormattedError`.\n\n  This was a type bug - these errors were never `GraphQLError` instances\n  to begin with, and the `GraphQLError` class has additional properties that can\n  never be correctly rehydrated from a GraphQL result.\n  The correct type to use here is `GraphQLFormattedError`.\n\n  Similarly, please ensure to use the type `FormattedExecutionResult`\n  instead of `ExecutionResult` - the non-\"Formatted\" versions of these types\n  are for use on the server only, but don't get transported over the network.\n\n- [#11930](https://github.com/apollographql/apollo-client/pull/11930) [`a768575`](https://github.com/apollographql/apollo-client/commit/a768575ac1454587208aad63abc811b6a966fe72) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Deprecates experimental schema testing utilities introduced in 3.10 in favor of recommending [`@apollo/graphql-testing-library`](https://github.com/apollographql/graphql-testing-library).\n\n### Patch Changes\n\n- [#11927](https://github.com/apollographql/apollo-client/pull/11927) [`2941824`](https://github.com/apollographql/apollo-client/commit/2941824dd66cdd20eee5f2293373ad7a9cf991a4) Thanks [@phryneas](https://github.com/phryneas)! - Add `restart` function to `useSubscription`.\n\n- [#11902](https://github.com/apollographql/apollo-client/pull/11902) [`96422ce`](https://github.com/apollographql/apollo-client/commit/96422ce95b923b560321a88acd2eec35cf2a1c18) Thanks [@phryneas](https://github.com/phryneas)! - Add `cause` field to `ApolloError`.\n\n- [#11806](https://github.com/apollographql/apollo-client/pull/11806) [`8df6013`](https://github.com/apollographql/apollo-client/commit/8df6013b6b45452ec058fab3e068b5b6d6c493f7) Thanks [@phryneas](https://github.com/phryneas)! - MockLink: add query default variables if not specified in mock request\n\n- [#11626](https://github.com/apollographql/apollo-client/pull/11626) [`228429a`](https://github.com/apollographql/apollo-client/commit/228429a1d36eae691473b24fb641ec3cd84c8a3d) Thanks [@phryneas](https://github.com/phryneas)! - Call `nextFetchPolicy` with \"variables-changed\" even if there is a `fetchPolicy` specified. (fixes #11365)\n\n- [#11719](https://github.com/apollographql/apollo-client/pull/11719) [`09a6677`](https://github.com/apollographql/apollo-client/commit/09a6677ec1a0cffedeecb2cbac5cd3a3c8aa0fa1) Thanks [@phryneas](https://github.com/phryneas)! - Allow wrapping `createQueryPreloader`\n\n- [#11921](https://github.com/apollographql/apollo-client/pull/11921) [`70406bf`](https://github.com/apollographql/apollo-client/commit/70406bfd2b9a645d781638569853d9b435e047df) Thanks [@phryneas](https://github.com/phryneas)! - add `ignoreResults` option to `useSubscription`\n\n## 3.10.8\n\n### Patch Changes\n\n- [#11911](https://github.com/apollographql/apollo-client/pull/11911) [`1f0460a`](https://github.com/apollographql/apollo-client/commit/1f0460a60fc613e8d6f218a74ded69e81e960791) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow `undefined` to be returned from a `cache.modify` modifier function when a generic type argument is used.\n\n## 3.10.7\n\n### Patch Changes\n\n- [#11901](https://github.com/apollographql/apollo-client/pull/11901) [`10a8c0a`](https://github.com/apollographql/apollo-client/commit/10a8c0a8f6f3e13ec3c67bf53cc11a948b60e6d9) Thanks [@phryneas](https://github.com/phryneas)! - update `canUseLayoutEffect` check to also allow for layout effects in React Native\n\n- [#11861](https://github.com/apollographql/apollo-client/pull/11861) [`1aed0e8`](https://github.com/apollographql/apollo-client/commit/1aed0e82fcc432380a56d4a446f414ce8b1a7a90) Thanks [@henryqdineen](https://github.com/henryqdineen)! - Defend against non-serializable params in `invariantWrappers`\n\n- [#11905](https://github.com/apollographql/apollo-client/pull/11905) [`29755da`](https://github.com/apollographql/apollo-client/commit/29755da8797dc94613a23fe050ddd6ef9ffab607) Thanks [@phryneas](https://github.com/phryneas)! - Add `.d.cts` files for cjs bundles\n\n- [#11906](https://github.com/apollographql/apollo-client/pull/11906) [`d104759`](https://github.com/apollographql/apollo-client/commit/d104759cfb4be31e2ffbe166531a9b11861ade99) Thanks [@phryneas](https://github.com/phryneas)! - chore: update TypeScript to 5.5\n\n## 3.10.6\n\n### Patch Changes\n\n- [#11900](https://github.com/apollographql/apollo-client/pull/11900) [`f745558`](https://github.com/apollographql/apollo-client/commit/f74555826995009a6bb9d824506cecb3508e3365) Thanks [@phryneas](https://github.com/phryneas)! - `useMutation`: use `useIsomorphicLayoutEffect` instead of `useLayoutEffect`\n\n## 3.10.5\n\n### Patch Changes\n\n- [#11888](https://github.com/apollographql/apollo-client/pull/11888) [`7fb7939`](https://github.com/apollographql/apollo-client/commit/7fb7939edb7ca8f4273b75554f96ea9936731458) Thanks [@phryneas](https://github.com/phryneas)! - switch `useRenderGuard` to an approach not accessing React's internals\n\n- [#11511](https://github.com/apollographql/apollo-client/pull/11511) [`6536369`](https://github.com/apollographql/apollo-client/commit/6536369cf213469d20d15b779c344268d70fecd5) Thanks [@phryneas](https://github.com/phryneas)! - `useLoadableQuery`: ensure that `loadQuery` is updated if the ApolloClient instance changes\n\n- [#11860](https://github.com/apollographql/apollo-client/pull/11860) [`8740f19`](https://github.com/apollographql/apollo-client/commit/8740f198805a99e01136617c4055d611b92cc231) Thanks [@alessbell](https://github.com/alessbell)! - Fixes [#11849](https://github.com/apollographql/apollo-client/issues/11849) by reevaluating `window.fetch` each time `BatchHttpLink` uses it, if not configured via `options.fetch`. Takes the same approach as PR [#8603](https://github.com/apollographql/apollo-client/pull/8603) which fixed the same issue in `HttpLink`.\n\n- [#11852](https://github.com/apollographql/apollo-client/pull/11852) [`d502a69`](https://github.com/apollographql/apollo-client/commit/d502a69654d8ffa31e09467da028304a934a9874) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where calling the `useMutation` `reset` function would point the hook to an outdated `client` reference.\n\n- [#11329](https://github.com/apollographql/apollo-client/pull/11329) [`3d164ea`](https://github.com/apollographql/apollo-client/commit/3d164ea16c17d271f6fa9e5ad8f013623eec23a0) Thanks [@PaLy](https://github.com/PaLy)! - Fix graphQLErrors in Error Link if networkError.result is an empty string\n\n- [#11852](https://github.com/apollographql/apollo-client/pull/11852) [`d502a69`](https://github.com/apollographql/apollo-client/commit/d502a69654d8ffa31e09467da028304a934a9874) Thanks [@phryneas](https://github.com/phryneas)! - Prevent writing to a ref in render in `useMutation`.\n  As a result, you might encounter problems in the future if you call the mutation's `execute` function during render. Please note that this was never supported behavior, and we strongly recommend against it.\n\n- [#11848](https://github.com/apollographql/apollo-client/pull/11848) [`ad63924`](https://github.com/apollographql/apollo-client/commit/ad6392424ddbeb6f91b165c806251490e1cdd69e) Thanks [@phryneas](https://github.com/phryneas)! - Ensure covariant behavior: `MockedResponse<X,Y>` should be assignable to `MockedResponse`\n\n- [#11851](https://github.com/apollographql/apollo-client/pull/11851) [`45c47be`](https://github.com/apollographql/apollo-client/commit/45c47be26d4e020cfcff359a5af19ccfc39b930e) Thanks [@phryneas](https://github.com/phryneas)! - Avoid usage of useRef in useInternalState to prevent ref access in render.\n\n- [#11877](https://github.com/apollographql/apollo-client/pull/11877) [`634d91a`](https://github.com/apollographql/apollo-client/commit/634d91aeb10ab308b05d5ffb918678806046af09) Thanks [@phryneas](https://github.com/phryneas)! - Add missing name to tuple member (fix TS5084)\n\n- [#11851](https://github.com/apollographql/apollo-client/pull/11851) [`45c47be`](https://github.com/apollographql/apollo-client/commit/45c47be26d4e020cfcff359a5af19ccfc39b930e) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where `useLazyQuery` would not pick up a client change.\n\n## 3.10.4\n\n### Patch Changes\n\n- [#11838](https://github.com/apollographql/apollo-client/pull/11838) [`8475346`](https://github.com/apollographql/apollo-client/commit/84753462af50d89c8693713990cccf432ff8267d) Thanks [@alex-kinokon](https://github.com/alex-kinokon)! - Don’t prompt for DevTools installation for browser extension page\n\n- [#11839](https://github.com/apollographql/apollo-client/pull/11839) [`6481fe1`](https://github.com/apollographql/apollo-client/commit/6481fe1196cedee987781dcb45ebdc0cafb3998c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix a regression in [3.9.5](https://github.com/apollographql/apollo-client/releases/tag/v3.9.5) where a merge function that returned an incomplete result would not allow the client to refetch in order to fulfill the query.\n\n- [#11844](https://github.com/apollographql/apollo-client/pull/11844) [`86984f2`](https://github.com/apollographql/apollo-client/commit/86984f24bd9076a6034acd59bbcb28a2ea1add93) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Honor the `@nonreactive` directive when using `cache.watchFragment` or the `useFragment` hook to avoid rerendering when using these directives.\n\n- [#11824](https://github.com/apollographql/apollo-client/pull/11824) [`47ad806`](https://github.com/apollographql/apollo-client/commit/47ad806c7b0c55f1e05dbf276ca87a354ac389e5) Thanks [@phryneas](https://github.com/phryneas)! - Create branded `QueryRef` type without exposed properties.\n\n  This change deprecates `QueryReference` in favor of a `QueryRef` type that doesn't expose any properties.\n  This change also updates `preloadQuery` to return a new `PreloadedQueryRef` type, which exposes the `toPromise` function as it does today. This means that query refs produced by `useBackgroundQuery` and `useLoadableQuery` now return `QueryRef` types that do not have access to a `toPromise` function, which was never meant to be used in combination with these hooks.\n\n  While we tend to avoid any types of breaking changes in patch releases as this, this change was necessary to support an upcoming version of the React Server Component integration, which needed to omit the `toPromise` function that would otherwise have broken at runtime.\n  Note that this is a TypeScript-only change. At runtime, `toPromise` is still present on all queryRefs currently created by this package - but we strongly want to discourage you from accessing it in all cases except for the `PreloadedQueryRef` use case.\n\n  Migration is as simple as replacing all references to `QueryReference` with `QueryRef`, so it should be possible to do this with a search & replace in most code bases:\n\n  ```diff\n  -import { QueryReference } from '@apollo/client'\n  +import { QueryRef } from '@apollo/client'\n\n  - function Component({ queryRef }: { queryRef: QueryReference<TData> }) {\n  + function Component({ queryRef }: { queryRef: QueryRef<TData> }) {\n    // ...\n  }\n  ```\n\n- [#11845](https://github.com/apollographql/apollo-client/pull/11845) [`4c5c820`](https://github.com/apollographql/apollo-client/commit/4c5c820b6172f6a2455bcdd974109513e0e2a39e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `@nonreactive` directives from queries passed to `MockLink` to ensure they are properly matched.\n\n- [#11837](https://github.com/apollographql/apollo-client/pull/11837) [`dff15b1`](https://github.com/apollographql/apollo-client/commit/dff15b1b03ebac9cae508c69bf607a29d0f6eccb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where a polled query created in React strict mode may not stop polling after the component unmounts while using the `cache-and-network` fetch policy.\n\n## 3.10.3\n\n### Patch Changes\n\n- [#11811](https://github.com/apollographql/apollo-client/pull/11811) [`d67d7f9`](https://github.com/apollographql/apollo-client/commit/d67d7f9a2943273cacaefb26a54184e81f12b022) Thanks [@phryneas](https://github.com/phryneas)! - Adjust some types for React 19 compat\n\n- [#11834](https://github.com/apollographql/apollo-client/pull/11834) [`7d8aad4`](https://github.com/apollographql/apollo-client/commit/7d8aad4a00b89e0208ee1563293c24025e6604ce) Thanks [@psamim](https://github.com/psamim)! - Fix error \"Cannot convert object to primitive value\"\n\n## 3.10.2\n\n### Patch Changes\n\n- [#11821](https://github.com/apollographql/apollo-client/pull/11821) [`2675d3c`](https://github.com/apollographql/apollo-client/commit/2675d3c97e6c47c6e298382004c7c9c2d3ffed0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix a regression where rerendering a component with `useBackgroundQuery` would recreate the `queryRef` instance when used with React's strict mode.\n\n- [#11821](https://github.com/apollographql/apollo-client/pull/11821) [`2675d3c`](https://github.com/apollographql/apollo-client/commit/2675d3c97e6c47c6e298382004c7c9c2d3ffed0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Revert the change introduced in\n  [3.9.10](https://github.com/apollographql/apollo-client/releases/tag/v3.9.10) via #11738 that disposed of queryRefs synchronously. This change caused too many issues with strict mode.\n\n## 3.10.1\n\n### Patch Changes\n\n- [#11792](https://github.com/apollographql/apollo-client/pull/11792) [`5876c35`](https://github.com/apollographql/apollo-client/commit/5876c35530a21473207954d1f0c2b7dd00c0b9ea) Thanks [@phryneas](https://github.com/phryneas)! - AutoCleanedCache: only schedule batched cache cleanup if the cache is full (fixes #11790)\n\n- [#11799](https://github.com/apollographql/apollo-client/pull/11799) [`1aca7ed`](https://github.com/apollographql/apollo-client/commit/1aca7ed5a3accf2303ccdf9b3dece7278f03ad62) Thanks [@phryneas](https://github.com/phryneas)! - `RenderPromises`: use `canonicalStringify` to serialize `variables` to ensure query deduplication is properly applied even when `variables` are specified in a different order.\n\n- [#11803](https://github.com/apollographql/apollo-client/pull/11803) [`bf9dd17`](https://github.com/apollographql/apollo-client/commit/bf9dd17b288f33901e9421bcc0eacb3894c087af) Thanks [@phryneas](https://github.com/phryneas)! - Update the `rehackt` dependency to `^0.1.0`\n\n- [#11756](https://github.com/apollographql/apollo-client/pull/11756) [`60592e9`](https://github.com/apollographql/apollo-client/commit/60592e95399c3695d1d49a4c39ad29f00d4059fd) Thanks [@henryqdineen](https://github.com/henryqdineen)! - Fix operation.setContext() type\n\n## 3.10.0\n\n### Minor Changes\n\n- [#11605](https://github.com/apollographql/apollo-client/pull/11605) [`e2dd4c9`](https://github.com/apollographql/apollo-client/commit/e2dd4c95290cea604b548cc446826d89aafe8e11) Thanks [@alessbell](https://github.com/alessbell)! - Adds `createMockFetch` utility for integration testing that includes the link chain\n\n- [#11760](https://github.com/apollographql/apollo-client/pull/11760) [`acd1982`](https://github.com/apollographql/apollo-client/commit/acd1982a59ed66fc44fa9e70b08a31c69dac35a6) Thanks [@alessbell](https://github.com/alessbell)! - `createTestSchema` now uses graphql-tools `mergeResolvers` to merge resolvers instead of a shallow merge.\n\n- [#11764](https://github.com/apollographql/apollo-client/pull/11764) [`f046aa9`](https://github.com/apollographql/apollo-client/commit/f046aa9fc24ac197a797045d280811a3bbe05806) Thanks [@alessbell](https://github.com/alessbell)! - Rename `createProxiedSchema` to `createTestSchema` and `createMockFetch` to `createSchemaFetch`.\n\n- [#11777](https://github.com/apollographql/apollo-client/pull/11777) [`5dfc79f`](https://github.com/apollographql/apollo-client/commit/5dfc79fa6d974362f38361f7dffbe984a9546377) Thanks [@alessbell](https://github.com/alessbell)! - Call `createMockSchema` inside `createTestSchema`.\n\n- [#11774](https://github.com/apollographql/apollo-client/pull/11774) [`2583488`](https://github.com/apollographql/apollo-client/commit/2583488677912cb4500e5fb9e3f91b5c113c4cdb) Thanks [@alessbell](https://github.com/alessbell)! - Add ability to set min and max delay in `createSchemaFetch`\n\n- [#11605](https://github.com/apollographql/apollo-client/pull/11605) [`e2dd4c9`](https://github.com/apollographql/apollo-client/commit/e2dd4c95290cea604b548cc446826d89aafe8e11) Thanks [@alessbell](https://github.com/alessbell)! - Adds proxiedSchema and createMockSchema testing utilities\n\n- [#11465](https://github.com/apollographql/apollo-client/pull/11465) [`7623da7`](https://github.com/apollographql/apollo-client/commit/7623da7720855b0c19e13ff9124679f426a39725) Thanks [@alessbell](https://github.com/alessbell)! - Add `watchFragment` method to the cache and expose it on ApolloClient, refactor `useFragment` using `watchFragment`.\n\n- [#11743](https://github.com/apollographql/apollo-client/pull/11743) [`78891f9`](https://github.com/apollographql/apollo-client/commit/78891f9ec81c0b7a7e010f5550a91965fa33a958) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove alpha designation for `queryRef.toPromise()` to stabilize the API.\n\n- [#11743](https://github.com/apollographql/apollo-client/pull/11743) [`78891f9`](https://github.com/apollographql/apollo-client/commit/78891f9ec81c0b7a7e010f5550a91965fa33a958) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove alpha designation for `createQueryPreloader` to stabilize the API.\n\n- [#11783](https://github.com/apollographql/apollo-client/pull/11783) [`440563a`](https://github.com/apollographql/apollo-client/commit/440563ab2c47efcb9c7d08f52531ade33d753037) Thanks [@alessbell](https://github.com/alessbell)! - Moves new testing utilities to their own entrypoint, `testing/experimental`\n\n### Patch Changes\n\n- [#11757](https://github.com/apollographql/apollo-client/pull/11757) [`9825295`](https://github.com/apollographql/apollo-client/commit/982529530893f66a1d236f0fff53862e513fc9a8) Thanks [@phryneas](https://github.com/phryneas)! - Adjust `useReadQuery` wrapper logic to work with transported objects.\n\n- [#11771](https://github.com/apollographql/apollo-client/pull/11771) [`e72cbba`](https://github.com/apollographql/apollo-client/commit/e72cbba07e5caa6d75b44ca8c766846e855a6c93) Thanks [@phryneas](https://github.com/phryneas)! - Wrap `useQueryRefHandlers` in `wrapHook`.\n\n- [#11754](https://github.com/apollographql/apollo-client/pull/11754) [`80d2ba5`](https://github.com/apollographql/apollo-client/commit/80d2ba579fe6d2a2d102d1fe79d7d503f31cd931) Thanks [@alessbell](https://github.com/alessbell)! - Export `WatchFragmentOptions` and `WatchFragmentResult` from main entrypoint and fix bug where `this` wasn't bound to the `watchFragment` method on `ApolloClient`.\n\n## 3.10.0-rc.1\n\n### Minor Changes\n\n- [#11760](https://github.com/apollographql/apollo-client/pull/11760) [`acd1982`](https://github.com/apollographql/apollo-client/commit/acd1982a59ed66fc44fa9e70b08a31c69dac35a6) Thanks [@alessbell](https://github.com/alessbell)! - `createTestSchema` now uses graphql-tools `mergeResolvers` to merge resolvers instead of a shallow merge.\n\n- [#11764](https://github.com/apollographql/apollo-client/pull/11764) [`f046aa9`](https://github.com/apollographql/apollo-client/commit/f046aa9fc24ac197a797045d280811a3bbe05806) Thanks [@alessbell](https://github.com/alessbell)! - Rename `createProxiedSchema` to `createTestSchema` and `createMockFetch` to `createSchemaFetch`.\n\n- [#11777](https://github.com/apollographql/apollo-client/pull/11777) [`5dfc79f`](https://github.com/apollographql/apollo-client/commit/5dfc79fa6d974362f38361f7dffbe984a9546377) Thanks [@alessbell](https://github.com/alessbell)! - Call `createMockSchema` inside `createTestSchema`.\n\n- [#11774](https://github.com/apollographql/apollo-client/pull/11774) [`2583488`](https://github.com/apollographql/apollo-client/commit/2583488677912cb4500e5fb9e3f91b5c113c4cdb) Thanks [@alessbell](https://github.com/alessbell)! - Add ability to set min and max delay in `createSchemaFetch`\n\n- [#11783](https://github.com/apollographql/apollo-client/pull/11783) [`440563a`](https://github.com/apollographql/apollo-client/commit/440563ab2c47efcb9c7d08f52531ade33d753037) Thanks [@alessbell](https://github.com/alessbell)! - Moves new testing utilities to their own entrypoint, `testing/experimental`\n\n### Patch Changes\n\n- [#11757](https://github.com/apollographql/apollo-client/pull/11757) [`9825295`](https://github.com/apollographql/apollo-client/commit/982529530893f66a1d236f0fff53862e513fc9a8) Thanks [@phryneas](https://github.com/phryneas)! - Adjust `useReadQuery` wrapper logic to work with transported objects.\n\n- [#11771](https://github.com/apollographql/apollo-client/pull/11771) [`e72cbba`](https://github.com/apollographql/apollo-client/commit/e72cbba07e5caa6d75b44ca8c766846e855a6c93) Thanks [@phryneas](https://github.com/phryneas)! - Wrap `useQueryRefHandlers` in `wrapHook`.\n\n- [#11754](https://github.com/apollographql/apollo-client/pull/11754) [`80d2ba5`](https://github.com/apollographql/apollo-client/commit/80d2ba579fe6d2a2d102d1fe79d7d503f31cd931) Thanks [@alessbell](https://github.com/alessbell)! - Export `WatchFragmentOptions` and `WatchFragmentResult` from main entrypoint and fix bug where `this` wasn't bound to the `watchFragment` method on `ApolloClient`.\n\n## 3.10.0-rc.0\n\n### Minor Changes\n\n- [#11605](https://github.com/apollographql/apollo-client/pull/11605) [`e2dd4c9`](https://github.com/apollographql/apollo-client/commit/e2dd4c95290cea604b548cc446826d89aafe8e11) Thanks [@alessbell](https://github.com/alessbell)! - Adds `createMockFetch` utility for integration testing that includes the link chain\n\n- [#11605](https://github.com/apollographql/apollo-client/pull/11605) [`e2dd4c9`](https://github.com/apollographql/apollo-client/commit/e2dd4c95290cea604b548cc446826d89aafe8e11) Thanks [@alessbell](https://github.com/alessbell)! - Adds proxiedSchema and createMockSchema testing utilities\n\n- [#11743](https://github.com/apollographql/apollo-client/pull/11743) [`78891f9`](https://github.com/apollographql/apollo-client/commit/78891f9ec81c0b7a7e010f5550a91965fa33a958) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove alpha designation for `queryRef.toPromise()` to stabilize the API.\n\n- [#11743](https://github.com/apollographql/apollo-client/pull/11743) [`78891f9`](https://github.com/apollographql/apollo-client/commit/78891f9ec81c0b7a7e010f5550a91965fa33a958) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove alpha designation for `createQueryPreloader` to stabilize the API.\n\n## 3.10.0-alpha.0\n\n### Minor Changes\n\n- [#11465](https://github.com/apollographql/apollo-client/pull/11465) [`7623da7`](https://github.com/apollographql/apollo-client/commit/7623da7720855b0c19e13ff9124679f426a39725) Thanks [@alessbell](https://github.com/alessbell)! - Add `watchFragment` method to the cache and expose it on ApolloClient, refactor `useFragment` using `watchFragment`.\n\n## 3.9.11\n\n### Patch Changes\n\n- [#11769](https://github.com/apollographql/apollo-client/pull/11769) [`04132af`](https://github.com/apollographql/apollo-client/commit/04132af121c9b48d6e03eb733b9b91f825defbac) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where using `skipToken` or the `skip` option with `useSuspenseQuery` in React's strict mode would perform a network request.\n\n## 3.9.10\n\n### Patch Changes\n\n- [#11738](https://github.com/apollographql/apollo-client/pull/11738) [`b1a5eb8`](https://github.com/apollographql/apollo-client/commit/b1a5eb80cae8bdf2e9d8627f1eab65e088c43438) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where rerendering `useBackgroundQuery` after the `queryRef` had been disposed, either via the auto dispose timeout or by unmounting `useReadQuery`, would cause the `queryRef` to be recreated potentially resulting in another network request.\n\n- [#11738](https://github.com/apollographql/apollo-client/pull/11738) [`b1a5eb8`](https://github.com/apollographql/apollo-client/commit/b1a5eb80cae8bdf2e9d8627f1eab65e088c43438) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Allow queryRefs to be disposed of synchronously when a suspense hook unmounts. This prevents some situations where using a suspense hook with the same query/variables as the disposed queryRef accidentally used the disposed queryRef rather than creating a new instance.\n\n- [#11670](https://github.com/apollographql/apollo-client/pull/11670) [`cc5c03b`](https://github.com/apollographql/apollo-client/commit/cc5c03b2690f452483d83eecb68611a23055d99e) Thanks [@phryneas](https://github.com/phryneas)! - Bail out of `executeSubSelectedArray` calls if the array has 0 elements.\n\n## 3.9.9\n\n### Patch Changes\n\n- [#11696](https://github.com/apollographql/apollo-client/pull/11696) [`466ef82`](https://github.com/apollographql/apollo-client/commit/466ef82198486fc696da64d17d82b46140760ac4) Thanks [@PiR1](https://github.com/PiR1)! - Immediately dispose of the `queryRef` if `useBackgroundQuery` unmounts before the auto dispose timeout kicks in.\n\n## 3.9.8\n\n### Patch Changes\n\n- [#11706](https://github.com/apollographql/apollo-client/pull/11706) [`8619bc7`](https://github.com/apollographql/apollo-client/commit/8619bc7e569c1c732afa6faf605c83a6ce0cdf0c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue in all suspense hooks where returning an empty array after calling `fetchMore` would rerender the component with an empty list.\n\n- [#11694](https://github.com/apollographql/apollo-client/pull/11694) [`835d5f3`](https://github.com/apollographql/apollo-client/commit/835d5f30c532c432e2434561580e6f1ec44cc908) Thanks [@phryneas](https://github.com/phryneas)! - Expose `setErrorMessageHandler` from `@apollo/client/dev` entrypoint.\n\n- [#11689](https://github.com/apollographql/apollo-client/pull/11689) [`cb8ffe5`](https://github.com/apollographql/apollo-client/commit/cb8ffe50e903397f741b62a44624bfe69b5f7b75) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where passing a new `from` option to `useFragment` would first render with the previous value before rerendering with the correct value.\n\n- [#11713](https://github.com/apollographql/apollo-client/pull/11713) [`642092c`](https://github.com/apollographql/apollo-client/commit/642092c713199093aede45f105a1ee3f637614cd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where setting a default `watchQuery` option in the `ApolloClient` constructor could break `startTransition` when used with suspense hooks.\n\n## 3.9.7\n\n### Patch Changes\n\n- [#11659](https://github.com/apollographql/apollo-client/pull/11659) [`652a61e`](https://github.com/apollographql/apollo-client/commit/652a61e96db0f0e27d0a22fafae1df388f3fdf36) Thanks [@phryneas](https://github.com/phryneas)! - Make `useRenderGuard` more resilient to changes in React internals.\n\n- [#11594](https://github.com/apollographql/apollo-client/pull/11594) [`50b1097`](https://github.com/apollographql/apollo-client/commit/50b10970ca0efa290ae415ef801650327a89ab8e) Thanks [@alessbell](https://github.com/alessbell)! - Adds a fix for multipart subscriptions that terminate with payload: null\n\n## 3.9.6\n\n### Patch Changes\n\n- [#11617](https://github.com/apollographql/apollo-client/pull/11617) [`f1d8bc4`](https://github.com/apollographql/apollo-client/commit/f1d8bc40c3d8e39340f721f4f1c3fd0ed77b8a6b) Thanks [@phryneas](https://github.com/phryneas)! - Allow Apollo Client instance to intercept hook functionality\n\n- [#11638](https://github.com/apollographql/apollo-client/pull/11638) [`bf93ada`](https://github.com/apollographql/apollo-client/commit/bf93adaa0321b573db0ea8fc3a5c364e1fdfeef3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where calling `fetchMore` from a suspense-enabled hook inside `startTransition` caused an unnecessary rerender.\n\n## 3.9.5\n\n### Patch Changes\n\n- [#11595](https://github.com/apollographql/apollo-client/pull/11595) [`8c20955`](https://github.com/apollographql/apollo-client/commit/8c20955874562e5b2ab35557325e047b059bc4fc) Thanks [@phryneas](https://github.com/phryneas)! - Bumps the dependency `rehackt` to 0.0.5\n\n- [#11592](https://github.com/apollographql/apollo-client/pull/11592) [`1133469`](https://github.com/apollographql/apollo-client/commit/1133469bd91ff76b9815e815a454a79d8e23a9bc) Thanks [@Stephen2](https://github.com/Stephen2)! - Strengthen `MockedResponse.newData` type\n\n- [#11579](https://github.com/apollographql/apollo-client/pull/11579) [`1ba2fd9`](https://github.com/apollographql/apollo-client/commit/1ba2fd919f79dfdc7b9d3f7d1a7aa5918e648349) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue where partial data is reported to `useQuery` when using `notifyOnNetworkStatusChange` after it errors while another overlapping query succeeds.\n\n- [#11579](https://github.com/apollographql/apollo-client/pull/11579) [`1ba2fd9`](https://github.com/apollographql/apollo-client/commit/1ba2fd919f79dfdc7b9d3f7d1a7aa5918e648349) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where a partial cache write for an errored query would result in automatically refetching that query.\n\n- [#11562](https://github.com/apollographql/apollo-client/pull/11562) [`65ab695`](https://github.com/apollographql/apollo-client/commit/65ab695470741e8dcaef1ebd7742c3c397526354) Thanks [@mspiess](https://github.com/mspiess)! - Mocks with an infinite delay no longer require result or error\n\n## 3.9.4\n\n### Patch Changes\n\n- [#11403](https://github.com/apollographql/apollo-client/pull/11403) [`b0c4f3a`](https://github.com/apollographql/apollo-client/commit/b0c4f3ad8198981a229b46dc430345a76e577e9c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix issue in `useLazyQuery` that results in a double network call when calling the execute function with no arguments after having called it previously with another set of arguments.\n\n- [#11576](https://github.com/apollographql/apollo-client/pull/11576) [`e855d00`](https://github.com/apollographql/apollo-client/commit/e855d00447e4d9ae478d98f6796d842ef6cc76d1) Thanks [@alessbell](https://github.com/alessbell)! - Revert PR [#11202](https://github.com/apollographql/apollo-client/pull/11202) to fix caching bug reported in [#11560](https://github.com/apollographql/apollo-client/issues/11560)\n\n## 3.9.3\n\n### Patch Changes\n\n- [#11525](https://github.com/apollographql/apollo-client/pull/11525) [`dce923a`](https://github.com/apollographql/apollo-client/commit/dce923ae57eb6b6d889e2980635cb90e2c6cbca3) Thanks [@vezaynk](https://github.com/vezaynk)! - Allows passing in client via options to useFragment\n\n- [#11558](https://github.com/apollographql/apollo-client/pull/11558) [`8cba16f`](https://github.com/apollographql/apollo-client/commit/8cba16f041609443111ecf5fb58faea1b3e79569) Thanks [@alessbell](https://github.com/alessbell)! - Fix [`unbound-method`](https://github.com/apollographql/apollo-client/issues/11554) linter error on ObservableQuery methods exposed on useQuery's QueryResult object.\n\n## 3.9.2\n\n### Patch Changes\n\n- [#11552](https://github.com/apollographql/apollo-client/pull/11552) [`6ac2b0c`](https://github.com/apollographql/apollo-client/commit/6ac2b0ce4d999c63478d85b40ad56ccda9624797) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix import in `useLazyRef` causing import issues in the nextjs package.\n\n## 3.9.1\n\n### Patch Changes\n\n- [#11516](https://github.com/apollographql/apollo-client/pull/11516) [`8390fea`](https://github.com/apollographql/apollo-client/commit/8390fea13175bada8361ba5f0df2e43197085aba) Thanks [@phryneas](https://github.com/phryneas)! - Fix an incorrect string substitution in a warning message.\n\n- [#11515](https://github.com/apollographql/apollo-client/pull/11515) [`c9bf93b`](https://github.com/apollographql/apollo-client/commit/c9bf93bdc2816f7fdba96961e1435f463f440bd1) Thanks [@vladar](https://github.com/vladar)! - Avoid redundant refetchQueries call for mutation with no-cache policy (fixes #10238)\n\n- [#11545](https://github.com/apollographql/apollo-client/pull/11545) [`84a6bea`](https://github.com/apollographql/apollo-client/commit/84a6beaeae69acdffea49ba6b8242752cc188172) Thanks [@alessbell](https://github.com/alessbell)! - Remove error thrown by `inFlightLinkObservables` intended to be removed before 3.9 release.\n\n## 3.9.0\n\n### Minor Changes\n\n#### Memory optimizations\n\n- [#11424](https://github.com/apollographql/apollo-client/pull/11424) [`62f3b6d`](https://github.com/apollographql/apollo-client/commit/62f3b6d0e89611e27d9f29812ee60e5db5963fd6) Thanks [@phryneas](https://github.com/phryneas)! - Simplify RetryLink, fix potential memory leak\n\n  Historically, `RetryLink` would keep a `values` array of all previous values, in case the operation would get an additional subscriber at a later point in time.\n\n  In practice, this could lead to a memory leak ([#11393](https://github.com/apollographql/apollo-client/pull/11393)) and did not serve any further purpose, as the resulting observable would only be subscribed to by Apollo Client itself, and only once - it would be wrapped in a `Concast` before being exposed to the user, and that `Concast` would handle subscribers on its own.\n\n- [#11435](https://github.com/apollographql/apollo-client/pull/11435) [`5cce53e`](https://github.com/apollographql/apollo-client/commit/5cce53e83b976f85d2d2b06e28cc38f01324fea1) Thanks [@phryneas](https://github.com/phryneas)! - Deprecates `canonizeResults`.\n\n  Using `canonizeResults` can result in memory leaks so we generally do not recommend using this option anymore. A future version of Apollo Client will contain a similar feature without the risk of memory leaks.\n\n- [#11254](https://github.com/apollographql/apollo-client/pull/11254) [`d08970d`](https://github.com/apollographql/apollo-client/commit/d08970d348cf4ad6d80c6baf85b4a4cd4034a3bb) Thanks [@benjamn](https://github.com/benjamn)! - Decouple `canonicalStringify` from `ObjectCanon` for better time and memory performance.\n\n- [#11356](https://github.com/apollographql/apollo-client/pull/11356) [`cc4ac7e`](https://github.com/apollographql/apollo-client/commit/cc4ac7e1917f046bcd177882727864eed40b910e) Thanks [@phryneas](https://github.com/phryneas)! - Fix a potential memory leak in `FragmentRegistry.transform` and `FragmentRegistry.findFragmentSpreads` that would hold on to passed-in `DocumentNodes` for too long.\n\n- [#11370](https://github.com/apollographql/apollo-client/pull/11370) [`25e2cb4`](https://github.com/apollographql/apollo-client/commit/25e2cb431c76ec5aa88202eaacbd98fad42edc7f) Thanks [@phryneas](https://github.com/phryneas)! - `parse` function: improve memory management\n\n  - use LRU `WeakCache` instead of `Map` to keep a limited number of parsed results\n  - cache is initiated lazily, only when needed\n  - expose `parse.resetCache()` method\n\n- [#11389](https://github.com/apollographql/apollo-client/pull/11389) [`139acd1`](https://github.com/apollographql/apollo-client/commit/139acd1153afa1445b69dcb4e139668ab8c5889a) Thanks [@phryneas](https://github.com/phryneas)! - `documentTransform`: use `optimism` and `WeakCache` instead of directly storing data on the `Trie`\n\n- [#11358](https://github.com/apollographql/apollo-client/pull/11358) [`7d939f8`](https://github.com/apollographql/apollo-client/commit/7d939f80fbc2c419c58a6c55b6a35ee7474d0379) Thanks [@phryneas](https://github.com/phryneas)! - Fixes a potential memory leak in `Concast` that might have been triggered when `Concast` was used outside of Apollo Client.\n\n- [#11344](https://github.com/apollographql/apollo-client/pull/11344) [`bd26676`](https://github.com/apollographql/apollo-client/commit/bd2667619700139af32a45364794d11f845ab6cf) Thanks [@phryneas](https://github.com/phryneas)! - Add a `resetCache` method to `DocumentTransform` and hook `InMemoryCache.addTypenameTransform` up to `InMemoryCache.gc`\n\n- [#11367](https://github.com/apollographql/apollo-client/pull/11367) [`30d17bf`](https://github.com/apollographql/apollo-client/commit/30d17bfebe44dbfa7b78c8982cfeb49afd37129c) Thanks [@phryneas](https://github.com/phryneas)! - `print`: use `WeakCache` instead of `WeakMap`\n\n- [#11387](https://github.com/apollographql/apollo-client/pull/11387) [`4dce867`](https://github.com/apollographql/apollo-client/commit/4dce8673b1757d8a3a4edd2996d780e86fad14e3) Thanks [@phryneas](https://github.com/phryneas)! - `QueryManager.transformCache`: use `WeakCache` instead of `WeakMap`\n\n- [#11369](https://github.com/apollographql/apollo-client/pull/11369) [`2a47164`](https://github.com/apollographql/apollo-client/commit/2a471646616e3af1b5c039e961f8d5717fad8f32) Thanks [@phryneas](https://github.com/phryneas)! - Persisted Query Link: improve memory management\n\n  - use LRU `WeakCache` instead of `WeakMap` to keep a limited number of hash results\n  - hash cache is initiated lazily, only when needed\n  - expose `persistedLink.resetHashCache()` method\n  - reset hash cache if the upstream server reports it doesn't accept persisted queries\n\n- [#10804](https://github.com/apollographql/apollo-client/pull/10804) [`221dd99`](https://github.com/apollographql/apollo-client/commit/221dd99ffd1990f8bd0392543af35e9b08d0fed8) Thanks [@phryneas](https://github.com/phryneas)! - use WeakMap in React Native with Hermes\n\n- [#11355](https://github.com/apollographql/apollo-client/pull/11355) [`7d8e184`](https://github.com/apollographql/apollo-client/commit/7d8e18493cd13134726c6643cbf0fadb08be2d37) Thanks [@phryneas](https://github.com/phryneas)! - InMemoryCache.gc now also triggers FragmentRegistry.resetCaches (if there is a FragmentRegistry)\n\n- [#11409](https://github.com/apollographql/apollo-client/pull/11409) [`2e7203b`](https://github.com/apollographql/apollo-client/commit/2e7203b3a9618952ddb522627ded7cceabd7f250) Thanks [@phryneas](https://github.com/phryneas)! - Adds an experimental `ApolloClient.getMemoryInternals` helper\n\n- [#11343](https://github.com/apollographql/apollo-client/pull/11343) [`776631d`](https://github.com/apollographql/apollo-client/commit/776631de4500d56252f6f5fdaf29a81c41dfbdc7) Thanks [@phryneas](https://github.com/phryneas)! - Add `reset` method to `print`, hook up to `InMemoryCache.gc`\n\n#### Suspense-enabled data fetching on user interaction with `useLoadableQuery`\n\n- [#11300](https://github.com/apollographql/apollo-client/pull/11300) [`a815873`](https://github.com/apollographql/apollo-client/commit/a8158733cfa3e65180ec23518d657ea41894bb2b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduces a new `useLoadableQuery` hook. This hook works similarly to `useBackgroundQuery` in that it returns a `queryRef` that can be used to suspend a component via the `useReadQuery` hook. It provides a more ergonomic way to load the query during a user interaction (for example when wanting to preload some data) that would otherwise be clunky with `useBackgroundQuery`.\n\n  ```tsx\n  function App() {\n    const [loadQuery, queryRef, { refetch, fetchMore, reset }] =\n      useLoadableQuery(query, options);\n\n    return (\n      <>\n        <button onClick={() => loadQuery(variables)}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <Child queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function Child({ queryRef }) {\n    const { data } = useReadQuery(queryRef);\n\n    // ...\n  }\n  ```\n\n#### Begin preloading outside of React with `createQueryPreloader`\n\n- [#11412](https://github.com/apollographql/apollo-client/pull/11412) [`58db5c3`](https://github.com/apollographql/apollo-client/commit/58db5c3295b88162f91019f0898f6baa4b9cced6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to start preloading a query outside React to begin fetching as early as possible. Call `createQueryPreloader` to create a `preloadQuery` function which can be called to start fetching a query. This returns a `queryRef` which is passed to `useReadQuery` and suspended until the query is done fetching.\n\n  ```tsx\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(QUERY, { variables, ...otherOptions });\n\n  function App() {\n    return {\n      <Suspense fallback={<div>Loading</div>}>\n        <MyQuery />\n      </Suspense>\n    }\n  }\n\n  function MyQuery() {\n    const { data } = useReadQuery(queryRef);\n\n    // do something with data\n  }\n  ```\n\n#### Testing utility improvements\n\n- [#11178](https://github.com/apollographql/apollo-client/pull/11178) [`4d64a6f`](https://github.com/apollographql/apollo-client/commit/4d64a6fa2ad5abe6f7f172c164f5e1fc2cb89829) Thanks [@sebakerckhof](https://github.com/sebakerckhof)! - Support re-using of mocks in the MockedProvider\n\n- [#6701](https://github.com/apollographql/apollo-client/pull/6701) [`8d2b4e1`](https://github.com/apollographql/apollo-client/commit/8d2b4e107d7c21563894ced3a65d631183b58fd9) Thanks [@prowe](https://github.com/prowe)! - Ability to dynamically match mocks\n\n  Adds support for a new property `MockedResponse.variableMatcher`: a predicate function that accepts a `variables` param. If `true`, the `variables` will be passed into the `ResultFunction` to help dynamically build a response.\n\n#### New `useQueryRefHandlers` hook\n\n- [#11412](https://github.com/apollographql/apollo-client/pull/11412) [`58db5c3`](https://github.com/apollographql/apollo-client/commit/58db5c3295b88162f91019f0898f6baa4b9cced6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Create a new `useQueryRefHandlers` hook that returns `refetch` and `fetchMore` functions for a given `queryRef`. This is useful to get access to handlers for a `queryRef` that was created by `createQueryPreloader` or when the handlers for a `queryRef` produced by a different component are inaccessible.\n\n  ```jsx\n  const MyComponent({ queryRef }) {\n    const { refetch, fetchMore } = useQueryRefHandlers(queryRef);\n\n    // ...\n  }\n  ```\n\n#### Bail out of `optimisticResponse` updates with the `IGNORE` sentinel object\n\n- [#11410](https://github.com/apollographql/apollo-client/pull/11410) [`07fcf6a`](https://github.com/apollographql/apollo-client/commit/07fcf6a3bf5bc78ffe6f3e598897246b4da02cbb) Thanks [@sf-twingate](https://github.com/sf-twingate)! - Allow returning `IGNORE` sentinel object from `optimisticResponse` functions to bail-out from the optimistic update.\n\n  Consider this example:\n\n  ```jsx\n  const UPDATE_COMMENT = gql`\n    mutation UpdateComment($commentId: ID!, $commentContent: String!) {\n      updateComment(commentId: $commentId, content: $commentContent) {\n        id\n        __typename\n        content\n      }\n    }\n  `;\n\n  function CommentPageWithData() {\n    const [mutate] = useMutation(UPDATE_COMMENT);\n    return (\n      <Comment\n        updateComment={({ commentId, commentContent }) =>\n          mutate({\n            variables: { commentId, commentContent },\n            optimisticResponse: (vars, { IGNORE }) => {\n              if (commentContent === \"foo\") {\n                // conditionally bail out of optimistic updates\n                return IGNORE;\n              }\n              return {\n                updateComment: {\n                  id: commentId,\n                  __typename: \"Comment\",\n                  content: commentContent,\n                },\n              };\n            },\n          })\n        }\n      />\n    );\n  }\n  ```\n\n  The `IGNORE` sentinel can be destructured from the second parameter in the callback function signature passed to `optimisticResponse`.\n\n#### Network adapters for multipart subscriptions usage with Relay and urql\n\n- [#11301](https://github.com/apollographql/apollo-client/pull/11301) [`46ab032`](https://github.com/apollographql/apollo-client/commit/46ab032af83a01f184bfcce5edba4b55dbb2962a) Thanks [@alessbell](https://github.com/alessbell)! - Add multipart subscription network adapters for Relay and urql\n\n  ##### Relay\n\n  ```tsx\n  import { createFetchMultipartSubscription } from \"@apollo/client/utilities/subscriptions/relay\";\n  import { Environment, Network, RecordSource, Store } from \"relay-runtime\";\n\n  const fetchMultipartSubs = createFetchMultipartSubscription(\n    \"http://localhost:4000\"\n  );\n\n  const network = Network.create(fetchQuery, fetchMultipartSubs);\n\n  export const RelayEnvironment = new Environment({\n    network,\n    store: new Store(new RecordSource()),\n  });\n  ```\n\n  ##### Urql\n\n  ```tsx\n  import { createFetchMultipartSubscription } from \"@apollo/client/utilities/subscriptions/urql\";\n  import { Client, fetchExchange, subscriptionExchange } from \"@urql/core\";\n\n  const url = \"http://localhost:4000\";\n\n  const multipartSubscriptionForwarder = createFetchMultipartSubscription(url);\n\n  const client = new Client({\n    url,\n    exchanges: [\n      fetchExchange,\n      subscriptionExchange({\n        forwardSubscription: multipartSubscriptionForwarder,\n      }),\n    ],\n  });\n  ```\n\n#### `skipPollAttempt` callback function\n\n- [#11397](https://github.com/apollographql/apollo-client/pull/11397) [`3f7eecb`](https://github.com/apollographql/apollo-client/commit/3f7eecbfbd4f4444cffcaac7dd9fd225c8c2a401) Thanks [@aditya-kumawat](https://github.com/aditya-kumawat)! - Adds a new `skipPollAttempt` callback function that's called whenever a refetch attempt occurs while polling. If the function returns `true`, the refetch is skipped and not reattempted until the next poll interval. This will solve the frequent use-case of disabling polling when the window is inactive.\n\n  ```ts\n  useQuery(QUERY, {\n    pollInterval: 1000,\n    skipPollAttempt: () => document.hidden, // or !document.hasFocus()\n  });\n  // or define it globally\n  new ApolloClient({\n    defaultOptions: {\n      watchQuery: {\n        skipPollAttempt: () => document.hidden, // or !document.hasFocus()\n      },\n    },\n  });\n  ```\n\n#### `QueryManager.inFlightLinkObservables` now uses a strong `Trie` as an internal data structure\n\n- [#11345](https://github.com/apollographql/apollo-client/pull/11345) [`1759066`](https://github.com/apollographql/apollo-client/commit/1759066a8f9a204e49228568aef9446a64890ff3) Thanks [@phryneas](https://github.com/phryneas)!\n\n  ##### Warning: requires `@apollo/experimental-nextjs-app-support` update\n\n  If you are using `@apollo/experimental-nextjs-app-support`, you will need to update that to at least 0.5.2, as it accesses this internal data structure.\n\n<details open>\n  <summary><h4>More Minor Changes</h4></summary>\n\n- [#11202](https://github.com/apollographql/apollo-client/pull/11202) [`7c2bc08`](https://github.com/apollographql/apollo-client/commit/7c2bc08b2ab46b9aa181d187a27aec2ad7129599) Thanks [@benjamn](https://github.com/benjamn)! - Prevent `QueryInfo#markResult` mutation of `result.data` and return cache data consistently whether complete or incomplete.\n\n- [#11442](https://github.com/apollographql/apollo-client/pull/11442) [`4b6f2bc`](https://github.com/apollographql/apollo-client/commit/4b6f2bccf3ba94643b38689b32edd2839e47aec1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the need to call `retain` from `useLoadableQuery` since `useReadQuery` will now retain the query. This means that a `queryRef` that is not consumed by `useReadQuery` within the given `autoDisposeTimeoutMs` will now be auto diposed for you.\n\n  Thanks to [#11412](https://github.com/apollographql/apollo-client/pull/11412), disposed query refs will be automatically resubscribed to the query when consumed by `useReadQuery` after it has been disposed.\n\n- [#11438](https://github.com/apollographql/apollo-client/pull/11438) [`6d46ab9`](https://github.com/apollographql/apollo-client/commit/6d46ab930a5e9bd5cae153d3b75b8966784fcd4e) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove the need to call `retain` from `useBackgroundQuery` since `useReadQuery` will now retain the query. This means that a `queryRef` that is not consumed by `useReadQuery` within the given `autoDisposeTimeoutMs` will now be auto diposed for you.\n\n  Thanks to [#11412](https://github.com/apollographql/apollo-client/pull/11412), disposed query refs will be automatically resubscribed to the query when consumed by `useReadQuery` after it has been disposed.\n\n- [#11175](https://github.com/apollographql/apollo-client/pull/11175) [`d6d1491`](https://github.com/apollographql/apollo-client/commit/d6d14911c40782cd6d69167b6f6169c890091ccb) Thanks [@phryneas](https://github.com/phryneas)! - To work around issues in React Server Components, especially with bundling for\n  the Next.js \"edge\" runtime we now use an external package to wrap `react` imports\n  instead of importing React directly.\n\n- [#11495](https://github.com/apollographql/apollo-client/pull/11495) [`1190aa5`](https://github.com/apollographql/apollo-client/commit/1190aa59a106217f7192c1f81099adfa5e4365c1) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Increase the default memory limits for `executeSelectionSet` and `executeSelectionSetArray`.\n\n</details>\n\n<details open>\n  <summary><h3>Patch Changes</h3></summary>\n\n- [#11275](https://github.com/apollographql/apollo-client/pull/11275) [`3862f9b`](https://github.com/apollographql/apollo-client/commit/3862f9ba9086394c4cf4c2ecd99e8e0f6cf44885) Thanks [@phryneas](https://github.com/phryneas)! - Add a `defaultContext` option and property on `ApolloClient`, e.g. for keeping track of changing auth tokens or dependency injection.\n\n  This can be used e.g. in authentication scenarios, where a new token might be generated outside of the link chain and should passed into the link chain.\n\n  ```js\n  import { ApolloClient, createHttpLink, InMemoryCache } from \"@apollo/client\";\n  import { setContext } from \"@apollo/client/link/context\";\n\n  const httpLink = createHttpLink({\n    uri: \"/graphql\",\n  });\n\n  const authLink = setContext((_, { headers, token }) => {\n    return {\n      headers: {\n        ...headers,\n        authorization: token ? `Bearer ${token}` : \"\",\n      },\n    };\n  });\n\n  const client = new ApolloClient({\n    link: authLink.concat(httpLink),\n    cache: new InMemoryCache(),\n  });\n\n  // somewhere else in your application\n  function onNewToken(newToken) {\n    // token can now be changed for future requests without need for a global\n    // variable, scoped ref or recreating the client\n    client.defaultContext.token = newToken;\n  }\n  ```\n\n- [#11443](https://github.com/apollographql/apollo-client/pull/11443) [`ff5a332`](https://github.com/apollographql/apollo-client/commit/ff5a332ff8b190c418df25371e36719d70061ebe) Thanks [@phryneas](https://github.com/phryneas)! - Adds a deprecation warning to the HOC and render prop APIs.\n\n  The HOC and render prop APIs have already been deprecated since 2020,\n  but we previously didn't have a `@deprecated` tag in the DocBlocks.\n\n- [#11385](https://github.com/apollographql/apollo-client/pull/11385) [`d9ca4f0`](https://github.com/apollographql/apollo-client/commit/d9ca4f0821c66ae4f03cf35a7ac93fe604cc6de3) Thanks [@phryneas](https://github.com/phryneas)! - ensure `defaultContext` is also used for mutations and subscriptions\n\n- [#11503](https://github.com/apollographql/apollo-client/pull/11503) [`67f62e3`](https://github.com/apollographql/apollo-client/commit/67f62e359bc471787d066319326e5582b4a635c8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Release changes from [`v3.8.10`](https://github.com/apollographql/apollo-client/releases/tag/v3.8.10)\n\n- [#11078](https://github.com/apollographql/apollo-client/pull/11078) [`14edebe`](https://github.com/apollographql/apollo-client/commit/14edebebefb7634c32b921d02c1c85c6c8737989) Thanks [@phryneas](https://github.com/phryneas)! - ObservableQuery: prevent reporting results of previous queries if the variables changed since\n\n- [#11439](https://github.com/apollographql/apollo-client/pull/11439) [`33454f0`](https://github.com/apollographql/apollo-client/commit/33454f0a40a05ea2b00633bda20a84d0ec3a4f4d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Address bundling issue introduced in [#11412](https://github.com/apollographql/apollo-client/pull/11412) where the `react/cache` internals ended up duplicated in the bundle. This was due to the fact that we had a `react/hooks` entrypoint that imported these files along with the newly introduced `createQueryPreloader` function, which lived outside of the `react/hooks` folder.\n\n- [#11371](https://github.com/apollographql/apollo-client/pull/11371) [`ebd8fe2`](https://github.com/apollographql/apollo-client/commit/ebd8fe2c1b8b50bfeb2da20aeca5671300fb5564) Thanks [@phryneas](https://github.com/phryneas)! - Clarify types of `EntityStore.makeCacheKey`.\n\n</details>\n\n## 3.8.10\n\n### Patch Changes\n\n- [#11489](https://github.com/apollographql/apollo-client/pull/11489) [`abfd02a`](https://github.com/apollographql/apollo-client/commit/abfd02abeb8585e44377e9e87e5d20e5d95be002) Thanks [@gronxb](https://github.com/gronxb)! - Fix `networkStatus` with `useSuspenseQuery` not properly updating to ready state when using a `cache-and-network` fetch policy that returns data equal to what is already in the cache.\n\n- [#11483](https://github.com/apollographql/apollo-client/pull/11483) [`6394dda`](https://github.com/apollographql/apollo-client/commit/6394dda47fa83d9ddd922e0d05e62bd872e4ea8e) Thanks [@pipopotamasu](https://github.com/pipopotamasu)! - Fix cache override warning output\n\n## 3.8.9\n\n### Patch Changes\n\n- [#11472](https://github.com/apollographql/apollo-client/pull/11472) [`afc844d`](https://github.com/apollographql/apollo-client/commit/afc844dd8d6f9f7a3e2003f9a5b541291dfe3fb4) Thanks [@alessbell](https://github.com/alessbell)! - Fix delay: Infinity when set on a MockResponse passed to Mocked Provider so it indefinitely enters loading state.\n\n- [#11464](https://github.com/apollographql/apollo-client/pull/11464) [`aac12b2`](https://github.com/apollographql/apollo-client/commit/aac12b221a6cb776d4941b6c8aadf04f0f0acd27) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prevent `useFragment` from excessively unsubscribing and resubscribing the fragment with the cache on every render.\n\n- [#11449](https://github.com/apollographql/apollo-client/pull/11449) [`f40cda4`](https://github.com/apollographql/apollo-client/commit/f40cda45841e93b056c781c19651b54464f7346a) Thanks [@phryneas](https://github.com/phryneas)! - Removes refences to the typescript \"dom\" lib.\n\n- [#11470](https://github.com/apollographql/apollo-client/pull/11470) [`e293bc9`](https://github.com/apollographql/apollo-client/commit/e293bc90d6f7937a6fc7c169f7b16eeb39d5fd49) Thanks [@phryneas](https://github.com/phryneas)! - Remove an unnecessary check from parseAndCheckHttpResponse.\n\n## 3.8.8\n\n### Patch Changes\n\n- [#11200](https://github.com/apollographql/apollo-client/pull/11200) [`ae5091a21`](https://github.com/apollographql/apollo-client/commit/ae5091a21f0feff1486503071ea8dc002cf1be41) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Enable `strict` in tsconfig for the entire project.\n\n- [#11332](https://github.com/apollographql/apollo-client/pull/11332) [`291aea56b`](https://github.com/apollographql/apollo-client/commit/291aea56bfaed3987a98be7fe4e6160114b62d2d) Thanks [@asvishnyakov](https://github.com/asvishnyakov)! - Add missed reexports of MutationFetchPolicy and RefetchWritePolicy to @apollo/client/core\n\n- [#10931](https://github.com/apollographql/apollo-client/pull/10931) [`e5acf910e`](https://github.com/apollographql/apollo-client/commit/e5acf910e39752b453540b6751046d1c19b66350) Thanks [@phryneas](https://github.com/phryneas)! - `useMutation`: also reset internal state on reset\n\n## 3.8.7\n\n### Patch Changes\n\n- [#11297](https://github.com/apollographql/apollo-client/pull/11297) [`c8c76a522`](https://github.com/apollographql/apollo-client/commit/c8c76a522e593de0d06cff73fde2d9e88152bed6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add an explicit return type for the `useReadQuery` hook called `UseReadQueryResult`. Previously the return type of this hook was inferred from the return value.\n\n- [#11337](https://github.com/apollographql/apollo-client/pull/11337) [`bb1da8349`](https://github.com/apollographql/apollo-client/commit/bb1da8349e785c54fb4030f269602c900adf23a0) Thanks [@phryneas](https://github.com/phryneas)! - #11206 used the TypeScript syntax `infer X extends Y` that was introduced in TS 4.8.\n  This caused some problems for some users, so we are rolling back to a more backwars-compatible (albeit slightly less performant) type.\n\n## 3.8.6\n\n### Patch Changes\n\n- [#11291](https://github.com/apollographql/apollo-client/pull/11291) [`2be7eafe3`](https://github.com/apollographql/apollo-client/commit/2be7eafe3c115d56d993dbda64d320550712df1f) Thanks [@ArioA](https://github.com/ArioA)! - Fix a bug that allows to only call `loadErrorMessages` without also calling `loadDevErrorMessages`.\n\n- [#11274](https://github.com/apollographql/apollo-client/pull/11274) [`b29f000f3`](https://github.com/apollographql/apollo-client/commit/b29f000f36f281e256809b5454eaeca2ec4450bf) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Start the query ref auto dispose timeout after the initial promise has settled. This prevents requests that run longer than the timeout duration from keeping the component suspended indefinitely.\n\n- [#11289](https://github.com/apollographql/apollo-client/pull/11289) [`b5894dbf0`](https://github.com/apollographql/apollo-client/commit/b5894dbf0fd5ea5ef1ff20dd896a658ef78c69dc) Thanks [@phryneas](https://github.com/phryneas)! - `MockedProvider`: default `connectToDevTools` to `false` in created `ApolloClient` instance.\n\n  This will prevent the mocked `ApolloClient` instance from trying to connect to the DevTools, which would start a `setTimeout` that might keep running after a test has finished.\n\n- [#11206](https://github.com/apollographql/apollo-client/pull/11206) [`dd2ce7687`](https://github.com/apollographql/apollo-client/commit/dd2ce7687ae9afa399e950a523fc7330284c25fe) Thanks [@phryneas](https://github.com/phryneas)! - `cache.modify`: Less strict types & new dev runtime warnings.\n\n## 3.8.5\n\n### Patch Changes\n\n- [#11266](https://github.com/apollographql/apollo-client/pull/11266) [`5192cf6e1`](https://github.com/apollographql/apollo-client/commit/5192cf6e1e958080bcae09e5967fa6851bd3a78c) Thanks [@phryneas](https://github.com/phryneas)! - Fixes argument handling for invariant log messages.\n\n- [#11235](https://github.com/apollographql/apollo-client/pull/11235) [`6cddaaf65`](https://github.com/apollographql/apollo-client/commit/6cddaaf6543f5c0b1fb04ba47480fb393ba10de7) Thanks [@phryneas](https://github.com/phryneas)! - Fix nextFetchPolicy behaviour with transformed documents by keeping `options` reference stable when passing it through QueryManager.\n\n- [#11252](https://github.com/apollographql/apollo-client/pull/11252) [`327a2abbd`](https://github.com/apollographql/apollo-client/commit/327a2abbd5db87ca27f2ffd1d2f8dccd75868a58) Thanks [@phryneas](https://github.com/phryneas)! - Fixes a race condition in asyncMap that caused issues in React Native when errors were returned in the response payload along with a data property that was null.\n\n- [#11229](https://github.com/apollographql/apollo-client/pull/11229) [`c372bad4e`](https://github.com/apollographql/apollo-client/commit/c372bad4ebd01a4f2e772cd76e873143bf043fe6) Thanks [@phryneas](https://github.com/phryneas)! - Remove (already throwing) SuspenseCache export that should have been removed in 3.8.\n\n- [#11267](https://github.com/apollographql/apollo-client/pull/11267) [`bc055e068`](https://github.com/apollographql/apollo-client/commit/bc055e0683e87b9445e321f73857f4a91b20a9ce) Thanks [@phryneas](https://github.com/phryneas)! - Remove some dead code.\n\n## 3.8.4\n\n### Patch Changes\n\n- [#11195](https://github.com/apollographql/apollo-client/pull/11195) [`9e59b251d`](https://github.com/apollographql/apollo-client/commit/9e59b251d4d63afb83d9821889f87c71c4adde0f) Thanks [@phryneas](https://github.com/phryneas)! - For `invariant.log` etc., error arguments are now serialized correctly in the link to the error page.\n\n## 3.8.3\n\n### Patch Changes\n\n- [#11193](https://github.com/apollographql/apollo-client/pull/11193) [`fd2a4cf0c`](https://github.com/apollographql/apollo-client/commit/fd2a4cf0c3ada968df3f9814d87dedaaa8eddb5e) Thanks [@phryneas](https://github.com/phryneas)! - Call devtools registration after ApolloClient is fully set up.\n\n## 3.8.2\n\n### Patch Changes\n\n- [#10072](https://github.com/apollographql/apollo-client/pull/10072) [`51045c336`](https://github.com/apollographql/apollo-client/commit/51045c336ff86befbdd598af6e7104ffe0d419d0) Thanks [@Huulivoide](https://github.com/Huulivoide)! - Fixes race conditions in useReactiveVar that may prevent updates to the reactive variable from propagating through the hook.\n\n- [#11162](https://github.com/apollographql/apollo-client/pull/11162) [`d9685f53c`](https://github.com/apollographql/apollo-client/commit/d9685f53c34483245e6ea21e91b669ef1180ae97) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensures GraphQL errors returned in subscription payloads adhere to the `errorPolicy` set in `client.subscribe(...)` calls.\n\n- [#11134](https://github.com/apollographql/apollo-client/pull/11134) [`96492e142`](https://github.com/apollographql/apollo-client/commit/96492e14279d78e2613c1381d31f88cdf5816f45) Thanks [@alessbell](https://github.com/alessbell)! - Use separate type imports in useSuspenseQuery and useBackgroundQuery to workaround SWC compiler issue.\n\n- [#11117](https://github.com/apollographql/apollo-client/pull/11117) [`6b8198109`](https://github.com/apollographql/apollo-client/commit/6b8198109bd9fe5eedf352421a0a773ac0acfb18) Thanks [@phryneas](https://github.com/phryneas)! - Adds a new devtools registration mechanism and tweaks the mechanism behind the\n  \"devtools not found\" mechanic.\n\n- [#11186](https://github.com/apollographql/apollo-client/pull/11186) [`f1d429f32`](https://github.com/apollographql/apollo-client/commit/f1d429f32ae8e896155b50f1fc7c51dfeb06c3ba) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where race conditions when rapidly switching between variables would sometimes result in the wrong `data` returned from the query. Specifically this occurs when a query is triggered with an initial set of variables (`VariablesA`), then triggers the same query with another set of variables (`VariablesB`) but switches back to the `VariablesA` before the response for `VariablesB` is returned. Previously this would result in the data for `VariablesB` to be displayed while `VariablesA` was active. The data is for `VariablesA` is now properly returned.\n\n- [#11163](https://github.com/apollographql/apollo-client/pull/11163) [`a8a9e11e9`](https://github.com/apollographql/apollo-client/commit/a8a9e11e917716538206eb7d5de21dbfd09630bd) Thanks [@bignimbus](https://github.com/bignimbus)! - Fix typo in error message: \"occured\" -> \"occurred\"\n\n- [#11180](https://github.com/apollographql/apollo-client/pull/11180) [`7d9c481e5`](https://github.com/apollographql/apollo-client/commit/7d9c481e53f3c9577ec6ed6231c9e3db8c8b374b) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixes an issue where refetching from `useBackgroundQuery` via `refetch` with an error after an error was already fetched would get stuck in a loading state.\n\n## 3.8.1\n\n### Patch Changes\n\n- [#11141](https://github.com/apollographql/apollo-client/pull/11141) [`c469b1616`](https://github.com/apollographql/apollo-client/commit/c469b1616517aac124a3357066cd83439463033c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove newly exported response iterator helpers that caused problems on some installs where `@types/node` was not available.\n\n  **IMPORTANT**\n\n  The following exports were added in version 3.8.0 that are removed with this patch.\n\n  - `isAsyncIterableIterator`\n  - `isBlob`\n  - `isNodeReadableStream`\n  - `isNodeResponse`\n  - `isReadableStream`\n  - `isStreamableBlob`\n\n## 3.8.0\n\n### Minor Changes\n\n#### Fetching with Suspense 🎉\n\n- [#10323](https://github.com/apollographql/apollo-client/pull/10323) [`64cb88a4b`](https://github.com/apollographql/apollo-client/commit/64cb88a4b6be8640c4e0d753dd06ddf4c25a2bc3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for React suspense with a new `useSuspenseQuery` hook.\n\n  `useSuspenseQuery` initiates a network request and causes the component calling it to suspend while the request is in flight. It can be thought of as a drop-in replacement for `useQuery` that allows you to take advantage of React's concurrent features while fetching during render.\n\n  Consider a `Dog` component that fetches and renders some information about a dog named Mozzarella:\n\n  <details>\n    <summary>View code 🐶</summary>\n\n  ```tsx\n  import { Suspense } from \"react\";\n  import { gql, TypedDocumentNode, useSuspenseQuery } from \"@apollo/client\";\n\n  interface Data {\n    dog: {\n      id: string;\n      name: string;\n    };\n  }\n\n  interface Variables {\n    name: string;\n  }\n\n  const GET_DOG_QUERY: TypedDocumentNode<Data, Variables> = gql`\n    query GetDog($name: String) {\n      dog(name: $name) {\n        id\n        name\n      }\n    }\n  `;\n\n  function App() {\n    return (\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog name=\"Mozzarella\" />\n      </Suspense>\n    );\n  }\n\n  function Dog({ name }: { name: string }) {\n    const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n      variables: { name },\n    });\n\n    return <>Name: {data.dog.name}</>;\n  }\n  ```\n\n  </details>\n\n  For a detailed explanation of `useSuspenseQuery`, see our [fetching with Suspense reference](https://www.apollographql.com/docs/react/data/suspense).\n\n- [#10755](https://github.com/apollographql/apollo-client/pull/10755) [`e3c676deb`](https://github.com/apollographql/apollo-client/commit/e3c676deb59d006f33d24a7211e58725a67641b8) Thanks [@alessbell](https://github.com/alessbell)! - Feature: adds `useBackgroundQuery` and `useReadQuery` hooks\n\n  `useBackgroundQuery` initiates a request for data in a parent component and returns a `QueryReference` which is used to read the data in a child component via `useReadQuery`. If the child component attempts to render before the data can be found in the cache, the child component will suspend until the data is available. On cache updates to watched data, the child component calling `useReadQuery` will re-render with new data **but the parent component will not re-render** (as it would, for example, if it were using `useQuery` to issue the request).\n\n  Consider an `App` component that fetches a list of breeds in the background while also fetching and rendering some information about an individual dog, Mozzarella:\n\n  <details>\n    <summary>View code 🐶</summary>\n\n  ```tsx\n  function App() {\n    const [queryRef] = useBackgroundQuery(GET_BREEDS_QUERY);\n    return (\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog name=\"Mozzarella\" queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  function Dog({\n    name,\n    queryRef,\n  }: {\n    name: string;\n    queryRef: QueryReference<BreedData>;\n  }) {\n    const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n      variables: { name },\n    });\n    return (\n      <>\n        Name: {data.dog.name}\n        <Suspense fallback={<div>Loading breeds...</div>}>\n          <Breeds queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  function Breeds({ queryRef }: { queryRef: QueryReference<BreedData> }) {\n    const { data } = useReadQuery(queryRef);\n    return data.breeds.map(({ characteristics }) =>\n      characteristics.map((characteristic) => (\n        <div key={characteristic}>{characteristic}</div>\n      ))\n    );\n  }\n  ```\n\n  </details>\n\n  For a detailed explanation of `useBackgroundQuery` and `useReadQuery`, see our [fetching with Suspense reference](https://www.apollographql.com/docs/react/data/suspense).\n\n#### Document transforms 📑\n\n- [#10509](https://github.com/apollographql/apollo-client/pull/10509) [`79df2c7ba`](https://github.com/apollographql/apollo-client/commit/79df2c7ba55b7cfee69fd54024174f77099a2550) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to specify custom GraphQL document transforms. These transforms are run before reading data from the cache, before local state is resolved, and before the query document is sent through the link chain.\n\n  To register a custom document transform, create a transform using the `DocumentTransform` class and pass it to the `documentTransform` option on `ApolloClient`.\n\n  ```ts\n  import { DocumentTransform } from \"@apollo/client\";\n\n  const documentTransform = new DocumentTransform((document) => {\n    // do something with `document`\n    return transformedDocument;\n  });\n\n  const client = new ApolloClient({ documentTransform: documentTransform });\n  ```\n\n  For more information on the behavior and API of `DocumentTransform`, see its [reference page in our documentation](https://www.apollographql.com/docs/react/data/document-transforms).\n\n#### New `removeTypenameFromVariables` link 🔗\n\n- [#10853](https://github.com/apollographql/apollo-client/pull/10853) [`300957960`](https://github.com/apollographql/apollo-client/commit/300957960a584920f2d346d29a0b3aaeb27d9489) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduce the new `removeTypenameFromVariables` link. This link will automatically remove `__typename` fields from `variables` for all operations. This link can be configured to exclude JSON-scalars for scalars that utilize `__typename`.\n\n  This change undoes some work from [#10724](https://github.com/apollographql/apollo-client/pull/10724) where `__typename` was automatically stripped for all operations with no configuration. This was determined to be a breaking change and therefore moved into this link.\n\n  For a detailed explanation of `removeTypenameFromVariables`, see its [API reference](https://www.apollographql.com/docs/react/api/link/apollo-link-remove-typename).\n\n#### New `skipToken` sentinel ⏭️\n\n- [#11112](https://github.com/apollographql/apollo-client/pull/11112) [`b4aefcfe9`](https://github.com/apollographql/apollo-client/commit/b4aefcfe97213461b9ce01946344e6a5e6d80704) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Adds support for a `skipToken` sentinel that can be used as `options` in `useSuspenseQuery` and `useBackgroundQuery` to skip execution of a query. This works identically to the `skip` option but is more type-safe and as such, becomes the recommended way to skip query execution. As such, the `skip` option has been deprecated in favor of `skipToken`.\n\n  We are considering the removal of the `skip` option from `useSuspenseQuery` and `useBackgroundQuery` in the next major. We are releasing with it now to make migration from `useQuery` easier and make `skipToken` more discoverable.\n\n  **`useSuspenseQuery`**\n\n  ```ts\n  import { skipToken, useSuspenseQuery } from \"@apollo/client\";\n\n  const id: number | undefined;\n\n  const { data } = useSuspenseQuery(\n    query,\n    id ? { variables: { id } } : skipToken\n  );\n  ```\n\n  **`useBackgroundQuery`**\n\n  ```ts\n  import { skipToken, useBackgroundQuery } from \"@apollo/client\";\n\n  function Parent() {\n    const [queryRef] = useBackgroundQuery(\n      query,\n      id ? { variables: { id } } : skipToken\n    );\n\n    return queryRef ? <Child queryRef={queryRef} /> : null;\n  }\n\n  function Child({ queryRef }: { queryRef: QueryReference<TData> }) {\n    const { data } = useReadQuery(queryRef);\n  }\n  ```\n\n  For a detailed explanation of `skipToken`, see its [API reference](https://www.apollographql.com/docs/react/api/react/hooks/#skiptoken).\n\n#### New error extraction mechanism, smaller bundles 📉\n\n- [#10887](https://github.com/apollographql/apollo-client/pull/10887) [`f8c0b965d`](https://github.com/apollographql/apollo-client/commit/f8c0b965d49fb7d802371bb9cc3cb0b60cf05e5d) Thanks [@phryneas](https://github.com/phryneas)! - Add a new mechanism for Error Extraction to reduce bundle size by including error message texts on an opt-in basis.\n\n  By default, errors will link to an error page with the entire error message.\n  This replaces \"development\" and \"production\" errors and works without\n  additional bundler configuration.\n\n  Bundling the text of error messages and development warnings can be enabled as follows:\n\n  ```js\n  import { loadErrorMessages, loadDevMessages } from \"@apollo/client/dev\";\n  if (process.env.NODE_ENV !== \"production\") {\n    loadErrorMessages();\n    loadDevMessages();\n  }\n  ```\n\n  For a detailed explanation, see our [reference on reducing bundle size](https://www.apollographql.com/docs/react/development-testing/reducing-bundle-size).\n\n#### New `@nonreactive` directive 🎬\n\n- [#10722](https://github.com/apollographql/apollo-client/pull/10722) [`c7e60f83d`](https://github.com/apollographql/apollo-client/commit/c7e60f83dd1dfe07a1b6ce60d9675d3616a2ce66) Thanks [@benjamn](https://github.com/benjamn)! - Implement a `@nonreactive` directive for selectively skipping reactive comparisons of query result subtrees.\n\n  The `@nonreactive` directive can be used to mark query fields or fragment spreads and is used to indicate that changes to the data contained within the subtrees marked `@nonreactive` should _not_ trigger re-rendering. This allows parent components to fetch data to be rendered by their children without re-rendering themselves when the data corresponding with fields marked as `@nonreactive` change.\n\n  Consider an `App` component that fetches and renders a list of ski trails:\n\n  <details>\n    <summary>View code 🎿</summary>\n\n  ```jsx\n  const TrailFragment = gql`\n    fragment TrailFragment on Trail {\n      name\n      status\n    }\n  `;\n\n  const ALL_TRAILS = gql`\n    query allTrails {\n      allTrails {\n        id\n        ...TrailFragment @nonreactive\n      }\n    }\n    ${TrailFragment}\n  `;\n\n  function App() {\n    const { data, loading } = useQuery(ALL_TRAILS);\n    return (\n      <main>\n        <h2>Ski Trails</h2>\n        <ul>\n          {data?.trails.map((trail) => (\n            <Trail key={trail.id} id={trail.id} />\n          ))}\n        </ul>\n      </main>\n    );\n  }\n  ```\n\n  </details>\n\n  The `Trail` component renders a trail's name and status and allows the user to execute a mutation to toggle the status of the trail between `\"OPEN\"` and `\"CLOSED\"`:\n\n  <details>\n    <summary>View code 🎿</summary>\n\n  ```jsx\n  const Trail = ({ id }) => {\n    const [updateTrail] = useMutation(UPDATE_TRAIL);\n    const { data } = useFragment({\n      fragment: TrailFragment,\n      from: {\n        __typename: \"Trail\",\n        id,\n      },\n    });\n    return (\n      <li key={id}>\n        {data.name} - {data.status}\n        <input\n          checked={data.status === \"OPEN\" ? true : false}\n          type=\"checkbox\"\n          onChange={(e) => {\n            updateTrail({\n              variables: {\n                trailId: id,\n                status: e.target.checked ? \"OPEN\" : \"CLOSED\",\n              },\n            });\n          }}\n        />\n      </li>\n    );\n  };\n  ```\n\n  </details>\n\n  Notice that the `Trail` component isn't receiving the entire `trail` object via props, only the `id` which is used along with the fragment document to create a live binding for each trail item in the cache. This allows each `Trail` component to react to the cache updates for a single trail independently. Updates to a trail's `status` will not cause the parent `App` component to rerender since the `@nonreactive` directive is applied to the `TrailFragment` spread, a fragment that includes the `status` field.\n\n  For a detailed explanation, see our [`@nonreactive` reference](https://www.apollographql.com/docs/react/data/directives/#nonreactive) and [@alessbell](https://github.com/alessbell)'s [post on the Apollo blog about using `@nonreactive` with `useFragment`](https://www.apollographql.com/blog/apollo-client/introducing-apollo-clients-nonreactive-directive-and-usefragment-hook/).\n\n#### Abort the `AbortController` signal more granularly 🛑\n\n- [#11040](https://github.com/apollographql/apollo-client/pull/11040) [`125ef5b2a`](https://github.com/apollographql/apollo-client/commit/125ef5b2a8fd2de1515b2bdd71785ebab3596cb2) Thanks [@phryneas](https://github.com/phryneas)! - `HttpLink`/`BatchHttpLink`: Abort the `AbortController` signal more granularly.\n\n  Before this change, when `HttpLink`/`BatchHttpLink` created an `AbortController` internally, the signal would always be `.abort`ed after the request was completed. This could cause issues with Sentry Session Replay and Next.js App Router Cache invalidations, which just replayed the fetch with the same options - including the cancelled `AbortSignal`.\n\n  With this change, the `AbortController` will only be `.abort()`ed by outside events, not as a consequence of the request completing.\n\n#### `useFragment` drops its experimental label 🎓\n\n- [#10916](https://github.com/apollographql/apollo-client/pull/10916) [`ea75e18de`](https://github.com/apollographql/apollo-client/commit/ea75e18dec3db090dd4ed3b2d249bf674b90ead4) Thanks [@alessbell](https://github.com/alessbell)! - Remove experimental labels.\n\n  `useFragment`, introduced in `3.7.0` as `useFragment_experimental`, is no longer an experimental API 🎉 We've removed the `_experimental` suffix from its named export and have made a number of improvements.\n\n  For a detailed explanation, see our [`useFragment` reference](https://www.apollographql.com/docs/react/api/react/hooks#usefragment) and [@alessbell](https://github.com/alessbell)'s [post on the Apollo blog](https://www.apollographql.com/blog/apollo-client/introducing-apollo-clients-nonreactive-directive-and-usefragment-hook/) about using `useFragment` with `@nonreactive` for improved performance when rendering lists.\n\n  <details>\n  <summary><h5><code>useFragment</code> improvements</h5></summary>\n\n  - [#10765](https://github.com/apollographql/apollo-client/pull/10765) [`35f36c5aa`](https://github.com/apollographql/apollo-client/commit/35f36c5aaefe1f215044e09fdf9386042bc59dd2) Thanks [@phryneas](https://github.com/phryneas)! - More robust types for the `data` property on `UseFragmentResult`. When a partial result is given, the type is now correctly set to `Partial<TData>`.\n\n  - [#11083](https://github.com/apollographql/apollo-client/pull/11083) [`f766e8305`](https://github.com/apollographql/apollo-client/commit/f766e8305d9f2dbde59a61b8e70c99c4b2b67d55) Thanks [@phryneas](https://github.com/phryneas)! - Adjust the rerender timing of `useQuery` to more closely align with `useFragment`. This means that cache updates delivered to both hooks should trigger renders at relatively the same time. Previously, the `useFragment` might rerender much faster leading to some confusion.\n\n  - [#10836](https://github.com/apollographql/apollo-client/pull/10836) [`6794893c2`](https://github.com/apollographql/apollo-client/commit/6794893c29cc945aa99f6fe54a9e4e70ec3e57fd) Thanks [@phryneas](https://github.com/phryneas)! - Remove the deprecated `returnPartialData` option from `useFragment` hook.\n\n  </details>\n\n<details open>\n  <summary><h4>More Minor Changes</h4></summary>\n\n- [#10895](https://github.com/apollographql/apollo-client/pull/10895) [`e187866fd`](https://github.com/apollographql/apollo-client/commit/e187866fdfbbd1e1e30646f289367fb4b5afb3c3) Thanks [@Gelio](https://github.com/Gelio)! - Add generic type parameter for the entity modified in `cache.modify`. Improves TypeScript type inference for that type's fields and values of those fields.\n\n  Example:\n\n  ```ts\n  cache.modify<Book>({\n    id: cache.identify(someBook),\n    fields: {\n      title: (title) => {\n        // title has type `string`.\n        // It used to be `any`.\n      },\n   => {\n        // author has type `Reference | Book[\"author\"]`.\n        // It used to be `any`.\n      },\n    },\n  });\n  ```\n\n- [#10895](https://github.com/apollographql/apollo-client/pull/10895) [`e187866fd`](https://github.com/apollographql/apollo-client/commit/e187866fdfbbd1e1e30646f289367fb4b5afb3c3) Thanks [@Gelio](https://github.com/Gelio)! - Use unique opaque types for the `DELETE` and `INVALIDATE` Apollo cache modifiers.\n\n  This increases type safety, since these 2 modifiers no longer have the `any` type. Moreover, it no longer triggers [the `@typescript-eslint/no-unsafe-return`\n  rule](https://typescript-eslint.io/rules/no-unsafe-return/).\n\n- [#10340](https://github.com/apollographql/apollo-client/pull/10340) [`4f73c5ca1`](https://github.com/apollographql/apollo-client/commit/4f73c5ca15d367aa23f02018d062f221c4506a4d) Thanks [@alessbell](https://github.com/alessbell)! - Avoid calling `useQuery` `onCompleted` for cache writes\n\n- [#10527](https://github.com/apollographql/apollo-client/pull/10527) [`0cc7e2e19`](https://github.com/apollographql/apollo-client/commit/0cc7e2e194f84e137a502395f26acdaef392ecae) Thanks [@phryneas](https://github.com/phryneas)! - Remove the `query`/`mutation`/`subscription` option from hooks that already take that value as their first argument.\n\n- [#10506](https://github.com/apollographql/apollo-client/pull/10506) [`2dc2e1d4f`](https://github.com/apollographql/apollo-client/commit/2dc2e1d4f77318d8a4c29445344b4f8c5b08b7e3) Thanks [@phryneas](https://github.com/phryneas)! - prevent accidental widening of inferred `TData` and `TVariables` generics for query hook option arguments\n\n- [#10521](https://github.com/apollographql/apollo-client/pull/10521) [`fbf729414`](https://github.com/apollographql/apollo-client/commit/fbf729414b6322a84158d9864bdfb5b17b2c7d77) Thanks [@benjamn](https://github.com/benjamn)! - Simplify `__DEV__` polyfill to use imports instead of global scope\n\n- [#10994](https://github.com/apollographql/apollo-client/pull/10994) [`2ebbd3abb`](https://github.com/apollographql/apollo-client/commit/2ebbd3abb31224ed383896ebea7c2791c9b42a22) Thanks [@phryneas](https://github.com/phryneas)! - Add .js file extensions to imports in src and dist/\\*_/_.d.ts\n\n- [#11045](https://github.com/apollographql/apollo-client/pull/11045) [`9c1d4a104`](https://github.com/apollographql/apollo-client/commit/9c1d4a104d721993b5b306ca4c21724a974e098d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - When changing variables back to a previously used set of variables, do not automatically cache the result as part of the query reference. Instead, dispose of the query reference so that the `InMemoryCache` can determine the cached behavior. This means that fetch policies that would guarantee a network request are now honored when switching back to previously used variables.\n\n- [#11058](https://github.com/apollographql/apollo-client/pull/11058) [`89bf33c42`](https://github.com/apollographql/apollo-client/commit/89bf33c425d08880eeaed4584bdd56c4caf085e7) Thanks [@phryneas](https://github.com/phryneas)! - (Batch)HttpLink: Propagate `AbortError`s to the user when a user-provided `signal` is passed to the link. Previously, these links would swallow all `AbortErrors`, potentially causing queries and mutations to never resolve. As a result of this change, users are now expected to handle `AbortError`s when passing in a user-provided `signal`.\n\n- [#10346](https://github.com/apollographql/apollo-client/pull/10346) [`3bcfc42d3`](https://github.com/apollographql/apollo-client/commit/3bcfc42d394b6a97900495eacdaf58c31ae96d9f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add the ability to allow `@client` fields to be sent to the link chain.\n\n- [#10567](https://github.com/apollographql/apollo-client/pull/10567) [`c2ce6496c`](https://github.com/apollographql/apollo-client/commit/c2ce6496c10e7ae7e29d25161c2d3cef3e2c6144) Thanks [@benjamn](https://github.com/benjamn)! - Allow `ApolloCache` implementations to specify default value for `assumeImmutableResults` client option, improving performance for applications currently using `InMemoryCache` without configuring `new ApolloClient({ assumeImmutableResults: true })`\n\n- [#10915](https://github.com/apollographql/apollo-client/pull/10915) [`3a62d8228`](https://github.com/apollographql/apollo-client/commit/3a62d8228ab6c15cdb7cd4ea106d13ba3e6f0029) Thanks [@phryneas](https://github.com/phryneas)! - Changes how development-only code is bundled in the library to more reliably enable consuming bundlers to reduce production bundle sizes while keeping compatibility with non-node environments.\n\n</details>\n\n<details open>\n  <summary><h3>Patch Changes</h3></summary>\n\n- [#11086](https://github.com/apollographql/apollo-client/pull/11086) [`0264fee06`](https://github.com/apollographql/apollo-client/commit/0264fee066cb715602eda26c7c0bb1254469eccb) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where a call to `refetch`, `fetchMore`, or changing `skip` to `false` that returned a result deeply equal to data in the cache would get stuck in a pending state and never resolve.\n\n- [#11053](https://github.com/apollographql/apollo-client/pull/11053) [`c0ca70720`](https://github.com/apollographql/apollo-client/commit/c0ca70720cf5fbedd6e4f128b460c1995d9c55a7) Thanks [@phryneas](https://github.com/phryneas)! - Add `SuspenseCache` as a lazy hidden property on ApolloClient.\n  This means that `SuspenseCache` is now an implementation details of Apollo Client and you no longer need to manually instantiate it and no longer need to pass it into `ApolloProvider`. Trying to instantiate a `SuspenseCache` instance in your code will now throw an error.\n\n- [#11115](https://github.com/apollographql/apollo-client/pull/11115) [`78739e3ef`](https://github.com/apollographql/apollo-client/commit/78739e3efe86f6db959dd792d21fa12e0427b12c) Thanks [@phryneas](https://github.com/phryneas)! - Enforce `export type` for all type-level exports.\n\n- [#11027](https://github.com/apollographql/apollo-client/pull/11027) [`e47cfd04e`](https://github.com/apollographql/apollo-client/commit/e47cfd04ec50cb4c19828f4d655eb0f989cdcf7d) Thanks [@phryneas](https://github.com/phryneas)! - Prevents the DevTool installation warning to be turned into a documentation link.\n\n- [#10594](https://github.com/apollographql/apollo-client/pull/10594) [`f221b5e8f`](https://github.com/apollographql/apollo-client/commit/f221b5e8fafef3970af2037218c2396ae7db505e) Thanks [@phryneas](https://github.com/phryneas)! - Add a `suspenseCache` option to `useSuspenseQuery`\n\n- [#10700](https://github.com/apollographql/apollo-client/pull/10700) [`12e37f46f`](https://github.com/apollographql/apollo-client/commit/12e37f46f17f0d5a6d408b89ebafbf7413f309ab) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a `queryKey` option to `useSuspenseQuery` that allows the hook to create a unique subscription instance.\n\n- [#10724](https://github.com/apollographql/apollo-client/pull/10724) [`e285dfd00`](https://github.com/apollographql/apollo-client/commit/e285dfd003c7074383732ee23e539d7a0316af10) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Automatically strips `__typename` fields from `variables` sent to the server when using [`HttpLink`](https://www.apollographql.com/docs/react/api/link/apollo-link-http), [`BatchHttpLink`](https://www.apollographql.com/docs/react/api/link/apollo-link-batch-http), or [`GraphQLWsLink`](https://www.apollographql.com/docs/react/api/link/apollo-link-subscriptions). This allows GraphQL data returned from a query to be used as an argument to a subsequent GraphQL operation without the need to strip the `__typename` in user-space.\n\n- [#10957](https://github.com/apollographql/apollo-client/pull/10957) [`445164d21`](https://github.com/apollographql/apollo-client/commit/445164d2177efe46637a514afa6a88502d3de10f) Thanks [@phryneas](https://github.com/phryneas)! - Use `React.version` as key for shared Contexts.\n\n- [#10635](https://github.com/apollographql/apollo-client/pull/10635) [`7df51ee19`](https://github.com/apollographql/apollo-client/commit/7df51ee19a49a92f48c0f58f91894d32091cb294) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue where cache updates would not propagate to `useSuspenseQuery` while in strict mode.\n\n- [#11013](https://github.com/apollographql/apollo-client/pull/11013) [`5ed2cfdaf`](https://github.com/apollographql/apollo-client/commit/5ed2cfdaf9030550d4c82200a5a690b112ad3335) Thanks [@alessbell](https://github.com/alessbell)! - Make private fields `inFlightLinkObservables` and `fetchCancelFns` protected in QueryManager in order to make types available in [`@apollo/experimental-nextjs-app-support`](https://www.npmjs.com/package/@apollo/experimental-nextjs-app-support) package when extending the `ApolloClient` class.\n\n- [#10869](https://github.com/apollographql/apollo-client/pull/10869) [`ba1d06166`](https://github.com/apollographql/apollo-client/commit/ba1d0616618ee040e9bcb20874b03d5783f7eff3) Thanks [@phryneas](https://github.com/phryneas)! - Ensure Context value stability when rerendering ApolloProvider with the same `client` and/or `suspenseCache` prop\n\n- [#11103](https://github.com/apollographql/apollo-client/pull/11103) [`e3d611daf`](https://github.com/apollographql/apollo-client/commit/e3d611daf7a014e5c92d6bed75d67b9187437eda) Thanks [@caylahamann](https://github.com/caylahamann)! - Fixes a bug in `useMutation` so that `onError` is called when an error is returned from the request with `errorPolicy` set to 'all' .\n\n- [#10657](https://github.com/apollographql/apollo-client/pull/10657) [`db305a800`](https://github.com/apollographql/apollo-client/commit/db305a8005664e9b6ec64046da230f41d293104d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Return `networkStatus` in the `useSuspenseQuery` result.\n\n- [#10937](https://github.com/apollographql/apollo-client/pull/10937) [`eea44eb87`](https://github.com/apollographql/apollo-client/commit/eea44eb87f6f296a6f9978d6ba1cf36e899c9131) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Moves `DocumentTransform` to the `utilities` sub-package to avoid a circular dependency between the `core` and `cache` sub-packages.\n\n- [#10951](https://github.com/apollographql/apollo-client/pull/10951) [`2e833b2ca`](https://github.com/apollographql/apollo-client/commit/2e833b2cacb71fc2050cb3976d0bbe710baeedff) Thanks [@alessbell](https://github.com/alessbell)! - Improve `useBackgroundQuery` type interface\n\n- [#10651](https://github.com/apollographql/apollo-client/pull/10651) [`8355d0e1e`](https://github.com/apollographql/apollo-client/commit/8355d0e1e9c1cee58cabd7df68d3ba09a3afaf6c) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixes an issue where `useSuspenseQuery` would not respond to cache updates when using a cache-first `fetchPolicy` after the hook was mounted with data already in the cache.\n\n- [#11026](https://github.com/apollographql/apollo-client/pull/11026) [`b8d405eee`](https://github.com/apollographql/apollo-client/commit/b8d405eee2a81df92861be5abd9bd874d7cad111) Thanks [@phryneas](https://github.com/phryneas)! - Store React.Context instance mapped by React.createContext instance, not React.version.\n  Using `React.version` can cause problems with `preact`, as multiple versions of `preact` will all identify themselves as React `17.0.2`.\n\n- [#11000](https://github.com/apollographql/apollo-client/pull/11000) [`1d43ab616`](https://github.com/apollographql/apollo-client/commit/1d43ab6169b2b2ebfd8f86366212667f9609f5f5) Thanks [@phryneas](https://github.com/phryneas)! - Use `import * as React` everywhere. This prevents an error when importing `@apollo/client` in a React Server component. (see [#10974](https://github.com/apollographql/apollo-client/issues/10974))\n\n- [#10852](https://github.com/apollographql/apollo-client/pull/10852) [`27fbdb3f9`](https://github.com/apollographql/apollo-client/commit/27fbdb3f9003cc304d26987cb38daf10910f2da6) Thanks [@phryneas](https://github.com/phryneas)! - Chore: Add ESLint rule for consistent type imports, apply autofix\n\n- [#10999](https://github.com/apollographql/apollo-client/pull/10999) [`c1904a78a`](https://github.com/apollographql/apollo-client/commit/c1904a78abb186f475303d632c2cb303bbd8d4f9) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug in `QueryReference` where `this.resolve` or `this.reject` might be executed even if `undefined`.\n\n- [#10940](https://github.com/apollographql/apollo-client/pull/10940) [`1d38f128f`](https://github.com/apollographql/apollo-client/commit/1d38f128f325ea7092bd04fe3799ebbb6e8bdfdd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for the `skip` option in `useBackgroundQuery` and `useSuspenseQuery`. Setting this option to `true` will avoid a network request.\n\n- [#10672](https://github.com/apollographql/apollo-client/pull/10672) [`932252b0c`](https://github.com/apollographql/apollo-client/commit/932252b0c54792ec8c5095de1b42c005a91ffe6d) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix the compatibility between `useSuspenseQuery` and React's `useDeferredValue` and `startTransition` APIs to allow React to show stale UI while the changes to the variable cause the component to suspend.\n\n  #### Breaking change\n\n  `nextFetchPolicy` support has been removed from `useSuspenseQuery`. If you are using this option, remove it, otherwise it will be ignored.\n\n- [#10964](https://github.com/apollographql/apollo-client/pull/10964) [`f33171506`](https://github.com/apollographql/apollo-client/commit/f331715066d65291b1f5df5e6fa2b6618dfc70b1) Thanks [@alessbell](https://github.com/alessbell)! - Fixes a bug in `BatchHttpLink` that removed variables from all requests by default.\n\n- [#10633](https://github.com/apollographql/apollo-client/pull/10633) [`90a06eeeb`](https://github.com/apollographql/apollo-client/commit/90a06eeeb5a50eb172f5c6211693ea051897d8f3) Thanks [@benjamn](https://github.com/benjamn)! - Fix type policy inheritance involving fuzzy `possibleTypes`\n\n- [#10754](https://github.com/apollographql/apollo-client/pull/10754) [`64b304862`](https://github.com/apollographql/apollo-client/commit/64b3048621de35bbfe9bdf47785a2d5583232830) Thanks [@sincraianul](https://github.com/sincraianul)! - Fix `includeUnusedVariables` option not working with `BatchHttpLink`\n\n- [#11018](https://github.com/apollographql/apollo-client/pull/11018) [`5618953f3`](https://github.com/apollographql/apollo-client/commit/5618953f332a10c7df1b385126ec714aa5809c48) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useBackgroundQuery` now uses its own options type called `BackgroundQueryHookOptions` rather than reusing `SuspenseQueryHookOptions`.\n\n- [#11035](https://github.com/apollographql/apollo-client/pull/11035) [`a3ab7456d`](https://github.com/apollographql/apollo-client/commit/a3ab7456d59be4a7beb58d0aff6d431c603448f5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Incrementally re-render deferred queries after calling `refetch` or setting `skip` to `false` to match the behavior of the initial fetch. Previously, the hook would not re-render until the entire result had finished loading in these cases.\n\n- [#10399](https://github.com/apollographql/apollo-client/pull/10399) [`652a1ae08`](https://github.com/apollographql/apollo-client/commit/652a1ae0868e4a5b75b9ff656d26f57eeca1081a) Thanks [@alessbell](https://github.com/alessbell)! - Silence useLayoutEffect warning when useSuspenseQuery runs on server\n\n- [#10919](https://github.com/apollographql/apollo-client/pull/10919) [`f796ce1ac`](https://github.com/apollographql/apollo-client/commit/f796ce1ac72f31a951a1d0f0b78d19dd039a6398) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fix an issue when using a link that relied on `operation.getContext` and `operation.setContext` would error out when it was declared after the `removeTypenameFromVariables` link.\n\n- [#10968](https://github.com/apollographql/apollo-client/pull/10968) [`b102390b2`](https://github.com/apollographql/apollo-client/commit/b102390b238e5ce083062541d98a00fc3a10e1e1) Thanks [@phryneas](https://github.com/phryneas)! - Use printed query for query deduplication. Cache `print` calls for GraphQL documents to speed up repeated operations.\n\n- [#11071](https://github.com/apollographql/apollo-client/pull/11071) [`4473e925a`](https://github.com/apollographql/apollo-client/commit/4473e925ac5d6a53dc2b34867f034eda1b05aa00) Thanks [@jerelmiller](https://github.com/jerelmiller)! - [#10509](https://github.com/apollographql/apollo-client/pull/10509) introduced some helpers for determining the type of operation for a GraphQL query. This imported the `OperationTypeNode` from graphql-js which is not available in GraphQL 14. To maintain compatibility with graphql-js v14, this has been reverted to use plain strings.\n\n- [#10766](https://github.com/apollographql/apollo-client/pull/10766) [`ffb179e55`](https://github.com/apollographql/apollo-client/commit/ffb179e5553fa6f9156ae0aaf782dfcbec7d08c7) Thanks [@jerelmiller](https://github.com/jerelmiller)! - More robust typings for the `data` property returned from `useSuspenseQuery` when using `returnPartialData: true` or an `errorPolicy` of `all` or `ignore`. `TData` now defaults to `unknown` instead of `any`.\n\n- [#10401](https://github.com/apollographql/apollo-client/pull/10401) [`3e5b41a75`](https://github.com/apollographql/apollo-client/commit/3e5b41a751673bb2120c0b624e22afd3b7b860e5) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Always throw network errors in `useSuspenseQuery` regardless of the set `errorPolicy`.\n\n- [#10877](https://github.com/apollographql/apollo-client/pull/10877) [`f40248598`](https://github.com/apollographql/apollo-client/commit/f402485985cc2551b51602c0bff213b7ffb856b9) Thanks [@phryneas](https://github.com/phryneas)! - Change an import in `useQuery` and `useMutation` that added an unnecessary runtime dependency on `@apollo/client/core`. This drastically reduces the bundle size of each the hooks.\n\n- [#10656](https://github.com/apollographql/apollo-client/pull/10656) [`54c4d2f3c`](https://github.com/apollographql/apollo-client/commit/54c4d2f3c719654e38e537ec38f1cb415c7c3f58) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure `refetch`, `fetchMore`, and `subscribeToMore` functions returned by `useSuspenseQuery` are referentially stable between renders, even as `data` is updated.\n\n- [#10324](https://github.com/apollographql/apollo-client/pull/10324) [`95eb228be`](https://github.com/apollographql/apollo-client/commit/95eb228bedc193a520604e351d1c455bfbedef06) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add `@defer` support to `useSuspenseQuery`.\n\n- [#10888](https://github.com/apollographql/apollo-client/pull/10888) [`1562a2f5a`](https://github.com/apollographql/apollo-client/commit/1562a2f5a91cf577d9c89c4e84088a6bccc73c28) Thanks [@alessbell](https://github.com/alessbell)! - Updates dependency versions in `package.json` by bumping:\n\n  - `@wry/context` to `^0.7.3`\n  - `@wry/equality` to `^0.5.6`\n  - `@wry/trie` to `^0.4.3`\n  - `optimism` to `^0.17.4`\n\n  to 1. [fix sourcemap warnings](https://github.com/benjamn/wryware/pull/497) and 2. a Codesandbox [sandpack (in-browser) bundler transpilation bug](https://github.com/codesandbox/sandpack/issues/940) with an [upstream optimism workaround](https://github.com/benjamn/optimism/pull/550).\n\n- [#11010](https://github.com/apollographql/apollo-client/pull/11010) [`1051a9c88`](https://github.com/apollographql/apollo-client/commit/1051a9c888ba86511b7fcb80a26d3b3050359258) Thanks [@alessbell](https://github.com/alessbell)! - Hide queryRef in a Symbol in `useBackgroundQuery`s return value.\n\n- [#10758](https://github.com/apollographql/apollo-client/pull/10758) [`9def7421f`](https://github.com/apollographql/apollo-client/commit/9def7421f3d028c91fcaa7971878b3da8281424d) Thanks [@phryneas](https://github.com/phryneas)! - use `React.use` where available\n\n- [#11032](https://github.com/apollographql/apollo-client/pull/11032) [`6a4da900a`](https://github.com/apollographql/apollo-client/commit/6a4da900a1bc5da3524caabd64bb30945e66f675) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Throw errors in `useSuspenseQuery` for errors returned in incremental chunks when `errorPolicy` is `none`. This provides a more consistent behavior of the `errorPolicy` in the hook.\n\n  #### Potentially breaking change\n\n  Previously, if you issued a query with `@defer` and relied on `errorPolicy: 'none'` to set the `error` property returned from `useSuspenseQuery` when the error was returned in an incremental chunk, this error is now thrown. Switch the `errorPolicy` to `all` to avoid throwing the error and instead return it in the `error` property.\n\n- [#10960](https://github.com/apollographql/apollo-client/pull/10960) [`ee407ef97`](https://github.com/apollographql/apollo-client/commit/ee407ef97317bf29c554732237aaf11552e06b01) Thanks [@alessbell](https://github.com/alessbell)! - Adds support for `returnPartialData` and `refetchWritePolicy` options in `useBackgroundQuery` hook.\n\n- [#10809](https://github.com/apollographql/apollo-client/pull/10809) [`49d28f764`](https://github.com/apollographql/apollo-client/commit/49d28f764980d132089ef8f6beca6e766b6120c0) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Fixed the ability to use `refetch` and `fetchMore` with React's `startTransition`. The hook will now behave correctly by allowing React to avoid showing the Suspense fallback when these functions are wrapped by `startTransition`. This change deprecates the `suspensePolicy` option in favor of `startTransition`.\n\n- [#11082](https://github.com/apollographql/apollo-client/pull/11082) [`0f1cde3a2`](https://github.com/apollographql/apollo-client/commit/0f1cde3a207699edb742dfaada817a815488d594) Thanks [@phryneas](https://github.com/phryneas)! - Restore Apollo Client 3.7 `getApolloContext` behaviour\n\n- [#10969](https://github.com/apollographql/apollo-client/pull/10969) [`525a9317a`](https://github.com/apollographql/apollo-client/commit/525a9317af729309f699fd6f8b787647a5f63eac) Thanks [@phryneas](https://github.com/phryneas)! - Slightly decrease bundle size and memory footprint of `SuspenseCache` by changing how cache entries are stored internally.\n\n- [#11025](https://github.com/apollographql/apollo-client/pull/11025) [`6092b6edf`](https://github.com/apollographql/apollo-client/commit/6092b6edf67ef311954c18c778ed0bdca1b77258) Thanks [@jerelmiller](https://github.com/jerelmiller)! - `useSuspenseQuery` and `useBackgroundQuery` will now properly apply changes to its options between renders.\n\n- [#10872](https://github.com/apollographql/apollo-client/pull/10872) [`96b4f8837`](https://github.com/apollographql/apollo-client/commit/96b4f8837881db67e951272b775dc62282e50d49) Thanks [@phryneas](https://github.com/phryneas)! - The \"per-React-Version-Singleton\" ApolloContext is now stored on `globalThis`, not `React.createContext`, and throws an error message when accessed from React Server Components.\n\n- [#10450](https://github.com/apollographql/apollo-client/pull/10450) [`f8bc33387`](https://github.com/apollographql/apollo-client/commit/f8bc33387f66e28456aede53bae75694c9a7a45f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add support for the `subscribeToMore` and `client` fields returned in the `useSuspenseQuery` result.\n\n</details>\n\n## 3.7.17\n\n### Patch Changes\n\n- [#10631](https://github.com/apollographql/apollo-client/pull/10631) [`b93388d75`](https://github.com/apollographql/apollo-client/commit/b93388d7582d88859c4975dff524c1ceb5bd2b4e) Thanks [@phryneas](https://github.com/phryneas)! - ObservableQuery.getCurrentResult: skip the cache if the running query should not access the cache\n\n## 3.7.16\n\n### Patch Changes\n\n- [#10806](https://github.com/apollographql/apollo-client/pull/10806) [`cb1540504`](https://github.com/apollographql/apollo-client/commit/cb15405041e0bd644fcf23d1b8fcaa09762c5a6a) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug in `PersistedQueryLink` that would cause it to permanently skip persisted queries after a 400 or 500 status code.\n\n- [#10807](https://github.com/apollographql/apollo-client/pull/10807) [`b32369592`](https://github.com/apollographql/apollo-client/commit/b3236959269ce27b18b8c2cae72106098a3ba1b8) Thanks [@phryneas](https://github.com/phryneas)! - `PersistedQueryLink` will now also check for error codes in `extensions`.\n\n- [#10982](https://github.com/apollographql/apollo-client/pull/10982) [`b9be7a814`](https://github.com/apollographql/apollo-client/commit/b9be7a814a64fc6b3e6ce23dd97a4f0c7140aba7) Thanks [@sdeleur-sc](https://github.com/sdeleur-sc)! - Update `relayStylePagination` to avoid populating `startCursor` when only a single cursor is present under the `edges` field. Use that cursor only as the `endCursor`.\n\n- [#10962](https://github.com/apollographql/apollo-client/pull/10962) [`772cfa3cb`](https://github.com/apollographql/apollo-client/commit/772cfa3cb563dccee878177e58c8250c4e5b5013) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Remove `useGETForQueries` option in `BatchHttpLink.Options` type since it is not supported.\n\n## 3.7.15\n\n### Patch Changes\n\n- [#10891](https://github.com/apollographql/apollo-client/pull/10891) [`ab42a5c08`](https://github.com/apollographql/apollo-client/commit/ab42a5c08840193cb915f4e66d71fac3834fec68) Thanks [@laverdet](https://github.com/laverdet)! - Fixes a bug in how multipart responses are read when using `@defer`. When reading a multipart body, `HttpLink` no longer attempts to parse the boundary (e.g. `\"---\"` or other boundary string) within the response data itself, only when reading the beginning of each mulitpart chunked message.\n\n- [#10789](https://github.com/apollographql/apollo-client/pull/10789) [`23a4e1578`](https://github.com/apollographql/apollo-client/commit/23a4e15786fe99658d741585366f3b02bcffb97f) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where other fields could be aliased to `__typename` or `id`, in which case an incoming result would be merged into the wrong cache entry.\n\n## 3.7.14\n\n### Patch Changes\n\n- [#10764](https://github.com/apollographql/apollo-client/pull/10764) [`1b0a61fe5`](https://github.com/apollographql/apollo-client/commit/1b0a61fe5a6593f319da26fec8692359232ccf9b) Thanks [@phryneas](https://github.com/phryneas)! - Deprecate `useFragment` `returnPartialData` option\n\n- [#10810](https://github.com/apollographql/apollo-client/pull/10810) [`a6252774f`](https://github.com/apollographql/apollo-client/commit/a6252774f43fd9a4be9c50b48b7a6d5a1c8e64ec) Thanks [@dleavitt](https://github.com/dleavitt)! - Fix type signature of `ServerError`.\n\n  In <3.7 `HttpLink` and `BatchHttpLink` would return a `ServerError.message` of e.g. `\"Unexpected token 'E', \\\"Error! Foo bar\\\" is not valid JSON\"` and a `ServerError.result` of `undefined` in the case where a server returned a >= 300 response code with a response body containing a string that could not be parsed as JSON.\n\n  In >=3.7, `message` became e.g. `Response not successful: Received status code 302` and `result` became the string from the response body, however the type in `ServerError.result` was not updated to include the `string` type, which is now properly reflected.\n\n## 3.7.13\n\n### Patch Changes\n\n- [#10805](https://github.com/apollographql/apollo-client/pull/10805) [`a5503666c`](https://github.com/apollographql/apollo-client/commit/a5503666c2cc8220ac1d877e3296556e54e58ff6) Thanks [@phryneas](https://github.com/phryneas)! - Fix a potential memory leak in SSR scenarios when many `persistedQuery` instances were created over time.\n\n- [#10718](https://github.com/apollographql/apollo-client/pull/10718) [`577c68bdd`](https://github.com/apollographql/apollo-client/commit/577c68bdd26519f8341fd1188ea4b8aabe357856) Thanks [@Hsifnus](https://github.com/Hsifnus)! - Delay Concast subscription teardown slightly in `useSubscription` to prevent unexpected Concast teardown when one `useSubscription` hook tears down its in-flight Concast subscription immediately followed by another `useSubscription` hook reusing and subscribing to that same Concast\n\n## 3.7.12\n\n### Patch Changes\n\n- [#10735](https://github.com/apollographql/apollo-client/pull/10735) [`895bcdcff`](https://github.com/apollographql/apollo-client/commit/895bcdcff146bc4575c8f3423c30fa9e885be16b) Thanks [@alessbell](https://github.com/alessbell)! - If a multipart chunk contains only `hasNext: false`, immediately complete the observable.\n\n## 3.7.11\n\n### Patch Changes\n\n- [#10586](https://github.com/apollographql/apollo-client/pull/10586) [`4175af594`](https://github.com/apollographql/apollo-client/commit/4175af59419dbb698c32c074f44229f3a5b3b83d) Thanks [@alessbell](https://github.com/alessbell)! - Improve WebSocket error handling for generic `Event` received on error. For more information see [https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event).\n\n- [#10411](https://github.com/apollographql/apollo-client/pull/10411) [`152baac34`](https://github.com/apollographql/apollo-client/commit/152baac343b8b68c7a2d4691d5dc60d9e43e62bb) Thanks [@lovasoa](https://github.com/lovasoa)! - Simplify error message generation and make 'undefined' an impossible message string.\n\n- [#10592](https://github.com/apollographql/apollo-client/pull/10592) [`cdb98ae08`](https://github.com/apollographql/apollo-client/commit/cdb98ae082ae4c7da6cd6a0fd5ad8457810fceda) Thanks [@alessbell](https://github.com/alessbell)! - Adds support for multipart subscriptions in `HttpLink`.\n\n- [#10698](https://github.com/apollographql/apollo-client/pull/10698) [`38508a251`](https://github.com/apollographql/apollo-client/commit/38508a251423057fd8a0df50230f50e0a5dde5fd) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Changes the behavior of `useLazyQuery` introduced in [#10427](https://github.com/apollographql/apollo-client/pull/10427) where unmounting a component before a query was resolved would reject the promise with an abort error. Instead, the promise will now resolve naturally with the result from the request.\n\n  Other notable fixes:\n\n  - Kicking off multiple requests in parallel with the execution function will now ensure each returned promise is resolved with the data from its request. Previously, each promise was resolved with data from the last execution.\n  - Re-rendering `useLazyQuery` with a different query document will now ensure the execution function uses the updated query document. Previously, only the query document rendered the first time would be used for the request.\n\n- [#10660](https://github.com/apollographql/apollo-client/pull/10660) [`364bee98f`](https://github.com/apollographql/apollo-client/commit/364bee98fe193a7915664c1a5b206fd52793f85a) Thanks [@alessbell](https://github.com/alessbell)! - Upgrades TypeScript to v5. This change is fully backward-compatible and transparent to users.\n\n- [#10597](https://github.com/apollographql/apollo-client/pull/10597) [`8fb9d190d`](https://github.com/apollographql/apollo-client/commit/8fb9d190dbf48147412517643e3e425a7d48c49c) Thanks [@phryneas](https://github.com/phryneas)! - Fix a bug where an incoming cache update could prevent future updates from the active link.\n\n- [#10629](https://github.com/apollographql/apollo-client/pull/10629) [`02605bb3c`](https://github.com/apollographql/apollo-client/commit/02605bb3c9e148bf87a6e52b4a9ecc7d523ef9f6) Thanks [@phryneas](https://github.com/phryneas)! - `useQuery`: delay unsubscribe to fix race conditions\n\n## 3.7.10\n\n### Patch Changes\n\n- [#9438](https://github.com/apollographql/apollo-client/pull/9438) [`52a9c8ea1`](https://github.com/apollographql/apollo-client/commit/52a9c8ea1ac08ee53fe1ddbd4ded899ea00a1f9f) Thanks [@dciesielkiewicz](https://github.com/dciesielkiewicz)! - Ensure the `client` option passed to `useMutation`'s execute function is used when provided. Previously this option was ignored.\n\n- [#9124](https://github.com/apollographql/apollo-client/pull/9124) [`975b923c0`](https://github.com/apollographql/apollo-client/commit/975b923c0c0e7ddc8553917a91981e9f41713bc1) Thanks [@andrebrantom](https://github.com/andrebrantom)! - Make `ApolloClient.writeQuery` and `ApolloClient.writeFragment` behave more like `cache.writeQuery` and `cache.writeFragment` by returning the reference returned by the cache.\n\n## 3.7.9\n\n### Patch Changes\n\n- [#10560](https://github.com/apollographql/apollo-client/pull/10560) [`a561ecf43`](https://github.com/apollographql/apollo-client/commit/a561ecf4306c56770ba0713f0136174275887f1a) Thanks [@benjamn](https://github.com/benjamn)! - Keep `__typename` fragment when it does not contain `@client` directive and strip out inline fragments which use a `@client` directive. Thanks @Gazler and @mtsmfm!\n\n- [#10560](https://github.com/apollographql/apollo-client/pull/10560) [`251a12806`](https://github.com/apollographql/apollo-client/commit/251a12806d1fa38bc8723540fb2d696c39db1097) Thanks [@benjamn](https://github.com/benjamn)! - Refactor `removeDirectivesFromDocument` to fix AST ordering sensitivities and avoid 1/3 AST traversals, potentially improving performance for large queries\n\n## 3.7.8\n\n### Patch Changes\n\n- [#7555](https://github.com/apollographql/apollo-client/pull/7555) [`45562d6fa`](https://github.com/apollographql/apollo-client/commit/45562d6fa20eab658bd86d79d092862ace4e1225) Thanks [@TheCeloReis](https://github.com/TheCeloReis)! - Adds `TVariables` generic to `GraphQLRequest` and `MockedResponse` interfaces.\n\n- [#10526](https://github.com/apollographql/apollo-client/pull/10526) [`1d13de4f1`](https://github.com/apollographql/apollo-client/commit/1d13de4f190150e96d61a9e987274ee6c249dbef) Thanks [@benjamn](https://github.com/benjamn)! - Tolerate undefined `concast.sources` if `complete` called earlier than `concast.start`\n\n- [#10497](https://github.com/apollographql/apollo-client/pull/10497) [`8a883d8a1`](https://github.com/apollographql/apollo-client/commit/8a883d8a1c8899f94a3e2ae09cb2069bde2b2150) Thanks [@nevir](https://github.com/nevir)! - Update `SingleExecutionResult` and `IncrementalPayload`'s `data` types such that they no longer include `undefined`, which was not a valid runtime value, to fix errors when TypeScript's `exactOptionalPropertyTypes` is enabled.\n\n## 3.7.7\n\n### Patch Changes\n\n- [#10502](https://github.com/apollographql/apollo-client/pull/10502) [`315faf9ca`](https://github.com/apollographql/apollo-client/commit/315faf9ca5b326852919ab7fc2082d6ba92bcb59) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Log a warning to the console when a mock passed to `MockedProvider` or `MockLink` cannot be matched to a query during a test. This makes it easier to debug user errors in the mock setup, such as typos, especially if the query under test is using an `errorPolicy` set to `ignore`, which makes it difficult to know that a match did not occur.\n\n- [#10499](https://github.com/apollographql/apollo-client/pull/10499) [`9e54f5dfa`](https://github.com/apollographql/apollo-client/commit/9e54f5dfa05fd363e534c432ba8c569bb96a6e35) Thanks [@phryneas](https://github.com/phryneas)! - Allow the execution function returned by `useLazyQuery` to change the query.\n\n- [#10362](https://github.com/apollographql/apollo-client/pull/10362) [`14a56b105`](https://github.com/apollographql/apollo-client/commit/14a56b105fefcbb2ce5daa9fd6924e5decafcc16) Thanks [@mccraveiro](https://github.com/mccraveiro)! - Fix error when server returns an error and we are also querying for a local field\n\n## 3.7.6\n\n### Patch Changes\n\n- [#10470](https://github.com/apollographql/apollo-client/pull/10470) [`47435e879`](https://github.com/apollographql/apollo-client/commit/47435e879ebc867d9fc3de5b6fd5785204b4dbd4) Thanks [@alessbell](https://github.com/alessbell)! - Bumps TypeScript to `4.9.4` (previously `4.7.4`) and updates types to account for changes in TypeScript 4.8 by [propagating contstraints on generic types](https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/#unconstrained-generics-no-longer-assignable-to). Technically this makes some types stricter as attempting to pass `null|undefined` into certain functions is now disallowed by TypeScript, but these were never expected runtime values in the first place.\n  This should only affect you if you are wrapping functions provided by Apollo Client with your own abstractions that pass in their generics as type arguments, in which case you might get an error like `error TS2344: Type 'YourGenericType' does not satisfy the constraint 'OperationVariables'`. In that case, make sure that `YourGenericType` is restricted to a type that only accepts objects via `extends`, like `Record<string, any>` or `@apollo/client`'s `OperationVariables`:\n\n  ```diff\n  import {\n    QueryHookOptions,\n    QueryResult,\n    useQuery,\n  + OperationVariables,\n  } from '@apollo/client';\n  - export function useWrappedQuery<T, TVariables>(\n  + export function useWrappedQuery<T, TVariables extends OperationVariables>(\n      query: DocumentNode,\n      queryOptions: QueryHookOptions<T, TVariables>\n    ): QueryResult<T, TVariables> {\n      const [execute, result] = useQuery<T, TVariables>(query);\n    }\n  ```\n\n- [#10408](https://github.com/apollographql/apollo-client/pull/10408) [`55ffafc58`](https://github.com/apollographql/apollo-client/commit/55ffafc585e9eb66314755b4f40804b8b8affb13) Thanks [@zlrlo](https://github.com/zlrlo)! - fix: modify BatchHttpLink to have a separate timer for each different batch key\n\n- [#9573](https://github.com/apollographql/apollo-client/pull/9573) [`4a4f48dda`](https://github.com/apollographql/apollo-client/commit/4a4f48dda8dd290ef110aed9e4e73d0c1c977c31) Thanks [@vladar](https://github.com/vladar)! - Improve performance of local resolvers by only executing selection sets that contain an `@client` directive. Previously, local resolvers were executed even when the field did not contain `@client`. While the result was properly discarded, the unncessary work could negatively affect query performance, sometimes signficantly.\n\n## 3.7.5\n\n### Patch Changes\n\n- [#10458](https://github.com/apollographql/apollo-client/pull/10458) [`b5ccef229`](https://github.com/apollographql/apollo-client/commit/b5ccef229046d230e82a68a4834ac09ae1ef2009) Thanks [@lennyburdette](https://github.com/lennyburdette)! - Passes `getServerSnapshot` to `useSyncExternalStore` so that it doesn't trigger a `Missing getServerSnapshot` error when using `useFragment_experimental` on the server.\n\n- [#10471](https://github.com/apollographql/apollo-client/pull/10471) [`895ddcb54`](https://github.com/apollographql/apollo-client/commit/895ddcb546b5692cd53caae1b604412728641374) Thanks [@alessbell](https://github.com/alessbell)! - More robust type definition for `headers` property passed to `createHttpLink`\n\n- [#10321](https://github.com/apollographql/apollo-client/pull/10321) [`bbaa3ef2d`](https://github.com/apollographql/apollo-client/commit/bbaa3ef2d95a03e2453ef86a25096c314fbd8998) Thanks [@alessbell](https://github.com/alessbell)! - Refetch should not return partial data with `errorPolicy: none` and `notifyOnNetworkStatusChange: true`.\n\n- [#10402](https://github.com/apollographql/apollo-client/pull/10402) [`0b07aa955`](https://github.com/apollographql/apollo-client/commit/0b07aa955bab2e929f21590b565507a66f930539) Thanks [@Hugodby](https://github.com/Hugodby)! - Improve context types\n\n- [#10469](https://github.com/apollographql/apollo-client/pull/10469) [`328c58f90`](https://github.com/apollographql/apollo-client/commit/328c58f90d3fd985a58a68d8ba07f7c03f9808f6) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add generic type defaults when using `useFragment` to allow passing `TData` directly to the function without needing to specify `TVars`.\n\n## 3.7.4\n\n### Patch Changes\n\n- [#10427](https://github.com/apollographql/apollo-client/pull/10427) [`28d909cff`](https://github.com/apollographql/apollo-client/commit/28d909cff086f8352e2ea75421a1cac590917573) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure in-flight promises executed by `useLazyQuery` are rejected when `useLazyQuery` unmounts.\n\n- [#10383](https://github.com/apollographql/apollo-client/pull/10383) [`5c5ca9b01`](https://github.com/apollographql/apollo-client/commit/5c5ca9b01a2b9905f94de85e5b80ffc29522e2e3) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Ensure the `onError` callback is called when the `errorPolicy` is set to \"all\" and partial data is returned.\n\n- [#10425](https://github.com/apollographql/apollo-client/pull/10425) [`86e35a6d2`](https://github.com/apollographql/apollo-client/commit/86e35a6d25e9838f39a9de652e52a358b9c08488) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Prefer the `onError` and `onCompleted` callback functions passed to the execute function returned from `useMutation` instead of calling both callback handlers.\n\n## 3.7.3\n\n### Patch Changes\n\n- [#10334](https://github.com/apollographql/apollo-client/pull/10334) [`7d923939d`](https://github.com/apollographql/apollo-client/commit/7d923939dd7e6db7d69f04f598c666104b076e78) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Better handle deferred queries that have cached or partial cached data for them\n\n- [#10368](https://github.com/apollographql/apollo-client/pull/10368) [`46b58e976`](https://github.com/apollographql/apollo-client/commit/46b58e9762abbffaee5c9abda8e309bea6d7a785) Thanks [@alessbell](https://github.com/alessbell)! - Fix: unblocks support for defer in mutations\n\n  If the `@defer` directive is present in the document passed to `mutate`, the Promise will resolve with the final merged data after the last multipart chunk has arrived in the response.\n\n## 3.7.2\n\n### Patch Changes\n\n- Only show dev tools suggestion in the console when `connectToDevTools` is `true`. <br/>\n  [@chris110408](https://github.com/chris110408) in [#10258](https://github.com/apollographql/apollo-client/pull/10258)\n\n- Pass `TCache` generic to `MutationHookOptions` for better type support in `useMutation`. <br />\n  [@igrlk](https://github.com/igrlk) in [#10223](https://github.com/apollographql/apollo-client/pull/10223)\n\n- Add `name` property to `ApolloError` to ensure better type safety and help error reporting tools better identify the error. <br />\n  [@aaronadamsCA](https://github.com/aaronadamsCA) in [#9323](https://github.com/apollographql/apollo-client/pull/9323)\n\n- Export a `ModifierDetails` type for the `details` parameter of a `Modifier` function. <br />\n  [@KeithGillette](https://github.com/KeithGillette) in [#7133](https://github.com/apollographql/apollo-client/pull/7133)\n\n- Revert use of `cloneDeep` to clone options when fetching queries. <br />\n  [@MrDoomBringer](https://github.com/MrDoomBringer) in [#10215](https://github.com/apollographql/apollo-client/pull/10215)\n\n## 3.7.1\n\n### Patch Changes\n\n- Fix issue where `loading` remains `true` after `observer.refetch` is called repeatedly with different variables when the same data are returned. <br/>\n  [@alessbell](https://github.com/alessbell) in [#10143](https://github.com/apollographql/apollo-client/pull/10143)\n\n- Fix race condition where `useFragment_experimental` could receive cache updates before initially calling `cache.watch` in `useEffect`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#10212](https://github.com/apollographql/apollo-client/pull/10212)\n\n## 3.7.0\n\n### Minor Changes\n\n- Implement preview support for the [`@defer` directive](https://github.com/graphql/graphql-spec/pull/742). <br/>\n  [@alessbell](https://github.com/alessbell) and [@benjamn](https://github.com/benjamn) in [#10018](https://github.com/apollographql/apollo-client/pull/10018)\n\n- Implement `useFragment_experimental` hook, which represents a lightweight live binding into the `ApolloCache`, and never triggers network requests of its own. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8782](https://github.com/apollographql/apollo-client/pull/8782)\n\n- Allow registering named fragments with `InMemoryCache` to support using `...NamedFragment` in queries without redeclaring `NamedFragment` repeatedly in every query that uses it. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9764](https://github.com/apollographql/apollo-client/pull/9764)\n\n- Support `onError` callback for `useSubscription` hook. <br/>\n  [@jeroenvisser101](https://github.com/jeroenvisser101) in [#9495](https://github.com/apollographql/apollo-client/pull/9495)\n\n- Implement `preserveHeaderCase` option for `http` context object, enabling preserved header capitalization for non-http-spec-compliant servers. <br/>\n  [@mrdoombringer](https://github.com/mrdoombringer) in [#9891](https://github.com/apollographql/apollo-client/pull/9891)\n\n### Patch Changes\n\n- Delay calling `onCompleted` and `onError` callbacks passed to `useQuery` using `Promise.resolve().then(() => ...)` to fix issue [#9794](https://github.com/apollographql/apollo-client/pull/9794). <br/>\n  [@dylanwulf](https://github.com/dylanwulf) in [#9823](https://github.com/apollographql/apollo-client/pull/9823)\n\n- Replace `concast.cleanup` method with simpler `concast.beforeNext` API, which promises to call the given callback function just before the next result/error is delivered. In addition, `concast.removeObserver` no longer takes a `quietly?: boolean` parameter, since that parameter was partly responsible for cleanup callbacks sometimes not getting called. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9718](https://github.com/apollographql/apollo-client/pull/9718)\n\n- Allow preserving header name capitalization when creating an `HttpLink` with `createHttpLink({ uri, preserveHeaderCase: true })`. Otherwise, header names are converted to lowercase to prevent case-sensitivity bugs. <br/>\n  [@MrDoomBringer](https://github.com/MrDoomBringer) in [#9891](https://github.com/apollographql/apollo-client/pull/9891)\n\n- Make queries with a `pollInterval` respect the `no-cache` fetch policy, instead of writing polled results into the cache. <br/>\n  [@MrDoomBringer](https://github.com/MrDoomBringer) in [#10020](https://github.com/apollographql/apollo-client/pull/10020)\n\n- Deprecate the `onSubscriptionData` callback in favor of a new `onData` callback for the `useSubscription` hook. Deprecate the `onSubscriptionComplete` callback in favor of a new `onComplete` callback for the `useSubscription` hook.<br/>\n  [@jerelmiller](https://github.com/jerelmiller) in [#10134](https://github.com/apollographql/apollo-client/pull/10134)\n\n### Potentially disruptive\n\n- The optional `subscribeAndCount` testing utility exported from `@apollo/client/testing/core` now takes a single generic `TResult` type parameter, instead of `TData`. This type will typically be inferred from the `observable` argument type, but if you have any explicit calls to `subscribeAndCount<TData>(...)` in your own codebase, you may need to adjust those calls accordingly. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9718](https://github.com/apollographql/apollo-client/pull/9718)\n\n## Apollo Client 3.6.10 (2022-09-29)\n\n### Improvements\n\n- The client options (`variables`, `context`, etc.) used for `mutation` calls are now available as the second argument to the `onCompleted` and `onError` callback functions. <br/>\n  [@MrDoomBringer](https://github.com/MrDoomBringer) in [#10052](https://github.com/apollographql/apollo-client/pull/10052)\n\n## Apollo Client 3.6.9 (2022-06-21)\n\n### Bug Fixes\n\n- Leave `fetchPolicy` unchanged when `skip: true` (or in standby) and `nextFetchPolicy` is available, even if `variables` change. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9823](https://github.com/apollographql/apollo-client/pull/9823)\n\n## Apollo Client 3.6.8 (2022-06-10)\n\n### Bug Fixes\n\n- Fix incorrect `variables` passed in `FieldFunctionOptions` for nested `readField` calls in `read` and `merge` functions. <br/>\n  [@stardustxx](https://github.com/stardustxx) in [#9808](https://github.com/apollographql/apollo-client/pull/9808)\n\n- Improve repository build scripts to work better on Windows. <br/>\n  [@dylanwulf](https://github.com/dylanwulf) in [#9805](https://github.com/apollographql/apollo-client/pull/9805)\n\n- Ensure `useQuery(query, { skip: true }).called === false` rather than always returning `called` as `true`. <br/>\n  [@KucharskiPiotr](https://github.com/KucharskiPiotr) in [#9798](https://github.com/apollographql/apollo-client/pull/9798)\n\n- Allow abandoned `reobserve` requests to unsubscribe from their underlying `Observable`. <br/>\n  [@javier-garcia-meteologica](https://github.com/javier-garcia-meteologica) in [#9791](https://github.com/apollographql/apollo-client/pull/9791)\n\n## Apollo Client 3.6.7 (2022-06-10)\n\n### Bug Fixes\n\n- Fix regression (introduced in v3.6.0) that caused `BatchHttpLink` to discard pending batched queries on early completion of the underlying `Observable`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9793](https://github.com/apollographql/apollo-client/pull/9793)\n\n## Apollo Client 3.6.6 (2022-05-26)\n\n### Bug Fixes\n\n- Allow `useLazyQuery(query, { defaultOptions })` to benefit from `defaultOptions.variables` and `client.defaultOptions.watchQuery.variables` merging. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9762](https://github.com/apollographql/apollo-client/pull/9762)\n\n## Apollo Client 3.6.5 (2022-05-23)\n\n### Bug Fixes\n\n- Restore pre-v3.6 `variables` replacement behavior of `ObservableQuery#reobserve` method, fixing a regression that prevented removal of variables. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9741](https://github.com/apollographql/apollo-client/pull/9741)\n\n- Preserve `previousData` even when different query or client provided to `useQuery`, instead of resetting `previousData` to undefined in those cases, matching behavior prior to v3.6.0. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9734](https://github.com/apollographql/apollo-client/pull/9734)\n\n- Fix bug where `onCompleted()` and `onError()` are stale for `useMutation()`. <br/>\n  [@charle692](https://github.com/charle692) in [#9740](https://github.com/apollographql/apollo-client/pull/9740)\n\n- Limit scope of `DeepMerger` object reuse, and avoid using `Object.isFrozen`, which can introduce differences between development and production if objects that were frozen using `Object.freeze` in development are left unfrozen in production. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9742](https://github.com/apollographql/apollo-client/pull/9742)\n\n- Properly merge `variables` from original `useLazyQuery(query, { variables })` with `variables` passed to execution function. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9758](https://github.com/apollographql/apollo-client/pull/9758)\n\n## Apollo Client 3.6.4 (2022-05-16)\n\n### Bug Fixes\n\n- Guarantee `Concast` cleanup without `Observable cancelled prematurely` rejection, potentially solving long-standing issues involving that error. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9701](https://github.com/apollographql/apollo-client/pull/9701)\n\n- Ensure `useSubscription` subscriptions are properly restarted after unmounting/remounting by React 18 in `<StrictMode>`. <br/>\n  [@kazekyo](https://github.com/kazekyo) in [#9707](https://github.com/apollographql/apollo-client/pull/9707)\n\n### Improvements\n\n- Internalize `useSyncExternalStore` shim, for more control than `use-sync-external-store` provides, fixing some React Native issues. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9675](https://github.com/apollographql/apollo-client/pull/9675) and [#9709](https://github.com/apollographql/apollo-client/pull/9709)\n\n- Provide `@apollo/client/**/*.cjs.native.js` versions of every `@apollo/client/**/*.cjs` bundle (including dependencies `ts-invariant` and `zen-observable-ts`) to help React Native's Metro bundler automatically resolve CommonJS entry point modules. **These changes should render unnecessary [the advice we gave in the v3.5.4 section below about `metro.config.js`](#apollo-client-354-2021-11-19).** <br/>\n  [@benjamn](https://github.com/benjamn) in [#9716](https://github.com/apollographql/apollo-client/pull/9716)\n\n- Handle falsy `incoming` data more gracefully in `offetLimitPagination().merge` function. <br/>\n  [@shobhitsharma](https://github.com/shobhitsharma) in [#9705](https://github.com/apollographql/apollo-client/pull/9705)\n\n## Apollo Client 3.6.3 (2022-05-05, only tagged `next` on npm)\n\n### Bug Fixes\n\n- Simplify `useQuery(query, { defaultOptions })` default options processing in order to fix bug where `skip: true` queries failed to execute upon switching to `skip: false`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9665](https://github.com/apollographql/apollo-client/pull/9665)\n\n- Add tests of skipping/unskipping and `useLazyQuery` with `defaultOptions`, and fix a bug causing duplicate requests. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9666](https://github.com/apollographql/apollo-client/pull/9666)\n\n- Update `ts-invariant` to version 0.10.2 to fix source map warnings. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9672](https://github.com/apollographql/apollo-client/pull/9672)\n\n- Test that `useQuery` queries with `skip: true` do not stall server-side rendering. <br/>\n  [@nathanmarks](https://github.com/nathanmarks) and [@benjamn](https://github.com/benjamn) in [#9677](https://github.com/apollographql/apollo-client/pull/9677)\n\n- Prevent `useLazyQuery` from making duplicate requests when its execution function is first called, and stop rejecting the `Promise` it returns when `result.error` is defined. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9684](https://github.com/apollographql/apollo-client/pull/9684)\n\n- Fix issue with `useQuery` returning `loading: true` state during server-side rendering with `skip: true`. <br/>\n  [@nathanmarks](https://github.com/nathanmarks) in [#9679](https://github.com/apollographql/apollo-client/pull/9679)\n\n## Apollo Client 3.6.2 (2022-05-02)\n\n### Bug Fixes\n\n- Pass `getServerSnapshot` function to `useSyncExternalStore` in addition to `getSnapshot`, though the two functions behave identically. This change should fix/unbreak React 18 server rendering. <br/>\n  [@hungphongbk](https://github.com/hungphongbk) in [#9652](https://github.com/apollographql/apollo-client/pull/9652)\n\n### Improvements\n\n- Consider `networkError.result.errors` in addition to `result.errors` in `PersistedQueryLink`. <br/>\n  [@redaid113](https://github.com/redaid113) and [@benjamn](https://github.com/benjamn) in [#9410](https://github.com/apollographql/apollo-client/pull/9410)\n\n## Apollo Client 3.6.1 (2022-04-28)\n\n### Bug Fixes\n\n- Remove recently-added, internal `fetchBlockingPromise` option from the `WatchQueryOptions` interface, due to regressions. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9504](https://github.com/apollographql/apollo-client/pull/9504)\n\n## Apollo Client 3.6.0 (2022-04-26)\n\n### Potentially disruptive changes\n\n- Calling `fetchMore` for queries using the `cache-and-network` or `network-only` fetch policies will no longer trigger additional network requests when cache results are complete. Instead, those complete cache results will be delivered as if using the `cache-first` fetch policy. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9504](https://github.com/apollographql/apollo-client/pull/9504)\n\n- Reimplement `useQuery` and `useLazyQuery` to use the [proposed `useSyncExternalStore` API](https://github.com/reactwg/react-18/discussions/86) from React 18. <br/>\n  [@brainkim](https://github.com/brainkim) and [@benjamn](https://github.com/benjamn) in [#8785](https://github.com/apollographql/apollo-client/pull/8785) and [#9596](https://github.com/apollographql/apollo-client/pull/9596)\n\n- Fixed bug where the `useLazyQuery` execution function would always use the `refetch` method of `ObservableQuery`, instead of properly reapplying the current `fetchPolicy` using the `reobserve` method. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9564](https://github.com/apollographql/apollo-client/pull/9564)\n\n  > Since this `reobserve` method is useful and used internally, we have now exposed it as `use[Lazy]Query(...).reobserve` (which optionally takes a `Partial<WatchQueryOptions>` of new options), to supplement the existing `refetch` method. Note that `reobserve` permanently updates the `variables` and other options of the `ObservableQuery`, unlike `refetch({ ...variables })`, which does not save those `variables`.\n\n- The internal use of `options.fetchBlockingPromise` by `useQuery` and `useLazyQuery` may slightly delay the delivery of network results, compared to previous versions of Apollo Client. Since network results are already delivered asynchronously, these timing differences should not be disruptive in most cases. Nevertheless, please open an issue if the timing differences are a problem for you (and you have no easy workaround). <br/>\n  [@benjamn](https://github.com/benjamn) in [#9599](https://github.com/apollographql/apollo-client/pull/9599)\n\n### React 18\n\nIn both its `peerDependencies` and its internal implementation, Apollo Client v3.6 should no longer prevent you from updating to React 18 in your applications.\n\nInternally, we have refactored `useQuery` and `useLazyQuery` to be implemented in terms of React's new (shimmable) `useSyncExternalStore` hook, demonstrating Apollo Client can serve as an external store with a referentially stable, synchronous API, as needed by React.\n\nAs part of this refactoring, we also improved the behavior of `useQuery` and `useLazyQuery` when used in `<React.StrictMode>`, which [double-renders components in development](https://github.com/reactwg/react-18/discussions/96). While this double-rendering always results in calling `useQuery` twice, forcing Apollo Client to create and then discard an unnecessary `ObservableQuery` object, we now have multiple defenses in place against executing any network queries for the unused `ObservableQuery` objects.\n\nIn upcoming v3.6.x and v3.7 (beta) releases, we will be completely overhauling our server-side rendering utilities (`getDataFromTree` et al.), and introducing suspenseful versions of our hooks, to take full advantage of the new patterns React 18+ enables for data management libraries like Apollo Client.\n\n### Improvements\n\n- Allow `BatchLink` to cancel queued and in-flight operations. <br/>\n  [@PowerKiKi](https://github.com/PowerKiKi) and [@benjamn](https://github.com/benjamn) in [#9248](https://github.com/apollographql/apollo-client/pull/9248)\n\n- Add `GraphQLWsLink` in `@apollo/client/link/subscriptions`. This link is similar to the existing `WebSocketLink` in `@apollo/client/link/ws`, but uses the newer [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) package and protocol instead of the older `subscriptions-transport-ws` implementation. This functionality was technically first released in `@apollo/client@3.5.10`, but semantically belongs in the 3.6.0 minor version.\n  [@glasser](https://github.com/glasser) in [#9369](https://github.com/apollographql/apollo-client/pull/9369)\n\n- Allow passing `defaultOptions` to `useQuery` to avoid clobbering/resetting existing options when `useQuery` is called repeatedly. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9563](https://github.com/apollographql/apollo-client/pull/9563), superseding [#9223](https://github.com/apollographql/apollo-client/pull/9223)\n\n- Provide additional context to `nextFetchPolicy` functions to assist with `fetchPolicy` transitions. More details can be found in the [`nextFetchPolicy` documentation](https://www.apollographql.com/docs/react/data/queries/#nextfetchpolicy). <br/>\n  [@benjamn](https://github.com/benjamn) in [#9222](https://github.com/apollographql/apollo-client/pull/9222)\n\n- Remove nagging deprecation warning about passing an `options.updateQuery` function to `fetchMore`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9504](https://github.com/apollographql/apollo-client/pull/9504)\n\n- Let `addTypenameToDocument` take any `ASTNode` (including `DocumentNode`, as before). <br/>\n  [@benjamn](https://github.com/benjamn) in [#9595](https://github.com/apollographql/apollo-client/pull/9595)\n\n- Set `useMutation` internal `isMounted` variable to `true` again when component remounted. <br/>\n  [@devpeerapong](https://github.com/devpeerapong) in [#9561](https://github.com/apollographql/apollo-client/pull/9561)\n\n## Apollo Client 3.5.10 (2022-02-24)\n\n### Improvements\n\n- Add `GraphQLWsLink` in `@apollo/client/link/subscriptions`. This link is similar to the existing `WebSocketLink` in `@apollo/client/link/ws`, but uses the newer [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) package and protocol instead of the older `subscriptions-transport-ws` implementation. <br/>\n  [@glasser](https://github.com/glasser) in [#9369](https://github.com/apollographql/apollo-client/pull/9369)\n\n  > Note from [@benjamn](https://github.com/benjamn): since `GraphQLWsLink` is new functionality, we would normally wait for the next minor version (v3.6), but we were asked to expedite this release. These changes are strictly additive/opt-in/backwards-compatible, so shipping them in a patch release (3.5.10) seems safe, if unusual.\n\n## Apollo Client 3.5.9 (2022-02-15)\n\n### Improvements\n\n- Interpret `keyFields: [...]` and `keyArgs: [...]` configurations in `InMemoryCache` type/field policies as `ReadonlyArray`s, since they are never mutated internally. <br/>\n  [@julienfouilhe](https://github.com/julienfouilhe) in [#9339](https://github.com/apollographql/apollo-client/pull/9339)\n\n- Avoid declaring a global type for the `__DEV__` constant, to avoid conflict with other such global declarations. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9386](https://github.com/apollographql/apollo-client/pull/9386)\n\n### Bug Fixes\n\n- Fix `useSubscription` executing `skip`ped subscription when input changes. <br/>\n  [@levrik](https://github.com/levrik) in [#9299](https://github.com/apollographql/apollo-client/pull/9299)\n\n- Fix partial data appearing in `useQuery().data` when `notifyOnNetworkStatusChange: true`. <br/>\n  [@brainkim](https://github.com/brainkim) in [#9367](https://github.com/apollographql/apollo-client/pull/9367)\n\n- Prevent `Promise`s returned by `useLazyQuery` execute functions from causing unhandled `Promise` rejection errors if uncaught. <br/>\n  [@brainkim](https://github.com/brainkim) in [#9380](https://github.com/apollographql/apollo-client/pull/9380)\n\n## Apollo Client 3.5.8 (2022-01-24)\n\n### Bug Fixes\n\n- Fix the type of the `called` property returned by `useQuery()` and `useLazyQuery()`. <br/>\n  [@sztadii](https://github.com/sztadii) in [#9304](https://github.com/apollographql/apollo-client/pull/9304)\n\n### Bug Fixes (by [@brainkim](https://github.com/brainkim) in [#9328](https://github.com/apollographql/apollo-client/pull/9328))\n\n- Fix `refetch()` not being called when `skip` is true.\n- Fix the promise returned from the `useLazyQuery()` execution function having stale variables.\n- Fix the promise returned from the `useLazyQuery()` execution function not rejecting when a query errors.\n\n## Apollo Client 3.5.7 (2022-01-10)\n\n### Bug Fixes\n\n- Fix regression that prevented calling `onError` or `onCompleted` in some cases when using `useQuery`. <br/>\n  [@mmahalwy](https://github.com/mmahalwy) in [#9226](https://github.com/apollographql/apollo-client/pull/9226)\n\n- Make `useQuery` respect `defaultOptions.watchQuery.fetchPolicy`. <br/>\n  [@yasharzolmajdi](https://github.com/yasharzolmajdi) in [#9210](https://github.com/apollographql/apollo-client/pull/9210)\n\n## Apollo Client 3.5.6 (2021-12-07)\n\n### Bug Fixes (by [@brainkim](https://github.com/brainkim) in [#9144](https://github.com/apollographql/apollo-client/pull/9144))\n\n- Restores old behavior where the callback passed to `useMutation()` is constant.\n- Fix `useMutation()` callbacks having stale closures.\n- Fix `useQuery()` variables being out of date.\n\n## Apollo Client 3.5.5 (2021-11-23)\n\n### Bug Fixes\n\n- Remove `printer: Printer` positional parameter from publicly-exported `selectHttpOptionsAndBody` function, whose addition in [#8699](https://github.com/apollographql/apollo-client/pull/8699) was a breaking change (starting in Apollo Client 3.5.0) for direct consumers of `selectHttpOptionsAndBody`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9103](https://github.com/apollographql/apollo-client/pull/9103)\n\n## Apollo Client 3.5.4 (2021-11-19)\n\n### Notices\n\n> ⚠️ The following advice about `metro.config.js` should no longer be necessary, as of Apollo Client v3.6.4.\n\n- [Relevant if you use Apollo Client with React Native] Since Apollo Client v3.5.0, CommonJS bundles provided by `@apollo/client` use a `.cjs` file extension rather than `.cjs.js`, so Node.js won't interpret them as ECMAScript modules. While this change should be an implementation detail, it may cause problems for the [Metro bundler](https://facebook.github.io/metro/) used by React Native, whose [`resolver.sourceExts`](https://facebook.github.io/metro/docs/configuration#sourceexts) configuration does not include the `cjs` extension by default.\n\n  As a workaround until [this issue](https://github.com/facebook/metro/issues/535) is resolved, you can configure Metro to understand the `.cjs` file extension by creating a `metro.config.js` file in the root of your React Native project:\n\n  ```js\n  // NOTE: No longer necessary in @apollo/client@3.6.4!\n  const { getDefaultConfig } = require(\"metro-config\");\n  const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();\n  exports.resolver = {\n    ...defaultResolver,\n    sourceExts: [...defaultResolver.sourceExts, \"cjs\"],\n  };\n  ```\n\n### Improvements\n\n- Restore the ability to pass `onError()` and `onCompleted()` to the mutation execution function. <br/> [@brainkim](https://github.com/brainkim) in [#9076](https://github.com/apollographql/apollo-client/pull/9076)\n\n- Work around webpack 5 errors of the form\n  ```\n  The request 'ts-invariant/process' failed to resolve only because it was resolved as fully specified\n  ```\n  by ensuring `import ... from 'ts-invariant/process'` is internally written to `import ... from 'ts-invariant/process/index.js'`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9083](https://github.com/apollographql/apollo-client/pull/9083)\n\n## Apollo Client 3.5.3 (2021-11-17)\n\n- Avoid rewriting non-relative imported module specifiers in `config/rewriteModuleIds.ts` script, thereby allowing bundlers to resolve those imports as they see fit. <br/>\n  [@benjamn](https://github.com/benjamn) in [#9073](https://github.com/apollographql/apollo-client/pull/9073)\n\n- Ensure only current file is matched when running VSCode debugger. <br/>\n  [@eps1lon](https://github.com/eps1lon) in [#9050](https://github.com/apollographql/apollo-client/pull/9050)\n\n## Apollo Client 3.5.2 (2021-11-10)\n\n- Fix `useMutation` execute function returning non-identical execution functions when passing similar options. <br/>\n  [@brainkim](https://github.com/brainkim) in [#9037](https://github.com/apollographql/apollo-client/pull/9037)\n\n## Apollo Client 3.5.1 (2021-11-09)\n\n- Remove npm from dependencies, and avoid referencing graphql-js enum value. <br/>\n  [@brainkim](https://github.com/brainkim) in [#9030](https://github.com/apollographql/apollo-client/pull/9030)\n\n## Apollo Client 3.5.0 (2021-11-08)\n\n### Improvements\n\n- Add `updateQuery` and `updateFragment` methods to `ApolloCache`, simplifying common `readQuery`/`writeQuery` cache update patterns. <br/>\n  [@wassim-k](https://github.com/wassim-k) in [#8382](https://github.com/apollographql/apollo-client/pull/8382)\n\n- Field directives and their arguments can now be included along with field argument names when using [field policy `keyArgs: [...]` notation](https://www.apollographql.com/docs/react/pagination/key-args/). For example, if you have a `Query.feed` field that takes an argument called `type` and uses a `@connection(key:...)` directive to keep `feed` data from different queries separate within the cache, you might configure both using the following `InMemoryCache` field policy:\n\n  ```ts\n  new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          feed: {\n            keyArgs: [\"type\", \"@connection\", [\"key\"]],\n          },\n        },\n      },\n    },\n  });\n  ```\n\n  [@benjamn](https://github.com/benjamn) in [#8678](https://github.com/apollographql/apollo-client/pull/8678)\n\n- Report single `MissingFieldError` instead of a potentially very large `MissingFieldError[]` array for incomplete cache reads, improving performance and memory usage. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8734](https://github.com/apollographql/apollo-client/pull/8734)\n\n- When writing results into `InMemoryCache`, each written object is now identified using `policies.identify` _after_ traversing the fields of the object (rather than before), simplifying identification and reducing duplicate work. If you have custom `keyFields` functions, they still receive the raw result object as their first parameter, but the `KeyFieldsContext` parameter now provides `context.storeObject` (the `StoreObject` just processed by `processSelectionSet`) and `context.readField` (a helper function for reading fields from `context.storeObject` and any `Reference`s it might contain, similar to `readField` for `read`, `merge`, and `cache.modify` functions). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8996](https://github.com/apollographql/apollo-client/pull/8996)\n\n- Ensure `cache.identify` never throws when primary key fields are missing, and include the source object in the error message when `keyFields` processing fails. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8679](https://github.com/apollographql/apollo-client/pull/8679)\n\n- The `HttpLink` constructor now accepts an optional `print` function that can be used to customize how GraphQL `DocumentNode` objects are transformed back into strings before they are sent over the network. <br/>\n  [@sarahgp](https://github.com/sarahgp) in [#8699](https://github.com/apollographql/apollo-client/pull/8699)\n\n- Make `@apollo/client/testing` a fully-fledged, independent entry point, instead of re-exporting `@apollo/client/utilities/testing` (which was never an entry point and no longer exists). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8769](https://github.com/apollographql/apollo-client/pull/8769)\n\n- A new nested entry point called `@apollo/client/testing/core` has been created. Importing from this entry point instead of `@apollo/client/testing` excludes any React-related dependencies. <br/>\n  [@wassim-k](https://github.com/wassim-k) in [#8687](https://github.com/apollographql/apollo-client/pull/8687)\n\n- Make `cache.batch` return the result of calling the `options.update` function. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8696](https://github.com/apollographql/apollo-client/pull/8696)\n\n- The `NetworkError` and `ErrorResponse` types have been changed to align more closely. <br/>\n  [@korywka](https://github.com/korywka) in [#8424](https://github.com/apollographql/apollo-client/pull/8424)\n\n- Include `graphql@16` in peer deps. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8997](https://github.com/apollographql/apollo-client/pull/8997)\n\n- Update `zen-observable-ts` to eliminate transitive dependency on `@types/zen-observable`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8695](https://github.com/apollographql/apollo-client/pull/8695)\n\n### React Refactoring\n\n#### Improvements (due to [@brainkim](https://github.com/brainkim) in [#8875](https://github.com/apollographql/apollo-client/pull/8875)):\n\n- The `useLazyQuery` function now returns a promise with the result.\n- The `useMutation` result now exposes a method which can be reset.\n\n#### Bug Fixes (due to [@brainkim](https://github.com/brainkim) in [#8596](https://github.com/apollographql/apollo-client/pull/8596)):\n\n- The `useQuery` and `useLazyQuery` hooks will now have `ObservableQuery` methods defined consistently.\n- Calling `useLazyQuery` methods like `startPolling` will start the query.\n- Calling the `useLazyQuery` execution function will now behave more like `refetch`. `previousData` will be preserved.\n- `standby` fetchPolicies will now act like `skip: true` more consistently.\n- Calling `refetch` on a skipped query will have no effect (issue [#8270](https://github.com/apollographql/apollo-client/issues/8270)).\n- Prevent `onError` and `onCompleted` functions from firing continuously, and improving their polling behavior.\n\n## Apollo Client 3.4.17 (2021-11-08)\n\n### Improvements\n\n- Allow `TOptions extends FieldFunctionOptions` to be passed as final (optional) type parameter of `FieldPolicy` type. <br/>\n  [@VictorGaiva](https://github.com/VictorGaiva) in [#9000](https://github.com/apollographql/apollo-client/pull/9000)\n\n## Apollo Client 3.4.16\n\n### Improvements\n\n- Prevent webpack from misresolving the `graphql` package as the local `@apollo/client/utilities/globals/graphql.js` module when `module.exports.resolve.preferRelative` is enabled in `webpack.config.js`.\n\n  > Note: if you encounter strange module resolution errors like `export 'isType' (imported as 'isType') was not found in 'graphql' (possible exports: removeTemporaryGlobals)` please try removing `preferRelative: true` from your `webpack.config.js` file, or find a way to disable that resolution behavior for packages within `node_modules`.\n\n  [@benjamn](https://github.com/benjamn) in [#8862](https://github.com/apollographql/apollo-client/pull/8862)\n\n- Avoid importing `isType` from the `graphql` package internally, to prevent bundlers from including as much as 3.4kB of unnecessary code. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8891](https://github.com/apollographql/apollo-client/pull/8891)\n\n- Make `client.resetStore` and `client.clearStore` pass appropriate `discardWatches` option to `cache.reset`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8873](https://github.com/apollographql/apollo-client/pull/8873)\n\n## Apollo Client 3.4.15\n\n### Bug Fixes\n\n- Require calling `cache.reset({ discardWatches: true })` to make `cache.reset` discard `cache.watches`, restoring behavior broken in v3.4.14 by [#8826](https://github.com/apollographql/apollo-client/pull/8826). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8852](https://github.com/apollographql/apollo-client/pull/8852)\n\n## Apollo Client 3.4.14\n\n### Bug Fixes\n\n- Disable `InMemoryCache` [result object canonization](https://github.com/apollographql/apollo-client/pull/7439) by default, to prevent unexpected memory growth and/or reuse of object references, with multiple ways to reenable it (per-cache, per-query, or a mixture of both). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8822](https://github.com/apollographql/apollo-client/pull/8822)\n\n- Clear `InMemoryCache` `watches` set when `cache.reset()` called. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8826](https://github.com/apollographql/apollo-client/pull/8826)\n\n- Stop excluding observerless queries from `refetchQueries: [...]` selection. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8825](https://github.com/apollographql/apollo-client/pull/8825)\n\n- Prevent optimistic cache evictions from evicting non-optimistic data. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8829](https://github.com/apollographql/apollo-client/pull/8829)\n\n- Ensure `cache.broadcastWatch` passes all relevant `WatchOptions` to `cache.diff` as `DiffOptions`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8832](https://github.com/apollographql/apollo-client/pull/8832)\n\n## Apollo Client 3.4.13\n\n### Bug Fixes\n\n- Fix `componentDidUpate` typo in `withSubscription` higher-order component. <br/>\n  [@YarBez](https://github.com/YarBez) in [#7506](https://github.com/apollographql/apollo-client/pull/7506)\n\n- Fix internal `canUseSymbol` import within `@apollo/client/utilities` to avoid breaking bundlers/builds. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8817](https://github.com/apollographql/apollo-client/pull/8817)\n\n- Tolerate unfreezable objects like `Uint8Array` and `Buffer` in `maybeDeepFreeze`. <br/>\n  [@geekuillaume](https://github.com/geekuillaume) and [@benjamn](https://github.com/benjamn) in [#8813](https://github.com/apollographql/apollo-client/pull/8813)\n\n## Apollo Client 3.4.12\n\n### Bug Fixes\n\n- Improve handling of falsy `existing` and/or `incoming` parameters in `relayStylePagination` field policy helper function. <br/>\n  [@bubba](https://github.com/bubba) and [@benjamn](https://github.com/benjamn) in [#8733](https://github.com/apollographql/apollo-client/pull/8733)\n\n- Associate Apollo context with `React.createContext` (instead of using a local `WeakMap`) again, so multiple copies of `@apollo/client` (uncommon) can share the same context. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8798](https://github.com/apollographql/apollo-client/pull/8798)\n\n## Apollo Client 3.4.11\n\n### Bug Fixes\n\n- Fix [Vite](https://vitejs.dev) tree-shaking by calling the `checkDEV()` function (at least once) in the module that exports it, `@apollo/client/utilities/globals/index.ts`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8767](https://github.com/apollographql/apollo-client/pull/8767)\n\n### Improvements\n\n- Export `PersistedQueryLink` namespace from `@apollo/client/link/persisted-queries`. <br/>\n  [@vedrani](https://github.com/vedrani) in [#8761](https://github.com/apollographql/apollo-client/pull/8761)\n\n### Documentation\n\n- Upgrade docs theme for new Algolia-powered search experience. <br/>\n  [@trevorblades](https://github.com/trevorblades) in [#8768](https://github.com/apollographql/apollo-client/pull/8768)\n\n## Apollo Client 3.4.10\n\n### Improvements\n\n- Warn when calling `refetch({ variables })` instead of `refetch(variables)`, except for queries that declare a variable named `$variables` (uncommon). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8702](https://github.com/apollographql/apollo-client/pull/8702)\n\n### Bug Fixes\n\n- Fix `ObservableQuery.getCurrentResult()` returning cached `data` with certain fetch policies. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8718](https://github.com/apollographql/apollo-client/pull/8718)\n\n- Prevent `ssrMode`/`ssrForceFetchDelay` from causing queries to hang. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8709](https://github.com/apollographql/apollo-client/pull/8709)\n\n- Import `@apollo/client/utilities/globals` internally wherever `__DEV__` is used, not just in `@apollo/client/**/index.js` entry points. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8720](https://github.com/apollographql/apollo-client/pull/8720)\n\n## Apollo Client 3.4.9\n\n### Bug Fixes\n\n- Fix unhandled `Promise` rejection warnings/errors whose message is `Observable cancelled prematurely`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8676](https://github.com/apollographql/apollo-client/pull/8676)\n\n- Enforce that `__DEV__` is polyfilled by every `@apollo/client/*` entry point that uses it. This build step considers not only explicit `__DEV__` usage but also `__DEV__` references injected near `invariant(...)` and `new InvariantError(...)` expressions. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8689](https://github.com/apollographql/apollo-client/pull/8689)\n\n## Apollo Client 3.4.8\n\n### Bug Fixes\n\n- Fix error thrown by nested `keyFields: [\"a\", [\"b\", \"c\"], \"d\"]` type policies when writing results into the cache where any of the key fields (`.a`, `.a.b`, `.a.c`, or `.d`) have been renamed by query field alias syntax. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8643](https://github.com/apollographql/apollo-client/pull/8643)\n\n- Fix regression from PR [#8422](https://github.com/apollographql/apollo-client/pull/8422) (first released in `@apollo/client@3.4.0-rc.15`) that caused `result.data` to be set to undefined in some cases after `ObservableQuery#getCurrentResult` reads an incomplete result from the cache. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8642](https://github.com/apollographql/apollo-client/pull/8642)\n\n## Apollo Client 3.4.7\n\n### Bug Fixes\n\n- Fix accidental reuse of recycled `MergeTree` objects in `StoreWriter` class used by `InMemoryCache`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8618](https://github.com/apollographql/apollo-client/pull/8618)\n\n## Apollo Client 3.4.6\n\n### Improvements\n\n- Reevaluate `window.fetch` each time `HttpLink` uses it, if not configured using `options.fetch`. This change enables a variety of strategies for instrumenting `window.fetch`, without requiring those strategies to run before `@apollo/client/link/http` is first imported. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8603](https://github.com/apollographql/apollo-client/pull/8603)\n\n- Clarify mutation `fetchPolicy` options (`\"network-only\"` or `\"no-cache\"`) using [`MutationFetchPolicy`](https://github.com/apollographql/apollo-client/blob/fa52875341ab33f3e8192ded90af5e2c208e0f75/src/core/watchQueryOptions.ts#L33-L37) union type. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8602](https://github.com/apollographql/apollo-client/pull/8602)\n\n### Bug Fixes\n\n- Restore full `@apollo/client/apollo-client.cjs.js` CommonJS bundle for older bundlers.\n\n  > Note that Node.js and CommonJS bundlers typically use the bundles specified by `\"main\"` fields in our generated `package.json` files, which are all independent and non-overlapping CommonJS modules. However, `apollo-client.cjs.js` is just one big bundle, so mixing imports of `apollo-client.cjs.js` with the other CommonJS bundles is discouraged, as it could trigger the [dual package hazard](https://nodejs.org/api/packages.html#packages_dual_commonjs_es_module_packages). In other words, please don't start using `apollo-client.cjs.js` if you're not already. <br/>\n\n  [@benjamn](https://github.com/benjamn) in [#8592](https://github.com/apollographql/apollo-client/pull/8592)\n\n- Log `MissingFieldError`s in `ObservableQuery#getCurrentResult` using `invariant.debug`, rather than reporting them via `result.error`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8604](https://github.com/apollographql/apollo-client/pull/8604)\n\n## Apollo Client 3.4.5\n\n### Bug Fixes\n\n- Fix double registration bug for mutation `refetchQueries` specified using legacy one-time `refetchQueries: [{ query, variables }]` style. Though the bug is fixed, we recommend using `refetchQueries: [query]` instead (when possible) to refetch an existing query using its `DocumentNode`, rather than creating, executing, and then deleting a new query, as the legacy `{ query, variables }` style unfortunately does. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8586](https://github.com/apollographql/apollo-client/pull/8586)\n\n- Fix `useQuery`/`useLazyQuery` stalling when clients or queries change. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8589](https://github.com/apollographql/apollo-client/pull/8589)\n\n## Apollo Client 3.4.4\n\n### Bug Fixes\n\n- Revert accidental addition of `engines.npm` section to published version of `@apollo/client/package.json`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8578](https://github.com/apollographql/apollo-client/pull/8578)\n\n## Apollo Client 3.4.3\n\n### Bug Fixes\n\n- Fix `{ ssr: false }` causing queries to hang on the client. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8574](https://github.com/apollographql/apollo-client/pull/8574)\n\n## Apollo Client 3.4.2\n\n### Bug Fixes\n\n- Use more default type parameters for mutation-related types in `react/types/types.ts`, to provide smoother backwards compatibility for code using those types explicitly. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8573](https://github.com/apollographql/apollo-client/pull/8573)\n\n## Apollo Client 3.4.1\n\n### Bug Fixes\n\n- Initialize `stringifyCanon` lazily, when `canonicalStringify` is first called, fixing `Uncaught ReferenceError: __DEV__ is not defined` errors due to usage of `__DEV__` before declaration. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8557](https://github.com/apollographql/apollo-client/pull/8557)\n\n## Apollo Client 3.4.0\n\n### New documentation\n\n- [**Refetching queries**](https://www.apollographql.com/docs/react/data/refetching/) with `client.refetchQueries`. <br/>\n  [@StephenBarlow](https://github.com/StephenBarlow) and [@benjamn](https://github.com/benjamn) in [#8265](https://github.com/apollographql/apollo-client/pull/8265)\n\n### Improvements\n\n- `InMemoryCache` now _guarantees_ that any two result objects returned by the cache (from `readQuery`, `readFragment`, etc.) will be referentially equal (`===`) if they are deeply equal. Previously, `===` equality was often achievable for results for the same query, on a best-effort basis. Now, equivalent result objects will be automatically shared among the result trees of completely different queries. This guarantee is important for taking full advantage of optimistic updates that correctly guess the final data, and for \"pure\" UI components that can skip re-rendering when their input data are unchanged. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7439](https://github.com/apollographql/apollo-client/pull/7439)\n\n- Mutations now accept an optional callback function called `onQueryUpdated`, which will be passed the `ObservableQuery` and `Cache.DiffResult` objects for any queries invalidated by cache writes performed by the mutation's final `update` function. Using `onQueryUpdated`, you can override the default `FetchPolicy` of the query, by (for example) calling `ObservableQuery` methods like `refetch` to force a network request. This automatic detection of invalidated queries provides an alternative to manually enumerating queries using the `refetchQueries` mutation option. Also, if you return a `Promise` from `onQueryUpdated`, the mutation will automatically await that `Promise`, rendering the `awaitRefetchQueries` option unnecessary. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7827](https://github.com/apollographql/apollo-client/pull/7827)\n\n- Support `client.refetchQueries` as an imperative way to refetch queries, without having to pass `options.refetchQueries` to `client.mutate`. <br/>\n  [@dannycochran](https://github.com/dannycochran) in [#7431](https://github.com/apollographql/apollo-client/pull/7431)\n\n- Improve standalone `client.refetchQueries` method to support automatic detection of queries needing to be refetched. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8000](https://github.com/apollographql/apollo-client/pull/8000)\n\n- Fix remaining barriers to loading [`@apollo/client/core`](https://cdn.jsdelivr.net/npm/@apollo/client@3.4.0/core/+esm) as native ECMAScript modules from a CDN like [esm.run](https://www.jsdelivr.com/esm). Importing `@apollo/client` from a CDN will become possible once we move all React-related dependencies into `@apollo/client/react` in Apollo Client 4. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8266](https://github.com/apollographql/apollo-client/issues/8266)\n\n- `InMemoryCache` supports a new method called `batch`, which is similar to `performTransaction` but takes named options rather than positional parameters. One of these named options is an `onDirty(watch, diff)` callback, which can be used to determine which watched queries were invalidated by the `batch` operation. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7819](https://github.com/apollographql/apollo-client/pull/7819)\n\n- Allow `merge: true` field policy to merge `Reference` objects with non-normalized objects, and vice-versa. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7778](https://github.com/apollographql/apollo-client/pull/7778)\n\n- Allow identical subscriptions to be deduplicated by default, like queries. <br/>\n  [@jkossis](https://github.com/jkossis) in [#6910](https://github.com/apollographql/apollo-client/pull/6910)\n\n- Always use `POST` request when falling back to sending full query with `@apollo/client/link/persisted-queries`. <br/>\n  [@rieset](https://github.com/rieset) in [#7456](https://github.com/apollographql/apollo-client/pull/7456)\n\n- The `FetchMoreQueryOptions` type now takes two instead of three type parameters (`<TVariables, TData>`), thanks to using `Partial<TVariables>` instead of `K extends typeof TVariables` and `Pick<TVariables, K>`. <br/>\n  [@ArnaudBarre](https://github.com/ArnaudBarre) in [#7476](https://github.com/apollographql/apollo-client/pull/7476)\n\n- Pass `variables` and `context` to a mutation's `update` function. **Note:** The type of the `update` function is now named `MutationUpdaterFunction` rather than `MutationUpdaterFn`, since the older type was [broken beyond repair](https://github.com/apollographql/apollo-client/issues/8506#issuecomment-881706613). If you are using `MutationUpdaterFn` in your own code, please use `MutationUpdaterFunction` instead. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#7902](https://github.com/apollographql/apollo-client/pull/7902)\n\n- A `resultCacheMaxSize` option may be passed to the `InMemoryCache` constructor to limit the number of result objects that will be retained in memory (to speed up repeated reads), and calling `cache.reset()` now releases all such memory. <br/>\n  [@SofianHn](https://github.com/SofianHn) in [#8107](https://github.com/apollographql/apollo-client/pull/8107)\n\n- Fully remove result cache entries from LRU dependency system when the corresponding entities are removed from `InMemoryCache` by eviction, or by any other means. <br/>\n  [@sofianhn](https://github.com/sofianhn) and [@benjamn](https://github.com/benjamn) in [#8147](https://github.com/apollographql/apollo-client/pull/8147)\n\n- Expose missing field errors in results. <br/>\n  [@brainkim](github.com/brainkim) in [#8262](https://github.com/apollographql/apollo-client/pull/8262)\n\n- Add expected/received `variables` to `No more mocked responses...` error messages generated by `MockLink`. <br/>\n  [@markneub](github.com/markneub) in [#8340](https://github.com/apollographql/apollo-client/pull/8340)\n\n- The `InMemoryCache` version of the `cache.gc` method now supports additional options for removing non-essential (recomputable) result caching data. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8421](https://github.com/apollographql/apollo-client/pull/8421)\n\n- Suppress noisy `Missing cache result fields...` warnings by default unless `setLogVerbosity(\"debug\")` called. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8489](https://github.com/apollographql/apollo-client/pull/8489)\n\n- Improve interaction between React hooks and React Fast Refresh in development. <br/>\n  [@andreialecu](https://github.com/andreialecu) in [#7952](https://github.com/apollographql/apollo-client/pull/7952)\n\n### Potentially disruptive changes\n\n- To avoid retaining sensitive information from mutation root field arguments, Apollo Client v3.4 automatically clears any `ROOT_MUTATION` fields from the cache after each mutation finishes. If you need this information to remain in the cache, you can prevent the removal by passing the `keepRootFields: true` option to `client.mutate`. `ROOT_MUTATION` result data are also passed to the mutation `update` function, so we recommend obtaining the results that way, rather than using `keepRootFields: true`, if possible. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8280](https://github.com/apollographql/apollo-client/pull/8280)\n\n- Internally, Apollo Client now controls the execution of development-only code using the `__DEV__` global variable, rather than `process.env.NODE_ENV`. While this change should not cause any visible differences in behavior, it will increase your minified+gzip bundle size by more than 3.5kB, unless you configure your minifier to replace `__DEV__` with a `true` or `false` constant, the same way you already replace `process.env.NODE_ENV` with a string literal like `\"development\"` or `\"production\"`. For an example of configuring a Create React App project without ejecting, see this pull request for our [React Apollo reproduction template](https://github.com/apollographql/react-apollo-error-template/pull/51). <br/>\n  [@benjamn](https://github.com/benjamn) in [#8347](https://github.com/apollographql/apollo-client/pull/8347)\n\n- Internally, Apollo Client now uses namespace syntax (e.g. `import * as React from \"react\"`) for imports whose types are re-exported (and thus may appear in `.d.ts` files). This change should remove any need to configure `esModuleInterop` or `allowSyntheticDefaultImports` in `tsconfig.json`, but might require updating bundler configurations that specify named exports of the `react` and `prop-types` packages, to include exports like `createContext` and `createElement` ([example](https://github.com/apollographql/apollo-client/commit/16b08e1af9ba9934041298496e167aafb128c15d)). <br/>\n  [@devrelm](https://github.com/devrelm) in [#7742](https://github.com/apollographql/apollo-client/pull/7742)\n\n- Respect `no-cache` fetch policy (by not reading any `data` from the cache) for `loading: true` results triggered by `notifyOnNetworkStatusChange: true`. <br />\n  [@jcreighton](https://github.com/jcreighton) in [#7761](https://github.com/apollographql/apollo-client/pull/7761)\n\n- The TypeScript return types of the `getLastResult` and `getLastError` methods of `ObservableQuery` now correctly include the possibility of returning `undefined`. If you happen to be calling either of these methods directly, you may need to adjust how the calling code handles the methods' possibly-`undefined` results. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8394](https://github.com/apollographql/apollo-client/pull/8394)\n\n- Log non-fatal `invariant.error` message when fields are missing from result objects written into `InMemoryCache`, rather than throwing an exception. While this change relaxes an exception to be merely an error message, which is usually a backwards-compatible change, the error messages are logged in more cases now than the exception was previously thrown, and those new error messages may be worth investigating to discover potential problems in your application. The errors are not displayed for `@client`-only fields, so adding `@client` is one way to handle/hide the errors for local-only fields. Another general strategy is to use a more precise query to write specific subsets of data into the cache, rather than reusing a larger query that contains fields not present in the written `data`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8416](https://github.com/apollographql/apollo-client/pull/8416)\n\n- The [`nextFetchPolicy`](https://github.com/apollographql/apollo-client/pull/6893) option for `client.watchQuery` and `useQuery` will no longer be removed from the `options` object after it has been applied, and instead will continue to be applied any time `options.fetchPolicy` is reset to another value, until/unless the `options.nextFetchPolicy` property is removed from `options`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8465](https://github.com/apollographql/apollo-client/pull/8465)\n\n- The `fetchMore`, `subscribeToMore`, and `updateQuery` functions returned from the `useQuery` hook may now return undefined in edge cases where the functions are called when the component is unmounted <br/> [@noghartt](https://github.com/noghartt) in [#7980](https://github.com/apollographql/apollo-client/pull/7980).\n\n### Bug fixes\n\n- In Apollo Client 2.x, a `refetch` operation would always replace existing data in the cache. With the introduction of field policy `merge` functions in Apollo Client 3, existing field values could be inappropriately combined with incoming field values by a custom `merge` function that does not realize a `refetch` has happened.\n\n  To give you more control over this behavior, we have introduced an `overwrite?: boolean = false` option for `cache.writeQuery` and `cache.writeFragment`, and an option called `refetchWritePolicy?: \"merge\" | \"overwrite\"` for `client.watchQuery`, `useQuery`, and other functions that accept `WatchQueryOptions`. You can use these options to make sure any `merge` functions involved in cache writes for `refetch` operations get invoked with `undefined` as their first argument, which simulates the absence of any existing data, while still giving the `merge` function a chance to determine the internal representation of the incoming data.\n\n  The default behaviors are `overwrite: true` and `refetchWritePolicy: \"overwrite\"`, which restores the Apollo Client 2.x behavior, but (if this change causes any problems for your application) you can easily recover the previous merging behavior by setting a default value for `refetchWritePolicy` in `defaultOptions.watchQuery`:\n\n  ```ts\n  new ApolloClient({\n    defaultOptions: {\n      watchQuery: {\n        refetchWritePolicy: \"merge\",\n      },\n    },\n  });\n  ```\n\n  [@benjamn](https://github.com/benjamn) in [#7810](https://github.com/apollographql/apollo-client/pull/7810)\n\n- Make sure the `MockedResponse` `ResultFunction` type is re-exported. <br/>\n  [@hwillson](https://github.com/hwillson) in [#8315](https://github.com/apollographql/apollo-client/pull/8315)\n\n- Fix polling when used with `skip`. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8346](https://github.com/apollographql/apollo-client/pull/8346)\n\n- `InMemoryCache` now coalesces `EntityStore` updates to guarantee only one `store.merge(id, fields)` call per `id` per cache write. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8372](https://github.com/apollographql/apollo-client/pull/8372)\n\n- Fix polling when used with `<React.StrictMode>`. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8414](https://github.com/apollographql/apollo-client/pull/8414)\n\n- Fix the React integration logging `Warning: Can't perform a React state update on an unmounted component`. <br/>\n  [@wuarmin](https://github.com/wuarmin) in [#7745](https://github.com/apollographql/apollo-client/pull/7745)\n\n- Make `ObservableQuery#getCurrentResult` always call `queryInfo.getDiff()`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8422](https://github.com/apollographql/apollo-client/pull/8422)\n\n- Make `readField` default to reading from current object only when the `from` option/argument is actually omitted, not when `from` is passed to `readField` with an undefined value. A warning will be printed when this situation occurs. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8508](https://github.com/apollographql/apollo-client/pull/8508)\n\n- The `fetchMore`, `subscribeToMore`, and `updateQuery` functions no longer throw `undefined` errors <br/> [@noghartt](https://github.com/noghartt) in [#7980](https://github.com/apollographql/apollo-client/pull/7980).\n\n## Apollo Client 3.3.21\n\n### Bug fixes\n\n- Fix race condition in `@apollo/client/link/context` that could leak subscriptions if the subscription is cancelled before `operation.setContext` is called. <br/>\n  [@sofianhn](https://github.com/sofianhn) in [#8399](https://github.com/apollographql/apollo-client/pull/8399)\n\n- Prefer `existing.pageInfo.startCursor` and `endCursor` (if defined) in `read` function of `relayStylePagination` policies. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8438](https://github.com/apollographql/apollo-client/pull/8438)\n\n### Improvements\n\n- Normalize user-provided `HttpLink` headers by lower-casing their names. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8449](https://github.com/apollographql/apollo-client/pull/8449)\n\n## Apollo Client 3.3.20\n\n### Bug fixes\n\n- Fix policy merging bug when calling `cache.policies.addTypePolicies` multiple times for the same type policy. <br/>\n  [@Banou26](https://github.com/Banou26) in [#8361](https://github.com/apollographql/apollo-client/pull/8361)\n\n## Apollo Client 3.3.19\n\n### Bug fixes\n\n- Use `export ... from` syntax to re-export `graphql-tag` named exports, making tree-shaking easier for some bundlers. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8221](https://github.com/apollographql/apollo-client/pull/8221)\n\n### Documentation\n\n- Replace Spectrum references with [community.apollographql.com](https://community.apollographql.com). <br/>\n  [@hwillson](https://github.com/hwillson) in [#8238](https://github.com/apollographql/apollo-client/pull/8238)\n\n## Apollo Client 3.3.18\n\n### Bug fixes\n\n- Add `\"sideEffects\": false` to all generated/published `package.json` files, to improve dead code elimination for nested entry points like `@apollo/client/cache`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8213](https://github.com/apollographql/apollo-client/pull/8213)\n\n## Apollo Client 3.3.17\n\n### Bug fixes\n\n- Make `useReactiveVar(rv)` recheck the latest `rv()` value in its `useEffect` callback, and immediately update state if the value has already changed, rather than calling `rv.onNextChange(setValue)` to listen for future changes. <br/>\n  [@benjamn](https://github.com/benjamn) in [#8135](https://github.com/apollographql/apollo-client/pull/8135)\n\n## Apollo Client 3.3.16\n\n### Bug fixes\n\n- Prevent `undefined` mutation result in `useMutation`. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#8018](https://github.com/apollographql/apollo-client/pull/8018)\n\n- Fix `useReactiveVar` not rerendering for successive synchronous calls. <br/>\n  [@brainkim](https://github.com/brainkim) in [#8022](https://github.com/apollographql/apollo-client/pull/8022)\n\n- Support `batchDebounce` option for `BatchLink` and `BatchHttpLink`. <br/>\n  [@dannycochran](https://github.com/dannycochran) in [#8024](https://github.com/apollographql/apollo-client/pull/8024)\n\n## Apollo Client 3.3.15\n\n- Increment `queryInfo.lastRequestId` only when making a network request through the `ApolloLink` chain, rather than every time `fetchQueryByPolicy` is called. <br/>\n  [@dannycochran](https://github.com/dannycochran) in [#7956](https://github.com/apollographql/apollo-client/pull/7956)\n\n- During server-side rendering, allow initial `useQuery` calls to return final `{ loading: false, data }` results when the cache already contains the necessary data. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7983](https://github.com/apollographql/apollo-client/pull/7983)\n\n## Apollo Client 3.3.14\n\n### Improvements\n\n- Adjust TypeScript types to allow `keyFields` and `keyArgs` functions to return `false`. <br/>\n  [@CarsonF](https://github.com/CarsonF) and [@benjamn](https://github.com/benjamn) in [#7900](https://github.com/apollographql/apollo-client/pull/7900)\n\n### Bug fixes\n\n- Prevent `RenderPromises` memory leak by calling `renderPromises.clear()` after `getMarkupFromTree` finishes. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7943](https://github.com/apollographql/apollo-client/pull/7943)\n\n- Cancel pending notify timeout when stopping a `QueryInfo` object. <br/>\n  [@hollandThomas](https://github.com/hollandThomas) in [#7935](https://github.com/apollographql/apollo-client/pull/7935)\n\n- Fix infinite rendering bug related to `useSubscription`. <br/>\n  [@brainkim](https://github.com/brainkim) in [#7917](https://github.com/apollographql/apollo-client/pull/7917)\n\n## Apollo Client 3.3.13\n\n### Improvements\n\n- Add missing `context` option to `useSubscription`. <br />\n  [@jcreighton](https://github.com/jcreighton) in [#7860](https://github.com/apollographql/apollo-client/pull/7860)\n\n- Remove unnecessary TypeScript global `Observable<T>[\"@@observable\"]` method declaration. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7888](https://github.com/apollographql/apollo-client/pull/7888)\n\n- Prevent skipped/observerless `ObservableQuery`s from being refetched by `refetchQueries`. <br/>\n  [@dannycochran](https://github.com/dannycochran) in [#7877](https://github.com/apollographql/apollo-client/pull/7877)\n\n## Apollo Client 3.3.12\n\n### Bug fixes\n\n- Maintain serial ordering of `asyncMap` mapping function calls, and prevent potential unhandled `Promise` rejection errors. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7818](https://github.com/apollographql/apollo-client/pull/7818)\n\n- Relax incompatible `children?: React.ReactElement` field type in `MockedProviderProps` interface. <br/>\n  [@kevinperaza](https://github.com/kevinperaza) in [#7833](https://github.com/apollographql/apollo-client/pull/7833)\n\n## Apollo Client 3.3.11\n\n### Bug fixes\n\n- Fix `useLazyQuery` `forceUpdate` loop regression introduced by [#7655](https://github.com/apollographql/apollo-client/pull/7655) in version 3.3.10. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7715](https://github.com/apollographql/apollo-client/pull/7715)\n\n## Apollo Client 3.3.10\n\n### Bug fixes\n\n- Revert PR [#7276](https://github.com/apollographql/apollo-client/pull/7276), but test that garbage collection reclaims torn-down `ObservableQuery` objects. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7695](https://github.com/apollographql/apollo-client/pull/7695)\n\n- Reset `QueryInfo.diff` and `QueryInfo.dirty` after canceling notify timeout in `QueryInfo.markResult` and `QueryInfo.markError`. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#7696](https://github.com/apollographql/apollo-client/pull/7696)\n\n### Improvements\n\n- Avoid calling `forceUpdate` when component is unmounted. <br/>\n  [@DylanVann](https://github.com/DylanVann) in [#7655](https://github.com/apollographql/apollo-client/pull/7655)\n\n- The `codemods/` top-level directory has been moved into the `scripts/` directory. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7675](https://github.com/apollographql/apollo-client/pull/7675)\n\n## Apollo Client 3.3.9\n\n### Bug Fixes\n\n- Prevent reactive variables from retaining otherwise unreachable `InMemoryCache` objects. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7661](https://github.com/apollographql/apollo-client/pull/7661)\n\n### Improvements\n\n- The [`graphql-tag`](https://www.npmjs.com/package/graphql-tag) dependency has been updated to version 2.12.0, after converting its repository to use TypeScript and ECMAScript module syntax. There should be no visible changes in behavior, though the internal changes seemed significant enough to mention here. <br/>\n  [@abdonrd](https://github.com/abdonrd) in [graphql-tag#273](https://github.com/apollographql/graphql-tag/pull/273) and\n  [@PowerKiKi](https://github.com/PowerKiKi) in [graphql-tag#325](https://github.com/apollographql/graphql-tag/pull/325)\n\n## Apollo Client 3.3.8\n\n### Bug Fixes\n\n- Catch updates in `useReactiveVar` with an additional check. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#7652](https://github.com/apollographql/apollo-client/pull/7652)\n\n- Reactivate forgotten reactive variables whenever `InMemoryCache` acquires its first watcher. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7657](https://github.com/apollographql/apollo-client/pull/7657)\n\n- Backport `Symbol.species` fix for `Concast` and `ObservableQuery` from [`release-3.4`](https://github.com/apollographql/apollo-client/pull/7399), fixing subscriptions in React Native Android when the Hermes JavaScript engine is enabled (among other benefits). <br/>\n  [@benjamn](https://github.com/benjamn) in [#7403](https://github.com/apollographql/apollo-client/pull/7403) and [#7660](https://github.com/apollographql/apollo-client/pull/7660)\n\n## Apollo Client 3.3.7\n\n### Bug Fixes\n\n- Fix a regression due to [#7310](https://github.com/apollographql/apollo-client/pull/7310) that caused `loading` always to be `true` for `skip: true` results during server-side rendering. <br/>\n  [@rgrove](https://github.com/rgrove) in [#7567](https://github.com/apollographql/apollo-client/pull/7567)\n\n- Avoid duplicate `useReactiveVar` listeners when rendering in `React.StrictMode`. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#7581](https://github.com/apollographql/apollo-client/pull/7581)\n\n### Improvements\n\n- Set `displayName` on `ApolloContext` objects for easier debugging. <br/>\n  [@dulmandakh](https://github.com/dulmandakh) in [#7550](https://github.com/apollographql/apollo-client/pull/7550)\n\n## Apollo Client 3.3.6\n\n### Bug Fixes\n\n- Immediately apply `queryType: true`, `mutationType: true`, and `subscriptionType: true` type policies, rather than waiting for the first time the policy is used, fixing a [regression](https://github.com/apollographql/apollo-client/issues/7443) introduced by [#7065](https://github.com/apollographql/apollo-client/pull/7065). <br/>\n  [@benjamn](https://github.com/benjamn) in [#7463](https://github.com/apollographql/apollo-client/pull/7463)\n\n- Check that `window` is defined even when `connectToDevTools` is `true`. <br/>\n  [@yasupeke](https://github.com/yasupeke) in [#7434](https://github.com/apollographql/apollo-client/pull/7434)\n\n### Improvements\n\n- Replace stray `console.debug` (undefined in React Native) with `invariant.log`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7454](https://github.com/apollographql/apollo-client/pull/7454)\n\n- Suggest Firefox Apollo DevTools as well as the Chrome extension. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7461](https://github.com/apollographql/apollo-client/pull/7461)\n\n## Apollo Client 3.3.5\n\n### Improvements\n\n- Restore `client.version` property, reflecting the current `@apollo/client` version from `package.json`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7448](https://github.com/apollographql/apollo-client/pull/7448)\n\n## Apollo Client 3.3.4\n\n### Improvements\n\n- Update `ts-invariant` to avoid potential [Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP)-violating `Function` fallback, thanks to [a clever new `globalThis` polyfill technique](https://mathiasbynens.be/notes/globalthis). <br/>\n  [@benjamn](https://github.com/benjamn) in [#7414](https://github.com/apollographql/apollo-client/pull/7414)\n\n## Apollo Client 3.3.3\n\n### Bug fixes\n\n- Make the `observer` parameter of `ApolloLink#onError` optional, fixing an unnecessary breaking change for any code that called `onError` directly. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7407](https://github.com/apollographql/apollo-client/pull/7407)\n\n## Apollo Client 3.3.2\n\n> ⚠️ **Note:** This version of `@apollo/client` contains no behavioral changes since version 3.3.1\n\n### Documentation\n\n- The [Pagination](https://www.apollographql.com/docs/react/pagination/overview/) article has been completely rewritten (and split into multiple pages) to cover Apollo Client 3 field policies. <br/>\n  [@benjamn](https://github.com/benjamn) and [@StephenBarlow](https://github.com/StephenBarlow) in [#7175](https://github.com/apollographql/apollo-client/pull/7175)\n\n- Revamp [local state tutorial chapter](https://www.apollographql.com/tutorials/fullstack-quickstart/managing-local-state) for Apollo Client 3, including reactive variables. <br/>\n  [@StephenBarlow](https://github.com/StephenBarlow) in [`apollographql@apollo#1050`](https://github.com/apollographql/apollo/pull/1050)\n\n- Add examples of using `ApolloLink` to modify response data asynchronously. <br/>\n  [@alichry](https://github.com/alichry) in [#7332](https://github.com/apollographql/apollo-client/pull/7332)\n\n- Consolidate separate v2.4, v2.5, and v2.6 documentation versions into one v2 version. <br/>\n  [@jgarrow](https://github.com/jgarrow) in [#7378](https://github.com/apollographql/apollo-client/pull/7378)\n\n## Apollo Client 3.3.1\n\n### Bug Fixes\n\n- Revert back to `default`-importing `React` internally, rather than using a namespace import. <br/>\n  [@benjamn](https://github.com/benjamn) in [113475b1](https://github.com/apollographql/apollo-client/commit/113475b163a19a40a67465c11e8e6f48a1de7e76)\n\n## Apollo Client 3.3.0\n\n### Bug Fixes\n\n- Update `@wry/equality` to consider undefined properties equivalent to missing properties. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7108](https://github.com/apollographql/apollo-client/pull/7108)\n\n- Prevent memory leaks involving unused `onBroadcast` function closure created in `ApolloClient` constructor. <br/>\n  [@kamilkisiela](https://github.com/kamilkisiela) in [#7161](https://github.com/apollographql/apollo-client/pull/7161)\n\n- Provide default empty cache object for root IDs like `ROOT_QUERY`, to avoid differences in behavior before/after `ROOT_QUERY` data has been written into `InMemoryCache`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7100](https://github.com/apollographql/apollo-client/pull/7100)\n\n- Cancel `queryInfo.notifyTimeout` in `QueryInfo#markResult` to prevent unnecessary network requests when using a `FetchPolicy` of `cache-and-network` or `network-only` in a React component with multiple `useQuery` calls. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7347](https://github.com/apollographql/apollo-client/pull/7347)\n\n### Potentially breaking changes\n\n- Ensure `cache.readQuery` and `cache.readFragment` always return `TData | null`, instead of throwing `MissingFieldError` exceptions when missing fields are encountered. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7098](https://github.com/apollographql/apollo-client/pull/7098)\n\n  > Since this change converts prior exceptions to `null` returns, and since `null` was already a possible return value according to the `TData | null` return type, we are confident this change will be backwards compatible (as long as `null` was properly handled before).\n\n- `HttpLink` will now automatically strip any unused `variables` before sending queries to the GraphQL server, since those queries are very likely to fail validation, according to the [All Variables Used](https://spec.graphql.org/draft/#sec-All-Variables-Used) rule in the GraphQL specification. If you depend on the preservation of unused variables, you can restore the previous behavior by passing `includeUnusedVariables: true` to the `HttpLink` constructor (which is typically passed as `options.link` to the `ApolloClient` constructor). <br/>\n  [@benjamn](https://github.com/benjamn) in [#7127](https://github.com/apollographql/apollo-client/pull/7127)\n\n- Ensure `MockLink` (used by `MockedProvider`) returns mock configuration errors (e.g. `No more mocked responses for the query ...`) through the Link's `Observable`, instead of throwing them. These errors are now available through the `error` property of a result. <br/>\n  [@hwillson](https://github.com/hwillson) in [#7110](https://github.com/apollographql/apollo-client/pull/7110)\n\n  > Returning mock configuration errors through the Link's `Observable` was the default behavior in Apollo Client 2.x. We changed it for 3, but the change has been problematic for those looking to migrate from 2.x to 3. We've decided to change this back with the understanding that not many people want or are relying on `MockLink`'s throwing exception approach. If you want to change this functionality, you can define custom error handling through `MockLink.setOnError`.\n\n- Unsubscribing the last observer from an `ObservableQuery` will once again unsubscribe from the underlying network `Observable` in all cases, as in Apollo Client 2.x, allowing network requests to be cancelled by unsubscribing. <br/>\n  [@javier-garcia-meteologica](https://github.com/javier-garcia-meteologica) in [#7165](https://github.com/apollographql/apollo-client/pull/7165) and [#7170](https://github.com/apollographql/apollo-client/pull/7170).\n\n- The independent `QueryBaseOptions` and `ModifiableWatchQueryOptions` interface supertypes have been eliminated, and their fields are now defined by `QueryOptions`. <br/>\n  [@DCtheTall](https://github.com/DCtheTall) in [#7136](https://github.com/apollographql/apollo-client/pull/7136)\n\n- Internally, Apollo Client now avoids nested imports from the `graphql` package, importing everything from the top-level package instead. For example,\n  ```ts\n  import { visit } from \"graphql/language/visitor\";\n  ```\n  is now just\n  ```ts\n  import { visit } from \"graphql\";\n  ```\n  Since the `graphql` package uses `.mjs` modules, your bundler may need to be configured to recognize `.mjs` files as ECMAScript modules rather than CommonJS modules. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7185](https://github.com/apollographql/apollo-client/pull/7185)\n\n### Improvements\n\n- Support inheritance of type and field policies, according to `possibleTypes`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7065](https://github.com/apollographql/apollo-client/pull/7065)\n\n- Allow configuring custom `merge` functions, including the `merge: true` and `merge: false` shorthands, in type policies as well as field policies. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7070](https://github.com/apollographql/apollo-client/pull/7070)\n\n- The verbosity of Apollo Client console messages can be globally adjusted using the `setLogVerbosity` function:\n\n  ```ts\n  import { setLogVerbosity } from \"@apollo/client\";\n  setLogVerbosity(\"log\"); // display all messages\n  setLogVerbosity(\"warn\"); // display only warnings and errors (default)\n  setLogVerbosity(\"error\"); // display only errors\n  setLogVerbosity(\"silent\"); // hide all console messages\n  ```\n\n  Remember that all logs, warnings, and errors are hidden in production. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7226](https://github.com/apollographql/apollo-client/pull/7226)\n\n- Modifying `InMemoryCache` fields that have `keyArgs` configured will now invalidate only the field value with matching key arguments, rather than invalidating all field values that share the same field name. If `keyArgs` has not been configured, the cache must err on the side of invalidating by field name, as before. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7351](https://github.com/apollographql/apollo-client/pull/7351)\n\n- Shallow-merge `options.variables` when combining existing or default options with newly-provided options, so new variables do not completely overwrite existing variables. <br/>\n  [@amannn](https://github.com/amannn) in [#6927](https://github.com/apollographql/apollo-client/pull/6927)\n\n- Avoid displaying `Cache data may be lost...` warnings for scalar field values that happen to be objects, such as JSON data. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7075](https://github.com/apollographql/apollo-client/pull/7075)\n\n- In addition to the `result.data` property, `useQuery` and `useLazyQuery` will now provide a `result.previousData` property, which can be useful when a network request is pending and `result.data` is undefined, since `result.previousData` can be rendered instead of rendering an empty/loading state. <br/>\n  [@hwillson](https://github.com/hwillson) in [#7082](https://github.com/apollographql/apollo-client/pull/7082)\n\n- Passing `validate: true` to the `SchemaLink` constructor will enable validation of incoming queries against the local schema before execution, returning validation errors in `result.errors`, just like a non-local GraphQL endpoint typically would. <br/>\n  [@amannn](https://github.com/amannn) in [#7094](https://github.com/apollographql/apollo-client/pull/7094)\n\n- Allow optional arguments in `keyArgs: [...]` arrays for `InMemoryCache` field policies. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7109](https://github.com/apollographql/apollo-client/pull/7109)\n\n- Avoid registering `QueryPromise` when `skip` is `true` during server-side rendering. <br/>\n  [@izumin5210](https://github.com/izumin5210) in [#7310](https://github.com/apollographql/apollo-client/pull/7310)\n\n- `ApolloCache` objects (including `InMemoryCache`) may now be associated with or disassociated from individual reactive variables by calling `reactiveVar.attachCache(cache)` and/or `reactiveVar.forgetCache(cache)`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7350](https://github.com/apollographql/apollo-client/pull/7350)\n\n## Apollo Client 3.2.9\n\n### Bug Fixes\n\n- Revert back to `default`-importing `React` internally, rather than using a namespace import. <br/>\n  [@benjamn](https://github.com/benjamn) in [113475b1](https://github.com/apollographql/apollo-client/commit/113475b163a19a40a67465c11e8e6f48a1de7e76)\n\n## Apollo Client 3.2.8\n\n### Bug Fixes\n\n- Ensure `sourcesContent` array is properly defined in `.js.map` files generated by `tsc`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7371](https://github.com/apollographql/apollo-client/pull/7371)\n\n- Avoid relying on global `Symbol` properties in `ApolloContext.ts`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7371](https://github.com/apollographql/apollo-client/pull/7371)\n\n## Apollo Client 3.2.7\n\n### Bug Fixes\n\n- Revert updating `symbol-observable` from version 2.x to version 3, which caused TypeScript errors with some `@types/node` versions, especially in Angular applications. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7340](https://github.com/apollographql/apollo-client/pull/7340)\n\n## Apollo Client 3.2.6\n\n### Bug Fixes\n\n- Always consider singleton IDs like `ROOT_QUERY` and `ROOT_MUTATION` to be root IDs during `cache.gc` garbage collection, regardless of whether they have been retained or released. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7333](https://github.com/apollographql/apollo-client/pull/7333)\n\n- Use optional chaining syntax (`this.currentObservable?.refetch`) in React `refetch` wrapper function to avoid crashing when an unmounted component is accidentally refetched. <br/>\n  [@tm1000](https://github.com/tm1000) in [#6314](https://github.com/apollographql/apollo-client/pull/6314) and\n  [@linmic](https://github.com/linmic) in [#7186](https://github.com/apollographql/apollo-client/pull/7186)\n\n### Improvements\n\n- Handle older `react-apollo` package in `codemods/ac2-to-ac3/imports.js` migration script. <br/>\n  [@tm1000](https://github.com/tm1000) in [#7216](https://github.com/apollographql/apollo-client/pull/7216)\n\n- Ensure `relayStylePagination` preserves `pageInfo.{start,end}Cursor` if `edges` is missing or empty. <br/>\n  [@beaucollins](https://github.com/beaucollins) in [#7224](https://github.com/apollographql/apollo-client/pull/7224)\n\n## Apollo Client 3.2.5\n\n### Improvements\n\n- Move `terser` dependency from `dependencies` to `devDependencies`. <br/>\n  [@SimenB](https://github.com/SimenB) in [#7188](https://github.com/apollographql/apollo-client/pull/7188)\n\n- Avoid all sub-package imports from the `graphql` npm package. <br/>\n  [@stoically](https://github.com/stoically) in [#7185](https://github.com/apollographql/apollo-client/pull/7185)\n\n## Apollo Client 3.2.4\n\n### Improvements\n\n- Update the `optimism` npm dependency to version 0.13.0 in order to use the new `optimistic.forget` method to fix a potential `cache.watch` memory leak. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7157](https://github.com/apollographql/apollo-client/pull/7157)\n\n- Consider `cache.reset` a destructive method, like `cache.evict` and `cache.modify`. <br/>\n  [@joshjg](https://github.com/joshjg) in [#7150](https://github.com/apollographql/apollo-client/pull/7150)\n\n- Avoid refetching observerless queries with `reFetchObservableQueries`. <br/>\n  [@joshjg](https://github.com/joshjg) in [#7146](https://github.com/apollographql/apollo-client/pull/7146)\n\n## Apollo Client 3.2.3\n\n### Improvements\n\n- Default `args.offset` to zero in `offsetLimitPagination`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7141](https://github.com/apollographql/apollo-client/pull/7141)\n\n## Apollo Client 3.2.2\n\n### Bug Fixes\n\n- Undo `TEdgeWrapper` approach for `relayStylePagination`, introduced by [f41e9efc](https://github.com/apollographql/apollo-client/commit/f41e9efc9e061b80fe5019456c049a3c56661e87) in [#7023](https://github.com/apollographql/apollo-client/pull/7023), since it was an unintended breaking change for existing code that used `cache.modify` to interact with field data managed by `relayStylePagination`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7103](https://github.com/apollographql/apollo-client/pull/7103)\n\n## Apollo Client 3.2.1\n\n### Bug Fixes\n\n- Fix `relayStylePagination` to handle the possibility that edges might be normalized `Reference` objects (uncommon). <br/>\n  [@anark](https://github.com/anark) and [@benjamn](https://github.com/benjamn) in [#7023](https://github.com/apollographql/apollo-client/pull/7023)\n\n- Disable \"Missing cache result fields\" warnings when `returnPartialData` is `true`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#7055](https://github.com/apollographql/apollo-client/pull/7055)\n\n### Improvements\n\n- Mark `subscriptions-transport-ws` `peerDependency` as optional. <br/>\n  [@MasterOdin](https://github.com/MasterOdin) in [#7047](https://github.com/apollographql/apollo-client/pull/7047)\n\n## Apollo Client 3.2.0\n\n### Bug Fixes\n\n- Use `options.nextFetchPolicy` internally to restore original `FetchPolicy` after polling with `fetchPolicy: \"network-only\"`, so that polling does not interfere with normal query watching. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)\n\n- Initialize `ObservableQuery` in `updateObservableQuery` even if `skip` is `true`. <br/>\n  [@mu29](https://github.com/mu29) in [#6999](https://github.com/apollographql/apollo-client/pull/6999)\n\n- Prevent full reobservation of queries affected by optimistic mutation updates, while still delivering results from the cache. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6854](https://github.com/apollographql/apollo-client/pull/6854)\n\n### Improvements\n\n- In TypeScript, all APIs that take `DocumentNode` parameters now may alternatively take `TypeDocumentNode<Data, Variables>`. This type has the same JavaScript representation but allows the APIs to infer the data and variable types instead of requiring you to specify types explicitly at the call site. <br/>\n  [@dotansimha](https://github.com/dotansimha) in [#6720](https://github.com/apollographql/apollo-client/pull/6720)\n\n- Bring back an improved form of heuristic fragment matching, by allowing `possibleTypes` to specify subtype regular expression strings, which count as matches if the written result object has all the fields expected for the fragment. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6901](https://github.com/apollographql/apollo-client/pull/6901)\n\n- Allow `options.nextFetchPolicy` to be a function that takes the current `FetchPolicy` and returns a new (or the same) `FetchPolicy`, making `nextFetchPolicy` more suitable for global use in `defaultOptions.watchQuery`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6893](https://github.com/apollographql/apollo-client/pull/6893)\n\n- Implement `useReactiveVar` hook for consuming reactive variables in React components. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6867](https://github.com/apollographql/apollo-client/pull/6867)\n\n- Move `apollo-link-persisted-queries` implementation to `@apollo/client/link/persisted-queries`. Try running our [automated imports transform](https://github.com/apollographql/apollo-client/tree/main/scripts/codemods/ac2-to-ac3) to handle this conversion, if you're using `apollo-link-persisted-queries`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6837](https://github.com/apollographql/apollo-client/pull/6837)\n\n- Disable feud-stopping logic after any `cache.evict` or `cache.modify` operation. <br/>\n  [@benjamn](https://github.com/benjamn) in\n  [#6817](https://github.com/apollographql/apollo-client/pull/6817) and\n  [#6898](https://github.com/apollographql/apollo-client/pull/6898)\n\n- Throw if `writeFragment` cannot identify `options.data` when no `options.id` provided. <br/>\n  [@jcreighton](https://github.com/jcreighton) in [#6859](https://github.com/apollographql/apollo-client/pull/6859)\n\n- Provide `options.storage` object to `cache.modify` functions, as provided to `read` and `merge` functions. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6991](https://github.com/apollographql/apollo-client/pull/6991)\n\n- Allow `cache.modify` functions to return `details.INVALIDATE` (similar to `details.DELETE`) to invalidate the current field, causing affected queries to rerun, even if the field's value is unchanged. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6991](https://github.com/apollographql/apollo-client/pull/6991)\n\n- Support non-default `ErrorPolicy` values (that is, `\"ignore\"` and `\"all\"`, in addition to the default value `\"none\"`) for mutations and subscriptions, like we do for queries. <br/>\n  [@benjamn](https://github.com/benjamn) in [#7003](https://github.com/apollographql/apollo-client/pull/7003)\n\n- Remove invariant forbidding a `FetchPolicy` of `cache-only` in `ObservableQuery#refetch`. <br/>\n  [@benjamn](https://github.com/benjamn) in [ccb0a79a](https://github.com/apollographql/apollo-client/pull/6774/commits/ccb0a79a588721f08bf87a131c31bf37fa3238e5), fixing [#6702](https://github.com/apollographql/apollo-client/issues/6702)\n\n## Apollo Client 3.1.5\n\n### Bug Fixes\n\n- Make `ApolloQueryResult.data` field non-optional again. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6997](https://github.com/apollographql/apollo-client/pull/6997)\n\n### Improvements\n\n- Allow querying `Connection` metadata without `args` in `relayStylePagination`. <br/>\n  [@anark](https://github.com/anark) in [#6935](https://github.com/apollographql/apollo-client/pull/6935)\n\n## Apollo Client 3.1.4\n\n### Bug Fixes\n\n- Restrict root object identification to `ROOT_QUERY` (the ID corresponding to the root `Query` object), allowing `Mutation` and `Subscription` as user-defined types. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6914](https://github.com/apollographql/apollo-client/pull/6914)\n\n- Prevent crash when `pageInfo` and empty `edges` are received by `relayStylePagination`. <br/>\n  [@fracmak](https://github.com/fracmak) in [#6918](https://github.com/apollographql/apollo-client/pull/6918)\n\n## Apollo Client 3.1.3\n\n### Bug Fixes\n\n- Consider only `result.data` (rather than all properties of `result`) when settling cache feuds. <br/>\n  [@danReynolds](https://github.com/danReynolds) in [#6777](https://github.com/apollographql/apollo-client/pull/6777)\n\n### Improvements\n\n- Provide [jscodeshift](https://www.npmjs.com/package/jscodeshift) transform for automatically converting Apollo Client 2.x `import` declarations to use Apollo Client 3.x packages. [Instructions](https://github.com/apollographql/apollo-client/tree/main/scripts/codemods/ac2-to-ac3). <br/>\n  [@dminkovsky](https://github.com/dminkovsky) and [@jcreighton](https://github.com/jcreighton) in [#6486](https://github.com/apollographql/apollo-client/pull/6486)\n\n## Apollo Client 3.1.2\n\n### Bug Fixes\n\n- Avoid making network requests when `skip` is `true`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6752](https://github.com/apollographql/apollo-client/pull/6752)\n\n### Improvements\n\n- Allow `SchemaLink.Options.context` function to be `async` (or return a `Promise`). <br/>\n  [@benjamn](https://github.com/benjamn) in [#6735](https://github.com/apollographql/apollo-client/pull/6735)\n\n## Apollo Client 3.1.1\n\n### Bug Fixes\n\n- Re-export cache types from `@apollo/client/core` (and thus also `@apollo/client`), again. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6725](https://github.com/apollographql/apollo-client/pull/6725)\n\n## Apollo Client 3.1.0\n\n### Bug Fixes\n\n- Rework interdependencies between `@apollo/client/*` entry points, so that CommonJS and ESM modules are supported equally well, without any duplication of shared code. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6656](https://github.com/apollographql/apollo-client/pull/6656) and\n  [#6657](https://github.com/apollographql/apollo-client/pull/6657)\n\n- Tolerate `!==` callback functions (like `onCompleted` and `onError`) in `useQuery` options, since those functions are almost always freshly evaluated each time `useQuery` is called. <br/>\n  [@hwillson](https://github.com/hwillson) and [@benjamn](https://github.com/benjamn) in [#6588](https://github.com/apollographql/apollo-client/pull/6588)\n\n- Respect `context.queryDeduplication` if provided, and otherwise fall back to `client.deduplication` (as before). <br/>\n  [@igaloly](https://github.com/igaloly) in [#6261](https://github.com/apollographql/apollo-client/pull/6261) and\n  [@Kujawadl](https://github.com/Kujawadl) in [#6526](https://github.com/apollographql/apollo-client/pull/6526)\n\n- Refactor `ObservableQuery#getCurrentResult` to reenable immediate delivery of warm cache results. As part of this refactoring, the `ApolloCurrentQueryResult` type was eliminated in favor of `ApolloQueryResult`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6710](https://github.com/apollographql/apollo-client/pull/6710)\n\n- Avoid clobbering `defaultOptions` with `undefined` values. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6715](https://github.com/apollographql/apollo-client/pull/6715)\n\n### Improvements\n\n- Apollo Client will no longer modify `options.fetchPolicy` unless you pass `options.nextFetchPolicy` to request an explicit change in `FetchPolicy` after the current request. Although this is technically a breaking change, `options.nextFieldPolicy` makes it easy to restore the old behavior (by passing `cache-first`). <br/>\n  [@benjamn](https://github.com/benjamn) in [#6712](https://github.com/apollographql/apollo-client/pull/6712), reverting [#6353](https://github.com/apollographql/apollo-client/pull/6353)\n\n- Errors of the form `Invariant Violation: 42` thrown in production can now be looked up much more easily, by consulting the auto-generated `@apollo/client/invariantErrorCodes.js` file specific to your `@apollo/client` version. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6665](https://github.com/apollographql/apollo-client/pull/6665)\n\n- Make the `client` field of the `MutationResult` type non-optional, since it is always provided. <br/>\n  [@glasser](https://github.com/glasser) in [#6617](https://github.com/apollographql/apollo-client/pull/6617)\n\n- Allow passing an asynchronous `options.renderFunction` to `getMarkupFromTree`. <br/>\n  [@richardscarrott](https://github.com/richardscarrott) in [#6576](https://github.com/apollographql/apollo-client/pull/6576)\n\n- Ergonomic improvements for `merge` and `keyArgs` functions in cache field policies. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6714](https://github.com/apollographql/apollo-client/pull/6714)\n\n## Apollo Client 3.0.2\n\n### Bug Fixes\n\n- Avoid duplicating `graphql/execution/execute` dependency in CommonJS bundle for `@apollo/client/link/schema`, fixing `instanceof` errors reported in [#6621](https://github.com/apollographql/apollo-client/issues/6621) and [#6614](https://github.com/apollographql/apollo-client/issues/6614). <br/>\n  [@benjamn](https://github.com/benjamn) in [#6624](https://github.com/apollographql/apollo-client/pull/6624)\n\n## Apollo Client 3.0.1\n\n### Bug Fixes\n\n- Make sure `useQuery` `onCompleted` is not fired when `skip` is `true`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6589](https://github.com/apollographql/apollo-client/pull/6589)\n\n- Revert changes to `peerDependencies` in `package.json` ([#6594](https://github.com/apollographql/apollo-client/pull/6594)), which would have allowed using incompatible future versions of `graphql` and/or `react` due to overly-permissive `>=` version constraints. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6605](https://github.com/apollographql/apollo-client/pull/6605)\n\n# Apollo Client 3.0.0\n\n## Improvements\n\n> ⚠️ **Note:** As of 3.0.0, Apollo Client uses a new package name: [`@apollo/client`](https://www.npmjs.com/package/@apollo/client)\n\n### `ApolloClient`\n\n- **[BREAKING]** `ApolloClient` is now only available as a named export. The default `ApolloClient` export has been removed. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5425](https://github.com/apollographql/apollo-client/pull/5425)\n\n- **[BREAKING]** The `queryManager` property of `ApolloClient` instances is now marked as `private`, paving the way for a more aggressive redesign of its API.\n\n- **[BREAKING]** Apollo Client will no longer deliver \"stale\" results to `ObservableQuery` consumers, but will instead log more helpful errors about which cache fields were missing. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6058](https://github.com/apollographql/apollo-client/pull/6058)\n\n- **[BREAKING]** `ApolloError`'s thrown by Apollo Client no longer prefix error messages with `GraphQL error:` or `Network error:`. To differentiate between GraphQL/network errors, refer to `ApolloError`'s public `graphQLErrors` and `networkError` properties. <br/>\n  [@lorensr](https://github.com/lorensr) in [#3892](https://github.com/apollographql/apollo-client/pull/3892)\n\n- **[BREAKING]** Support for the `@live` directive has been removed, but might be restored in the future if a more thorough implementation is proposed. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6221](https://github.com/apollographql/apollo-client/pull/6221)\n\n- **[BREAKING]** Apollo Client 2.x allowed `@client` fields to be passed into the `link` chain if `resolvers` were not set in the constructor. This allowed `@client` fields to be passed into Links like `apollo-link-state`. Apollo Client 3 enforces that `@client` fields are local only, meaning they are no longer passed into the `link` chain, under any circumstances. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5982](https://github.com/apollographql/apollo-client/pull/5982)\n\n- **[BREAKING?]** Refactor `QueryManager` to make better use of observables and enforce `fetchPolicy` more reliably. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6221](https://github.com/apollographql/apollo-client/pull/6221)\n\n- The `updateQuery` function previously required by `fetchMore` has been deprecated with a warning, and will be removed in the next major version of Apollo Client. Please consider using a `merge` function to handle incoming data instead of relying on `updateQuery`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6464](https://github.com/apollographql/apollo-client/pull/6464)\n\n  - Helper functions for generating common pagination-related field policies may be imported from `@apollo/client/utilities`. The most basic helper is `concatPagination`, which emulates the concatenation behavior of typical `updateQuery` functions. A more sophisticated helper is `offsetLimitPagination`, which implements offset/limit-based pagination. If you are consuming paginated data from a Relay-friendly API, use `relayStylePagination`. Feel free to use [these helper functions](https://github.com/apollographql/apollo-client/blob/main/src/utilities/policies/pagination.ts) as inspiration for your own field policies, and/or modify them to suit your needs. <br/>\n    [@benjamn](https://github.com/benjamn) in [#6465](https://github.com/apollographql/apollo-client/pull/6465)\n\n- Updated to work with `graphql@15`. <br/>\n  [@durchanek](https://github.com/durchanek) in [#6194](https://github.com/apollographql/apollo-client/pull/6194) and [#6279](https://github.com/apollographql/apollo-client/pull/6279) <br/>\n  [@hagmic](https://github.com/hagmic) in [#6328](https://github.com/apollographql/apollo-client/pull/6328)\n\n- Apollo Link core and HTTP related functionality has been merged into `@apollo/client`. Functionality that was previously available through the `apollo-link`, `apollo-link-http-common` and `apollo-link-http` packages is now directly available from `@apollo/client` (e.g. `import { HttpLink } from '@apollo/client'`). The `ApolloClient` constructor has also been updated to accept new `uri`, `headers` and `credentials` options. If `uri` is specified, Apollo Client will take care of creating the necessary `HttpLink` behind the scenes. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5412](https://github.com/apollographql/apollo-client/pull/5412)\n\n- The `gql` template tag should now be imported from the `@apollo/client` package, rather than the `graphql-tag` package. Although the `graphql-tag` package still works for now, future versions of `@apollo/client` may change the implementation details of `gql` without a major version bump. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5451](https://github.com/apollographql/apollo-client/pull/5451)\n\n- `@apollo/client/core` can be used to import the Apollo Client core, which includes everything the main `@apollo/client` package does, except for all React related functionality. <br/>\n  [@kamilkisiela](https://github.com/kamilkisiela) in [#5541](https://github.com/apollographql/apollo-client/pull/5541)\n\n- Several deprecated methods have been fully removed:\n\n  - `ApolloClient#initQueryManager`\n  - `QueryManager#startQuery`\n  - `ObservableQuery#currentResult`\n\n- Apollo Client now supports setting a new `ApolloLink` (or link chain) after `new ApolloClient()` has been called, using the `ApolloClient#setLink` method. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6193](https://github.com/apollographql/apollo-client/pull/6193)\n\n- The final time a mutation `update` function is called, it can no longer accidentally read optimistic data from other concurrent mutations, which ensures the use of optimistic updates has no lasting impact on the state of the cache after mutations have finished. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6551](https://github.com/apollographql/apollo-client/pull/6551)\n\n- Apollo links that were previously maintained in https://github.com/apollographql/apollo-link have been merged into the Apollo Client project. They should be accessed using the new entry points listed in the [migration guide](./docs/source/migrating/apollo-client-3-migration.md). <br/>\n  [@hwillson](https://github.com/hwillson) in [#](TODO)\n\n### `InMemoryCache`\n\n> ⚠️ **Note:** `InMemoryCache` has been significantly redesigned and rewritten in Apollo Client 3.0. Please consult the [migration guide](https://www.apollographql.com/docs/react/v3.0-beta/migrating/apollo-client-3-migration/#cache-improvements) and read the new [documentation](https://www.apollographql.com/docs/react/v3.0-beta/caching/cache-configuration/) to understand everything that has been improved.\n\n- The `InMemoryCache` constructor should now be imported directly from `@apollo/client`, rather than from a separate package. The `apollo-cache-inmemory` package is no longer supported.\n\n  > The `@apollo/client/cache` entry point can be used to import `InMemoryCache` without importing other parts of the Apollo Client codebase. <br/> > [@hwillson](https://github.com/hwillson) in [#5577](https://github.com/apollographql/apollo-client/pull/5577)\n\n- **[BREAKING]** `FragmentMatcher`, `HeuristicFragmentMatcher`, and `IntrospectionFragmentMatcher` have all been removed. We now recommend using `InMemoryCache`’s `possibleTypes` option instead. For more information see the [Defining `possibleTypes` manually](https://www.apollographql.com/docs/react/v3.0-beta/data/fragments/#defining-possibletypes-manually) section of the docs. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5073](https://github.com/apollographql/apollo-client/pull/5073)\n\n- **[BREAKING]** As promised in the [Apollo Client 2.6 blog post](https://blog.apollographql.com/whats-new-in-apollo-client-2-6-b3acf28ecad1), all cache results are now frozen/immutable. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5153](https://github.com/apollographql/apollo-client/pull/5153)\n\n- **[BREAKING]** Eliminate \"generated\" cache IDs to avoid normalizing objects with no meaningful ID, significantly reducing cache memory usage. This might be a backwards-incompatible change if your code depends on the precise internal representation of normalized data in the cache. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5146](https://github.com/apollographql/apollo-client/pull/5146)\n\n- **[BREAKING]** `InMemoryCache` will no longer merge the fields of written objects unless the objects are known to have the same identity, and the values of fields with the same name will not be recursively merged unless a custom `merge` function is defined by a field policy for that field, within a type policy associated with the `__typename` of the parent object. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5603](https://github.com/apollographql/apollo-client/pull/5603)\n\n- **[BREAKING]** `InMemoryCache` now _throws_ when data with missing or undefined query fields is written into the cache, rather than just warning in development. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6055](https://github.com/apollographql/apollo-client/pull/6055)\n\n- **[BREAKING]** `client|cache.writeData` have been fully removed. `writeData` usage is one of the easiest ways to turn faulty assumptions about how the cache represents data internally, into cache inconsistency and corruption. `client|cache.writeQuery`, `client|cache.writeFragment`, and/or `cache.modify` can be used to update the cache. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5923](https://github.com/apollographql/apollo-client/pull/5923)\n\n- `InMemoryCache` now supports tracing garbage collection and eviction. Note that the signature of the `evict` method has been simplified in a potentially backwards-incompatible way. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5310](https://github.com/apollographql/apollo-client/pull/5310)\n\n  - **[beta-BREAKING]** Please note that the `cache.evict` method now requires `Cache.EvictOptions`, though it previously supported positional arguments as well. <br/>\n    [@danReynolds](https://github.com/danReynolds) in [#6141](https://github.com/apollographql/apollo-client/pull/6141)\n    [@benjamn](https://github.com/benjamn) in [#6364](https://github.com/apollographql/apollo-client/pull/6364)\n\n  - Removing an entity object using the `cache.evict` method does not automatically remove dangling references to that entity elsewhere in the cache, but dangling references will be automatically filtered from lists whenever those lists are read from the cache. You can define a custom field `read` function to customize this behavior. See [#6412](https://github.com/apollographql/apollo-client/pull/6412), [#6425](https://github.com/apollographql/apollo-client/pull/6425), and [#6454](https://github.com/apollographql/apollo-client/pull/6454) for further explanation.\n\n- Cache methods that would normally trigger a broadcast, like `cache.evict`, `cache.writeQuery`, and `cache.writeFragment`, can now be called with a named options object, which supports a `broadcast: boolean` property that can be used to silence the broadcast, for situations where you want to update the cache multiple times without triggering a broadcast each time. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6288](https://github.com/apollographql/apollo-client/pull/6288)\n\n- `InMemoryCache` now `console.warn`s in development whenever non-normalized data is dangerously overwritten, with helpful links to documentation about normalization and custom `merge` functions. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6372](https://github.com/apollographql/apollo-client/pull/6372)\n\n- The result caching system (introduced in [#3394](https://github.com/apollographql/apollo-client/pull/3394)) now tracks dependencies at the field level, rather than at the level of whole entity objects, allowing the cache to return identical (`===`) results much more often than before. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5617](https://github.com/apollographql/apollo-client/pull/5617)\n\n- `InMemoryCache` now has a method called `modify` which can be used to update the value of a specific field within a specific entity object:\n\n  ```ts\n  cache.modify({\n    id: cache.identify(post),\n    fields: {\n      comments(comments: Reference[], { readField }) {\n        return comments.filter(\n          (comment) => idToRemove !== readField(\"id\", comment)\n        );\n      },\n    },\n  });\n  ```\n\n  This API gracefully handles cases where multiple field values are associated with a single field name, and also removes the need for updating the cache by reading a query or fragment, modifying the result, and writing the modified result back into the cache. Behind the scenes, the `cache.evict` method is now implemented in terms of `cache.modify`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5909](https://github.com/apollographql/apollo-client/pull/5909)\n  and [#6178](https://github.com/apollographql/apollo-client/pull/6178)\n\n- `InMemoryCache` provides a new API for storing client state that can be updated from anywhere:\n\n  ```ts\n  import { makeVar } from \"@apollo/client\";\n  const v = makeVar(123);\n  console.log(v()); // 123\n  console.log(v(v() + 1)); // 124\n  console.log(v()); // 124\n  v(\"asdf\"); // TS type error\n  ```\n\n  These variables are _reactive_ in the sense that updating their values invalidates any previously cached query results that depended on the old values. <br/>\n  [@benjamn](https://github.com/benjamn) in\n  [#5799](https://github.com/apollographql/apollo-client/pull/5799),\n  [#5976](https://github.com/apollographql/apollo-client/pull/5976), and\n  [#6512](https://github.com/apollographql/apollo-client/pull/6512)\n\n- Various cache read and write performance optimizations, cutting read and write times by more than 50% in larger benchmarks. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5948](https://github.com/apollographql/apollo-client/pull/5948)\n\n- The `cache.readQuery` and `cache.writeQuery` methods now accept an `options.id` string, which eliminates most use cases for `cache.readFragment` and `cache.writeFragment`, and skips the implicit conversion of fragment documents to query documents performed by `cache.{read,write}Fragment`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5930](https://github.com/apollographql/apollo-client/pull/5930)\n\n- Support `cache.identify(entity)` for easily computing entity ID strings. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5642](https://github.com/apollographql/apollo-client/pull/5642)\n\n- Support eviction of specific entity fields using `cache.evict(id, fieldName)`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5643](https://github.com/apollographql/apollo-client/pull/5643)\n\n- Make `InMemoryCache#evict` remove data from all `EntityStore` layers. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5773](https://github.com/apollographql/apollo-client/pull/5773)\n\n- Stop paying attention to `previousResult` in `InMemoryCache`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5644](https://github.com/apollographql/apollo-client/pull/5644)\n\n- Improve optimistic update performance by limiting cache key diversity. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5648](https://github.com/apollographql/apollo-client/pull/5648)\n\n- Custom field `read` functions can read from neighboring fields using the `readField(fieldName)` helper, and may also read fields from other entities by calling `readField(fieldName, objectOrReference)`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5651](https://github.com/apollographql/apollo-client/pull/5651)\n\n- Expose cache `modify` and `identify` to the mutate `update` function. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5956](https://github.com/apollographql/apollo-client/pull/5956)\n\n- Add a default `gc` implementation to `ApolloCache`. <br/>\n  [@justinwaite](https://github.com/justinwaite) in [#5974](https://github.com/apollographql/apollo-client/pull/5974)\n\n### React\n\n- **[BREAKING]** The `QueryOptions`, `MutationOptions`, and `SubscriptionOptions` React Apollo interfaces have been renamed to `QueryDataOptions`, `MutationDataOptions`, and `SubscriptionDataOptions` (to avoid conflicting with similarly named and exported Apollo Client interfaces).\n\n- **[BREAKING]** Results with `loading: true` will no longer redeliver previous data, though they may provide partial data from the cache, when available. <br/>\n  [@benjamn](https://github.com/benjamn) in [#6566](https://github.com/apollographql/apollo-client/pull/6566)\n\n- **[BREAKING?]** Remove `fixPolyfills.ts`, except when bundling for React Native. If you have trouble with `Map` or `Set` operations due to frozen key objects in React Native, either update React Native to version 0.59.0 (or 0.61.x, if possible) or investigate why `fixPolyfills.native.js` is not included in your bundle. <br/>\n  [@benjamn](https://github.com/benjamn) in [#5962](https://github.com/apollographql/apollo-client/pull/5962)\n\n- The contents of the `@apollo/react-hooks` package have been merged into `@apollo/client`, enabling the following all-in-one `import`:\n\n  ```ts\n  import { ApolloClient, ApolloProvider, useQuery } from \"@apollo/client\";\n  ```\n\n  [@hwillson](https://github.com/hwillson) in [#5357](https://github.com/apollographql/apollo-client/pull/5357)\n\n- React SSR features (previously accessed via `@apollo/react-ssr`) can now be accessed from the separate Apollo Client entry point of `@apollo/client/react/ssr`. These features are not included in the default `@apollo/client` bundle. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6499](https://github.com/apollographql/apollo-client/pull/6499)\n\n### General\n\n- **[BREAKING]** Removed `graphql-anywhere` since it's no longer used by Apollo Client. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5159](https://github.com/apollographql/apollo-client/pull/5159)\n\n- **[BREAKING]** Removed `apollo-boost` since Apollo Client 3.0 provides a boost like getting started experience out of the box. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5217](https://github.com/apollographql/apollo-client/pull/5217)\n\n- **[BREAKING]** We are no longer exporting certain (intended to be) internal utilities. If you are depending on some of the lesser known exports from `apollo-cache`, `apollo-cache-inmemory`, or `apollo-utilities`, they may no longer be available from `@apollo/client`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5437](https://github.com/apollographql/apollo-client/pull/5437) and [#5514](https://github.com/apollographql/apollo-client/pull/5514)\n\n  > Utilities that were previously externally available through the `apollo-utilities` package are now only available by importing from `@apollo/client/utilities`. <br/> > [@hwillson](https://github.com/hwillson) in [#5683](https://github.com/apollographql/apollo-client/pull/5683)\n\n- Make sure all `graphql-tag` public exports are re-exported. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5861](https://github.com/apollographql/apollo-client/pull/5861)\n\n- Fully removed `prettier`. The Apollo Client team has decided to no longer automatically enforce code formatting across the codebase. In most cases existing code styles should be followed as much as possible, but this is not a hard and fast rule. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5227](https://github.com/apollographql/apollo-client/pull/5227)\n\n- Make sure `ApolloContext` plays nicely with IE11 when storing the shared context. <br/>\n  [@ms](https://github.com/ms) in [#5840](https://github.com/apollographql/apollo-client/pull/5840)\n\n- Migrated React Apollo HOC and Components functionality into Apollo Client, making it accessible from `@apollo/client/react/components` and `@apollo/client/react/hoc` entry points. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6558](https://github.com/apollographql/apollo-client/pull/6558)\n\n- Support passing a `context` object through the link execution chain when using subscriptions. <br/>\n  [@sgtpepper43](https://github.com/sgtpepper43) in [#4925](https://github.com/apollographql/apollo-client/pull/4925)\n\n- `MockSubscriptionLink` now supports multiple subscriptions. <br/>\n  [@dfrankland](https://github.com/dfrankland) in [#6081](https://github.com/apollographql/apollo-client/pull/6081)\n\n### Bug Fixes\n\n- `useMutation` adjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying the `useState` based mutation result directly. <br/>\n  [@hwillson](https://github/com/hwillson) in [#5770](https://github.com/apollographql/apollo-client/pull/5770)\n\n- Missing `__typename` fields no longer cause the `InMemoryCache#diff` result to be marked `complete: false`, if those fields were added by `InMemoryCache#transformDocument` (which calls `addTypenameToDocument`). <br/>\n  [@benjamn](https://github.com/benjamn) in [#5787](https://github.com/apollographql/apollo-client/pull/5787)\n\n- Fixed an issue that allowed `@client @export` based queries to lead to extra unnecessary network requests being fired. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5946](https://github.com/apollographql/apollo-client/pull/5946)\n\n- Refined `useLazyQuery` types to help prevent runtime errors. <br/>\n  [@benmosher](https://github.com/benmosher) in [#5935](https://github.com/apollographql/apollo-client/pull/5935)\n\n- Make sure `@client @export` variables used in watched queries are updated each time the query receives new data that changes the value of the `@export` variable. <br/>\n  [@hwillson](https://github.com/hwillson) in [#5986](https://github.com/apollographql/apollo-client/pull/5986)\n\n- Ensure `useMutation` passes a defined `errorPolicy` option into its underlying `ApolloClient.mutate()` call. <br/>\n  [@jamesreggio](https://github.com/jamesreggio) in [#5863](https://github.com/apollographql/apollo-client/pull/5863)\n\n- `useQuery`: Prevent new data re-render attempts during an existing render. This helps avoid React 16.13.0's \"Cannot update a component from inside the function body of a different component\" warning (https://github.com/facebook/react/pull/17099). <br/>\n  [@hwillson](https://github.com/hwillson) in [#6107](https://github.com/apollographql/apollo-client/pull/6107)\n\n- Expand `ApolloError` typings to include `ServerError` and `ServerParseError`. <br/>\n  [@dmarkow](https://github.com/dmarkow) in [#6319](https://github.com/apollographql/apollo-client/pull/6319)\n\n- Fast responses received over the link chain will no longer conflict with `skip` settings. <br/>\n  [@hwillson](https://github.com/hwillson) in [#6587](https://github.com/apollographql/apollo-client/pull/6587)\n\n## Apollo Client 2.6.8\n\n### Apollo Client (2.6.8)\n\n- Update the `fetchMore` type signature to accept `context`. <br/>\n  [@koenpunt](https://github.com/koenpunt) in [#5147](https://github.com/apollographql/apollo-client/pull/5147)\n\n- Fix type for `Resolver` and use it in the definition of `Resolvers`. <br />\n  [@peoplenarthax](https://github.com/peoplenarthax) in [#4943](https://github.com/apollographql/apollo-client/pull/4943)\n\n- Local state resolver functions now receive a `fragmentMap: FragmentMap`\n  object, in addition to the `field: FieldNode` object, via the `info`\n  parameter. <br/>\n  [@mjlyons](https://github.com/mjlyons) in [#5388](https://github.com/apollographql/apollo-client/pull/5388)\n\n- Documentation updates. <br/>\n  [@tomquirk](https://github.com/tomquirk) in [#5645](https://github.com/apollographql/apollo-client/pull/5645) <br/>\n  [@Sequoia](https://github.com/Sequoia) in [#5641](https://github.com/apollographql/apollo-client/pull/5641) <br/>\n  [@phryneas](https://github.com/phryneas) in [#5628](https://github.com/apollographql/apollo-client/pull/5628) <br/>\n  [@AryanJ-NYC](https://github.com/AryanJ-NYC) in [#5560](https://github.com/apollographql/apollo-client/pull/5560)\n\n### GraphQL Anywhere (4.2.6)\n\n- Fix `filter` edge case involving `null`. <br/>\n  [@lifeiscontent](https://github.com/lifeiscontent) in [#5110](https://github.com/apollographql/apollo-client/pull/5110)\n\n### Apollo Boost (0.4.7)\n\n- Replace `GlobalFetch` reference with `WindowOrWorkerGlobalScope`. <br/>\n  [@abdonrd](https://github.com/abdonrd) in [#5373](https://github.com/apollographql/apollo-client/pull/5373)\n\n- Add `assumeImmutableResults` typing to apollo boost `PresetConfig` interface. <br/>\n  [@bencoullie](https://github.com/bencoullie) in [#5571](https://github.com/apollographql/apollo-client/pull/5571)\n\n## Apollo Client (2.6.4)\n\n### Apollo Client (2.6.4)\n\n- Modify `ObservableQuery` to allow queries with `notifyOnNetworkStatusChange`\n  to be notified when loading after an error occurs. <br />\n  [@jasonpaulos](https://github.com/jasonpaulos) in [#4992](https://github.com/apollographql/apollo-client/pull/4992)\n\n- Add `graphql` as a `peerDependency` of `apollo-cache` and\n  `graphql-anywhere`. <br/>\n  [@ssalbdivad](https://github.com/ssalbdivad) in [#5081](https://github.com/apollographql/apollo-client/pull/5081)\n\n- Documentation updates. </br>\n  [@raibima](https://github.com/raibima) in [#5132](https://github.com/apollographql/apollo-client/pull/5132) <br/>\n  [@hwillson](https://github.com/hwillson) in [#5141](https://github.com/apollographql/apollo-client/pull/5141)\n\n## Apollo Client (2.6.3)\n\n### Apollo Client (2.6.3)\n\n- A new `ObservableQuery.resetQueryStoreErrors()` method is now available that\n  can be used to clear out `ObservableQuery` query store errors. <br/>\n  [@hwillson](https://github.com/hwillson) in [#4941](https://github.com/apollographql/apollo-client/pull/4941)\n- Documentation updates. <br/>\n  [@michael-watson](https://github.com/michael-watson) in [#4940](https://github.com/apollographql/apollo-client/pull/4940) <br/>\n  [@hwillson](https://github.com/hwillson) in [#4969](https://github.com/apollographql/apollo-client/pull/4969)\n\n## Apollo Client (2.6.1)\n\n### Apollo Utilities 1.3.2\n\n- Reimplement `isEqual` without pulling in massive `lodash.isequal`. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4924](https://github.com/apollographql/apollo-client/pull/4924)\n\n## Apollo Client (2.6.1)\n\n- In all Apollo Client packages, the compilation of `lib/bundle.esm.js` to `lib/bundle.cjs.js` and `lib/bundle.umd.js` now uses Babel instead of Rollup, since Babel correctly compiles some [edge cases](https://github.com/apollographql/apollo-client/issues/4843#issuecomment-495717720) that neither Rollup nor TypeScript compile correctly. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4911](https://github.com/apollographql/apollo-client/pull/4911)\n\n### Apollo Cache In-Memory 1.6.1\n\n- Pretend that `__typename` exists on the root Query when matching fragments. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4853](https://github.com/apollographql/apollo-client/pull/4853)\n\n### Apollo Utilities 1.3.1\n\n- The `isEqual` function has been reimplemented using the `lodash.isequal` npm package, to better support circular references. Since the `lodash.isequal` package is already used by `react-apollo`, this change is likely to decrease total bundle size. <br/>\n  [@capaj](https://github.com/capaj) in [#4915](https://github.com/apollographql/apollo-client/pull/4915)\n\n## Apollo Client (2.6.0)\n\n- In production, `invariant(condition, message)` failures will now include\n  a unique error code that can be used to trace the error back to the\n  point of failure. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4521](https://github.com/apollographql/apollo-client/pull/4521)\n\n### Apollo Client 2.6.0\n\n- If you can be sure your application code does not modify cache result objects (see `freezeResults` note below), you can unlock substantial performance improvements by communicating this assumption via\n\n  ```ts\n  new ApolloClient({ assumeImmutableResults: true });\n  ```\n\n  which allows the client to avoid taking defensive snapshots of past results using `cloneDeep`, as explained by [@benjamn](https://github.com/benjamn) in [#4543](https://github.com/apollographql/apollo-client/pull/4543).\n\n- Identical overlapping queries are now deduplicated internally by `apollo-client`, rather than using the `apollo-link-dedup` package. <br/>\n  [@benjamn](https://github.com/benjamn) in commit [7cd8479f](https://github.com/apollographql/apollo-client/pull/4586/commits/7cd8479f27ce38930f122e4f703c4081a75a63a7)\n\n- The `FetchPolicy` type has been split into two types, so that passing `cache-and-network` to `ApolloClient#query` is now forbidden at the type level, whereas previously it was forbidden by a runtime `invariant` assertion:\n\n  ```ts\n  export type FetchPolicy =\n    | \"cache-first\"\n    | \"network-only\"\n    | \"cache-only\"\n    | \"no-cache\"\n    | \"standby\";\n\n  export type WatchQueryFetchPolicy = FetchPolicy | \"cache-and-network\";\n  ```\n\n  The exception thrown if you ignore the type error has also been improved to explain the motivation behind this restriction. <br/>\n  [Issue #3130 (comment)](https://github.com/apollographql/apollo-client/issues/3130#issuecomment-478409066) and commit [cf069bc7](github.com/apollographql/apollo-client/commit/cf069bc7ee6577092234b0eb0ac32e05d50f5a1c)\n\n- Avoid updating (and later invalidating) cache watches when `fetchPolicy` is `'no-cache'`. <br/>\n  [@bradleyayers](https://github.com/bradleyayers) in [PR #4573](https://github.com/apollographql/apollo-client/pull/4573), part of [issue #3452](https://github.com/apollographql/apollo-client/issues/3452)\n\n- Remove temporary `queryId` after `fetchMore` completes. <br/>\n  [@doomsower](https://github.com/doomsower) in [#4440](https://github.com/apollographql/apollo-client/pull/4440)\n\n- Call `clearStore` callbacks after clearing store. <br/>\n  [@ds8k](https://github.com/ds8k) in [#4695](https://github.com/apollographql/apollo-client/pull/4695)\n\n- Perform all `DocumentNode` transforms once, and cache the results. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4601](https://github.com/apollographql/apollo-client/pull/4601)\n\n- Accommodate `@client @export` variable changes in `ObservableQuery`. <br/>\n  [@hwillson](https://github.com/hwillson) in [#4604](https://github.com/apollographql/apollo-client/pull/4604)\n\n- Support the `returnPartialData` option for watched queries again. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4743](https://github.com/apollographql/apollo-client/pull/4743)\n\n- Preserve `networkStatus` for incomplete `cache-and-network` queries. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4765](https://github.com/apollographql/apollo-client/pull/4765)\n\n- Preserve `cache-and-network` `fetchPolicy` when refetching. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4840](https://github.com/apollographql/apollo-client/pull/4840)\n\n- Update the React Native docs to remove the request for external example apps that we can link to. We're no longer going to manage a list of external example apps. <br />\n  [@hwillson](https://github.com/hwillson) in [#4531](https://github.com/apollographql/apollo-client/pull/4531)\n\n- Polling queries are no longer batched together, so their scheduling should be more predictable. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4800](https://github.com/apollographql/apollo-client/pull/4800)\n\n### Apollo Cache In-Memory 1.6.0\n\n- Support `new InMemoryCache({ freezeResults: true })` to help enforce immutability. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4514](https://github.com/apollographql/apollo-client/pull/4514)\n\n- Allow `IntrospectionFragmentMatcher` to match fragments against the root `Query`, as `HeuristicFragmentMatcher` does. <br/>\n  [@rynobax](https://github.com/rynobax) in [#4620](https://github.com/apollographql/apollo-client/pull/4620)\n\n- Rerential identity (`===`) of arrays in cache results will now be preserved for unchanged data. <br/>\n  [@benjamn](https://github.com/benjamn) in commit [f3091d6a](https://github.com/apollographql/apollo-client/pull/4586/commits/f3091d6a7e91be98549baea58903282cc540f460)\n\n- Avoid adding `__typename` field to `@client` selection sets that have been `@export`ed as input variables. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4784](https://github.com/apollographql/apollo-client/pull/4784)\n\n### GraphQL Anywhere 4.2.2\n\n- The `graphql` function can now be configured to ignore `@include` and\n  `@skip` directives (useful when walking a fragment to generate prop types\n  or filter result data). <br/>\n  [@GreenGremlin](https://github.com/GreenGremlin) in [#4373](https://github.com/apollographql/apollo-client/pull/4373)\n\n## Apollo Client 2.5.1\n\n### apollo-client 2.5.1\n\n- Fixes `A tuple type element list cannot be empty` issue. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4502](https://github.com/apollographql/apollo-client/pull/4502)\n\n### graphql-anywhere 4.2.1\n\n- Adds back the missing `graphql-anywhere/lib/async` entry point. <br/>\n  [@benjamn](https://github.com/benjamn) in [#4503](https://github.com/apollographql/apollo-client/pull/4503)\n\n## Apollo Client (2.5.0)\n\n### Apollo Client (2.5.0)\n\n- Introduces new local state management features (client-side schema\n  and local resolver / `@client` support) and many overall code improvements,\n  to help reduce the Apollo Client bundle size. <br/>\n  [#4361](https://github.com/apollographql/apollo-client/pull/4361)\n- Revamped CJS and ESM bundling approach with Rollup. <br/>\n  [@rosskevin](https://github.com/rosskevin) in [#4261](https://github.com/apollographql/apollo-client/pull/4261)\n- Fixes an issue where the `QueryManager` was accidentally returning cached\n  data for `network-only` queries. <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#4352](https://github.com/apollographql/apollo-client/pull/4352)\n- Fixed an issue in the repo `.gitattributes` that was causing binary files\n  to have their line endings adjusted, and cleaned up corrupted documentation\n  images (ref: https://github.com/apollographql/apollo-client/pull/4232). <br/>\n  [@rajington](https://github.com/rajington) in [#4438](https://github.com/apollographql/apollo-client/pull/4438)\n- Improve (and shorten) query polling implementation. <br/>\n  [PR #4337](https://github.com/apollographql/apollo-client/pull/4337)\n\n## Apollo Client (2.4.13)\n\n### Apollo Client (2.4.13)\n\n- Resolve \"invalidate\" -> \"invalidated\" typo in `QueryManager`. <br/>\n  [@quazzie](https://github.com/quazzie) in [#4041](https://github.com/apollographql/apollo-client/pull/4041)\n\n- Properly type `setQuery` and fix now typed callers. <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#4369](https://github.com/apollographql/apollo-client/pull/4369)\n\n- Align with the React Apollo decision that result `data` should be\n  `TData | undefined` instead of `TData | {}`. <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#4356](https://github.com/apollographql/apollo-client/pull/4356)\n\n- Documentation updates. <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#4340](https://github.com/apollographql/apollo-client/pull/4340) <br />\n  [@justyn-clark](https://github.com/justyn-clark) in [#4383](https://github.com/apollographql/apollo-client/pull/4383) <br />\n  [@jtassin](https://github.com/jtassin) in [#4287](https://github.com/apollographql/apollo-client/pull/4287) <br />\n  [@Gongreg](https://github.com/Gongreg) in [#4386](https://github.com/apollographql/apollo-client/pull/4386) <br />\n  [@davecardwell](https://github.com/davecardwell) in [#4399](https://github.com/apollographql/apollo-client/pull/4399) <br />\n  [@michaelknoch](https://github.com/michaelknoch) in [#4384](https://github.com/apollographql/apollo-client/pull/4384) <br />\n\n## Apollo Client (2.4.12)\n\n### Apollo Client (2.4.12)\n\n- Support `ApolloClient#stop` method for safe client disposal. <br/>\n  [PR #4336](https://github.com/apollographql/apollo-client/pull/4336)\n\n## Apollo Client (2.4.11)\n\n- Added explicit dependencies on the\n  [`tslib`](https://www.npmjs.com/package/tslib) package to all client\n  packages to fix\n  [Issue #4332](https://github.com/apollographql/apollo-client/issues/4332).\n\n### Apollo Client (2.4.11)\n\n- Reverted some breaking changes accidentally released in a patch version\n  (2.4.10). [PR #4334](https://github.com/apollographql/apollo-client/pull/4334)\n\n## Apollo Client (2.4.10)\n\n### Apollo Client (2.4.10)\n\n- The `apollo-client` package no longer exports a `printAST` function from\n  `graphql/language/printer`. If you need this functionality, import it\n  directly: `import { print } from \"graphql/language/printer\"`\n\n- Query polling now uses a simpler scheduling strategy based on a single\n  `setTimeout` interval rather than multiple `setInterval` timers. The new\n  timer fires at the rate of the fastest polling interval, and queries\n  with longer polling intervals fire whenever the time elapsed since they\n  last fired exceeds their desired interval. <br/>\n  [PR #4243](https://github.com/apollographql/apollo-client/pull/4243)\n\n### Apollo Cache In-Memory (1.4.1)\n\n- The `optimism` npm package has been updated to a version (0.6.9) that\n  provides its own TypeScript declarations, which should fix problems like\n  [Issue #4327](https://github.com/apollographql/apollo-client/issues/4327). <br/>\n  [PR #4331](https://github.com/apollographql/apollo-client/pull/4331)\n\n- Error messages involving GraphQL queries now print the queries using\n  `JSON.stringify` instead of the `print` function exported by the\n  `graphql` package, to avoid pulling unnecessary printing logic into your\n  JavaScript bundle. <br/>\n  [PR #4234](https://github.com/apollographql/apollo-client/pull/4234)\n\n- The `QueryKeyMaker` abstraction has been removed, meaning that cache\n  results for non-identical queries (or sub-queries) with equivalent\n  structure will no longer be cached together. This feature was a nice\n  optimization in certain specific use cases, but it was not worth the\n  additional complexity or bundle size. <br/>\n  [PR #4245](https://github.com/apollographql/apollo-client/pull/4245)\n\n### Apollo Utilities (1.1.1)\n\n- The `flattenSelections` helper function is no longer exported from\n  `apollo-utilities`, since `getDirectiveNames` has been reimplemented\n  without using `flattenSelections`, and `flattenSelections` has no clear\n  purpose now. If you need the old functionality, use a visitor:\n\n  ```ts\n  import { visit } from \"graphql/language/visitor\";\n\n  function flattenSelections(selection: SelectionNode) {\n    const selections: SelectionNode[] = [];\n    visit(selection, {\n      SelectionSet(ss) {\n        selections.push(...ss.selections);\n      },\n    });\n    return selections;\n  }\n  ```\n\n## Apollo Client (2.4.9)\n\n### Apollo Client (2.4.9)\n\n- Apollo Client has been updated to use `graphql` 14.x as a dev dependency. <br/>\n  [@hwillson](https://github.com/hwillson) in [#4233](https://github.com/apollographql/apollo-client/pull/4233)\n\n- The `onClearStore` function can now be used to register callbacks that should\n  be triggered when calling `clearStore`. <br/>\n  [@joe-re](https://github.com/joe-re) in [#4082](https://github.com/apollographql/apollo-client/pull/4082)\n\n- Make `isApolloError` available for external use. <br/>\n  [@FredyC](https://github.com/FredyC) in [#4223](https://github.com/apollographql/apollo-client/pull/4223)\n\n- The `QueryManager` now calls `complete` on the observables used by\n  Apollo Client's Subscription handling. This gives finite subscriptions a\n  chance to handle cleanup. <br/>\n  [@sujeetsr](https://github.com/sujeetsr) in [#4290](https://github.com/apollographql/apollo-client/pull/4290)\n\n- Documentation updates. <br/>\n  [@lifedup](https://github.com/lifedup) in [#3931](https://github.com/apollographql/apollo-client/pull/3931) <br />\n  [@Dem0n3D](https://github.com/Dem0n3D) in [#4008](https://github.com/apollographql/apollo-client/pull/4008) <br />\n  [@anand-sundaram-zocdoc](https://github.com/anand-sundaram-zocdoc) in [#4009](https://github.com/apollographql/apollo-client/pull/4009) <br />\n  [@mattphoto](https://github.com/mattphoto) in [#4026](https://github.com/apollographql/apollo-client/pull/4026) <br />\n  [@birge](https://github.com/birge) in [#4029](https://github.com/apollographql/apollo-client/pull/4029) <br />\n  [@mxstbr](https://github.com/mxstbr) in [#4127](https://github.com/apollographql/apollo-client/pull/4127) <br/>\n  [@Caerbannog](https://github.com/Caerbannog) in [#4140](https://github.com/apollographql/apollo-client/pull/4140) <br/>\n  [@jedwards1211](https://github.com/jedwards1211) in [#4179](https://github.com/apollographql/apollo-client/pull/4179) <br/>\n  [@nutboltu](https://github.com/nutboltu) in [#4182](https://github.com/apollographql/apollo-client/pull/4182) <br/>\n  [@CarloPalinckx](https://github.com/CarloPalinckx) in [#4189](https://github.com/apollographql/apollo-client/pull/4189) <br/>\n  [@joebernard](https://github.com/joebernard) in [#4206](https://github.com/apollographql/apollo-client/pull/4206) <br/>\n  [@evans](https://github.com/evans) in [#4213](https://github.com/apollographql/apollo-client/pull/4213) <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#4214](https://github.com/apollographql/apollo-client/pull/4214) <br/>\n  [@stubailo](https://github.com/stubailo) in [#4220](https://github.com/apollographql/apollo-client/pull/4220) <br/>\n  [@haysclark](https://github.com/haysclark) in [#4255](https://github.com/apollographql/apollo-client/pull/4255) <br/>\n  [@shelmire](https://github.com/shelmire) in [#4266](https://github.com/apollographql/apollo-client/pull/4266) <br/>\n  [@peggyrayzis](https://github.com/peggyrayzis) in [#4280](https://github.com/apollographql/apollo-client/pull/4280) <br/>\n  [@caydie-tran](https://github.com/caydie-tran) in [#4300](https://github.com/apollographql/apollo-client/pull/4300)\n\n### Apollo Utilities (1.1.0)\n\n- Transformation utilities have been refactored to work with `graphql` 14.x.\n  GraphQL AST's are no longer being directly modified. <br/>\n  [@hwillson](https://github.com/hwillson) in [#4233](https://github.com/apollographql/apollo-client/pull/4233)\n\n### Apollo Cache In-Memory (1.4.0)\n\n- The speed and memory usage of optimistic reads and writes has been\n  improved dramatically using a new layering technique that does not\n  require copying the non-optimistic contents of the cache. <br/>\n  [PR #4319](https://github.com/apollographql/apollo-client/pull/4319/)\n\n- The `RecordingCache` abstraction has been removed, and thus is no longer\n  exported from `apollo-cache-inmemory`. <br/>\n  [PR #4319](https://github.com/apollographql/apollo-client/pull/4319/)\n\n- Export the optimism `wrap` function using ES2015 export syntax, instead of\n  CommonJS. <br/>\n  [@ardatan](https://github.com/ardatan) in [#4158](https://github.com/apollographql/apollo-client/pull/4158)\n\n## Apollo Client (2.4.8)\n\n### Apollo Client (2.4.8)\n\n- Documentation and config updates. <br/>\n  [@justinanastos](https://github.com/justinanastos) in [#4187](https://github.com/apollographql/apollo-client/pull/4187) <br/>\n  [@PowerKiKi](https://github.com/PowerKiKi) in [#3693](https://github.com/apollographql/apollo-client/pull/3693) <br/>\n  [@nandito](https://github.com/nandito) in [#3865](https://github.com/apollographql/apollo-client/pull/3865)\n\n- Schema/AST tranformation utilities have been updated to work properly with\n  `@client` directives. <br/>\n  [@justinmakaila](https://github.com/justinmakaila) in [#3482](https://github.com/apollographql/apollo-client/pull/3482)\n\n### Apollo Cache In-Memory (1.3.12)\n\n- Avoid using `DepTrackingCache` for optimistic reads.\n  [PR #4521](https://github.com/apollographql/apollo-client/pull/4251)\n\n- When creating an `InMemoryCache` object, it's now possible to disable the\n  result caching behavior introduced in [#3394](https://github.com/apollographql/apollo-client/pull/3394),\n  either for diagnostic purposes or because the benefit of caching repeated\n  reads is not worth the extra memory usage in your application:\n  ```ts\n  new InMemoryCache({\n    resultCaching: false,\n  });\n  ```\n  Part of [PR #4521](https://github.com/apollographql/apollo-client/pull/4251).\n\n## Apollo Client (2.4.7)\n\n### Apollo Client (2.4.7)\n\n- The `ApolloClient` constructor has been updated to accept `name` and\n  `version` params, that can be used to support Apollo Server [Client Awareness](https://www.apollographql.com/docs/apollo-server/v2/features/metrics.html#Client-Awareness)\n  functionality. These client awareness properties are passed into the\n  defined Apollo Link chain, and are then ultimately sent out as custom\n  headers with outgoing requests. <br/>\n  [@hwillson](https://github.com/hwillson) in [#4154](https://github.com/apollographql/apollo-client/pull/4154)\n\n### Apollo Boost (0.1.22)\n\n- No changes.\n\n### Apollo Cache (1.1.21)\n\n- No changes.\n\n### Apollo Cache In-Memory (1.3.11)\n\n- No changes.\n\n### Apollo Utilities (1.0.26)\n\n- No changes.\n\n### Graphql Anywhere (4.1.23)\n\n- No changes.\n\n## Apollo Client (2.4.6)\n\n### Apollo Cache In-Memory (1.3.10)\n\n- Added some `return`s to prevent errors with `noImplicitReturns`\n  TypeScript rule.\n  [PR #4137](https://github.com/apollographql/apollo-client/pull/4137)\n\n- Exclude the `src/` directory when publishing `apollo-cache-inmemory`.\n  [Issue #4083](https://github.com/apollographql/apollo-client/issues/4083)\n\n## Apollo Client (2.4.5)\n\n- Optimistic tests cleanup.\n  [PR #3834](https://github.com/apollographql/apollo-client/pull/3834) by\n  [@joshribakoff](https://github.com/joshribakoff)\n\n- Documentation updates.\n  [PR #3840](https://github.com/apollographql/apollo-client/pull/3840) by\n  [@chentsulin](https://github.com/chentsulin) and\n  [PR #3844](https://github.com/apollographql/apollo-client/pull/3844) by\n  [@lorensr](https://github.com/lorensr)\n\n- Implement `ObservableQuery#isDifferentFromLastResult` to fix\n  [Issue #4054](https://github.com/apollographql/apollo-client/issues/4054) and\n  [Issue #4031](https://github.com/apollographql/apollo-client/issues/4031).\n  [PR #4069](https://github.com/apollographql/apollo-client/pull/4069)\n\n### Apollo Cache (1.1.20)\n\n- Add `readQuery` test to make sure options aren't mutated.\n  [@CarloPalinckx](https://github.com/CarloPalinckx) in\n  [#3838](https://github.com/apollographql/apollo-client/pull/3838)\n\n### Apollo Cache In-Memory (1.3.9)\n\n- Avoid modifying source objects when merging cache results.\n  [Issue #4081](https://github.com/apollographql/apollo-client/issues/4081)\n  [PR #4089](https://github.com/apollographql/apollo-client/pull/4089)\n\n### Apollo Utilities (1.0.25)\n\n- Fix `apollo-utilities` `isEqual` bug due to missing `hasOwnProperty`\n  check. [PR #4072](https://github.com/apollographql/apollo-client/pull/4072)\n  by [@samkline](https://github.com/samkline)\n\n## Apollo Client (2.4.4)\n\n### Apollo Utilities (1.0.24)\n\n- Discard property accessor functions in `cloneDeep` helper, to fix\n  [issue #4034](https://github.com/apollographql/apollo-client/issues/4034).\n\n- Unconditionally remove `cloneDeep` property accessors.\n  [PR #4039](https://github.com/apollographql/apollo-client/pull/4039)\n\n- Avoid copying non-enumerable and/or `Symbol` keys in `cloneDeep`.\n  [PR #4052](https://github.com/apollographql/apollo-client/pull/4052)\n\n### Apollo Cache In-Memory (1.3.7)\n\n- Throw when querying non-scalar objects without a selection set.\n  [Issue #4025](https://github.com/apollographql/apollo-client/issues/4025)\n  [PR #4038](https://github.com/apollographql/apollo-client/pull/4038)\n\n- Work around spec non-compliance of `Map#set` and `Set#add` in IE11.\n  [Issue #4024](https://github.com/apollographql/apollo-client/issues/4024)\n  [PR #4012](https://github.com/apollographql/apollo-client/pull/4012)\n\n## Apollo Client (2.4.3)\n\n- Add additional checks to make sure we don't try to set the network status\n  of queries in the store, when the store doesn't exist. <br/>\n  [@i6mi6](https://github.com/i6mi6) in [#3914](https://github.com/apollographql/apollo-client/pull/3914)\n- Documentation updates. <br/>\n  [@shanonvl](https://github.com/shanonvl) in [#3925](https://github.com/apollographql/apollo-client/pull/3925) <br/>\n  [@ojh102](https://github.com/ojh102) in [#3920](https://github.com/apollographql/apollo-client/pull/3920) <br/>\n  [@Bkucera](https://github.com/Bkucera) in [#3919](https://github.com/apollographql/apollo-client/pull/3919) <br/>\n  [@j4chou](https://github.com/j4chou) in [#3915](https://github.com/apollographql/apollo-client/pull/3915) <br/>\n  [@billfienberg](https://github.com/billfienberg) in [#3886](https://github.com/apollographql/apollo-client/pull/3886) <br/>\n  [@TLadd](https://github.com/TLadd) in [#3884](https://github.com/apollographql/apollo-client/pull/3884)\n\n- The `ObservableQuery` class now makes a deep clone of `lastResult` when\n  first received, so that the `isDifferentResult` logic will not be\n  confused if the result object is modified later.\n  [Issue #3992](https://github.com/apollographql/apollo-client/issues/3992)\n  [PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/e66027c5341dc7aaf71ee7ffcba1305b9a553525)\n\n### Apollo Cache In-Memory (1.3.6)\n\n- Optimize repeated `apollo-cache-inmemory` reads by caching partial query\n  results, for substantial performance improvements. As a consequence, watched\n  queries will not be rebroadcast unless the data have changed.\n  [PR #3394](https://github.com/apollographql/apollo-client/pull/3394)\n\n- Include root ID and fragment matcher function in cache keys computed by\n  `StoreReader#executeStoreQuery` and `executeSelectionSet`, and work\n  around bugs in the React Native `Map` and `Set` polyfills.\n  [PR #3964](https://github.com/apollographql/apollo-client/pull/3964)\n  [React Native PR #21492 (pending)](https://github.com/facebook/react-native/pull/21492)\n\n- The `apollo-cache-inmemory` package now allows `graphql@^14.0.0` as a\n  peer dependency.\n  [Issue #3978](https://github.com/apollographql/apollo-client/issues/3978)\n\n- The `apollo-cache-inmemory` package now correctly broadcasts changes\n  even when the new data is `===` to the old data, since the contents of\n  the data object may have changed.\n  [Issue #3992](https://github.com/apollographql/apollo-client/issues/3992)\n  [PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/d6a673fbc1444e115e90cc9e4c7fa3fc67bb7e56)\n\n### Apollo GraphQL Anywhere (4.1.20)\n\n- Make `graphql-anywhere` `filter` function generic (typescript). <br/>\n  [@minznerjosh](https://github.com/minznerjosh) in [#3929](https://github.com/apollographql/apollo-client/pull/3929)\n\n### Apollo Utilities (1.0.22)\n\n- The `fclone` package has been replaced with a custom `cloneDeep`\n  implementation that is tolerant of cycles, symbol properties, and\n  non-enumerable properties.\n  [PR #4032](https://github.com/apollographql/apollo-client/pull/4032/commits/78e2ad89f950da2829f49c7876f968adb2bc1302)\n\n### Apollo Boost (0.1.17)\n\n- Remove duplicate InMemoryCache export for Babel 6 compatibility.\n  [Issue #3910](https://github.com/apollographql/apollo-client/issues/3910)\n  [PR #3932](https://github.com/apollographql/apollo-client/pull/3932)\n\n### Apollo Cache (1.1.18)\n\n- No changes.\n\n## Apollo Client (2.4.2)\n\n### Apollo Client (2.4.2)\n\n- Apollo Client no longer deep freezes query results.\n  [@hwillson](https://github.com/hwillson) in [#3883](https://github.com/apollographql/apollo-client/pull/3883)\n- A new `clearStore` method has been added, that will remove all data from\n  the store. Unlike `resetStore`, it will not refetch active queries after\n  removing store data.\n  [@hwillson](https://github.com/hwillson) in [#3885](https://github.com/apollographql/apollo-client/pull/3885)\n\n### Apollo Utilities (1.0.21)\n\n- Replace the custom `cloneDeep` implementation with\n  [`fclone`](https://www.npmjs.com/package/fclone), to avoid crashing when\n  encountering circular references. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3881](https://github.com/apollographql/apollo-client/pull/3881)\n\n### Apollo Boost (0.1.16)\n\n- No changes.\n\n### Apollo Cache (1.1.17)\n\n- No changes.\n\n### Apollo Cache In-Memory (1.2.10)\n\n- No changes.\n\n### Apollo GraphQL Anywhere (4.1.19)\n\n- No changes.\n\n## 2.4.1 (August 26, 2018)\n\n### Apollo Client (2.4.1)\n\n- `mutate`'s `refetchQueries` option now allows queries to include a custom\n  `context` option. This `context` will be used when refetching the query.\n  For example:\n\n  ```js\n  context = {\n    headers: {\n      token: 'some auth token',\n    },\n  };\n  client.mutate({\n    mutation: UPDATE_CUSTOMER_MUTATION,\n    variables: {\n      userId: user.id,\n      firstName,\n      ...\n    },\n    refetchQueries: [{\n      query: CUSTOMER_MESSAGES_QUERY,\n      variables: { userId: user.id },\n      context,\n    }],\n    context,\n  });\n  ```\n\n  The `CUSTOMER_MESSAGES_QUERY` above will be refetched using `context`.\n  Normally queries are refetched using the original context they were first\n  started with, but this provides a way to override the context, if needed. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3852](https://github.com/apollographql/apollo-client/pull/3852)\n\n- Documentation updates. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3841](https://github.com/apollographql/apollo-client/pull/3841)\n\n### Apollo Boost (0.1.15)\n\n- Various internal infrastructure changes related to building, bundling,\n  testing, etc.\n  [@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)\n\n### Apollo Cache (1.1.16)\n\n- Various internal infrastructure changes related to building, bundling,\n  testing, etc.\n  [@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)\n\n### Apollo Cache In-Memory (1.2.9)\n\n- Various internal infrastructure changes related to building, bundling,\n  testing, etc.\n  [@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)\n\n### Apollo Utilities (1.0.20)\n\n- Various internal infrastructure changes related to building, bundling,\n  testing, etc.\n  [@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)\n\n### Apollo GraphQL Anywhere (4.1.18)\n\n- Various internal infrastructure changes related to building, bundling,\n  testing, etc.\n  [@hwillson](https://github.com/hwillson) in [#3817](https://github.com/apollographql/apollo-client/pull/3817)\n\n## 2.4.0 (August 17, 2018)\n\n### Apollo Client (2.4.0)\n\n- Add proper error handling for subscriptions. If you have defined an `error`\n  handler on your subscription observer, it will now be called when an error\n  comes back in a result, and the `next` handler will be skipped (similar to\n  how we're handling errors with mutations). Previously, the error was\n  just passed in the result to the `next` handler. If you don't have an\n  `error` handler defined, the previous functionality is maintained, meaning\n  the error is passed in the result, giving the next handler a chance to deal\n  with it. This should help address backwards compatibility (and is the reason\n  for the minor version bumo in this release). <br/>\n  [@clayne11](https://github.com/clayne11) in [#3800](https://github.com/apollographql/apollo-client/pull/3800)\n- Allow an `optimistic` param to be passed into `ApolloClient.readQuery` and\n  `ApolloClient.readFragment`, that when set to `true`, will allow\n  optimistic results to be returned. Is `false` by default. <br/>\n  [@jay1337](https://github.com/jay1337) in [#2429](https://github.com/apollographql/apollo-client/pull/2429)\n- Optimistic tests cleanup. <br/>\n  [@joshribakoff](https://github.com/joshribakoff) in [#3713](https://github.com/apollographql/apollo-client/pull/3713)\n- Make sure each package has its own `.npmignore`, so they're taken into\n  consideration when publishing via lerna. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3828](https://github.com/apollographql/apollo-client/pull/3828)\n- Documentation updates. <br/>\n  [@toolness](https://github.com/toolness) in [#3804](https://github.com/apollographql/apollo-client/pull/3804) <br/>\n  [@pungggi](https://github.com/pungggi) in [#3798](https://github.com/apollographql/apollo-client/pull/3798) <br/>\n  [@lorensr](https://github.com/lorensr) in [#3748](https://github.com/apollographql/apollo-client/pull/3748) <br/>\n  [@joshribakoff](https://github.com/joshribakoff) in [#3730](https://github.com/apollographql/apollo-client/pull/3730) <br/>\n  [@yalamber](https://github.com/yalamber) in [#3819](https://github.com/apollographql/apollo-client/pull/3819) <br/>\n  [@pschreibs85](https://github.com/pschreibs85) in [#3812](https://github.com/apollographql/apollo-client/pull/3812) <br/>\n  [@msreekm](https://github.com/msreekm) in [#3808](https://github.com/apollographql/apollo-client/pull/3808) <br/>\n  [@kamaltmo](https://github.com/kamaltmo) in [#3806](https://github.com/apollographql/apollo-client/pull/3806) <br/>\n  [@lorensr](https://github.com/lorensr) in [#3739](https://github.com/apollographql/apollo-client/pull/3739) <br/>\n  [@brainkim](https://github.com/brainkim) in [#3680](https://github.com/apollographql/apollo-client/pull/3680)\n\n### Apollo Cache In-Memory (1.2.8)\n\n- Fix typo in `console.warn` regarding fragment matching error message. <br/>\n  [@combizs](https://github.com/combizs) in [#3701](https://github.com/apollographql/apollo-client/pull/3701)\n\n### Apollo Boost (0.1.14)\n\n- No changes.\n\n### Apollo Cache (1.1.15)\n\n- No changes.\n\n### Apollo Utilities (1.0.19)\n\n- No changes.\n\n### Apollo GraphQL Anywhere (4.1.17)\n\n- No changes.\n\n## 2.3.8 (August 9, 2018)\n\n### Apollo Client (2.3.8)\n\n- Adjusted the `graphql` peer dependency to cover explicit minor ranges.\n  Since the ^ operator only covers any minor version if the major version\n  is not 0 (since a major version of 0 is technically considered development by\n  semver 2), the current ^0.11.0 || ^14.0.0 graphql range doesn't cover\n  0.12._ or 0.13._. This fixes the `apollo-client@X has incorrect peer dependency \"graphql@^0.11.0 || ^14.0.0\"` errors that people might have\n  seen using `graphql` 0.12.x or 0.13.x. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3746](https://github.com/apollographql/apollo-client/pull/3746)\n- Document `setVariables` internal API status. <br/>\n  [@PowerKiKi](https://github.com/PowerKiKi) in [#3692](https://github.com/apollographql/apollo-client/pull/3692)\n- Corrected `ApolloClient.queryManager` typing as it may be `undefined`. <br/>\n  [@danilobuerger](https://github.com/danilobuerger) in [#3661](https://github.com/apollographql/apollo-client/pull/3661)\n- Make sure using a `no-cache` fetch policy with subscriptions prevents data\n  from being cached. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3773](https://github.com/apollographql/apollo-client/pull/3773)\n- Fixed an issue that sometimes caused empty query results, when using the\n  `no-cache` fetch policy. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3777](https://github.com/apollographql/apollo-client/pull/3777)\n- Documentation updates. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3750](https://github.com/apollographql/apollo-client/pull/3750) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3754](https://github.com/apollographql/apollo-client/pull/3754) <br/>\n  [@TheMightyPenguin](https://github.com/TheMightyPenguin) in [#3725](https://github.com/apollographql/apollo-client/pull/3725) <br/>\n  [@bennypowers](https://github.com/bennypowers) in [#3668](https://github.com/apollographql/apollo-client/pull/3668) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3762](https://github.com/apollographql/apollo-client/pull/3762) <br/>\n  [@chentsulin](https://github.com/chentsulin) in [#3688](https://github.com/apollographql/apollo-client/pull/3688) <br/>\n  [@chentsulin](https://github.com/chentsulin) in [#3687](https://github.com/apollographql/apollo-client/pull/3687) <br/>\n  [@ardouglass](https://github.com/ardouglass) in [#3645](https://github.com/apollographql/apollo-client/pull/3645) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3764](https://github.com/apollographql/apollo-client/pull/3764) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3767](https://github.com/apollographql/apollo-client/pull/3767) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3774](https://github.com/apollographql/apollo-client/pull/3774) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3779](https://github.com/apollographql/apollo-client/pull/3779)\n\n### Apollo Boost (0.1.13)\n\n- No changes.\n\n### Apollo Cache In-Memory (1.2.7)\n\n- No changes.\n\n### Apollo Cache (1.1.14)\n\n- No changes.\n\n### Apollo Utilities (1.0.18)\n\n- No changes.\n\n### Apollo GraphQL Anywhere (4.1.16)\n\n- No changes.\n\n## 2.3.7 (July 24, 2018)\n\n### Apollo Client (2.3.7)\n\n- Release 2.3.6 broke Typescript compilation. `QueryManager`'s\n  `getQueryWithPreviousResult` method included an invalid `variables` return\n  type in the auto-generated `core/QueryManager.d.ts` declaration file. The\n  type definition had a locally referenced path, that appears to have been\n  caused by the typescript compiler getting confused at compile/publish time.\n  `getQueryWithPreviousResult` return types are now excplicity identified,\n  which helps Typescript avoid the local type reference. For more details,\n  see https://github.com/apollographql/apollo-client/issues/3729. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3731](https://github.com/apollographql/apollo-client/pull/3731)\n\n### Apollo Boost (0.1.12)\n\n- No changes.\n\n## 2.3.6 (July 24, 2018)\n\n### Apollo Client (2.3.6)\n\n- Documentation updates. <br/>\n  [@ananth99](https://github.com/ananth99) in [#3599](https://github.com/apollographql/apollo-client/pull/3599) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3635](https://github.com/apollographql/apollo-client/pull/3635) <br/>\n  [@JakeDawkins](https://github.com/JakeDawkins) in [#3642](https://github.com/apollographql/apollo-client/pull/3642) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3644](https://github.com/apollographql/apollo-client/pull/3644) <br/>\n  [@gbau](https://github.com/gbau) in [#3644](https://github.com/apollographql/apollo-client/pull/3600) <br/>\n  [@chentsulin](https://github.com/chentsulin) in [#3608](https://github.com/apollographql/apollo-client/pull/3608) <br/>\n  [@MikaelCarpenter](https://github.com/MikaelCarpenter) in [#3609](https://github.com/apollographql/apollo-client/pull/3609) <br/>\n  [@Gamezpedia](https://github.com/Gamezpedia) in [#3612](https://github.com/apollographql/apollo-client/pull/3612) <br/>\n  [@jinxac](https://github.com/jinxac) in [#3647](https://github.com/apollographql/apollo-client/pull/3647) <br/>\n  [@abernix](https://github.com/abernix) in [#3705](https://github.com/apollographql/apollo-client/pull/3705) <br/>\n  [@dandv](https://github.com/dandv) in [#3703](https://github.com/apollographql/apollo-client/pull/3703) <br/>\n  [@hwillson](https://github.com/hwillson) in [#3580](https://github.com/apollographql/apollo-client/pull/3580) <br/>\n- Updated `graphql` `peerDependencies` to handle 14.x versions. <br/>\n  [@ivank](https://github.com/ivank) in [#3598](https://github.com/apollographql/apollo-client/pull/3598)\n- Add optional generic type params for variables on low level methods. <br/>\n  [@mvestergaard](https://github.com/mvestergaard) in [#3588](https://github.com/apollographql/apollo-client/pull/3588)\n- Add a new `awaitRefetchQueries` config option to the Apollo Client\n  `mutate` function, that when set to `true` will wait for all\n  `refetchQueries` to be fully refetched, before resolving the mutation\n  call. `awaitRefetchQueries` is `false` by default. <br/>\n  [@jzimmek](https://github.com/jzimmek) in [#3169](https://github.com/apollographql/apollo-client/pull/3169)\n\n### Apollo Boost (0.1.11)\n\n- Allow `fetch` to be given as a configuration option to `ApolloBoost`. <br/>\n  [@mbaranovski](https://github.com/mbaranovski) in [#3590](https://github.com/apollographql/apollo-client/pull/3590)\n- The `apollo-boost` `ApolloClient` constructor now warns about unsupported\n  options. <br/>\n  [@quentin-](https://github.com/quentin-) in [#3551](https://github.com/apollographql/apollo-client/pull/3551)\n\n### Apollo Cache (1.1.13)\n\n- No changes.\n\n### Apollo Cache In-Memory (1.2.6)\n\n- Add `__typename` and `id` properties to `dataIdFromObject` parameter\n  (typescript) <br/>\n  [@jfurler](https://github.com/jfurler) in [#3641](https://github.com/apollographql/apollo-client/pull/3641)\n- Fixed an issue caused by `dataIdFromObject` considering returned 0 values to\n  be falsy, instead of being a valid ID, which lead to the store not being\n  updated properly in some cases. <br/>\n  [@hwillson](https://github.com/hwillson) in [#3711](https://github.com/apollographql/apollo-client/pull/3711)\n\n### Apollo Utilities (1.0.17)\n\n- No changes.\n\n### Apollo GraphQL Anywhere (4.1.15)\n\n- Add support for arrays to `graphql-anywhere`'s filter utility. <br/>\n  [@jsweet314](https://github.com/jsweet314) in [#3591](https://github.com/apollographql/apollo-client/pull/3591)\n- Fix `Cannot convert object to primitive value` error that was showing up\n  when attempting to report a missing property on an object. <br/>\n  [@benjie](https://github.com/benjie) in [#3618](https://github.com/apollographql/apollo-client/pull/3618)\n\n## 2.3.5 (June 19, 2018)\n\n### Apollo Client (2.3.5)\n\n- Internal code formatting updates.\n  - [@chentsulin](https://github.com/chentsulin) in [#3574](https://github.com/apollographql/apollo-client/pull/3574)\n- Documentation updates.\n  - [@andtos90](https://github.com/andtos90) in [#3596](https://github.com/apollographql/apollo-client/pull/3596)\n  - [@serranoarevalo](https://github.com/serranoarevalo) in [#3554](https://github.com/apollographql/apollo-client/pull/3554)\n  - [@cooperka](https://github.com/cooperka) in [#3594](https://github.com/apollographql/apollo-client/pull/3594)\n  - [@pravdomil](https://github.com/pravdomil) in [#3587](https://github.com/apollographql/apollo-client/pull/3587)\n  - [@excitement-engineer](https://github.com/excitement-engineer) in [#3309](https://github.com/apollographql/apollo-client/pull/3309)\n\n### Apollo Boost (0.1.10)\n\n- No changes.\n\n### Apollo Cache (1.1.12)\n\n- No changes.\n\n### Apollo Cache In-Memory (1.2.5)\n\n- No changes.\n\n### Apollo Utilities (1.0.16)\n\n- Removed unnecessary whitespace from error message.\n  - [@mbaranovski](https://github.com/mbaranovski) in [#3593](https://github.com/apollographql/apollo-client/pull/3593)\n\n### Apollo GraphQL Anywhere (4.1.14)\n\n- No changes.\n\n## 2.3.4 (June 13, 2018)\n\n### Apollo Client (2.3.4)\n\n- Export the `QueryOptions` interface, to make sure it can be used by other\n  projects (like `apollo-angular`).\n- Fixed an issue caused by typescript changes to the constructor\n  `defaultOptions` param, that prevented `query` defaults from passing type\n  checks.\n  ([@hwillson](https://github.com/hwillson) in [#3585](https://github.com/apollographql/apollo-client/pull/3585))\n\n### Apollo Boost (0.1.9)\n\n- No changes\n\n### Apollo Cache (1.1.11)\n\n- No changes\n\n### Apollo Cache In-Memory (1.2.4)\n\n- No changes\n\n### Apollo Utilities (1.0.15)\n\n- No changes\n\n### Apollo GraphQL Anywhere (4.1.13)\n\n- No changes\n\n## 2.3.3 (June 13, 2018)\n\n### Apollo Client (2.3.3)\n\n- Typescript improvements. Made observable query parameterized on data and\n  variables: `ObservableQuery<TData, TVariables>`\n  ([@excitement-engineer](https://github.com/excitement-engineer) in [#3140](https://github.com/apollographql/apollo-client/pull/3140))\n- Added optional generics to cache manipulation methods (typescript).\n  ([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))\n- Typescript improvements. Created a new `QueryOptions` interface that\n  is now used by `ApolloClient.query` options, instead of the previous\n  `WatchQueryOptions` interface. This helps reduce confusion (especially\n  in the docs) that made it look like `ApolloClient.query` accepted\n  `ApolloClient.watchQuery` only options, like `pollingInterval`.\n  ([@hwillson](https://github.com/hwillson) in [#3569](https://github.com/apollographql/apollo-client/pull/3569))\n\n### Apollo Boost (0.1.8)\n\n- Allow `cache` to be given as a configuration option to `ApolloBoost`.\n  ([@dandean](https://github.com/dandean) in [#3561](https://github.com/apollographql/apollo-client/pull/3561))\n- Allow `headers` and `credentials` to be passed in as configuration\n  parameters to the `apollo-boost` `ApolloClient` constructor.\n  ([@rzane](https://github.com/rzane) in [#3098](https://github.com/apollographql/apollo-client/pull/3098))\n\n### Apollo Cache (1.1.10)\n\n- Added optional generics to cache manipulation methods (typescript).\n  ([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))\n\n### Apollo Cache In-Memory (1.2.3)\n\n- Added optional generics to cache manipulation methods (typescript).\n  ([@mvestergaard](https://github.com/mvestergaard) in [#3541](https://github.com/apollographql/apollo-client/pull/3541))\n- Restore non-enumerability of `resultFields[ID_KEY]`.\n  ([@benjamn](https://github.com/benjamn) in [#3544](https://github.com/apollographql/apollo-client/pull/3544))\n- Cache query documents transformed by InMemoryCache.\n  ([@benjamn](https://github.com/benjamn) in [#3553](https://github.com/apollographql/apollo-client/pull/3553))\n\n### Apollo Utilities (1.0.14)\n\n- Store key names generated by `getStoreKeyName` now leverage a more\n  deterministic approach to handling JSON based strings. This prevents store\n  key names from differing when using `args` like\n  `{ prop1: 'value1', prop2: 'value2' }` and\n  `{ prop2: 'value2', prop1: 'value1' }`.\n  ([@gdi2290](https://github.com/gdi2290) in [#2869](https://github.com/apollographql/apollo-client/pull/2869))\n- Avoid needless `hasOwnProperty` check in `deepFreeze`.\n  ([@benjamn](https://github.com/benjamn) in [#3545](https://github.com/apollographql/apollo-client/pull/3545))\n\n### Apollo GraphQL Anywhere (4.1.12)\n\n- No new changes.\n\n## 2.3.2 (May 29, 2018)\n\n### Apollo Client (2.3.2)\n\n- Fix SSR and `cache-and-network` fetch policy\n  ([@dastoori](https://github.com/dastoori) in [#3372](https://github.com/apollographql/apollo-client/pull/3372))\n- Fixed an issue where the `updateQuery` method passed to\n  `ObservableQuery.fetchMore` was receiving the original query variables,\n  instead of the new variables that it used to fetch more data.\n  ([@abhiaiyer91](https://github.com/abhiaiyer91) in [#3500](https://github.com/apollographql/apollo-client/pull/3500))\n- Fixed an issue involving `Object.setPrototypeOf()` not working on JSC\n  (Android), by instead setting the `prototype` of `this` manually.\n  ([@seklyza](https://github.com/seklyza) in [#3306](https://github.com/apollographql/apollo-client/pull/3306))\n- Added safeguards to make sure `QueryStore.initQuery` and\n  `QueryStore.markQueryResult` don't try to set the network status of a\n  `fetchMoreForQueryId` query, if it does not exist in the store. This was\n  happening when a query component was unmounted while a `fetchMore` was still\n  in flight.\n  ([@conrad-vanl](https://github.com/conrad-vanl) in [#3367](https://github.com/apollographql/apollo-client/pull/3367), [@doomsower](https://github.com/doomsower) in [#3469](https://github.com/apollographql/apollo-client/pull/3469))\n\n### Apollo Boost (0.1.7)\n\n- Various internal code cleanup, tooling and dependency changes.\n\n### Apollo Cache (1.1.9)\n\n- Various internal code cleanup, tooling and dependency changes.\n\n### Apollo Cache In-Memory (1.2.2)\n\n- Fixed an issue that caused fragment only queries to sometimes fail.\n  ([@abhiaiyer91](https://github.com/abhiaiyer91) in [#3507](https://github.com/apollographql/apollo-client/pull/3507))\n- Fixed cache invalidation for inlined mixed types in union fields within\n  arrays.\n  ([@dferber90](https://github.com/dferber90) in [#3422](https://github.com/apollographql/apollo-client/pull/3422))\n\n### Apollo Utilities (1.0.13)\n\n- Make `maybeDeepFreeze` a little more defensive, by always using\n  `Object.prototype.hasOwnProperty` (to avoid cases where the object being\n  frozen doesn't have its own `hasOwnProperty`).\n  ([@jorisroling](https://github.com/jorisroling) in [#3418](https://github.com/apollographql/apollo-client/pull/3418))\n- Remove certain small internal caches to prevent memory leaks when using SSR.\n  ([@brunorzn](https://github.com/brunorzn) in [#3444](https://github.com/apollographql/apollo-client/pull/3444))\n\n### Apollo GraphQL Anywhere (4.1.11)\n\n- Source files are now excluded when publishing to npm.\n  ([@hwillson](https://github.com/hwillson) in [#3454](https://github.com/apollographql/apollo-client/pull/3454))\n"
  },
  {
    "path": "CLAUDE.md",
    "content": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## Apollo Client Overview\n\nApollo Client is a comprehensive caching GraphQL client for TypeScript/JavaScript. The project is maintained at version 4.x.x and uses a monorepo structure with npm workspaces.\n\n## Common Development Commands\n\n### Build Commands\n\n- `npm run build` - Build the entire project\n- `npm run build -w codegen` - Build specific workspace (e.g., codegen)\n\n### Testing Commands\n\n- `npm test` - Run all tests with Jest\n- `npm run test:type-benches` - Run type benchmarks\n- `npm run test:memory` - Run memory tests\n\n### Code Quality Commands\n\n- `npm run typecheck` - Run TypeScript type checking\n- `npm run lint` - Run ESLint with extended rules\n- `npm run format` - Format code with Prettier\n- `npm run check:format` - Check if code is formatted correctly\n- `npm run knip` - Check for unused files/exports\n- `npm run madge` - Check for circular dependencies\n\n### Documentation & API\n\n- `npm run extract-api` - Generate API documentation\n- `npm run typedoc` - Generate TypeDoc documentation\n- `npm run docmodel` - Generate API documentation model\n\n### Release & Publishing\n\n- `npx changeset` - Create a changeset for your changes\n\n## High-Level Architecture\n\n### Core Modules\n\n1. **Core (`src/core/`)** - Main Apollo Client implementation\n\n   - `ApolloClient.ts` - Main client class\n   - `ObservableQuery.ts` - Observable query implementation\n   - `QueryManager.ts` - Query lifecycle management\n\n2. **Cache (`src/cache/`)** - Caching layer\n\n   - `inmemory/` - InMemoryCache implementation (default cache)\n   - `core/` - Base cache abstractions\n\n3. **Link (`src/link/`)** - Network layer abstraction\n\n   - `http/` - HTTP link for GraphQL over HTTP\n   - `batch/` - Batch link for combining queries\n   - `error/` - Error handling link\n   - `schema/` - Schema link for local execution\n   - `ws/` - WebSocket link for subscriptions\n\n4. **React Integration (`src/react/`)** - React hooks and components\n\n   - `hooks/` - React hooks (useQuery, useMutation, etc.)\n   - `ssr/` - Server-side rendering support\n   - `context/` - React context providers\n\n5. **Utilities (`src/utilities/`)** - Shared utilities\n\n   - `graphql/` - GraphQL document utilities\n   - `internal/` - Internal utilities\n   - `invariant/` - Error handling utilities\n\n6. **Testing (`src/testing/`)** - Testing utilities\n\n   - `core/` - Core testing utilities\n   - `react/` - React testing utilities (MockedProvider)\n\n7. **Masking (`src/masking/`)** - Data masking for fragment colocation\n\n8. **Local State (`src/local-state/`)** - Local state management\n\n### TypeScript Configuration\n\n- Uses TypeScript 5.7.3 with strict mode enabled\n- Module resolution: NodeNext\n- Target: ESNext\n- Separate tsconfig files for different purposes:\n  - `tsconfig.json` - Main configuration\n  - `tsconfig.build.json` - Build configuration\n  - `tsconfig.tests.json` - Test configuration\n\n### Testing Infrastructure\n\n- Jest with ts-jest for testing\n- Custom test environment extending jsdom\n- React Testing Library for React component tests\n- Multiple React version testing (17, 18, 19)\n- Coverage reporting with lcov\n\n### Build System\n\n- Uses custom build script (`config/build.ts`)\n- API Extractor for API documentation\n- Size limit checking for bundle size\n- Source map verification\n- Publint for package publishing validation\n\n### Code Organization Patterns\n\n1. **Exports** - All public exports go through index files\n2. **Internal APIs** - Use `@apollo/client/*/internal` paths\n3. **Environment-specific builds** - Production/development variants\n4. **Type safety** - Heavy use of TypeScript generics and type inference\n5. **Reactive programming** - Uses RxJS for observables\n6. **Immutability** - Emphasizes immutable data structures\n\n### Contributing Guidelines\n\n- All changes require a changeset (`npx changeset`)\n- PRs should include tests for bug fixes\n- Follow existing code style (enforced by ESLint/Prettier)\n- Large features need design discussion first\n- Code review required from core contributors\n\n### Important Notes\n\n- This is a monorepo with workspaces: main package, codegen, and codemods\n- The project is currently at version 4.x.x (release candidate)\n- Supports multiple peer dependencies (React 17/18/19, GraphQL 16)\n- Uses patch-package for dependency patches\n- Has extensive CI checks that must pass before merging\n\n## Additional Instructions\n\n@.claude/documentation.md\n@.claude/hooks.md\n"
  },
  {
    "path": "COLLABORATORS.md",
    "content": "# Apollo OSS Collaborator Guidelines\n\nThanks for helping make Apollo OSS better! Here are a few quick repo maintenance guidelines intended to help keep Apollo projects happy and healthy.\n\n## Overall\n\n- Please remember to be polite and respectful to all community members, no matter what is being reported, contributed, etc. People who are taking time out of their lives to participate in the Apollo ecosystem should feel welcomed, included and appreciated.\n\n## Issues\n\n- Issues are for bugs only. All other requests should be redirected accordingly, then closed. Feature requests have their own [repo](https://github.com/apollographql/apollo-feature-requests), and requests for help should go to [our community forums](https://community.apollographql.com) or [Stack Overflow](http://stackoverflow.com).\n- If a bug report is valid, add the `confirmed` label, and optionally decide if community help should be requested using the `help-wanted` label. If you’re planning on working on it, assign the issue to yourself.\n- If an issue isn’t easily reproducible, ask for a reproduction and add a `reproduction-needed` label.\n- If a reproduction has been asked for but hasn’t been received in 1 week, close the issue.\n\n## Pull Requests\n\n- Ensure PR’s have tests (when it makes sense, which is almost always).\n- Make sure `CHANGELOG`’s are updated/maintained. Either request that the PR author adds a `CHANGELOG` entry, or add one yourself. Make sure the PR is referenced along with their GitHub username, and link to their profile (to give them extra kudos).\n- Don’t forget to consider how a PR you’re merging will affect the docs; either ask contributors for docs changes, open a new issue to track outstanding changes, or consider implementing the docs changes yourself.\n- Always think about backwards compatibility; please don’t merge PR’s that require major version bumps, unless talking it over with the core team.\n- If the PR has a small number of commits, or a large number of semantically unimportant commits, squash and merge the PR. If the PR commits are well thought out, isolated and would add value to the git history if kept separate, do a merge commit.\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Apollo Contributor Guide\n\nExcited about Apollo and want to make it better? We’re excited too!\n\nApollo is a community of developers just like you, striving to create the best tools and libraries around GraphQL. We welcome anyone who wants to contribute or provide constructive feedback, no matter the age or level of experience. If you want to help but don't know where to start, let us know, and we'll find something for you.\n\nOh, and if you haven't already, join our [community forums](https://community.apollographql.com).\n\nHere are some ways to contribute to the project, from easiest to most difficult:\n\n- [Issues](#issues)\n  - [Reporting bugs](#reporting-bugs)\n  - [Improving the documentation](#improving-the-documentation)\n  - [Responding to issues](#responding-to-issues)\n  - [Changesets](#changesets)\n  - [Small bug fixes](#small-bug-fixes)\n  - [Suggesting features](#suggesting-features)\n- [Big PRs](#big-prs)\n  - [Code review guidelines](#code-review-guidelines)\n- [Development](#development)\n  - [Building](#building)\n  - [Testing](#testing)\n  - [Wiring a checkout into an application](#wiring-a-checkout-into-an-application)\n\n## Issues\n\n### Reporting bugs\n\nIf you encounter a bug, please file an issue on GitHub via the repository of the sub-project you think contains the bug. If an issue you have is already reported, please add additional information or add a 👍 reaction to indicate your agreement.\n\nWhile we will try to be as helpful as we can on any issue reported, please include the following to maximize the chances of a quick fix:\n\n1. **Intended outcome:** What you were trying to accomplish when the bug occurred, and as much code as possible related to the source of the problem.\n2. **Actual outcome:** A description of what actually happened, including a screenshot or copy-paste of any related error messages, logs, or other output that might be related. Places to look for information include your browser console, server console, and network logs. Please avoid non-specific phrases like “didn’t work” or “broke”.\n3. **How to reproduce the issue:** Instructions for how the issue can be reproduced by a maintainer or contributor. Be as specific as possible, and only mention what is necessary to reproduce the bug. If possible, build a reproduction with our [error template](https://github.com/apollographql/react-apollo-error-template) to isolate the exact circumstances in which the bug occurs. Avoid speculation over what the cause might be.\n\nCreating a good reproduction really helps contributors investigate and resolve your issue quickly. In many cases, the act of creating a minimal reproduction illuminates that the source of the bug was somewhere outside the library in question, saving time and effort for everyone.\n\n### Improving the documentation\n\nImproving the documentation, examples, and other open source content can be the easiest way to contribute to the library. If you see a piece of content that can be better, open a PR with an improvement, no matter how small! If you would like to suggest a big change or major rewrite, we’d love to hear your ideas! Please open a feature request for discussion, over in the [Apollo Client Feature Request repo](https://github.com/apollographql/apollo-feature-requests), before writing the PR.\n\n### Responding to issues\n\nIn addition to reporting issues, a great way to contribute to Apollo is to respond to other peoples' issues and try to identify the problem or help them work around it. If you’re interested in taking a more active role in this process, please go ahead and respond to issues. And don't forget to say \"Hi\" in our [community forums](https://community.apollographql.com)!\n\n### Changesets\n\nApollo Client uses [changesets](https://github.com/changesets/changesets) to automate its versioning and release process. When contributing to Apollo Client, your PR should contain a \"changeset\" that can be generated by running `npx changeset` from your branch locally.\n\nThe changeset CLI will ask you to enter the corresponding [semver bump type](https://semver.org/) and a description of your changes: feel free to enter a brief description via the command line and continue editing the generated Markdown file found inside of `.changeset` in your editor of choice. When editing your changeset's Markdown file, you can leverage any of the features of GitHub flavored markdown! The description you provide in your changeset will be used to generate an entry in `CHANGELOG.md` and the release notes in a future release, so the more complete and descriptive the better.\n\n### Small bug fixes\n\nFor a small bug fix change (less than 20 lines of code changed), feel free to open a pull request. We’ll try to merge it as fast as possible and ideally publish a new release on the same day. The only requirement is, make sure you also add a test that verifies the bug you are trying to fix.\n\n### Suggesting features\n\nMost of the features in Apollo Client came from suggestions by you, the community! We welcome any ideas about how to make Apollo better for your use case. Head on over to the [Apollo Client Feature Request repo](https://github.com/apollographql/apollo-feature-requests), and open up a new feature request / discussion issue with your details.\n\n**Note:** Feature requests and non-bug related discussions are no longer managed in this repo's issue tracker. Feature request and/or discussions opened here will be closed.\n\n## Big PRs\n\nThis includes:\n\n- Big bug fixes\n- New features\n\nFor significant changes to a repository, it’s important to settle on a design before starting on the implementation. This way, we can make sure that major improvements get the care and attention they deserve. Since big changes can be risky and might not always get merged, it’s good to reduce the amount of possible wasted effort by agreeing on an implementation design/plan first.\n\n1. **Open an issue.** Open an issue about your bug in this repo, or about your feature request in the [Apollo Client Feature Request repo](https://github.com/apollographql/apollo-feature-requests).\n2. **Reach consensus.** Some contributors and community members should reach an agreement that this feature or bug is important, and that someone should work on implementing or fixing it.\n3. **Agree on intended behavior.** On the issue, reach an agreement about the desired behavior. In the case of a bug fix, it should be clear what it means for the bug to be fixed, and in the case of a feature, it should be clear what it will be like for developers to use the new feature.\n4. **Agree on implementation plan.** Write a plan for how this feature or bug fix should be implemented. What modules need to be added or rewritten? Should this be one pull request or multiple incremental improvements? Who is going to do each part?\n5. **Submit PR.** In the case where multiple dependent patches need to be made to implement the change, only submit one at a time. Otherwise, the others might get stale while the first is reviewed and merged. Make sure to avoid “while we’re here” type changes - if something isn’t relevant to the improvement at hand, it should be in a separate PR; this especially includes code style changes of unrelated code.\n6. **Review.** At least one core contributor should sign off on the change before it’s merged. Look at the “code review” section below to learn about factors are important in the code review. If you want to expedite the code being merged, try to review your own code first!\n7. **Merge and release!**\n\n### Code review guidelines\n\nIt’s important that every piece of code in Apollo packages is reviewed by at least one core contributor familiar with that codebase. Here are some things we look for:\n\n1. **Required CI checks pass.** This is a prerequisite for the review, and it is the PR author's responsibility. As long as the tests don’t pass, the PR won't get reviewed.\n2. **Simplicity.** Is this the simplest way to achieve the intended goal? If there are too many files, redundant functions, or complex lines of code, suggest a simpler way to do the same thing. In particular, avoid implementing an overly general solution when a simple, small, and pragmatic fix will do.\n3. **Testing.** Do the tests ensure this code won’t break when other stuff changes around it? When it does break, will the tests added help us identify which part of the library has the problem? Did we cover an appropriate set of edge cases? Look at the test coverage report if there is one. Are all significant code paths in the new code exercised at least once?\n4. **No unnecessary or unrelated changes.** PRs shouldn’t come with random formatting changes, especially in unrelated parts of the code. If there is some refactoring that needs to be done, it should be in a separate PR from a bug fix or feature, if possible.\n5. **Code has appropriate comments.** Code should be commented, or written in a clear “self-documenting” way.\n6. **Idiomatic use of the language.** In TypeScript, make sure the typings are specific and correct. In ES2015, make sure to use imports rather than require and const instead of var, etc. Ideally a linter enforces a lot of this, but use your common sense and follow the style of the surrounding code.\n\n## Development\n\n### Building\n\n**Build Apollo Client once:**\n\n```\nnpm run build\n```\n\n### Testing\n\n**Run all tests once:**\n\n```\nnpm run test\n```\n\n**Run all tests in watch mode:**\n\n```\nnpm run test:watch\n```\n\n**Run specific tests:**\n\nCall jest directly making sure to pass in the jest config, and use its `testRegex` option:\n\n```\njest --config ./config/jest.config.ts --testRegex __tests__/useQuery.test.tsx\n```\n\n### Wiring a checkout into an application\n\nIt can be useful to link an Apollo Client checkout into an application, to test how Apollo Client development changes impact a real app. We'll use the [Apollo fullstack tutorial application](https://github.com/apollographql/fullstack-tutorial) to demonstrate this.\n\n1. Clone and install Apollo Client.\n\n```\ngit clone https://github.com/apollographql/apollo-client.git\ncd apollo-client\nnpm i\ncd ..\n```\n\n> From this point forward `[apollo-client-root]` represents the root directory of your Apollo Client checkout (e.g. `/some/path/apollo-client`).\n\n2. Clone and install the fullstack tutorial.\n\n```\ngit clone https://github.com/apollographql/fullstack-tutorial.git\ncd fullstack-tutorial\ncd final/server\nnpm i\ncd ../client\nnpm i\n```\n\n> From this point forward `[fullstack-tutorial-root]` represents the root directory of your Fullstack Tutorial checkout (e.g. `/some/path/fullstack-tutorial`).\n\n3. Link the application's `@apollo/client` package to your Apollo Client checkout's compiled files.\n\n```\n# ... assuming still in [fullstack-tutorial-root]/final/client from step 2\ncd node_modules/@apollo\nrm -Rf ./client\nln -s [apollo-client-root]/dist client\n```\n\n4. If using React, prevent a duplicate React version lookup error by telling your application to use Apollo Client's React version.\n\n```\n# ... assuming still in [fullstack-tutorial-root]/final/client/node_modules/@apollo from step 3\ncd ..\nrm -Rf ./react ./react-dom\nln -s [apollo-client-root]/node_modules/react\nln -s [apollo-client-root]/node_modules/react-dom\n```\n\n5. Start the fullstack tutorial.\n\nServer:\n\n```\n# ... assuming still in [fullstack-tutorial-root]/final/client/node_modules from step 4\ncd ../../server\nnpm start\n```\n\nClient:\n\n```\n# ... in a separate terminal window\ncd [fullstack-tutorial-root]/final/client\nnpm start\n```\n\n6. Start building Apollo Client and watching for file changes.\n\n```\n# ... in a separate terminal window\ncd [apollo-client-root]\nnpm run watch\n```\n\n7. Verify Apollo Client changes show up in the fullstack tutorial.\n\n```\n# ... assuming still in [apollo-client-root] from step 6\ncd src\necho \"console.log('it worked');\" >> index.ts\n```\n\nVisit http://localhost:3000/ and open your browsers dev console. After the Apollo Client rebuild finishes, you should see `it worked` in the console.\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2022 Apollo Graph, Inc. (Formerly Meteor Development Group, Inc.)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n"
  },
  {
    "path": "README.md",
    "content": "<header>\n  <div align=\"center\">\n    <a href=\"https://www.apollographql.com?utm_medium=github&utm_source=apollographql_apollo-client&utm_campaign=readme\"><img src=\"https://raw.githubusercontent.com/apollographql/apollo-client-devtools/main/assets/apollo-wordmark.svg\" height=\"100\" alt=\"Apollo Logo\"></a>\n  </div>\n  <h1 align=\"center\">Apollo Client</h1>\n\n**The industry-leading GraphQL client for TypeScript, JavaScript, React, Vue, Angular, and more.** Apollo Client delivers powerful caching, intuitive APIs, and comprehensive developer tools to accelerate your app development.\n\n➡️ [**Get Started with Apollo Client →**](https://www.apollographql.com/docs/react/get-started?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)\n\n  <div align=\"center\">\n\n[![npm version](https://badge.fury.io/js/%40apollo%2Fclient.svg)](https://badge.fury.io/js/%40apollo%2Fclient) [![Build Status](https://circleci.com/gh/apollographql/apollo-client.svg?style=svg)](https://circleci.com/gh/apollographql/apollo-client) [![Join the community](https://img.shields.io/discourse/status?label=Join%20the%20community&server=https%3A%2F%2Fcommunity.apollographql.com)](https://community.apollographql.com)\n\n  </div>\n</header>\n\n## ❓ Why Choose Apollo Client?\n\n✅ Zero-config caching - Intelligent caching out of the box<br>\n✅ Framework agnostic - Works with React, Vue, Angular, Svelte, and vanilla JavaScript<br>\n✅ TypeScript-first - Full type safety and IntelliSense support<br>\n✅ React 19 ready - Supports Suspense, RSC, Compiler, and more<br>\n✅ Production-tested - Powers countless apps worldwide that serve millions of end users<br>\n\n## 🚀 Quick Start\n\n```sh\nnpm install @apollo/client graphql\n```\n\n## Apollo Client Skill\n\nGive your AI agent specialized Apollo Client knowledge and setup guidance:\n\n```sh\nnpx skills add apollographql/skills --skill apollo-client\n```\n\n## 💡 Resources\n\n| Resource                  | Description                       | Link                                                                                                                                                                                             |\n| ------------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| **Getting Started Guide** | Complete setup and first query    | [Start Here →](https://www.apollographql.com/docs/react/get-started?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)                                                |\n| **Full Documentation**    | Comprehensive guides and examples | [Read Docs →](https://www.apollographql.com/docs/react?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)                                                             |\n| **API Reference**         | Complete API documentation        | [Browse API →](https://www.apollographql.com/docs/react/api/apollo-client?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)                                          |\n| **VS Code Extension**     | Enhanced development experience   | [Install Extension →](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo)                                                                                           |\n| **DevTools**              | Debug your GraphQL apps           | [Chrome](https://chrome.google.com/webstore/detail/apollo-client-devtools/jdkknkkbebbapilgoeccciglkfbmbnfm) \\| [Firefox](https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/) |\n| **Free Course**           | Learn GraphQL and Apollo Client   | [Take Course →](https://odyssey.apollographql.com?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)                                                                  |\n\n## 💬 Get Support\n\n**Need help?** We're here for you:\n\n- [**Community Forum**](https://community.apollographql.com?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- Q\\&A and discussions\n- [**GraphQL Discord**](https://discord.graphql.org) \\- Real-time chat with the community\n\n## 🧑‍🚀 About Apollo\n\nDeliver tomorrow's roadmap today with our comprehensive suite of API orchestration tools:\n\n- [**Apollo Client**](https://www.apollographql.com/docs/react?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- Type-safe apps with GraphQL-powered on-device caching ([React](https://www.apollographql.com/docs/react?utm_medium=github&utm_source=apollographql_apollo-client&utm_campaign=readme), [iOS](https://www.apollographql.com/docs/ios?utm_medium=github&utm_source=apollographql_apollo-client&utm_campaign=readme), [Kotlin](https://www.apollographql.com/docs/kotlin?utm_medium=github&utm_source=apollographql_apollo-client&utm_campaign=readme))\n- [**Apollo Connectors**](https://www.apollographql.com/graphos/apollo-connectors?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- Compose all your GraphQL and REST APIs into one GraphQL endpoint\n- [**Apollo MCP Server**](https://www.apollographql.com/apollo-mcp-server?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- AI needs APIs. The fastest way to ship reliable AI experiences\n- [**Apollo Router**](https://www.apollographql.com/docs/router?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- Scale your APIs seamlessly with GraphQL Federation, Security, Auth, and more\n- [**GraphOS**](https://www.apollographql.com/graphos?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme) \\- Deploy, manage, govern, and explore your APIs ([start for free, no credit card needed](https://www.apollographql.com/pricing?utm_medium=github&utm_source=apollographql_apollo-client&utm_campaign=readme))\n\n[**Explore the Complete Apollo Platform →**](https://www.apollographql.com/?utm_source=github&utm_medium=apollographql-_apollo-client&utm_campaign=readme)\n\n## 🛠️ Maintained by\n\n| Name              | Username                                       |\n| ----------------- | ---------------------------------------------- |\n| Jeff Auriemma     | [@bignimbus](https://github.com/bignimbus)     |\n| Jerel Miller      | [@jerelmiller](https://github.com/jerelmiller) |\n| Lenz Weber-Tronic | [@phryneas](https://github.com/phryneas)       |\n\n## Versioning Policy\n\nWhile Apollo Client follows SemVer, it might introduce changes like changing transpilation targets, updating dependencies or dropping support for older versions of dependencies in minor releases. For more details, see our [Versioning Policy](./VERSIONING_POLICY.md).\n\n## 🗺️ Roadmap\n\nWe regularly update our [public roadmap](https://github.com/apollographql/apollo-client/blob/main/ROADMAP.md) with the status of our work-in-progress and upcoming features.\n\n## 📣 Tell us what you think\n\n| ☑️ Apollo Client User Survey                                                                                                                                                                                                                                                                                                                                                             |\n| :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| What do you like best about Apollo Client? What needs to be improved? Please tell us by taking a [one-minute survey](https://docs.google.com/forms/d/e/1FAIpQLSczNDXfJne3ZUOXjk9Ursm9JYvhTh1_nFTDfdq3XBAFWCzplQ/viewform?usp=pp_url&entry.1170701325=Apollo+Client&entry.204965213=Readme). Your responses will help us understand Apollo Client usage and allow us to serve you better. |\n\n## 🗓️ Events\n\nJoin these live events to meet other GraphQL users and learn more:\n\n🎪 [**GraphQL Summit 2025**](https://summit.graphql.com?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)\nOct 6-8, 2025 • San Francisco\n_1000+ engineers, talks, workshops, and office hours_\n\n🌟 [**GraphQLConf 2025**](https://graphql.org/conf/2025)\nSep 8-10, 2025 • Amsterdam\n_Celebrating 10 Years of GraphQL_\n\n[**View All Events →**](https://www.apollographql.com/events?utm_source=github&utm_medium=apollographql_apollo-client&utm_campaign=readme)\n\n## 🏆 Contributing\n\nThank you for your interest in submitting a Pull Request to Apollo Client! Read our [guidelines](https://github.com/apollographql/apollo-client/blob/main/CONTRIBUTING.md) first, and don't hesitate to get in touch.\n\n**New to open source?** Check out our [**Good First Issues**](https://github.com/apollographql/apollo-client/issues?q=is%3Aopen%20label%3A%22%3Abooks%3A%20good-first-issue%22) to get started.\n\n## 🤝 Code of Conduct\n\nPlease read our [Code of Conduct](https://community.apollographql.com/faq). This applies to any space run by Apollo, including our GitHub repositories, the Apollo GraphOS Discord, the Apollo GraphQL Forum. The Code of Conduct reflects our commitment to making the Apollo Community a welcoming and safe space in which individuals can interact.\n\n## 🪪 License\n\nSource code in this repository is available under the terms of the MIT License. Read the full text [here](https://github.com/apollographql/apollo-client/blob/main/LICENSE).\n"
  },
  {
    "path": "ROADMAP.md",
    "content": "# 🔮 Apollo Client Ecosystem Roadmap\n\nFor up to date release notes, refer to the project's [Changelog](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md).\n\n> **Please note:** This is an approximation of **larger effort** work planned for the next 6 - 12 months. It does not cover all new functionality that will be added, and nothing here is set in stone. Also note that each of these releases, and several patch releases in-between, will include bug fixes (based on issue triaging) and community submitted PRs.\n\n## ✋ Community feedback & prioritization\n\n- Please report feature requests or bugs as a new [issue](https://github.com/apollographql/apollo-client/issues/new/choose).\n- If you already see an issue that interests you please add a 👍 or a comment so we can measure community interest.\n\n---\n\n## Ecosystem\n\n### Apollo Client\n\n_No planned work_\n\n### GraphQL Testing Library\n\n_No planned work_\n\n### VSCode Extension\n\n_No planned work_\n\n### GraphQL Tag\n\n_No planned work_\n\n### Apollo Client DevTools\n\n- Support for inspecting Apollo Client instances in iframes\n\n### Apollo Client React Framework Integrations\n\n- Client integration documentation\n\n**TanStack Start**\n\n- Support for Apollo Client Streaming in TanStack Start - will stay release candidate\n\n**React Router**\n\n- Support for Apollo Client Streaming in React Router 7 - will stay alpha\n"
  },
  {
    "path": "VERSIONING_POLICY.md",
    "content": "# Apollo Client Versioning Policy\n\nApollo Client tries to follow SemVer versioning.\n\nHowever, we reserve the right to change transpilation targets, drop polyfills or update required dependencies. These changes will be released in minor versions.\nThis is to ensure that Apollo Client can take advantage of the latest JavaScript features, performance improvements, and security fixes.\n\nThis document outlines the versioning strategy for Apollo Client's dependencies.\n\n## Syntax transpilation target\n\nThe current transpilation target for Apollo Client is `@babel/preset-env` with the `browserlist` target `since 2023, node >= 20, not dead`.\n\nThat means Apollo Client supports the following environments and their derivatives:\n\n| Environment      | Version |\n| ---------------- | ------- |\n| Chrome           | 97+     |\n| Firefox          | 96+     |\n| Edge             | 97+     |\n| Safari           | 15.4+   |\n| Opera            | 83+     |\n| Samsung Internet | 17+     |\n| Node.js          | 20+     |\n\nUsing Apollo Client in different environments may require you to transpile the syntax using a lower version, or polyfilling missing APIs.\n\nWe reserve the right to update the transpilation target in minor releases, but we commit to always include at least two years of browser support and the officially supported Node.js versions in the target.\n\n## Language features\n\nApollo Client might start using new APIs and language features that are considered [\"Baseline: Widely available\"](https://developer.mozilla.org/en-US/docs/Glossary/Baseline/Compatibility) by MDN. Usage of new language features will be released in a new minor version.\n\n### Non-polyfillable, non-transpilable language features\n\nWe try to avoid new features that cannot be transpiled or polyfilled.\n\nHowever, we consider the following features to be supported widely enough that Apollo Client can use them at any time without considering it a major breaking change.\n\n- [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) (already used in Apollo Client)\n- [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) (already used in Apollo Client)\n- [`WeakRef`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef) (already used by dependencies)\n- [`FinalizationRegistry`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry) (already used by dependencies)\n- [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)\n\n> [!NOTE]\n> Not all of the these features are currently used at this time. Usage of these features might fluctuate between minor versions.\n\n## TypeScript types\n\nWe reserve the right to update TypeScript types as needed, such as to fix bugs, align types with actual runtime behavior or add compatibility with changes in upcoming TypeScript versions.\nUpdates to types might requires changes to your application, and while we are careful to keep such changes to a minimum, we do not consider these breaking changes in the sense of SemVer.\n\n## Dependencies\n\n### TypeScript\n\nWe make an effort to only use TypeScript features that have been available as stable for at least one year. This generally means we support the [last four minor versions](https://github.com/microsoft/TypeScript/wiki/TypeScript%27s-Release-Process#how-often-does-typescript-release) of TypeScript. If you use a TypeScript version older than these, you might experience some type compatibility issues with Apollo Client.\n\n> Note that this is a shorter support window than [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped#support-window).\n\nHowever, we reserve the right to use newer syntax in new features, in a way that doesn't break compilation with older TypeScript versions. These new features might not be available to consumers on older TypeScript versions.\n\n### React\n\nWe aim to support, at minimum, the latest two major versions of React.\nSome Apollo Client features might require the latest major version of React and won't be available to consumers on older React versions (e.g. `useSuspenseQuery` which relies on React Suspense).\n\nWe will note when such a case occurs so that you understand when a feature requires a specific React version.\n\n> Please note that the React team almost never backports bugfixes to older major versions. From time to time, you might encounter bugs when using Apollo Client caused by React itself that are fixed in recent React versions, but are unavailable in older major versions. We strongly recommend you keep up-to-date with the latest React version.\n\n### React Native\n\nWe try to support, at minimum, the latest version of React Native. Note that React Native relies on many polyfills that might differ from the implementations of other platforms. Some polyfills might also be missing.\n\nWhere possible, we try to avoid using APIs that are not available in React Native.\nIf an API is not available, we will try to provide workarounds using the [`react-native` exports condition](https://reactnative.dev/blog/2023/06/21/package-exports-support#the-new-react-native-condition).\n\n### The `graphql` package\n\nWe commit to supporting the latest major version of the `graphql` package, with a grace period of at least one year before we drop support for older versions.\n\nWithin a `graphql` major, we only guarantee compatibility with the latest minor version. We strongly encourage consumers to regularly update the `graphql` package to get the latest bugfixes and features.\n\n### Other dependencies\n\nWe reserve the right to update dependencies in minor releases of Apollo Client, as well as dropping support for older versions of dependencies.\n\n### Peer dependencies\n\nThe rules stated above apply to peer dependencies as well. Peer dependencies can be updated in minor releases, just like regular dependencies.\nHowever, we do commit to not adding new peer dependencies during the lifetime of a major - but if an existing peer dependency is renamed, we might follow that rename in a minor release.\n"
  },
  {
    "path": "api-extractor.json",
    "content": "/**\n * Config file for API Extractor.  For more info, please visit: https://api-extractor.com\n */\n{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json\",\n  \"projectFolder\": \".\",\n  \"mainEntryPointFilePath\": \"<projectFolder>/dist/core/index.d.ts\",\n  \"bundledPackages\": [\"@apollo/client\"],\n  \"newlineKind\": \"lf\",\n  \"enumMemberOrder\": \"preserve\",\n\n  /**\n   * Set to true when invoking API Extractor's test harness. When `testMode` is true, the `toolVersion` field in the\n   * .api.json file is assigned an empty string to prevent spurious diffs in output files tracked for tests.\n   *\n   * DEFAULT VALUE: \"false\"\n   */\n  // \"testMode\": false,\n\n  /**\n   * Determines how the TypeScript compiler engine will be invoked by API Extractor.\n   */\n  \"compiler\": {\n    \"overrideTsconfig\": { \"compilerOptions\": { \"lib\": [\"ESNext\"] } },\n    \"skipLibCheck\": true\n  },\n\n  /**\n   * Configures how the API report file (*.api.md) will be generated.\n   */\n  \"apiReport\": {\n    \"enabled\": true,\n    \"reportFileName\": \"<unscopedPackageName>.api.md\",\n    \"reportFolder\": \"<projectFolder>/.api-reports/\",\n    \"reportTempFolder\": \"<projectFolder>/.api-reports/temp/\",\n    \"includeForgottenExports\": true\n  },\n\n  \"docModel\": {\n    \"enabled\": false,\n    \"apiJsonFilePath\": \"<projectFolder>/docs/public/<unscopedPackageName>.api.json\",\n    \"includeForgottenExports\": true\n  },\n\n  \"dtsRollup\": {\n    \"enabled\": false\n  },\n  \"tsdocMetadata\": {\n    \"enabled\": false,\n    \"tsdocMetadataFilePath\": \"<projectFolder>/docs/public/tsdoc-metadata.json\"\n  },\n\n  /**\n   * Configures how API Extractor reports error and warning messages produced during analysis.\n   *\n   * There are three sources of messages:  compiler messages, API Extractor messages, and TSDoc messages.\n   */\n  \"messages\": {\n    /**\n     * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing\n     * the input .d.ts files.\n     *\n     * TypeScript message identifiers start with \"TS\" followed by an integer.  For example: \"TS2551\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"compilerMessageReporting\": {\n      /**\n       * Configures the default routing for messages that don't match an explicit rule in this table.\n       */\n      \"default\": {\n        /**\n         * Specifies whether the message should be written to the the tool's output log.  Note that\n         * the \"addToApiReportFile\" property may supersede this option.\n         *\n         * Possible values: \"error\", \"warning\", \"none\"\n         *\n         * Errors cause the build to fail and return a nonzero exit code.  Warnings cause a production build fail\n         * and return a nonzero exit code.  For a non-production build (e.g. when \"api-extractor run\" includes\n         * the \"--local\" option), the warning is displayed but the build will not fail.\n         *\n         * DEFAULT VALUE: \"warning\"\n         */\n        \"logLevel\": \"warning\"\n\n        /**\n         * When addToApiReportFile is true:  If API Extractor is configured to write an API report file (.api.md),\n         * then the message will be written inside that file; otherwise, the message is instead logged according to\n         * the \"logLevel\" option.\n         *\n         * DEFAULT VALUE: false\n         */\n        // \"addToApiReportFile\": false\n      }\n\n      // \"TS2551\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by API Extractor during its analysis.\n     *\n     * API Extractor message identifiers start with \"ae-\".  For example: \"ae-extra-release-tag\"\n     *\n     * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings\n     */\n    \"extractorMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"warning\"\n        // \"addToApiReportFile\": false\n      },\n\n      \"ae-missing-release-tag\": {\n        \"logLevel\": \"none\"\n      },\n\n      \"ae-internal-missing-underscore\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      },\n\n      \"ae-unresolved-link\": {\n        \"logLevel\": \"warning\",\n        \"addToApiReportFile\": true\n      }\n    },\n    \"tsdocMessageReporting\": {\n      \"tsdoc-escape-greater-than\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "codegen/CHANGELOG.md",
    "content": "# @apollo/client-graphql-codegen\n\n## 2.0.0\n\n### Major Changes\n\n- [#13014](https://github.com/apollographql/apollo-client/pull/13014) [`b9a1964`](https://github.com/apollographql/apollo-client/commit/b9a19647442842d1192a67bfded3bd8b27952832) Thanks [@phryneas](https://github.com/phryneas)! - bump upstream dependencies by major version\n\n## 1.0.0\n\n### Major Changes\n\n- [#12617](https://github.com/apollographql/apollo-client/pull/12617) [`ea633a1`](https://github.com/apollographql/apollo-client/commit/ea633a110b7ffa138a33f68a0b41b0437aee61d8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduce a new GraphQL Codegen plugin aimed at creating resolver types for `LocalState`. This plugin is similar to `@graphql-codegen/typescript-resolvers` but tailored to provide types that work with `LocalState`.\n\n  To use the plugin, install `@apollo/client-graphql-codegen` and add the following to your codegen config:\n\n  ```ts\n  // codegen.ts\n\n  const config: CodegenConfig = {\n    // ...\n    generates: {\n      \"./path/to/local/resolvers.ts\": {\n        schema: [\"./path/to/localSchema.graphql\"],\n        plugins: [\"typescript\", \"@apollo/client-graphql-codegen/local-state\"],\n        // ...\n      },\n    },\n  };\n  ```\n\n  This will generate a `Resolvers` type in the generated file that can be used to provide type information to `LocalState`.\n\n  ```ts\n  import type { Resolvers } from \"./path/to/resolvers-types.ts\";\n\n  const localState = new LocalState<Resolvers>({\n    // ...\n  });\n  ```\n\n  It is also recommended to add the following config:\n\n  ```ts\n  // codegen.ts\n  import type { LocalStatePluginConfig } from \"@apollo/client-graphql-codegen/local-state\";\n\n  const config: CodegenConfig = {\n    // ...\n    generates: {\n      \"./path/to/local/resolvers.ts\": {\n        config: {\n          // Ensures you return a `__typename` for any `@client` fields that\n          // return object or array types\n          nonOptionalTypename: true,\n\n          // Required if your localSchema extends existing schema types.\n          baseTypesPath: \"./relative/path/to/base/schema/types\",\n\n          // If you provide a `context` function to customize the context value,\n          // provide the path or type here.\n          contextType: \"./path/to/contextValue#ContextValue\",\n        } satisfies LocalStatePluginConfig,\n      },\n    },\n  };\n  ```\n\n  NOTE: It is recommended that the schema file passed to the `schema` option is your local schema, not your entire app schema in order to only generate resolver types for your local fields, otherwise the plugin will generate resolver types for your entire remote schema as well.\n\n- [#12723](https://github.com/apollographql/apollo-client/pull/12723) [`1f9ed72`](https://github.com/apollographql/apollo-client/commit/1f9ed7200a249676e3efec6b61814376f47ce596) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only for codegen to release as `rc`.\n\n## 1.0.0-rc.0\n\n### Major Changes\n\n- [#12723](https://github.com/apollographql/apollo-client/pull/12723) [`1f9ed72`](https://github.com/apollographql/apollo-client/commit/1f9ed7200a249676e3efec6b61814376f47ce596) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Version bump only for codegen to release as `rc`.\n\n## 1.0.0-alpha.0\n\n### Major Changes\n\n- [#12617](https://github.com/apollographql/apollo-client/pull/12617) [`ea633a1`](https://github.com/apollographql/apollo-client/commit/ea633a110b7ffa138a33f68a0b41b0437aee61d8) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Introduce a new GraphQL Codegen plugin aimed at creating resolver types for `LocalState`. This plugin is similar to `@graphql-codegen/typescript-resolvers` but tailored to provide types that work with `LocalState`.\n\n  To use the plugin, install `@apollo/client-graphql-codegen` and add the following to your codegen config:\n\n  ```ts\n  // codegen.ts\n\n  const config: CodegenConfig = {\n    // ...\n    generates: {\n      \"./path/to/local/resolvers.ts\": {\n        schema: [\"./path/to/localSchema.graphql\"],\n        plugins: [\"typescript\", \"@apollo/client-graphql-codegen/local-state\"],\n        // ...\n      },\n    },\n  };\n  ```\n\n  This will generate a `Resolvers` type in the generated file that can be used to provide type information to `LocalState`.\n\n  ```ts\n  import type { Resolvers } from \"./path/to/resolvers-types.ts\";\n\n  const localState = new LocalState<Resolvers>({\n    // ...\n  });\n  ```\n\n  It is also recommended to add the following config:\n\n  ```ts\n  // codegen.ts\n  import type { LocalStatePluginConfig } from \"@apollo/client-graphql-codegen/local-state\";\n\n  const config: CodegenConfig = {\n    // ...\n    generates: {\n      \"./path/to/local/resolvers.ts\": {\n        config: {\n          // Ensures you return a `__typename` for any `@client` fields that\n          // return object or array types\n          nonOptionalTypename: true,\n\n          // Required if your localSchema extends existing schema types.\n          baseTypesPath: \"./relative/path/to/base/schema/types\",\n\n          // If you provide a `context` function to customize the context value,\n          // provide the path or type here.\n          contextType: \"./path/to/contextValue#ContextValue\",\n        } satisfies LocalStatePluginConfig,\n      },\n    },\n  };\n  ```\n\n  NOTE: It is recommended that the schema file passed to the `schema` option is your local schema, not your entire app schema in order to only generate resolver types for your local fields, otherwise the plugin will generate resolver types for your entire remote schema as well.\n"
  },
  {
    "path": "codegen/local-state/config.ts",
    "content": "/**\n * Adapted from\n * https://github.com/dotansimha/graphql-code-generator/blob/master/packages/plugins/typescript/resolvers/src/config.ts\n *\n * https://github.com/dotansimha/graphql-code-generator/blob/master/LICENSE\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Dotan Simha\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND ONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport type {\n  AvoidOptionalsConfig,\n  RawConfig,\n} from \"@graphql-codegen/visitor-plugin-common\";\n\n/**\n * This plugin generates TypeScript signature for `resolve` functions of your GraphQL API.\n * You can use this plugin to generate simple resolvers signature based on your GraphQL types, or you can change its behavior be providing custom model types (mappers).\n *\n * You can find a blog post explaining the usage of this plugin here: https://the-guild.dev/blog/better-type-safety-for-resolvers-with-graphql-codegen\n */\nexport interface LocalStatePluginConfig extends RawConfig {\n  /**\n   * Path to base schema types used to import schema type definitions for\n   * extended types in your local schema. This is required if your schema type\n   * definitions defines an extended type (i.e. `extend type User {...}`).\n   *\n   * @example\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\"typescript\", \"@apollo/client/local-state/codegen\"],\n   *       config: {\n   *         baseTypesPath: \"./relative/path/to/schema/types\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  baseTypesPath?: string;\n\n  /**\n   * The import name for the base schema types.\n   *\n   * @defaultValue BaseSchemaTypes\n   *\n   * @example\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\"typescript\", \"@apollo/client/local-state/codegen\"],\n   *       config: {\n   *         baseSchemaTypesImportName: \"MyBaseSchemaTypes\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  baseSchemaTypesImportName?: string;\n\n  /**\n   * This will cause the generator to avoid using optionals (`?`),\n   * so all field resolvers must be implemented in order to avoid compilation errors.\n   * @defaultValue false\n   *\n   * @example\n   *\n   * ## Override all definition types\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\"typescript\", \"@apollo/client/local-state/codegen\"],\n   *       config: {\n   *         avoidOptionals: true,\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   *\n   * ## Override only specific definition types\n   *\n   * ```ts filename=\"codegen.ts\"\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\"typescript\", \"@apollo/client/local-state/codegen\"],\n   *       config: {\n   *         avoidOptionals: {\n   *           field: true,\n   *           inputValue: true,\n   *           object: true,\n   *           defaultValue: true,\n   *           query: true,\n   *           mutation: true,\n   *           subscription: true,\n   *         },\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  avoidOptionals?: boolean | AvoidOptionalsConfig;\n\n  /**\n   * Adds `_` to generated `Args` types in order to avoid duplicate identifiers.\n   *\n   * @example\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         addUnderscoreToArgsType: true,\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  addUnderscoreToArgsType?: boolean;\n  /**\n   * Use this configuration to set a custom type for your `context`, and it will\n   * affect all the resolvers, without the need to override it using generics each time.\n   * If you wish to use an external type and import it from another file, you can use `add` plugin\n   * and add the required `import` statement, or you can use a `module#type` syntax.\n   *\n   * @example\n   *\n   * ## Custom Context Type\n   *\n   * ```ts filename=\"codegen.ts\"\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         contextType: \"MyContext\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   *\n   * ## Custom Context Type by Path\n   *\n   * Note that the path should be relative to the generated file.\n   *\n   * ```ts filename=\"codegen.ts\"\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         contextType: \"./my-types#MyContext\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  contextType?: string;\n  /**\n   * Adds a suffix to the imported names to prevent name clashes.\n   *\n   * @example\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         mapperTypeSuffix: \"Model\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  mapperTypeSuffix?: string;\n  /**\n   * Replaces a GraphQL type usage with a custom type, allowing you to return custom object from\n   * your resolvers.\n   * You can use both `module#type` and `module#namespace#type` syntax.\n   *\n   * @example\n   *\n   * ## Custom Context Type\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         mappers: {\n   *           User: \"./my-models#UserDbObject\",\n   *           Book: \"./my-models#Collections\",\n   *         },\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  mappers?: {\n    [typeName: string]: string;\n  };\n  /**\n   * Allow you to set the default mapper when it's not being override by `mappers` or generics.\n   * You can specify a type name, or specify a string in `module#type` or `module#namespace#type` format.\n   * The default value of mappers is the TypeScript type generated by `typescript` package.\n   *\n   * @example\n   *\n   * ## Replace with any\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         defaultMapper: \"any\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   *\n   * ## Custom Base Object\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         defaultMapper: \"./my-file#BaseObject\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   *\n   * ## Wrap default types with Partial\n   *\n   * You can also specify a custom wrapper for the original type, without overriding the original generated types, use `{T}` to specify the identifier. (for flow, use `$Shape<{T}>`)\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       // plugins...\n   *       config: {\n   *         defaultMapper: \"Partial<{T}>\",\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   *\n   * ## Allow deep partial with `utility-types`\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\n   *         \"typescript\",\n   *         \"@apollo/client/local-state/codegen\",\n   *         { add: { content: \"import { DeepPartial } from 'utility-types';\" } },\n   *       ],\n   *       config: {\n   *         defaultMapper: \"DeepPartial<{T}>\",\n   *         avoidCheckingAbstractTypesRecursively: true, // required if you have complex nested abstract types\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  defaultMapper?: string;\n  /**\n   * Warns about unused mappers.\n   *\n   * @defaultValue true\n   *\n   * @example\n   *\n   * ```ts\n   * import type { CodegenConfig } from \"@graphql-codegen/cli\";\n   *\n   * const config: CodegenConfig = {\n   *   // ...\n   *   generates: {\n   *     \"path/to/file\": {\n   *       plugins: [\"typescript\", \"@apollo/client/local-state/codegen\"],\n   *       config: {\n   *         showUnusedMappers: true,\n   *       },\n   *     },\n   *   },\n   * };\n   * export default config;\n   * ```\n   */\n  showUnusedMappers?: boolean;\n  /**\n   * Generates immutable types by adding `readonly` to properties and uses `ReadonlyArray`.\n   *\n   * @defaultValue false\n   */\n  immutableTypes?: boolean;\n  /**\n   * Prefixes all GraphQL related generated types with that value, as namespaces import.\n   * You can use this feature to allow separation of plugins to different files.\n   *\n   * @defaultValue ''\n   */\n  namespacedImportName?: string;\n  /**\n   * Suffix we add to each generated type resolver.\n   *\n   * @defaultValue Resolvers\n   */\n  resolverTypeSuffix?: string;\n  /**\n   * The type name to use when exporting all resolvers signature as unified type.\n   *\n   * @defaultValue Resolvers\n   */\n  allResolversTypeName?: string;\n}\n"
  },
  {
    "path": "codegen/local-state/index.ts",
    "content": "export type { LocalStatePluginConfig } from \"./config.js\";\nexport { plugin } from \"./plugin.js\";\n"
  },
  {
    "path": "codegen/local-state/plugin.ts",
    "content": "/**\n * Adapted from\n * https://github.com/dotansimha/graphql-code-generator/blob/master/packages/plugins/typescript/resolvers/src/index.ts\n *\n * https://github.com/dotansimha/graphql-code-generator/blob/master/LICENSE\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Dotan Simha\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND ONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport type { PluginFunction, Types } from \"@graphql-codegen/plugin-helpers\";\nimport {\n  getCachedDocumentNodeFromSchema,\n  oldVisit,\n} from \"@graphql-codegen/plugin-helpers\";\nimport type { RootResolver } from \"@graphql-codegen/visitor-plugin-common\";\nimport type { GraphQLSchema } from \"graphql\";\n\nimport type { LocalStatePluginConfig } from \"./config.js\";\nimport { LocalStateVisitor } from \"./visitor.js\";\n\nexport const plugin: PluginFunction<\n  LocalStatePluginConfig,\n  Types.ComplexPluginOutput<{\n    generatedResolverTypes: RootResolver[\"generatedResolverTypes\"];\n  }>\n> = async (\n  schema: GraphQLSchema,\n  _documents: Types.DocumentFile[],\n  config: LocalStatePluginConfig\n) => {\n  const imports: string[] = [];\n  const showUnusedMappers =\n    typeof config.showUnusedMappers === \"boolean\" ?\n      config.showUnusedMappers\n    : true;\n\n  const importType = config.useTypeImports ? \"import type\" : \"import\";\n  const prepend: string[] = [];\n\n  // Extended types are types that extend existing schema types (i.e. `extend type User {...}`)\n  const extendedTypes = Object.entries(schema.getTypeMap()).reduce(\n    (memo, [typename, type]) => {\n      return type.astNode?.loc?.startToken.value === \"extend\" ?\n          memo.add(typename)\n        : memo;\n    },\n    new Set<string>()\n  );\n\n  if (extendedTypes.size > 0) {\n    if (!config.baseTypesPath) {\n      throw new Error(\n        \"`baseTypesPath` must be defined when your local schema extends existing schema types.\"\n      );\n    }\n\n    prepend.push(\n      `import * as ${\n        config.baseSchemaTypesImportName ?? \"BaseSchemaTypes\"\n      } from '${config.baseTypesPath}';`\n    );\n  }\n\n  const visitor = new LocalStateVisitor(config, schema, extendedTypes);\n  const astNode = getCachedDocumentNodeFromSchema(schema);\n\n  // runs visitor\n  const visitorResult = oldVisit(astNode, { leave: visitor as any });\n\n  const resolversTypeMapping = visitor.buildResolversTypes();\n  const resolversParentTypeMapping = visitor.buildResolversParentTypes();\n  const resolversUnionTypeMapping = visitor.buildResolversUnionTypes();\n  const resolversInterfaceTypeMapping = visitor.buildResolversInterfaceTypes();\n  const { getRootResolver, mappersImports, unusedMappers } = visitor;\n\n  if (showUnusedMappers && unusedMappers.length) {\n    console.warn(`Unused mappers: ${unusedMappers.join(\",\")}`);\n  }\n\n  if (imports.length) {\n    prepend.push(`${importType} { ${imports.join(\", \")} } from 'graphql';`);\n  }\n\n  prepend.push(\n    `${importType} { LocalState } from '@apollo/client/local-state'`,\n    `${importType} { DeepPartial } from '@apollo/client/utilities';`\n  );\n\n  prepend.push(...mappersImports, ...visitor.globalDeclarations);\n\n  const rootResolver = getRootResolver();\n\n  return {\n    prepend,\n    content: [\n      resolversTypeMapping,\n      resolversParentTypeMapping,\n      resolversInterfaceTypeMapping,\n      resolversUnionTypeMapping,\n      ...visitorResult.definitions.filter(\n        (d: unknown) => typeof d === \"string\"\n      ),\n      rootResolver.content,\n    ].join(\"\\n\"),\n    meta: {\n      generatedResolverTypes: rootResolver.generatedResolverTypes,\n    },\n  };\n};\n"
  },
  {
    "path": "codegen/local-state/visitor.ts",
    "content": "/**\n * Adapted from\n * https://github.com/dotansimha/graphql-code-generator/blob/master/packages/plugins/typescript/resolvers/src/visitor.ts\n *\n * https://github.com/dotansimha/graphql-code-generator/blob/master/LICENSE\n *\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Dotan Simha\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND ONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\nimport { TypeScriptOperationVariablesToObject } from \"@graphql-codegen/typescript\";\nimport type {\n  DeclarationKind,\n  FieldDefinitionResult,\n  ParsedMapper,\n  ParsedResolversConfig,\n  ResolverTypes,\n  RootResolver,\n} from \"@graphql-codegen/visitor-plugin-common\";\nimport {\n  BaseResolversVisitor,\n  DeclarationBlock,\n  getBaseTypeNode,\n  getConfigValue,\n  indent,\n  normalizeAvoidOptionals,\n  parseMapper,\n} from \"@graphql-codegen/visitor-plugin-common\";\nimport type {\n  DirectiveDefinitionNode,\n  EnumTypeDefinitionNode,\n  FieldDefinitionNode,\n  GraphQLNamedType,\n  GraphQLSchema,\n  InterfaceTypeDefinitionNode,\n  ListTypeNode,\n  NamedTypeNode,\n  NonNullTypeNode,\n  ObjectTypeDefinitionNode,\n  ScalarTypeDefinitionNode,\n  UnionTypeDefinitionNode,\n} from \"graphql\";\nimport {\n  isEnumType,\n  isInterfaceType,\n  isObjectType,\n  isUnionType,\n  Kind,\n} from \"graphql\";\n\nimport type { LocalStatePluginConfig } from \"./config.js\";\n\ntype FieldDefinitionPrintFn = (\n  parentName: string,\n  avoidResolverOptionals: boolean\n) => string | null;\n\nconst ENUM_RESOLVERS_SIGNATURE =\n  \"export type EnumResolverSignature<T, AllowedValues = any> = { [key in keyof T]?: AllowedValues };\";\n\ninterface ParsedTypeScriptResolversConfig extends ParsedResolversConfig {\n  allowParentTypeOverride: boolean;\n  extendedTypes: Set<string>;\n  baseSchemaTypesImportName: string;\n  contextType: ParsedMapper;\n  rootValueType: never;\n}\n\nexport class LocalStateVisitor extends BaseResolversVisitor<\n  LocalStatePluginConfig,\n  ParsedTypeScriptResolversConfig\n> {\n  constructor(\n    pluginConfig: LocalStatePluginConfig,\n    schema: GraphQLSchema,\n    extendedTypes: Set<string>\n  ) {\n    super(\n      pluginConfig,\n      {\n        avoidOptionals: normalizeAvoidOptionals(pluginConfig.avoidOptionals),\n        allowParentTypeOverride: false,\n        contextType: parseMapper(\n          pluginConfig.contextType || \"@apollo/client#DefaultContext\",\n          \"DefaultContext\"\n        ),\n        baseSchemaTypesImportName: getConfigValue(\n          pluginConfig.baseSchemaTypesImportName,\n          \"BaseSchemaTypes\"\n        ),\n        extendedTypes,\n      } as ParsedTypeScriptResolversConfig,\n      schema\n    );\n    this.setVariablesTransformer(\n      new TypeScriptOperationVariablesToObject(\n        this.scalars,\n        this.convertName,\n        this.config.avoidOptionals,\n        this.config.immutableTypes,\n        this.config.namespacedImportName,\n        [],\n        this.config.enumPrefix,\n        this.config.enumSuffix,\n        this.config.enumValues\n      )\n    );\n  }\n\n  protected applyResolverTypeWrapper(str: string): string {\n    return str;\n  }\n\n  protected createResolversFields({\n    applyWrapper,\n    clearWrapper,\n    getTypeToUse,\n    currentType,\n    shouldInclude,\n  }: {\n    applyWrapper: (str: string) => string;\n    clearWrapper: (str: string) => string;\n    getTypeToUse: (str: string) => string;\n    currentType: \"ResolversTypes\" | \"ResolversParentTypes\";\n    shouldInclude?: (type: GraphQLNamedType) => boolean;\n  }): ResolverTypes {\n    if (currentType === \"ResolversTypes\") {\n      return super.createResolversFields({\n        applyWrapper,\n        clearWrapper,\n        getTypeToUse,\n        currentType,\n        shouldInclude,\n        onNotMappedObjectType: ({ typeName, initialType }) => {\n          let result = initialType;\n          if (\n            this._federation.getMeta()[typeName]?.referenceSelectionSetsString\n          ) {\n            result += ` | ${this.convertName(\n              \"FederationReferenceTypes\"\n            )}['${typeName}']`;\n          }\n          return result;\n        },\n      });\n    }\n\n    const allSchemaTypes = this.schema.getTypeMap();\n    const typeNames = this._federation.filterTypeNames(\n      Object.keys(allSchemaTypes)\n    );\n\n    // avoid checking all types recursively if we have no `mappers` defined\n    if (Object.keys(this.config.mappers).length > 0) {\n      for (const typeName of typeNames) {\n        if (this[\"_shouldMapType\"][typeName] === undefined) {\n          const schemaType = allSchemaTypes[typeName];\n          this[\"_shouldMapType\"][typeName] = this.shouldMapType(schemaType);\n        }\n      }\n    }\n\n    return typeNames.reduce((prev: ResolverTypes, typeName: string) => {\n      const schemaType = allSchemaTypes[typeName];\n\n      if (\n        typeName.startsWith(\"__\") ||\n        (shouldInclude && !shouldInclude(schemaType))\n      ) {\n        return prev;\n      }\n\n      const isRootType = this._rootTypeNames.has(typeName);\n      const isMapped = this.config.mappers[typeName];\n      const isScalar = this.config.scalars[typeName];\n      const hasDefaultMapper = !!this.config.defaultMapper?.type;\n\n      if (isRootType) {\n        if (this.config.extendedTypes.has(typeName)) {\n          const node = allSchemaTypes[typeName]\n            .astNode as ObjectTypeDefinitionNode;\n\n          const baseType = `DeepPartial<${this.config.baseSchemaTypesImportName}.${typeName}>`;\n          const localFieldNames =\n            node.fields?.map((field) => `'${field.name.value}'`) ?? [];\n\n          prev[typeName] = applyWrapper(\n            // Don't define fields from local resolvers on the root type\n            // since the root value passed to a local root resolver only\n            // contains keys from the server schema. The schema types might\n            // however be generated from both the local and remote schema in\n            // order to generate queries that contain both types of fields.\n            // Filtering the local fields out ensures a more accurate type in\n            // this situation.\n            localFieldNames.length > 0 ?\n              `Omit<${baseType}, ${localFieldNames.join(\" | \")}>`\n            : baseType\n          );\n        } else {\n          prev[typeName] = applyWrapper(\"{}\");\n        }\n\n        return prev;\n      }\n      if (\n        isMapped &&\n        this.config.mappers[typeName].type &&\n        !hasPlaceholder(this.config.mappers[typeName].type)\n      ) {\n        this.markMapperAsUsed(typeName);\n        prev[typeName] = applyWrapper(this.config.mappers[typeName].type);\n      } else if (isEnumType(schemaType) && this.config.enumValues[typeName]) {\n        const isExternalFile = !!this.config.enumValues[typeName].sourceFile;\n        prev[typeName] =\n          isExternalFile ?\n            this.convertName(this.config.enumValues[typeName].typeIdentifier, {\n              useTypesPrefix: false,\n              useTypesSuffix: false,\n            })\n          : this.config.enumValues[typeName].sourceIdentifier!;\n      } else if (\n        hasDefaultMapper &&\n        !hasPlaceholder(this.config.defaultMapper!.type)\n      ) {\n        prev[typeName] = applyWrapper(this.config.defaultMapper!.type);\n      } else if (isScalar) {\n        prev[typeName] = applyWrapper(this._getScalar(typeName));\n      } else if (isInterfaceType(schemaType)) {\n        this._hasReferencedResolversInterfaceTypes = true;\n        const type = this.convertName(\"ResolversInterfaceTypes\");\n        const generic = this.convertName(currentType);\n        prev[typeName] = applyWrapper(`${type}<${generic}>['${typeName}']`);\n        return prev;\n      } else if (isUnionType(schemaType)) {\n        this._hasReferencedResolversUnionTypes = true;\n        const type = this.convertName(\"ResolversUnionTypes\");\n        const generic = this.convertName(currentType);\n        prev[typeName] = applyWrapper(`${type}<${generic}>['${typeName}']`);\n      } else if (isEnumType(schemaType)) {\n        prev[typeName] = this.convertName(\n          typeName,\n          {\n            useTypesPrefix: this.config.enumPrefix,\n            useTypesSuffix: this.config.enumSuffix,\n          },\n          true\n        );\n      } else {\n        prev[typeName] = this.convertName(typeName, {}, true);\n\n        if (prev[typeName] !== \"any\" && isObjectType(schemaType)) {\n          const relevantFields = this[\"getRelevantFieldsToOmit\"]({\n            schemaType,\n            getTypeToUse,\n            shouldInclude,\n          });\n\n          // If relevantFields, puts ResolverTypeWrapper on top of an entire type\n          let internalType =\n            relevantFields.length > 0 ?\n              this.replaceFieldsInType(prev[typeName], relevantFields)\n            : prev[typeName];\n\n          if (isMapped) {\n            // replace the placeholder with the actual type\n            if (hasPlaceholder(internalType)) {\n              internalType = replacePlaceholder(internalType, typeName);\n            }\n            if (\n              this.config.mappers[typeName].type &&\n              hasPlaceholder(this.config.mappers[typeName].type)\n            ) {\n              internalType = replacePlaceholder(\n                this.config.mappers[typeName].type,\n                internalType\n              );\n            }\n          }\n\n          if (this.config.extendedTypes.has(typeName)) {\n            const node = allSchemaTypes[typeName]?.astNode;\n\n            if (node?.kind !== Kind.OBJECT_TYPE_DEFINITION) {\n              throw new Error(\n                \"Extended type must be an object type definition\"\n              );\n            }\n\n            const baseType = `${this.config.baseSchemaTypesImportName}.${typeName}`;\n\n            const localFieldNames =\n              node.fields?.map((field) => `'${field.name.value}'`) ?? [];\n\n            prev[typeName] =\n              // Don't define fields from local resolvers on the parent type\n              // since the parent type passed to a local resolver only contains\n              // keys from the server schema. The schema types might however be\n              // generated from both the local and remote schema in order to\n              // generate queries that contain both types of fields. Filtering\n              // the local fields out ensures a more accurate type in this\n              // situation.\n              localFieldNames.length > 0 ?\n                `Omit<DeepPartial<${baseType}>, ${localFieldNames.join(\" | \")}>`\n              : baseType;\n          } else {\n            prev[typeName] = applyWrapper(internalType);\n          }\n        }\n      }\n\n      if (\n        !isMapped &&\n        hasDefaultMapper &&\n        hasPlaceholder(this.config.defaultMapper!.type)\n      ) {\n        const originalTypeName =\n          isScalar ? this._getScalar(typeName) : prev[typeName];\n\n        if (isUnionType(schemaType)) {\n          // Don't clear ResolverTypeWrapper from Unions\n          prev[typeName] = replacePlaceholder(\n            this.config.defaultMapper!.type,\n            originalTypeName\n          );\n        } else {\n          const name = clearWrapper(originalTypeName);\n          const replaced = replacePlaceholder(\n            this.config.defaultMapper!.type,\n            name\n          );\n          prev[typeName] = applyWrapper(replaced);\n        }\n      }\n\n      return prev;\n    }, {} as ResolverTypes);\n  }\n\n  protected formatRootResolver(\n    schemaTypeName: string,\n    resolverType: string,\n    declarationKind: DeclarationKind\n  ): string {\n    const avoidOptionals = this.config.avoidOptionals.resolvers;\n\n    return `${schemaTypeName}${\n      avoidOptionals ? \"\" : \"?\"\n    }: ${resolverType}${this.getPunctuation(declarationKind)}`;\n  }\n\n  private clearOptional(str: string): string {\n    if (str.startsWith(\"Maybe\")) {\n      return str.replace(/Maybe<(.*?)>$/, \"$1\");\n    }\n\n    return str;\n  }\n\n  ListType(node: ListTypeNode): string {\n    return `Maybe<${super.ListType(node)}>`;\n  }\n\n  DirectiveDefinition(\n    _node: DirectiveDefinitionNode,\n    _key: string | number,\n    _parent: any\n  ): string {\n    return \"\";\n  }\n\n  EnumTypeDefinition(node: EnumTypeDefinitionNode): string {\n    const rawTypeName = node.name.value;\n\n    // If we have enumValues set, and it's point to an external enum - we need to allow internal values resolvers\n    // In case we have enumValues set but as explicit values, no need to to do mapping since it's already\n    // have type validation (the original enum has been modified by base types plugin).\n    // If we have mapper for that type - we can skip\n    if (\n      !this.config.mappers[rawTypeName] &&\n      !this.config.enumValues[rawTypeName]\n    ) {\n      return \"\";\n    }\n\n    const name = this.convertName(node, {\n      suffix: this.config.resolverTypeSuffix,\n    });\n    this._collectedResolvers[rawTypeName] = {\n      typename: name,\n      baseGeneratedTypename: name,\n    };\n    const hasExplicitValues = this.config.enumValues[rawTypeName]?.mappedValues;\n\n    return new DeclarationBlock(this._declarationBlockConfig)\n      .export()\n      .asKind(\"type\")\n      .withName(name)\n      .withContent(\n        hasExplicitValues ?\n          this.buildEnumResolversExplicitMappedValues(\n            node,\n            this.config.enumValues[rawTypeName].mappedValues!\n          )\n        : this.buildEnumResolverContentBlock(\n            node,\n            this.getTypeToUse(rawTypeName)\n          )\n      ).string;\n  }\n\n  ObjectTypeDefinition(node: ObjectTypeDefinitionNode): string {\n    const declarationKind = \"type\";\n    const name = this.convertName(node, {\n      suffix: this.config.resolverTypeSuffix,\n    });\n    const typeName = node.name.value;\n\n    const rootType = ((): false | \"query\" | \"mutation\" | \"subscription\" => {\n      if (this.schema.getQueryType()?.name === typeName) {\n        return \"query\";\n      }\n      if (this.schema.getMutationType()?.name === typeName) {\n        return \"mutation\";\n      }\n      if (this.schema.getSubscriptionType()?.name === typeName) {\n        return \"subscription\";\n      }\n      return false;\n    })();\n\n    const fieldsContent = (node.fields as unknown as FieldDefinitionResult[])\n      .map((f) => {\n        return f.printContent(\n          node,\n          (rootType === \"query\" && this.config.avoidOptionals.query) ||\n            (rootType === \"mutation\" && this.config.avoidOptionals.mutation) ||\n            (rootType === \"subscription\" &&\n              this.config.avoidOptionals.subscription) ||\n            (rootType === false && this.config.avoidOptionals.resolvers)\n        ).value;\n      })\n      .filter((v) => v);\n\n    const block = new DeclarationBlock(this._declarationBlockConfig)\n      .export()\n      .asKind(declarationKind)\n      .withName(name)\n      .withBlock(fieldsContent.join(\"\\n\"));\n\n    this._collectedResolvers[typeName] = {\n      typename: name,\n      baseGeneratedTypename: name,\n    };\n\n    return block.string;\n  }\n\n  UnionTypeDefinition(\n    _node: UnionTypeDefinitionNode,\n    _key: string | number,\n    _parent: any\n  ): string {\n    return \"\";\n  }\n\n  FieldDefinition(\n    node: FieldDefinitionNode,\n    key: string | number,\n    parent: any\n  ): FieldDefinitionResult {\n    const hasArguments = node.arguments && node.arguments.length > 0;\n    const declarationKind = \"type\";\n\n    const original: FieldDefinitionNode = parent[key];\n\n    return {\n      node: original,\n      printContent: (\n        parentNode: ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode,\n        avoidResolverOptionals\n      ) => {\n        const parentName = parentNode.name.value;\n\n        let argsType =\n          hasArguments ?\n            this.convertName(\n              parentName +\n                (this.config.addUnderscoreToArgsType ? \"_\" : \"\") +\n                this.convertName(node.name, {\n                  useTypesPrefix: false,\n                  useTypesSuffix: false,\n                }) +\n                \"Args\",\n              {\n                useTypesPrefix: true,\n              },\n              true\n            )\n          : null;\n\n        if (argsType !== null) {\n          const argsToForceRequire = original.arguments!.filter(\n            (arg) => !!arg.defaultValue || arg.type.kind === \"NonNullType\"\n          );\n\n          if (argsToForceRequire.length > 0) {\n            argsType = this.applyRequireFields(argsType, argsToForceRequire);\n          } else if (original.arguments!.length > 0) {\n            argsType = this.applyOptionalFields(argsType, original.arguments!);\n          }\n        }\n        const { mappedTypeKey, resolverType } = ((): {\n          mappedTypeKey: string;\n          resolverType: string;\n        } => {\n          const baseType = getBaseTypeNode(original.type);\n          const realType = baseType.name.value;\n          const typeToUse = this.getTypeToUse(realType);\n          /**\n           * Turns GraphQL type to TypeScript types (`mappedType`) e.g.\n           *\n           * - String! -> ResolversTypes['String']>\n           * - String -> Maybe<ResolversTypes['String']>\n           * - [String] -> Maybe<Array<Maybe<ResolversTypes['String']>>>\n           * - [String!]! -> Array<ResolversTypes['String']>\n           */\n          const mappedType =\n            this._variablesTransformer.wrapAstTypeWithModifiers(\n              typeToUse,\n              original.type\n            );\n\n          return {\n            mappedTypeKey: mappedType,\n            resolverType: \"LocalState.Resolver\",\n          };\n        })();\n\n        const signature: {\n          name: string;\n          modifier: string;\n          type: string;\n          genericTypes: string[];\n        } = {\n          name: node.name.value,\n          modifier: avoidResolverOptionals ? \"\" : \"?\",\n          type: resolverType,\n          genericTypes: [\n            mappedTypeKey,\n            this.getParentTypeToUse(parentName),\n            this.config.contextType.type,\n            argsType!,\n          ].filter((f) => f),\n        };\n\n        return {\n          value: indent(\n            `${signature.name}${signature.modifier}: ${\n              signature.type\n            }<${signature.genericTypes.join(\", \")}>${this.getPunctuation(\n              declarationKind\n            )}`\n          ),\n          meta: {},\n        };\n      },\n    };\n  }\n\n  InterfaceTypeDefinition(_node: InterfaceTypeDefinitionNode): string {\n    return \"\";\n  }\n\n  public getRootResolver(): RootResolver {\n    const name = this.convertName(this.config.allResolversTypeName);\n    const declarationKind = \"type\";\n\n    const userDefinedTypes: RootResolver[\"generatedResolverTypes\"][\"userDefined\"] =\n      {};\n    const content = [\n      new DeclarationBlock(this._declarationBlockConfig)\n        .export()\n        .asKind(declarationKind)\n        .withName(name)\n        .withBlock(\n          Object.keys(this._collectedResolvers)\n            .map((schemaTypeName) => {\n              const resolverType = this._collectedResolvers[schemaTypeName];\n\n              if (resolverType.baseGeneratedTypename) {\n                userDefinedTypes[schemaTypeName] = {\n                  name: resolverType.baseGeneratedTypename,\n                  hasIsTypeOf:\n                    this._parsedSchemaMeta.typesWithIsTypeOf[schemaTypeName] ||\n                    false,\n                };\n              }\n\n              return indent(\n                this.formatRootResolver(\n                  schemaTypeName,\n                  resolverType.typename,\n                  declarationKind\n                )\n              );\n            })\n            .join(\"\\n\")\n        ).string,\n    ].join(\"\\n\");\n\n    return {\n      content,\n      generatedResolverTypes: {\n        resolversMap: { name },\n        userDefined: userDefinedTypes,\n      },\n    };\n  }\n\n  protected wrapWithListType(str: string): string {\n    return `${this.config.immutableTypes ? \"ReadonlyArray\" : \"Array\"}<${str}>`;\n  }\n\n  protected getParentTypeForSignature(_node: FieldDefinitionNode) {\n    return \"ParentType\";\n  }\n\n  NamedType(node: NamedTypeNode): string {\n    return `Maybe<${super.NamedType(node)}>`;\n  }\n\n  NonNullType(node: NonNullTypeNode): string {\n    const baseValue = super.NonNullType(node);\n\n    return this.clearOptional(baseValue);\n  }\n\n  ScalarTypeDefinition(node: ScalarTypeDefinitionNode): string {\n    console.warn(\n      `Custom scalars type '${node.name.value}' is ignored and cannot be resolved with \\`LocalState\\`. Please map the scalar type to a primitive with the \\`scalars\\` config.`\n    );\n    this._hasScalars = true;\n    return \"\";\n  }\n\n  protected getPunctuation(_declarationKind: DeclarationKind): string {\n    return \";\";\n  }\n\n  protected buildEnumResolverContentBlock(\n    node: EnumTypeDefinitionNode,\n    mappedEnumType: string\n  ): string {\n    const valuesMap = `{ ${(node.values || [])\n      .map(\n        (v) =>\n          `${v.name.value}${\n            this.config.avoidOptionals.resolvers ? \"\" : \"?\"\n          }: any`\n      )\n      .join(\", \")} }`;\n\n    this._globalDeclarations.add(ENUM_RESOLVERS_SIGNATURE);\n\n    return `EnumResolverSignature<${valuesMap}, ${mappedEnumType}>`;\n  }\n\n  protected buildEnumResolversExplicitMappedValues(\n    node: EnumTypeDefinitionNode,\n    valuesMapping: { [valueName: string]: string | number }\n  ): string {\n    return `{ ${(node.values || [])\n      .map((v) => {\n        const valueName = v.name.value;\n        const mappedValue = valuesMapping[valueName];\n\n        return `${valueName}: ${\n          typeof mappedValue === \"number\" ? mappedValue : `'${mappedValue}'`\n        }`;\n      })\n      .join(\", \")} }`;\n  }\n}\n\nfunction replacePlaceholder(pattern: string, typename: string): string {\n  return pattern.replace(/\\{T\\}/g, typename);\n}\n\nfunction hasPlaceholder(pattern: string): boolean {\n  return pattern.includes(\"{T}\");\n}\n"
  },
  {
    "path": "codegen/package.json",
    "content": "{\n  \"name\": \"@apollo/client-graphql-codegen\",\n  \"version\": \"2.0.0\",\n  \"description\": \"Apollo Client GraphQL Codegen Plugins\",\n  \"keywords\": [\n    \"apollo\",\n    \"client\",\n    \"graphql\",\n    \"codegen\"\n  ],\n  \"author\": \"packages@apollographql.com\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"sideEffects\": false,\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/apollographql/apollo-client.git\",\n    \"directory\": \"codegen\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/apollographql/apollo-client/issues\"\n  },\n  \"homepage\": \"https://www.apollographql.com/docs/react/\",\n  \"exports\": {\n    \"./local-state\": \"./dist/local-state/index.js\"\n  },\n  \"files\": [\n    \"dist\"\n  ],\n  \"scripts\": {\n    \"prebuild\": \"npm run clean\",\n    \"clean\": \"rimraf dist\",\n    \"build\": \"tsc\",\n    \"prepack\": \"npm run build\",\n    \"publint\": \"publint run --strict .\"\n  },\n  \"devDependencies\": {\n    \"typescript\": \"^5.8.3\",\n    \"@graphql-codegen/plugin-helpers\": \"^6.0.0\",\n    \"@graphql-codegen/typescript\": \"^5.0.0\",\n    \"@graphql-codegen/visitor-plugin-common\": \"^6.0.0\"\n  },\n  \"peerDependencies\": {\n    \"@graphql-codegen/plugin-helpers\": \"^6.0.0\",\n    \"@graphql-codegen/typescript\": \"^5.0.0\",\n    \"@graphql-codegen/visitor-plugin-common\": \"^6.0.0\"\n  }\n}\n"
  },
  {
    "path": "codegen/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noEmit\": false,\n    \"target\": \"ESNext\",\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"lib\": [\"DOM\", \"ES2022\"],\n    \"paths\": {},\n    \"types\": [],\n    \"rootDir\": \"./\",\n    \"outDir\": \"./dist\",\n    \"declaration\": true,\n    \"sourceMap\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true\n  },\n  \"include\": [\"**/*.ts\"],\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n"
  },
  {
    "path": "config/FixJSDOMEnvironment.js",
    "content": "const { default: JSDOMEnvironment } = require(\"jest-environment-jsdom\");\n\n// https://github.com/facebook/jest/blob/v29.4.3/website/versioned_docs/version-29.4/Configuration.md#testenvironment-string\nclass FixJSDOMEnvironment extends JSDOMEnvironment {\n  constructor(...args) {\n    super(...args);\n\n    // FIXME https://github.com/jsdom/jsdom/issues/1724\n    this.global.Headers = Headers;\n    this.global.Request = Request;\n    this.global.Response = Response;\n\n    // FIXME: setting a global fetch breaks HttpLink tests\n    // and setting AbortController breaks PersistedQueryLink tests, which may\n    // indicate a memory leak\n    // this.global.fetch = fetch;\n    this.global.AbortController = AbortController;\n  }\n}\n\nmodule.exports = FixJSDOMEnvironment;\n"
  },
  {
    "path": "config/apiExtractor.ts",
    "content": "import { spawnSync } from \"node:child_process\";\nimport fs from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { format, join, parse } from \"node:path\";\nimport { parseArgs } from \"node:util\";\nimport * as path from \"path\";\n\nimport type { IConfigFile } from \"@microsoft/api-extractor\";\nimport {\n  Extractor,\n  ExtractorConfig,\n  ExtractorLogLevel,\n} from \"@microsoft/api-extractor\";\n\nimport pkg from \"../dist/package.json\" with { type: \"json\" };\n\nimport type { ExportsCondition } from \"./entryPoints.ts\";\nimport { buildDocEntryPoints } from \"./entryPoints.ts\";\nimport {\n  patchApiExtractorInternals,\n  withPseudoNodeModules,\n} from \"./helpers.ts\";\n\npatchApiExtractorInternals();\n\nconst parsed = parseArgs({\n  options: {\n    generate: {\n      type: \"string\",\n      multiple: true,\n      default: [\"apiReport\"],\n    },\n    \"main-only\": {\n      type: \"boolean\",\n      default: false,\n    },\n  },\n});\n\nif (\n  !parsed.values.generate!.every((v) => [\"apiReport\", \"docModel\"].includes(v))\n) {\n  throw new Error(\n    \"invalid value for --generate. Only allowed values are `apiReport` and `docModel`!\"\n  );\n}\n\n// Load and parse the api-extractor.json file\nconst configObjectFullPath = path.resolve(\n  import.meta.dirname,\n  \"../api-extractor.json\"\n);\nconst baseConfig = ExtractorConfig.loadFile(configObjectFullPath);\nconst packageJsonFullPath = path.resolve(\n  import.meta.dirname,\n  \"../package.json\"\n);\nconst reportFolder = baseConfig.apiReport.reportFolder!.replace(\n  \"<projectFolder>\",\n  join(import.meta.dirname, \"..\")\n);\n\nconst entryPoints = Object.entries(pkg.exports as ExportsCondition)\n  .filter(([key]) => !(key.includes(\"*\") || key.includes(\".json\")))\n  .map(([key, value]) => {\n    return {\n      path: key.slice(\"./\".length),\n      key,\n      value,\n    };\n  });\n\nprocess.exitCode = 0;\n\nconst tempDir = fs.mkdtempSync(\n  path.join(import.meta.dirname, \"..\", \"dist\", \"api-model\")\n);\ntry {\n  if (parsed.values.generate?.includes(\"docModel\")) {\n    console.log(\n      \"\\n\\nCreating API extractor docmodel for the a combination of all entry points\"\n    );\n    const entryPointFile = path.join(tempDir, \"entry.d.ts\");\n    fs.writeFileSync(\n      entryPointFile,\n      buildDocEntryPoints({\n        rootDir: path.resolve(import.meta.dirname, \"..\"),\n        targetDir: \"dist\",\n        jsExt: \"js\",\n      })\n    );\n\n    const result = await buildReport(\n      \"@apollo/client\",\n      entryPointFile,\n      \"docModel\"\n    );\n    if (process.exitCode === 50) {\n      process.exitCode = 0; // if there were only warnings, we still want to exit with 0\n    }\n\n    console.log(\"Creating file with all possible canonical references...\");\n    const canonicalReferences = new Set<string>();\n    const file = await readFile(result.extractorConfig.apiJsonFilePath, \"utf8\");\n    JSON.parse(file, (key, value) => {\n      if (\n        key === \"canonicalReference\" &&\n        typeof value === \"string\" &&\n        value.startsWith(\"@apollo/client\")\n      ) {\n        canonicalReferences.add(value);\n      }\n      return undefined;\n    });\n    await writeFile(\n      format({\n        ...parse(result.extractorConfig.apiJsonFilePath),\n        base: \"canonical-references.json\",\n      }),\n      JSON.stringify([...canonicalReferences.values()], null, 2),\n      \"utf8\"\n    );\n  }\n\n  if (parsed.values.generate?.includes(\"apiReport\")) {\n    for (const entryPoint of entryPoints) {\n      let entry = entryPoint.value;\n      while (typeof entry === \"object\") {\n        entry = entry.types || Object.values(entry).at(-1);\n      }\n      const mainEntryPointFilePath = `<projectFolder>/dist/${entry}`\n        .replace(\"//\", \"/\")\n        .replace(/\\.cjs$/, \".d.cts\")\n        .replace(/\\.js$/, \".d.ts\");\n      console.log(\n        \"\\n\\nCreating API extractor report for \" + mainEntryPointFilePath\n      );\n      const reportFileName = `api-report${\n        entryPoint.path ? \"-\" + entryPoint.path.replace(/\\//g, \"_\") : \"\"\n      }.api.md`;\n      await buildReport(\n        join(\"@apollo/client\", entryPoint.key),\n        mainEntryPointFilePath,\n        \"apiReport\",\n        reportFileName\n      );\n    }\n  }\n} finally {\n  fs.rmSync(tempDir, { recursive: true });\n}\n\nasync function buildReport(\n  bundledPackages: string | string[],\n  mainEntryPointFilePath: string,\n  mode: \"apiReport\" | \"docModel\",\n  reportFileName = \"\"\n) {\n  if (!Array.isArray(bundledPackages)) {\n    bundledPackages = [bundledPackages];\n  }\n  const configObject: IConfigFile = {\n    ...(JSON.parse(JSON.stringify(baseConfig)) as IConfigFile),\n    mainEntryPointFilePath,\n  };\n  configObject.bundledPackages = bundledPackages;\n\n  if (mode === \"apiReport\") {\n    configObject.apiReport!.enabled = true;\n    configObject.docModel = { enabled: false };\n    configObject.messages!.extractorMessageReporting![\n      \"ae-unresolved-link\"\n    ]!.logLevel = ExtractorLogLevel.None;\n    configObject.apiReport!.reportFileName = reportFileName;\n  } else {\n    configObject.docModel!.enabled = true;\n    configObject.apiReport = {\n      enabled: false,\n      // this has to point to an existing folder, otherwise the extractor will fail\n      // but it will not write the file\n      reportFileName: \"disabled.md\",\n      reportFolder: tempDir,\n    };\n  }\n\n  const extractorConfig = ExtractorConfig.prepare({\n    configObject,\n    packageJsonFullPath,\n    configObjectFullPath,\n  });\n\n  const extractorResult = await withPseudoNodeModules(() =>\n    Extractor.invoke(extractorConfig, {\n      localBuild: process.env.CI === undefined || process.env.CI === \"false\",\n      showVerboseMessages: true,\n    })\n  );\n\n  if (extractorResult.succeeded) {\n    console.log(`✅ API Extractor completed successfully`);\n  } else {\n    process.exitCode = extractorResult.errorCount === 0 ? 50 : 1;\n    console.error(\n      `❗ API Extractor completed with ${extractorResult.errorCount} errors` +\n        ` and ${extractorResult.warningCount} warnings`\n    );\n    if (extractorResult.apiReportChanged) {\n      spawnSync(\n        \"diff\",\n        [\n          join(reportFolder, reportFileName),\n          join(reportFolder, \"temp\", reportFileName),\n        ],\n        {\n          stdio: \"inherit\",\n        }\n      );\n    }\n  }\n  return extractorResult;\n}\n"
  },
  {
    "path": "config/babel.ts",
    "content": "import { transformFromAstAsync } from \"@babel/core\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { applyRecast } from \"./helpers.ts\";\n\nexport const babelTransform: BuildStep = async (options) => {\n  return applyRecast({\n    glob: `**/*.${options.jsExt}`,\n    cwd: options.targetDir,\n    async transformStep({ ast, sourceName, relativeSourcePath }) {\n      const result = await transformFromAstAsync(ast as any, undefined, {\n        filename: sourceName,\n        sourceFileName: sourceName,\n        sourceMaps: true,\n        code: false,\n        ast: true,\n        cloneInputAst: false,\n        retainLines: true,\n        presets: [\n          [\n            \"@babel/preset-env\",\n            {\n              modules: false,\n              targets: \"since 2023, node >= 20, not dead\",\n            } satisfies import(\"@babel/preset-env\").Options,\n          ],\n        ],\n      });\n      return { ast: result.ast!, map: result.map };\n    },\n  });\n};\n"
  },
  {
    "path": "config/build.ts",
    "content": "import { join, resolve } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { $ } from \"zx\";\n\nimport { babelTransform } from \"./babel.ts\";\nimport { compileTs } from \"./compileTs.ts\";\nimport { deprecateInternals } from \"./deprecateInternals.ts\";\nimport { addExports } from \"./exports.ts\";\nimport { distDir } from \"./helpers.ts\";\nimport { inlineInheritDoc } from \"./inlineInheritDoc.ts\";\nimport { prepareDist } from \"./prepareDist.ts\";\nimport { preserveTsIgnore } from \"./preserveTsIgnore.ts\";\nimport { processInvariants } from \"./processInvariants.ts\";\nimport { reactCompiler } from \"./react-compiler.ts\";\nimport { verifySourceMaps } from \"./verifySourceMaps.ts\";\nimport { updateVersion, verifyVersion } from \"./version.ts\";\n\nexport interface BuildStepOptions {\n  type: \"esm\" | \"cjs\";\n  rootDir: string;\n  packageRoot: string;\n  /** build target directory, relative to `rootDir` */\n  targetDir: string;\n  jsExt: \"js\" | \"cjs\";\n  tsExt: \"ts\" | \"cts\";\n  first: boolean;\n  last: boolean;\n}\nexport type BuildStep = {\n  (options: BuildStepOptions): void | Promise<void>;\n};\ntype BuildSteps = Record<string, BuildStep>;\n\n$.cwd = join(import.meta.dirname, \"..\");\n$.verbose = true;\n\nconst buildSteps = {\n  prepareDist,\n  addExports,\n  typescript: compileTs,\n  babelTransform,\n  updateVersion,\n  inlineInheritDoc,\n  deprecateInternals,\n  preserveTsIgnore,\n  processInvariants,\n  reactCompiler,\n  verifyVersion,\n  verifySourceMaps,\n} satisfies BuildSteps;\nconst additionalSteps = {} satisfies BuildSteps;\n\nconst args = parseArgs({\n  options: {\n    step: {\n      type: \"string\",\n      multiple: true,\n      default: [\"build\"],\n    },\n  },\n});\n\nconst allSteps = Object.assign(\n  {},\n  buildSteps,\n  additionalSteps\n) satisfies BuildSteps;\n\nconst runSteps = args.values.step.flatMap((step) =>\n  step === \"build\" ? Object.keys(buildSteps) : [step]\n);\n\nconst wrongSteps = runSteps.filter((step) => !(step in allSteps));\nif (wrongSteps.length) {\n  throw new Error(\n    `Unknown steps: ${wrongSteps.join(\", \")}. Valid steps are ${Object.keys(\n      allSteps\n    ).join(\", \")}`\n  );\n}\n\nconsole.log(\"Running build steps: %s\", runSteps.join(\", \"));\n\nconst buildStepOptions = [\n  // this order is important so that globs on the esm build don't accidentally match the cjs build\n  { type: \"esm\", targetDir: \"dist\", jsExt: \"js\", tsExt: \"ts\" },\n  { type: \"cjs\", targetDir: \"dist/__cjs\", jsExt: \"cjs\", tsExt: \"cts\" },\n] satisfies Omit<\n  BuildStepOptions,\n  \"first\" | \"last\" | \"rootDir\" | \"packageRoot\"\n>[];\nfor (const options of buildStepOptions) {\n  const first = options === buildStepOptions.at(0);\n  const last = options === buildStepOptions.at(-1);\n  const rootDir = resolve(import.meta.dirname, \"..\");\n\n  for (const step of runSteps) {\n    const buildStep: BuildStep = allSteps[step];\n\n    console.log(\"--- Step %s: running ---\", step);\n    await buildStep({ ...options, first, last, rootDir, packageRoot: distDir });\n    if (process.exitCode) {\n      console.error(\n        `\\n\\nStep ${step} failed, exiting with code ${process.exitCode}`\n      );\n      process.exit();\n    }\n    console.log(\"--- Step %s: done ---\", step);\n  }\n}\n"
  },
  {
    "path": "config/bundlesize.ts",
    "content": "import { readFileSync } from \"fs\";\nimport { join } from \"path\";\nimport { gzipSync } from \"zlib\";\n\nimport bytes from \"bytes\";\n\nconst gzipBundleByteLengthLimit = bytes(\"35.25KB\");\nconst minFile = join(\"dist\", \"apollo-client.min.cjs\");\nconst minPath = join(import.meta.dirname, \"..\", minFile);\nconst gzipByteLen = gzipSync(readFileSync(minPath)).byteLength;\nconst overLimit = gzipByteLen > gzipBundleByteLengthLimit;\n\nconst message = `Minified + GZIP-encoded bundle size for ${minFile} = ${bytes(\n  gzipByteLen,\n  { unit: \"KB\" }\n)}, ${overLimit ? \"exceeding\" : \"under\"} limit ${bytes(\n  gzipBundleByteLengthLimit,\n  { unit: \"KB\" }\n)}`;\n\nif (overLimit) {\n  throw new Error(message);\n} else {\n  console.log(message);\n}\n"
  },
  {
    "path": "config/compare-build-output-to.sh",
    "content": "#!/usr/bin/env bash\nset -euo pipefail\nupstream=$1\ncomparison=\"${RUNNER_TEMP:-/tmp}/comparison_checkout\"\nroot=$(git rev-parse --show-toplevel)\n\ntemp=$(mktemp --tmpdir=\"${RUNNER_TEMP:-/tmp}\")\ntrap 'rm -f \"$temp\"' EXIT\n\npatterndiff(){\n  cd dist || { echo \"dist folder not found\"; exit 1; }\n  count=0\n  while IFS= read -r -d '' file\n  do\n    if ! filediff=\"$(diff <(tr \"'\" '\"' < \"$comparison/dist/$file\") <(tr \"'\" '\"' < \"$root/dist/$file\"))\"; then\n      (( count++ ))\n      echo \"$file\"\n      if [[ \"$file\" == *.min.* ]]; then\n        echo \"> Minified file differs.\"\n      else\n        echo \"$filediff\"\n      fi\n    fi\n  done >\"$temp\" < <(find . -name \"$1\" -print0)\n\n  output=\"$(cat <\"$temp\")\"\n\n  cat <<EOF\n\n## differences in $1 files\n\n<details>\n  <summary>\n\n### $count files with differences\n\n  </summary>\n\n\\`\\`\\`diff\n\n$output\n\n\\`\\`\\`\n\n</details>\nEOF\n\n  cd ..\n}\n\n[ -z \"$upstream\" ] && { echo \"need upstream argument\"; exit 1; }\n\ngit worktree add --force --detach --checkout \"$comparison\" \"$upstream\" || { cd \"$comparison\" && git checkout \"$upstream\"; } || exit 1\n\ncd \"$comparison\" || { echo \"checkout failed\"; exit 1; }\n[ -d node_modules ] || cp -r \"$root/node_modules\" .\nnpm i >&2\ngit status >&2\nnpm run build >&2\nnode config/apiExtractor.ts --main-only --generate docModel >&2\ncd \"$root\" || exit 1\ngit status >&2\nnpm run build >&2\nnode config/apiExtractor.ts --main-only --generate docModel >&2\n\nset +e\n\npatterndiff \"*.js\"\npatterndiff \"*.cjs\"\npatterndiff \"*.d.ts\"\npatterndiff \"*.d.cts\"\n\ncat <<EOF\n\n## DocModel differences\n\n<details>\n  <summary>\n\n### $(diff -qr \"$comparison/docs/public\" \"docs/public\" | wc -l) files with differences\n\n  </summary>\n\n\\`\\`\\`diff\n\n$(diff -r \"$comparison/docs/public\" \"docs/public\")\n\n\\`\\`\\`\n\n</details>\n\n## differences in other files\n\n<details>\n  <summary>\n\n### $(diff -qr \"$comparison/dist\" \"dist\" -x \"*.map\" -x \"*.native.*\" -x \"*.js\" -x \"*.cjs\" -x \"*.d.ts\" -x \"*.d.cts\" -w | wc -l) files with differences\n\n  </summary>\n\n\\`\\`\\`diff\n\n$(diff -r \"$comparison/dist\" \"dist\" -x \"*.map\" -x \"*.native.*\" -x \"*.js\" -x \"*.cjs\" -x \"*.d.ts\" -x \"*.d.cts\" -w)\n\n\\`\\`\\`\n\n</details>\nEOF\n"
  },
  {
    "path": "config/compileTs.ts",
    "content": "import { readFileSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { visit } from \"recast\";\nimport { parseConfigFileTextToJson } from \"typescript\";\nimport { $ } from \"zx\";\n\nimport type { BuildStep, BuildStepOptions } from \"./build.ts\";\nimport type { ExportsCondition } from \"./entryPoints.ts\";\nimport { applyRecast, updatePackageJson } from \"./helpers.ts\";\n\nexport const compileTs: BuildStep = async (options) => {\n  // TODO use `await using` instead of the `try..finally` here once Node supports it\n  const tsconfig = await withBuildTsConfig();\n  try {\n    if (options.type === \"esm\") {\n      await $`npx tsc --project tsconfig.build.json --outDir ${options.targetDir}`;\n    } else {\n      const packageJsonPath = join(import.meta.dirname, \"..\", `package.json`);\n      const originalPackageJson = await readFile(\n        join(options.rootDir, \"package.json\"),\n        \"utf-8\"\n      );\n      try {\n        // module `node18` will compile to CommonJS if the [detected module format](https://www.typescriptlang.org/docs/handbook/modules/reference.html#module-format-detection)\n        // is CommonJS, so we temporarily overwrite the `package.json` file\n        // this is the right way to build CommonJS, the `commonjs` module option should actually not be used\n        // see https://www.typescriptlang.org/docs/handbook/modules/reference.html#commonjs\n        await updatePackageJson(options.rootDir, (packageJson) => {\n          packageJson.type = \"commonjs\";\n        });\n        // noCheck is required to suppress errors like\n        // error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import(\"@wry/equality\")' call instead.\n        await $`npx tsc --project tsconfig.build.json --outDir ${options.targetDir} --module node16 --moduleResolution node16 --noCheck`;\n      } finally {\n        await writeFile(packageJsonPath, originalPackageJson);\n      }\n\n      await renameJsFilesToCjs(options);\n    }\n  } finally {\n    await tsconfig[Symbol.asyncDispose]();\n  }\n};\n\nfunction renameJsFilesToCjs(options: BuildStepOptions) {\n  return applyRecast({\n    glob: `**/*.{js,d.ts}`,\n    cwd: options.targetDir,\n    transformStep({ ast, sourceName }) {\n      return {\n        ast: visit(ast, {\n          visitCallExpression(path) {\n            const node = path.node;\n            if (\n              node.callee.type === \"Identifier\" &&\n              node.callee.name === \"require\" &&\n              node.arguments.length === 1 &&\n              node.arguments[0].type === \"StringLiteral\" &&\n              node.arguments[0].value.startsWith(\".\") &&\n              node.arguments[0].value.endsWith(\".js\")\n            ) {\n              node.arguments[0].value = node.arguments[0].value.replace(\n                /\\.js$/,\n                \".cjs\"\n              );\n            }\n            this.traverse(path);\n          },\n          visitExportAllDeclaration(path) {\n            const node = path.node;\n            if (\n              node.source &&\n              node.source.type === \"StringLiteral\" &&\n              node.source.value.startsWith(\".\") &&\n              node.source.value.endsWith(\".js\")\n            ) {\n              node.source.value = node.source.value.replace(/\\.js$/, \".cjs\");\n            }\n            this.traverse(path);\n          },\n          visitExportNamedDeclaration(path) {\n            const node = path.node;\n            if (\n              node.source &&\n              node.source.type === \"StringLiteral\" &&\n              node.source.value.startsWith(\".\") &&\n              node.source.value.endsWith(\".js\")\n            ) {\n              node.source.value = node.source.value.replace(/\\.js$/, \".cjs\");\n            }\n            this.traverse(path);\n          },\n          visitImportDeclaration(path) {\n            const node = path.node;\n            if (\n              node.source.type === \"StringLiteral\" &&\n              node.source.value.startsWith(\".\") &&\n              node.source.value.endsWith(\".js\")\n            ) {\n              node.source.value = node.source.value.replace(/\\.js$/, \".cjs\");\n            }\n            this.traverse(path);\n          },\n          visitTSImportType(path) {\n            const node = path.node;\n            if (\n              node.argument.type === \"StringLiteral\" &&\n              node.argument.value.startsWith(\".\") &&\n              node.argument.value.endsWith(\".js\")\n            ) {\n              node.argument.value = node.argument.value.replace(\n                /\\.js$/,\n                \".cjs\"\n              );\n            }\n            this.traverse(path);\n          },\n        }),\n        targetFileName: sourceName\n          .replace(/\\.js$/, \".cjs\")\n          .replace(/\\.d\\.ts$/, \".d.cts\"),\n      };\n    },\n  });\n}\n\nasync function withBuildTsConfig() {\n  const tsconfigPath = join(import.meta.dirname, \"..\", `tsconfig.build.json`);\n  const originalTsconfig = await readFile(tsconfigPath, \"utf-8\");\n  const tsconfig = parseConfigFileTextToJson(\n    tsconfigPath,\n    originalTsconfig\n  ).config;\n  tsconfig.files = getEntryPoints();\n  await writeFile(tsconfigPath, JSON.stringify(tsconfig, null, 2));\n  return {\n    [Symbol.asyncDispose]() {\n      return writeFile(tsconfigPath, originalTsconfig);\n    },\n  };\n}\n\nfunction getEntryPoints() {\n  const pkg = JSON.parse(\n    readFileSync(join(import.meta.dirname, \"..\", \"package.json\"), \"utf-8\")\n  );\n  const acc = new Set<ExportsCondition>([pkg.exports]);\n  const results = new Set<string>([\"./src/react/types/types.documentation.ts\"]);\n  for (const entry of acc) {\n    if (typeof entry === \"string\") {\n      results.add(entry);\n    } else if (typeof entry === \"object\") {\n      Object.values(entry).forEach((e) => acc.add(e));\n    }\n  }\n  return Array.from(results);\n}\n"
  },
  {
    "path": "config/deprecateInternals.ts",
    "content": "import { visit } from \"recast\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { applyRecast, frameComment } from \"./helpers.ts\";\n\nexport const deprecateInternals: BuildStep = async (options) =>\n  applyRecast({\n    glob: `**/*.{${options.jsExt},d.${options.tsExt}}`,\n    cwd: options.targetDir,\n    transformStep({ ast }) {\n      return {\n        ast: visit(ast, {\n          visitNode(path) {\n            this.traverse(path);\n            const node = path.node;\n\n            if (!node.comments) {\n              return;\n            }\n\n            for (const comment of node.comments) {\n              if (\n                comment.type === \"CommentBlock\" &&\n                comment.value.includes(\"@internal\")\n              ) {\n                if (comment.value.includes(\"@deprecated\")) continue;\n\n                comment.value = frameComment(\n                  comment.value.trim() +\n                    \"\\n\\n@deprecated This is an internal API and should not be used directly. This can be removed or changed at any time.\"\n                );\n              }\n            }\n          },\n        }),\n      };\n    },\n  });\n"
  },
  {
    "path": "config/dirname.cjs",
    "content": "// workaround for `entryPoints.ts` that needs access to the current directory,\n// but cannot use `import.meta` as the file is required by Jest, which transpiles\n// the file to CommonJS - ending up with \"SyntaxError: Cannot use 'import.meta' outside a module\"\nmodule.exports.__dirname = __dirname;\n"
  },
  {
    "path": "config/entryPoints.ts",
    "content": "import { readFileSync } from \"fs\";\nimport path from \"path\";\n\n// @ts-ignore An import path can only end with a '.cts' extension when 'allowImportingTsExtensions' is enabled.\nimport type { BuildStepOptions } from \"./build.ts\";\nimport { __dirname } from \"./dirname.cjs\";\n\nconst pkg = JSON.parse(\n  readFileSync(path.resolve(__dirname, \"../package.json\"), {\n    encoding: \"utf-8\",\n  })\n) as typeof import(\"../package.json\");\n\nexport type ExportsCondition = string | { [key: string]: ExportsCondition };\n\ntype EntryPoint = {\n  dirs: string[];\n  key: string;\n  value: ExportsCondition;\n};\nexport const entryPoints = Object.entries(pkg.exports).map<EntryPoint>(\n  ([key, value]) => ({\n    dirs: key\n      .slice(\"./\".length)\n      .split(\"/\")\n      .filter((d) => d !== \"\"),\n    key,\n    value,\n  })\n);\n\nexport const buildDocEntryPoints = (\n  options: Pick<BuildStepOptions, \"rootDir\" | \"targetDir\" | \"jsExt\">\n) => {\n  const acc = entryPoints.map((entryPoint) => {\n    let identifier = \"\";\n    if (entryPoint.dirs.length) {\n      identifier =\n        `entrypoint_` + entryPoint.dirs.join(\"__\").replace(/-/g, \"_\");\n    }\n    if (identifier === \"core\") return;\n    return `export * ${identifier ? `as ${identifier}` : \"\"} from \"${path.join(\n      \"@apollo/client\",\n      ...entryPoint.dirs\n    )}\";`;\n  });\n  acc.push(\n    `export * from \"${path.join(\n      options.rootDir,\n      options.targetDir,\n      \"react\",\n      \"types\",\n      `types.documentation.${options.jsExt}`\n    )}\";`\n  );\n  return acc.join(\"\\n\");\n};\n"
  },
  {
    "path": "config/exports.ts",
    "content": "import assert from \"node:assert\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { entryPoints } from \"./entryPoints.ts\";\nimport { updatePackageJson } from \"./helpers.ts\";\n\ntype ConditionRoot = {\n  import?: string;\n  \"module-sync\"?: string;\n  module?: string;\n  require?: string;\n  default?: string;\n};\n\nexport const addExports: BuildStep = async (options) => {\n  await updatePackageJson(options.packageRoot, (pkg) => {\n    // normal entry points a la `@apollo/client` and `@apollo/client/core`.\n    // these entry points will be used in most cases and point to the right file depending\n    // on how the user is consuming the package.\n    for (const entryPoint of entryPoints) {\n      if (typeof entryPoint.value === \"string\") {\n        pkg.exports[entryPoint.key] = processEntryPoint(\n          entryPoint.value,\n          pkg.exports[entryPoint.key]\n        );\n      } else {\n        for (const [key, value] of Object.entries(entryPoint.value)) {\n          if (!pkg.exports[entryPoint.key]) {\n            pkg.exports[entryPoint.key] = {};\n          }\n          assert(\n            typeof value === \"string\",\n            \"nesting of this complexity is not supported yet\"\n          );\n          pkg.exports[entryPoint.key][key] = processEntryPoint(\n            value,\n            pkg.exports[entryPoint.key][key]\n          );\n        }\n      }\n    }\n  });\n\n  // add legacy-style exports for `@apollo/client/index.js`, `@apollo/client/core/index.js`,\n  // `@apollo/client/main.cjs`, `@apollo/client/core/core.cjs`, etc.\n  // adding full entries for these would completely reiterate the other exports,\n  // not doing so would break things like a `production`/`development` distinction.\n  // instead, we create a new directory structure with stub files that `export * from \"@apollo/client/...\"\n  // which will then be picked up by the detailed export maps\n  for (const entryPoint of entryPoints) {\n    const from = `@apollo/client/${entryPoint.key.substring(2)}`.replace(\n      /\\/$/,\n      \"\"\n    );\n    const baseName =\n      options.type === \"esm\" ? \"index\" : entryPoint.dirs.at(-1) || \"main\";\n    await writeLegacyExport(entryPoint.dirs, baseName, from);\n  }\n  if (options.type === \"cjs\") {\n    // Legacy entry point for `@apollo/client/apollo-client.cjs`.\n    // This was a rolled-up build in the past, while now it's one of many compiled files.\n    // It's probably still better to have this available in case someone ever used it with bundlers.\n    await writeLegacyExport([], \"apollo-client\", \"@apollo/client\");\n  }\n\n  function processEntryPoint(value: string, existing: ConditionRoot = {}) {\n    value = value.replace(\n      /^.\\/src/,\n      `.${options.targetDir.replace(/^dist/, \"\")}`\n    );\n\n    if (options.type === \"esm\") {\n      const target = value.replace(/\\.ts$/, `.${options.jsExt}`);\n      existing.module = target;\n      existing[\"module-sync\"] = target;\n      // this will be handled by `default`, which directly follows, so we can omit it\n      // existing.import = target;\n      existing.default = target;\n    } else {\n      existing.require = value.replace(/\\.ts$/, `.${options.jsExt}`);\n    }\n    return JSON.parse(\n      JSON.stringify(existing, [\n        // ensure the order of keys is consistent\n        \"react-compiler\",\n        \"module\",\n        \"module-sync\",\n        \"require\",\n        \"import\",\n        \"default\",\n      ])\n    );\n  }\n\n  async function writeLegacyExport(\n    dirs: string[],\n    baseName: string,\n    from: string\n  ) {\n    const dirname = join(options.packageRoot, \"legacyEntryPoints\", ...dirs);\n    await mkdir(dirname, { recursive: true });\n    await writeFile(\n      join(dirname, `${baseName}.d.${options.tsExt}`),\n      `export * from \"${from}\";`,\n      { encoding: \"utf-8\" }\n    );\n    await writeFile(\n      join(dirname, `${baseName}.${options.jsExt}`),\n      options.type === \"esm\" ?\n        `export * from \"${from}\";`\n      : `module.exports = require(\"${from}\");`,\n      { encoding: \"utf-8\" }\n    );\n  }\n};\n"
  },
  {
    "path": "config/helpers.ts",
    "content": "import * as assert from \"node:assert\";\nimport { glob, unlink, writeFile } from \"node:fs/promises\";\nimport { mkdir, readFile, rm, symlink } from \"node:fs/promises\";\nimport { relative } from \"node:path\";\nimport * as path from \"path\";\n\nimport { ApiModelGenerator } from \"@microsoft/api-extractor/lib/generators/ApiModelGenerator.js\";\nimport type { ApiItem, ApiPackage } from \"@microsoft/api-extractor-model\";\nimport {\n  ApiDeclaredItem,\n  ApiEntryPoint,\n  ApiNamespace,\n} from \"@microsoft/api-extractor-model\";\nimport { apiItem_onParentChanged } from \"@microsoft/api-extractor-model/lib/items/ApiItem.js\";\nimport { TSDocParser } from \"@microsoft/tsdoc\";\nimport { DeclarationReference } from \"@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference.js\";\nimport * as recast from \"recast\";\nimport * as parser from \"recast/parsers/babel.js\";\nimport * as tsParser from \"recast/parsers/typescript.js\";\n// @ts-ignore unfortunately we don't have types for this as it's JS with JSDoc\n// eslint-disable-next-line import/no-unresolved\nimport * as sorcery from \"sorcery\";\n\nimport type { JSONSchemaForNPMPackageJsonFiles } from \"./schema.package.json.ts\";\n\nexport const distDir = path.resolve(import.meta.dirname, \"..\", \"dist\");\n\nexport function reparse(source: string) {\n  return recast.parse(source, { parser });\n}\n\nexport function reprint(ast: ReturnType<typeof reparse>) {\n  return recast.print(ast).code;\n}\n\ntype MaybePromise<T> = T | Promise<T>;\n\nexport async function applyRecast({\n  glob: globString,\n  cwd,\n  transformStep,\n}: {\n  glob: string;\n  cwd: string;\n  transformStep: (options: {\n    ast: recast.types.ASTNode;\n    sourceName: string;\n    relativeSourcePath: string;\n  }) => MaybePromise<{\n    ast: recast.types.ASTNode;\n    targetFileName?: string;\n    copy?: boolean;\n  }>;\n}) {\n  for await (let sourceFile of glob(globString, {\n    withFileTypes: true,\n    cwd,\n    exclude(fileName) {\n      return fileName.parentPath.indexOf(\"legacyEntryPoints\") !== -1;\n    },\n  })) {\n    const baseDir = sourceFile.parentPath;\n    const sourceFileName = sourceFile.name;\n    const sourcePath = path.join(baseDir, sourceFile.name);\n    const source = await readFile(sourcePath, { encoding: \"utf8\" });\n    const sourceMapName = source.match(/\\/\\/# sourceMappingURL=(.*)$/m)?.[1];\n    assert.ok(\n      sourceMapName,\n      `No source map found for file ${sourcePath} in ${source}`\n    );\n    const sourceMapPath = path.join(baseDir, sourceMapName);\n    const sourceMapContents = JSON.parse(\n      await readFile(sourceMapPath, {\n        encoding: \"utf8\",\n      })\n    );\n\n    // from now on, we're treating this data as if it were from an \"intermediate\" file instead\n    // we might want to override the original source file after all\n    // we place this in a \"parallel folder\" so relative paths have the same depth\n    const intermediateName = path.join(\"../intermediate\", sourceFileName);\n    const intermediateNamePath = path.join(baseDir, intermediateName);\n\n    const ast = recast.parse(source, {\n      parser: tsParser,\n      sourceFileName: intermediateName,\n    });\n    const transformResult = await transformStep({\n      ast,\n      sourceName: sourceFileName,\n      relativeSourcePath: relative(cwd, sourcePath),\n    });\n    const targetFileName = transformResult.targetFileName || sourceFileName;\n    const targetFilePath = path.join(baseDir, targetFileName);\n\n    const result = recast.print(transformResult.ast, {\n      sourceMapName: `${targetFileName}.map`,\n    });\n\n    if (!transformResult.copy) {\n      if (targetFileName !== sourceFileName) {\n        // we are renaming the files - as we won't be overriding in place,\n        // delete the old files\n        await rm(sourcePath);\n        await rm(sourceMapPath);\n      } else if (result.code === source) {\n        // no changes, so we can skip writing the file, which guarantees no further\n        // changes to the source map\n        continue;\n      }\n    }\n\n    // load the resulting \"targetFileName\" and the intermediate file into sorcery\n    // it will read the original .ts source from the file system\n    const virtualFiles = {\n      content: {\n        [intermediateNamePath]: source,\n        [targetFilePath]: result.code,\n      },\n      sourcemaps: {\n        [intermediateNamePath]: sourceMapContents,\n        [targetFilePath]: result.map,\n      },\n    };\n    // we use sorcery to combine all these source maps back into one\n    const chain = await sorcery.load(targetFilePath, virtualFiles);\n    // save everything back to the file system, applying the source map changes of the transformation\n    await chain.write();\n  }\n}\n\n/**\n * creates a pseudo \"dist/node_modules\" folder with\n * \"dist/node_modules/@apollo/client\" symlinked to \"dist\"\n * so that tools can pick up the client package as an \"external\" package\n */\nexport async function withPseudoNodeModules<T>(fn: () => T) {\n  const node_modules = path.join(distDir, \"node_modules\");\n  const parent = path.join(node_modules, \"@apollo\");\n  const link = path.join(parent, \"client\");\n\n  try {\n    await mkdir(parent, { recursive: true });\n    await unlink(link).catch(() => {});\n    await symlink(distDir, link);\n\n    return await fn();\n  } finally {\n    await rm(node_modules, { recursive: true });\n  }\n}\n\nexport function frameComment(text: string) {\n  const framed = text\n    .split(\"\\n\")\n    .map((t) => (t.match(/\\s+\\*/) ? t.trim() : t))\n    .map((t) => (!t.startsWith(\"*\") ? \"* \" + t : t))\n    .join(\"\\n\")\n    .replaceAll(/(^(\\s*\\*\\s*\\n)*|(\\n\\s*\\*\\s*)*$)/g, \"\");\n  return `*\\n${framed}\\n`;\n}\n\ntype PackageJson = Omit<JSONSchemaForNPMPackageJsonFiles, \"author\"> & {\n  author: string;\n};\n\nexport async function updatePackageJson(\n  dirname: string,\n  updater: (pkg: PackageJson) => PackageJson | void,\n  replacer: null | ((this: any, key: string, value: any) => any) = null\n) {\n  const packageJsonPath = path.join(dirname, \"package.json\");\n  const pkg = JSON.parse(\n    await readFile(packageJsonPath, \"utf8\")\n  ) as PackageJson;\n  const newContents = updater(pkg) ?? pkg;\n  await writeFile(\n    packageJsonPath,\n    JSON.stringify(newContents, replacer, 2) + \"\\n\"\n  );\n}\n\nexport function patchApiExtractorInternals() {\n  // The TSDoc parser mangles some parts of DocBlocks in a way that's problematic\n  // for us.\n  // This code is used to keep the original DocComment intact, so that we can\n  // use it later in the API docs.\n\n  const orig_parseRange = TSDocParser.prototype.parseRange;\n  TSDocParser.prototype.parseRange = function (range) {\n    const parsed = orig_parseRange.call(this, range);\n    parsed.docComment.emitAsTsdoc = function () {\n      return range.toString();\n    };\n    return parsed;\n  };\n\n  /*\n    In `buildDocEntryPoints` we create a file with namespace re-exports for all sub-entrypoints.\n    We don't want to actually export these as namespaces, but instead want to turn them into additional `EntryPoint` objects.\n    API Extractor itself cannot load more than one entrypoint, although the file format supports it - so we patch the logic here to reorganize the structure before saving.\n    */\n  const orig_buildApiPackage = ApiModelGenerator.prototype.buildApiPackage;\n  ApiModelGenerator.prototype.buildApiPackage = function (\n    this: ApiModelGenerator\n  ) {\n    const mappings: Record<string, string> = {};\n    const apiPackage: ApiPackage = orig_buildApiPackage.call(this);\n    const mainEntrypoint = apiPackage.entryPoints[0];\n    for (const [index, namespace] of Object.entries(\n      mainEntrypoint.members\n      // we iterate backwards so that we can remove entries without affecting the indexes\n    ).reverse()) {\n      if (\n        !(namespace instanceof ApiNamespace) ||\n        !namespace.name.startsWith(\"entrypoint_\")\n      ) {\n        continue;\n      }\n      // we want to turn namespaces into entry points\n      const entryPoint = new ApiEntryPoint({\n        name: namespace.name\n          .slice(\"entrypoint_\".length)\n          .replace(/__/g, \"/\")\n          .replace(/_/g, \"-\"),\n        members: [],\n      });\n\n      for (const member of namespace.members) {\n        // this is an internal function call - the only way to \"detach\" an existing node\n        // from its parent, so that it can be added to the new entry point\n        member[apiItem_onParentChanged](undefined);\n        entryPoint.addMember(member);\n      }\n\n      apiPackage.addMember(entryPoint);\n\n      (mainEntrypoint.members as ApiItem[]).splice(+index, 1);\n\n      mappings[\n        namespace.canonicalReference.toString().slice(0, -\":namespace\".length)\n      ] = entryPoint.canonicalReference.toString();\n    }\n\n    function fixup(item: ApiItem) {\n      item.members.forEach(fixup);\n      if (item instanceof ApiDeclaredItem) {\n        for (const excerpt of item.excerptTokens) {\n          const stringified = excerpt.canonicalReference?.toString();\n          if (stringified?.startsWith(\"@apollo/client!entrypoint_\")) {\n            // @ts-ignore\n            excerpt[\"_canonicalReference\"] = DeclarationReference.parse(\n              stringified.replace(\n                /(@apollo\\/client!entrypoint_[^.]+)[.:]/,\n                (_, start) => {\n                  if (!mappings[start]) {\n                    throw new Error(\n                      `No mapping found for ${start} in ${JSON.stringify(\n                        mappings\n                      )}`\n                    );\n                  }\n                  return mappings[start];\n                }\n              )\n            );\n          }\n        }\n      }\n    }\n\n    fixup(apiPackage);\n    return apiPackage;\n  };\n\n  return () => {\n    TSDocParser.prototype.parseRange = orig_parseRange;\n    ApiModelGenerator.prototype.buildApiPackage = orig_buildApiPackage;\n  };\n}\n"
  },
  {
    "path": "config/inlineInheritDoc.ts",
    "content": "/**\n * This build step will inline docblocks specified with `@inheritDoc` on build.\n *\n * E.g. a in a dockblock like this:\n *\n * ```js\n * /** {@inheritDoc @apollo/client!QueryOptions#query:member} *\\/\n * ```\n *\n * the annotation (everything from `{` to `}`) will be replaced with the docblock\n * of the `QueryOptions.query` member function.\n *\n * We need this here for situations where inheritance is not possible for `docModel`\n * generation (`interface Foo extends Omit<Bar, 'baz'> {}` is too complicated a\n * type for it to parse) and we want to flatten types - or going forward, for\n * generally flattening types without repeating docs everywhere.\n *\n * You can get these \"canonical ids\" by running\n *\n * ```sh\n * yarn docmodel\n * ```\n *\n * and looking at the generated [`client.api.json`](../docs/shared/client.api.json) file.\n */\n/** End file docs */\n\n// @ts-ignore\n\nimport fs, { mkdirSync, symlinkSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport {\n  Extractor,\n  ExtractorConfig,\n  ExtractorLogLevel,\n} from \"@microsoft/api-extractor\";\nimport { ApiDocumentedItem, ApiModel } from \"@microsoft/api-extractor-model\";\nimport type { DocComment, DocExcerpt, DocNode } from \"@microsoft/tsdoc\";\nimport type { TextRange } from \"@microsoft/tsdoc\";\nimport { DeclarationReference } from \"@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference.js\";\nimport { visit } from \"recast\";\n\nimport type { BuildStep, BuildStepOptions } from \"./build.ts\";\nimport { buildDocEntryPoints } from \"./entryPoints.ts\";\nimport {\n  applyRecast,\n  frameComment,\n  patchApiExtractorInternals,\n  withPseudoNodeModules,\n} from \"./helpers.ts\";\n\nexport const inlineInheritDoc: BuildStep = async (options) => {\n  console.log(\n    \"Processing {@inheritDoc <canonicalReference>} comments in .d.ts files.\"\n  );\n\n  const model = await withPseudoNodeModules(() => loadApiModel(options));\n  await processComments(model, options);\n};\n\nfunction getCommentFor(\n  canonicalReference: string,\n  variables: undefined | Record<string, string>,\n  model: ApiModel\n) {\n  const apiItem = model.resolveDeclarationReference(\n    DeclarationReference.parse(canonicalReference),\n    undefined\n  ).resolvedApiItem;\n  if (!apiItem)\n    throw new Error(\n      `Could not resolve canonical reference \"${canonicalReference}\"`\n    );\n  if (apiItem instanceof ApiDocumentedItem) {\n    if (!apiItem.tsdocComment) return \"\";\n    const unusedVariables = new Set(Object.keys(variables || {}));\n    let string = renderDocComment(apiItem.tsdocComment);\n\n    string = string.replaceAll(/\\\\?\\{\\\\?\\{(\\w+)\\\\?\\}\\\\?\\}/g, (_, variable) => {\n      unusedVariables.delete(variable);\n      const value = variables?.[variable];\n      if (value === undefined) {\n        throw new Error(\n          `Variable \"${variable}\" is required but not defined for @inheritDoc \"${canonicalReference}\"`\n        );\n      }\n      return value;\n    });\n    if (unusedVariables.size > 0) {\n      throw new Error(\n        `Variables ${[...unusedVariables].join(\n          \", \"\n        )} are defined but not used in @inheritDoc \"${canonicalReference}\"`\n      );\n    }\n    return string;\n  } else {\n    throw new Error(\n      `\"${canonicalReference}\" is not documented, so no documentation can be inherited.`\n    );\n  }\n}\n\nfunction loadApiModel(options: BuildStepOptions) {\n  const tempDir = fs.mkdtempSync(\"api-model\");\n  try {\n    const entryPointFile = path.join(tempDir, \"entry.d.ts\");\n    fs.writeFileSync(entryPointFile, buildDocEntryPoints(options));\n    mkdirSync(path.join(tempDir, \"node_modules\", \"@apollo\"), {\n      recursive: true,\n    });\n    symlinkSync(\n      options.packageRoot,\n      path.join(tempDir, \"node_modules\", \"@apollo\", \"client\")\n    );\n\n    // Load and parse the api-extractor.json file\n    const configObjectFullPath = path.resolve(\n      import.meta.dirname,\n      \"../api-extractor.json\"\n    );\n    const packageJsonFullPath = path.resolve(\n      import.meta.dirname,\n      \"../package.json\"\n    );\n    const tempModelFile = path.join(tempDir, \"client.api.json\");\n\n    const configObject = ExtractorConfig.loadFile(configObjectFullPath);\n    configObject.mainEntryPointFilePath = entryPointFile;\n    configObject.docModel = {\n      ...configObject.docModel,\n      enabled: true,\n      apiJsonFilePath: tempModelFile,\n    };\n    configObject.apiReport = {\n      enabled: false,\n      reportFileName: \"disabled.md\",\n      reportFolder: tempDir,\n    };\n\n    configObject.messages = {\n      extractorMessageReporting: {\n        default: {\n          logLevel: ExtractorLogLevel.None,\n        },\n      },\n      compilerMessageReporting: {\n        default: {\n          logLevel: ExtractorLogLevel.None,\n        },\n      },\n      tsdocMessageReporting: {\n        default: {\n          logLevel: ExtractorLogLevel.None,\n        },\n      },\n    };\n    const extractorConfig = ExtractorConfig.prepare({\n      configObject,\n      packageJsonFullPath,\n      configObjectFullPath,\n    });\n\n    const restore = patchApiExtractorInternals();\n    Extractor.invoke(extractorConfig);\n    restore();\n\n    const model = new ApiModel();\n    model.loadPackage(tempModelFile);\n    return model;\n  } finally {\n    fs.rmSync(tempDir, { recursive: true });\n  }\n}\n\nfunction processComments(model: ApiModel, options: BuildStepOptions) {\n  const inheritDocRegex =\n    /\\{\\s*@inheritDoc\\s+(\\S+)(?:\\s+(\\{[^}]*\\}))?\\s*\\}(?:\\s*$)?/;\n\n  return applyRecast({\n    glob: `**/*.{${options.jsExt},d.${options.tsExt}}`,\n    cwd: options.targetDir,\n    transformStep({ ast, sourceName }) {\n      return {\n        ast: visit(ast, {\n          visitNode(path) {\n            this.traverse(path);\n            const node = path.node;\n\n            if (!node.comments) {\n              return;\n            }\n\n            for (const comment of node.comments) {\n              if (comment.type === \"CommentBlock\") {\n                let newText = comment.value;\n                while (inheritDocRegex.test(newText)) {\n                  newText = newText.replace(\n                    inheritDocRegex,\n                    (_, canonicalReference, variables) => {\n                      try {\n                        return (\n                          getCommentFor(\n                            canonicalReference,\n                            variables ? JSON.parse(variables) : undefined,\n                            model\n                          ) || \"\"\n                        );\n                      } catch (e) {\n                        console.warn(\"\\n\\n\" + e.message);\n                        process.exitCode = 1;\n                      }\n                    }\n                  );\n                }\n                if (newText.includes(\"@inheritDoc\")) {\n                  console.warn(\n                    \"\\n\\nFound @inheritDoc after processing, something went wrong.\",\n                    {\n                      sourceName,\n                      originalText: comment.value,\n                      finalReplacement: newText,\n                    }\n                  );\n                  process.exitCode = 1;\n                }\n                if (comment.value !== newText) {\n                  comment.value = frameComment(newText);\n                }\n              }\n            }\n          },\n        }),\n      };\n    },\n  });\n}\n\nfunction renderDocComment(node: DocComment): string {\n  let commentRange: TextRange | undefined = undefined;\n  function iterate(node: undefined | DocNode | readonly DocNode[]) {\n    if (!node) return; // no node\n    if (commentRange) return; // we already found what we're looking for\n    if (\"forEach\" in node) {\n      node.forEach(iterate);\n      return;\n    }\n    if (node.kind === \"Excerpt\") {\n      const excerptNode = node as DocExcerpt;\n      commentRange = excerptNode.content.parserContext.commentRange;\n    }\n    node.getChildNodes().forEach(iterate);\n  }\n  iterate(node);\n\n  if (!commentRange) {\n    return \"\";\n  }\n\n  let text = commentRange.toString();\n  return text\n    .slice(2, -2)\n    .split(\"\\n\")\n    .map((line) =>\n      line\n        // remove leading ` *` or ` * `\n        .replace(/^\\s*\\* ?/, \"\")\n        // remove singular trailing spaces, but preserve multiple trailing spaces as those have a meaning in markdown\n        .replace(/(?<! ) $/, \"\")\n    )\n    .join(\"\\n\");\n}\n"
  },
  {
    "path": "config/jest/react-dom-17-client.js",
    "content": "// Shim for React 17 react-dom/client entrypoint imported by React Testing\n// Library\n\nmodule.exports = {\n  hydrateRoot: () => {\n    throw new Error(\n      \"Cannot use hydrateRoot with React 17. Ensure this uses legacy root instead\"\n    );\n  },\n  createRoot: () => {\n    throw new Error(\n      \"Cannot use createRoot with React 17. Ensure this uses legacy root instead\"\n    );\n  },\n};\n"
  },
  {
    "path": "config/jest.config.ts",
    "content": "import { join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst defaults = {\n  rootDir: \"src\",\n  preset: \"ts-jest\",\n  testEnvironment: fileURLToPath(\n    import.meta.resolve(\"./FixJSDOMEnvironment.js\")\n  ),\n  setupFilesAfterEnv: [\"<rootDir>/config/jest/setup.ts\"],\n  testEnvironmentOptions: {\n    url: \"http://localhost\",\n  },\n  snapshotFormat: {\n    escapeString: true,\n    printBasicPrototype: true,\n  },\n  transform: {\n    \"(dist/.+\\\\.js|\\\\.tsx?)$\": [\n      \"ts-jest\",\n      {\n        // just transpile, no type checking. We type-check in CI by running `tsc` directly.\n        tsconfig: join(import.meta.dirname, \"..\", \"tsconfig.tests.json\"),\n      },\n    ],\n  },\n  resolver: \"<rootDir>/config/jest/resolver.ts\",\n  transformIgnorePatterns: [\"/node_modules/(?!(rxjs)/)\"],\n  prettierPath: null,\n  moduleNameMapper: {\n    // Our internal testing utilities are not part of the final build, so we\n    // want to always import them from the source directory.\n    \"^@apollo/client/testing/internal$\": \"<rootDir>/testing/internal/index.ts\",\n  },\n};\n\nconst ignoreDTSFiles = \".d.ts$\";\nconst ignoreTSFiles = \".ts$\";\nconst ignoreTSXFiles = \".tsx$\";\n\nconst reactSharedTestFileIgnoreList = [\n  ignoreDTSFiles,\n  ignoreTSFiles,\n  \"src/react/hooks/__tests__/useBackgroundQuery/testUtils.tsx\",\n  \"src/react/hooks/__tests__/useSuspenseQuery/testUtils.tsx\",\n];\n\nconst react17TestFileIgnoreList = [\n  ...reactSharedTestFileIgnoreList,\n  // We only support Suspense with React 18, so don't test suspense hooks with\n  // React 17\n  \"src/testing/experimental/__tests__/createTestSchema.test.tsx\",\n  \"src/react/hooks/__tests__/useSuspenseFragment.test.tsx\",\n  \"src/react/hooks/__tests__/useSuspenseFragment/*\",\n  \"src/react/hooks/__tests__/useSuspenseQuery.test.tsx\",\n  \"src/react/hooks/__tests__/useSuspenseQuery/*\",\n  \"src/react/hooks/__tests__/useBackgroundQuery.test.tsx\",\n  \"src/react/hooks/__tests__/useBackgroundQuery/*\",\n  \"src/react/hooks/__tests__/useLoadableQuery.test.tsx\",\n  \"src/react/hooks/__tests__/useLoadableQuery/*\",\n  \"src/react/hooks/__tests__/useQueryRefHandlers.test.tsx\",\n  \"src/react/query-preloader/__tests__/createQueryPreloader.test.tsx\",\n  \"src/react/ssr/__tests__/prerenderStatic.test.tsx\",\n  \"src/react/ssr/__tests__/useQueryEndToEnd.test.tsx\",\n];\n\nconst tsStandardConfig = {\n  ...defaults,\n  displayName: \"Core Tests\",\n  testPathIgnorePatterns: [\n    ignoreDTSFiles,\n    ignoreTSXFiles,\n    \"src/local-state/__tests__/LocalState/testUtils.ts\",\n    \"src/local-state/__tests__/LocalState/fixtures/.*.ts$\",\n  ],\n};\n\nconst tsRxJSMinConfig = {\n  ...tsStandardConfig,\n  displayName: \"Core Tests - RxJS min version\",\n  moduleNameMapper: {\n    ...tsStandardConfig.moduleNameMapper,\n    \"^rxjs$\": \"rxjs-min\",\n  },\n};\n\n// For both React (Jest) \"projects\", ignore core tests (.ts files) as they\n// do not import React, to avoid running them twice.\nconst standardReact19Config = {\n  ...defaults,\n  displayName: \"ReactDOM 19\",\n  testPathIgnorePatterns: reactSharedTestFileIgnoreList,\n};\n\nconst standardReact18Config = {\n  ...defaults,\n  displayName: \"ReactDOM 18\",\n  testPathIgnorePatterns: [\n    ...reactSharedTestFileIgnoreList,\n    \"src/react/ssr/__tests__/prerenderStatic.test.tsx\",\n  ],\n  moduleNameMapper: {\n    ...defaults.moduleNameMapper,\n    \"^react$\": \"react-18\",\n    \"^react-dom$\": \"react-dom-18\",\n    \"^react-dom/(.*)$\": \"react-dom-18/$1\",\n  },\n};\n\nconst standardReact17Config = {\n  ...defaults,\n  displayName: \"ReactDOM 17\",\n  testPathIgnorePatterns: react17TestFileIgnoreList,\n  moduleNameMapper: {\n    ...defaults.moduleNameMapper,\n    \"^react$\": \"react-17\",\n    \"^react-dom$\": \"react-dom-17\",\n    \"^react-dom/client$\": \"<rootDir>/../config/jest/react-dom-17-client.js\",\n    \"^react-dom/server$\": \"react-dom-17/server\",\n    \"^react-dom/test-utils$\": \"react-dom-17/test-utils\",\n  },\n};\n\nexport default {\n  projects: [\n    tsStandardConfig,\n    tsRxJSMinConfig,\n    standardReact17Config,\n    standardReact18Config,\n    standardReact19Config,\n  ],\n};\n"
  },
  {
    "path": "config/listImports.ts",
    "content": "/**\n * used via e.g.\n *\n * ```sh\n * node --experimental-transform-types --no-warnings --conditions 'react-server' config/listImports.ts @apollo/client/react\n * ```\n *\n * from `src/__tests__/exports.ts`\n */\n// @ts-ignore\nimport { registerHooks } from \"node:module\";\n\nregisterHooks({\n  resolve(specifier, context, nextResolve) {\n    try {\n      return nextResolve(specifier, context);\n    } catch (e) {\n      if (specifier.endsWith(\".js\")) {\n        for (const ext of [\".ts\", \".tsx\"]) {\n          return nextResolve(specifier.slice(0, -3) + ext, context);\n        }\n      }\n      throw e;\n    }\n  },\n});\n\nObject.keys(await import(process.argv[2]))\n  .sort()\n  .forEach((i) => console.log(i));\n"
  },
  {
    "path": "config/madge.ts",
    "content": "import { join } from \"node:path\";\n\nimport * as madgePkg from \"madge\";\nconst madge = madgePkg.default;\nprocess.env.DEBUG = \"*\";\n\nfor (const customConditions of [[], [\"development\"], [\"production\"]]) {\n  const inst = await madge(join(import.meta.dirname, \"../src\"), {\n    baseDir: join(import.meta.dirname, \"..\"),\n    fileExtensions: [\"ts\", \"tsx\", \"js\", \"jsx\"],\n    tsConfig: {\n      compilerOptions: {\n        moduleResolution: \"NodeNext\",\n        customConditions,\n      },\n    },\n    includeNpm: true,\n    detectiveOptions: {\n      ts: {\n        skipTypeImports: true,\n      },\n    },\n  });\n  const circular = inst.circular();\n  if (circular.length) {\n    process.exitCode = 1;\n    console.warn(\n      \"❌ Circular dependencies found for customConditions:\",\n      customConditions\n    );\n    console.log(circular);\n  } else {\n    console.log(\n      \"✅ No circular dependencies found for customConditions:\",\n      customConditions\n    );\n  }\n}\n"
  },
  {
    "path": "config/precheck.ts",
    "content": "import lockfile from \"../package-lock.json\" with { type: \"json\" };\nconst { lockfileVersion } = lockfile;\n\nconst expectedVersion = 3;\n\nif (typeof lockfileVersion !== \"number\" || lockfileVersion < expectedVersion) {\n  throw new Error(\n    `Old lockfileVersion (${lockfileVersion}) found in package-lock.json (expected ${expectedVersion} or later)`\n  );\n}\n\nconsole.log(\"ok\", {\n  lockfileVersion,\n  expectedVersion,\n});\n"
  },
  {
    "path": "config/prepareDist.ts",
    "content": "// The Apollo Client source that is published to npm is located in the\n// \"dist\" directory. This utility script is called when building Apollo Client,\n// to make sure the \"dist\" directory is prepared for publishing.\n//\n// This script will:\n//\n// - Copy the current root package.json into \"dist\" after adjusting it for\n//   publishing.\n// - Copy the supporting files from the root into \"dist\" (e.g. `README.MD`,\n//   `LICENSE`, etc.).\n// - Create a new `package.json` for each sub-set bundle we support, and\n//   store it in the appropriate dist sub-directory.\n\nimport { copyFile, mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { updatePackageJson } from \"./helpers.ts\";\n\nexport const prepareDist: BuildStep = async (options) => {\n  if (!options.first) return;\n\n  await mkdir(options.packageRoot, { recursive: true });\n  await copyFile(\n    join(options.rootDir, \"package.json\"),\n    join(options.packageRoot, \"package.json\")\n  );\n  await updatePackageJson(\n    options.packageRoot,\n    (packageJson) => {\n      // The root package.json is marked as private to prevent publishing\n      // from happening in the root of the project. This sets the package back to\n      // public so it can be published from the \"dist\" directory.\n      packageJson.private = false;\n\n      // Remove package.json items that we don't need to publish\n      delete packageJson.scripts;\n      delete packageJson.bundlesize;\n      delete packageJson.devEngines;\n      delete packageJson.devDependencies;\n      delete packageJson.overrides;\n\n      packageJson.exports = {\n        \"./package.json\": \"./package.json\",\n        \"./*.js\": \"./legacyEntryPoints/*.js\",\n        \"./*.cjs\": \"./legacyEntryPoints/*.cjs\",\n        \"./*.d.ts\": \"./legacyEntryPoints/*.d.ts\",\n        \"./*.d.cts\": \"./legacyEntryPoints/*.d.cts\",\n      };\n    },\n    (_key: any, value: any) => {\n      // The root package.json points to the CJS/ESM source in \"dist\", to support\n      // on-going package development (e.g. running tests, supporting npm link, etc.).\n      // When publishing from \"dist\" however, we need to update the package.json\n      // to point to the files within the same directory.\n      if (typeof value === \"string\" && value.startsWith(\"./dist/\")) {\n        const parts = value.split(\"/\");\n        parts.splice(1, 1); // remove dist\n        return parts.join(\"/\");\n      }\n      return value;\n    }\n  );\n\n  // Copy supporting files into \"dist\"\n  await copyFile(\n    `${options.rootDir}/README.md`,\n    `${options.packageRoot}/README.md`\n  );\n  await copyFile(\n    `${options.rootDir}/LICENSE`,\n    `${options.packageRoot}/LICENSE`\n  );\n  await copyFile(\n    `${options.rootDir}/CHANGELOG.md`,\n    `${options.packageRoot}/CHANGELOG.md`\n  );\n};\n"
  },
  {
    "path": "config/preserveTsIgnore.ts",
    "content": "/**\n * TypeScript removes normal comments when it creates declaration files.\n *\n * That means that `// @ts-ignore` comments are removed, which can lead to\n * unwanted errors in the generated declaration files, if those comments\n * are still necessary in the generated `.d.ts` files.\n *\n * As a workaround, it's possible to use `/** @ts-ignore ...` instead,\n * as these are preserved in the generated declaration files.\n * The downside to this is that these comments then also might end up in\n * IDE inline documentation, which we want to avoid.\n *\n * This build step post-processes all `.d.ts` files if a block-comment\n * starts with `* @ts-ignore`, it removes the leading `*`, effectively\n * turning them into non-docBlock comments for shipping.\n */\n\nimport { visit } from \"recast\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { applyRecast, frameComment } from \"./helpers.ts\";\n\nexport const preserveTsIgnore: BuildStep = async (options) =>\n  applyRecast({\n    glob: `**/*.{${options.jsExt},d.${options.tsExt}}`,\n    cwd: options.targetDir,\n    transformStep({ ast }) {\n      return {\n        ast: visit(ast, {\n          visitNode(path) {\n            this.traverse(path);\n            const node = path.node;\n\n            if (!node.comments) {\n              return;\n            }\n\n            for (const comment of node.comments) {\n              if (\n                comment.type === \"CommentBlock\" &&\n                comment.value.match(/^\\*\\s*@ts-ignore/)\n              ) {\n                comment.value = comment.value.substring(1);\n              }\n            }\n          },\n        }),\n      };\n    },\n  });\n"
  },
  {
    "path": "config/prettier/format-jsdoc.js",
    "content": "/** @import { TSESTree as AST } from '@typescript-eslint/types' */\n/** @import { Plugin, Printer } from 'prettier' */\n\nimport * as prettier from \"prettier\";\nimport estree from \"prettier/plugins/estree.js\";\nimport { parsers as tsParsers } from \"prettier/plugins/typescript\";\n\n/** @type {Plugin[\"languages\"]} */\nexport const languages = [\n  {\n    name: \"TypeScript\",\n    parsers: [\"typescript-with-jsdoc\"],\n  },\n];\n/** @type {Plugin[\"parsers\"]} */\nexport const parsers = {\n  \"typescript-with-jsdoc\": {\n    ...tsParsers.typescript,\n    astFormat: \"typescript-with-jsdoc\",\n  },\n};\n/** @type {Printer} */\nconst estreePrinter = estree.printers.estree;\n/** @type {Plugin[\"printers\"]} */\nexport const printers = {\n  \"typescript-with-jsdoc\": {\n    ...estreePrinter,\n    print(path, options, print, args) {\n      return estreePrinter.print(path, options, print, args);\n    },\n    embed(path, options) {\n      if (path.node.comments) {\n        return async (textToDocForEmbed, mainPrint, path, options) => {\n          const newComments = await Promise.all(\n            Object.entries(path.node.comments)\n              .filter(\n                (/* @type {[string, AST.Comment]} */ [, comment]) =>\n                  comment.type === \"Block\" && comment.value[0] === \"*\"\n              )\n              .map(\n                async (/* @type {[string, AST.Comment]} */ [key, comment]) => {\n                  const doc = await textToDocForEmbed(\n                    comment.value\n                      .split(\"\\n\")\n                      .map((line) => line.replace(/^\\s*\\*/g, \"\"))\n                      .join(\"\\n\"),\n                    {\n                      parser: \"markdown\",\n                    }\n                  );\n                  const string = prettier.doc.printer.printDocToString(doc, {\n                    ...options,\n                    proseWrap: \"preserve\",\n                    trailingComma: \"none\",\n                  }).formatted;\n                  // keep it single-line if it originally was single-line\n                  if (\n                    comment.value.trim().indexOf(\"\\n\") === -1 &&\n                    string.trim().indexOf(\"\\n\") === -1\n                  ) {\n                    return [key, `* ${string} `];\n                  }\n\n                  return [\n                    key,\n                    \"*\\n\" +\n                      string\n                        .split(\"\\n\")\n                        .map((line) => \"* \" + line)\n                        .join(\"\\n\") +\n                      \"\\n\",\n                  ];\n                }\n              )\n          );\n          for (const [i, newCommment] of newComments) {\n            /* @type {AST.Comment} */\n            const nodeComent = path.node.comments[i];\n            nodeComent.value = newCommment;\n          }\n\n          return mainPrint(path.node);\n        };\n      }\n      return undefined;\n    },\n  },\n};\n"
  },
  {
    "path": "config/prettier/format-mdx3.js",
    "content": "/** @import { Plugin } from 'prettier' */\n\nimport * as prettier from \"prettier\";\nimport markdown from \"prettier/plugins/markdown.js\";\n\n/** @type {Plugin[\"languages\"]} */\nexport const languages = [\n  {\n    name: \"MDX\",\n    parsers: [\"mdx3\"],\n    extensions: [\".mdx\"],\n  },\n];\n/** @type {Plugin[\"parsers\"]} */\nexport const parsers = {\n  mdx3: {\n    ...markdown.parsers.mdx,\n    astFormat: \"mdx3\",\n  },\n};\n\n// matches e.g. \"[!code ++]\" \"[!code highlight:3]\" \"[!code word:Cache]\" or \"[!code word:Cache:123]\"\nconst codePattern = /\\[!code ([a-z+-]+|word:((?:\\\\.|[^:\\]])+))(:\\d+)?\\]/;\n// matches repetitions with surrounding and in-between spaces, so e.g. \"[!code ++] [!code highlight:3]\"\nconst multiCodePattern = new RegExp(`(\\\\s*${codePattern.source})+\\\\s*`);\nconst patterns = [\n  // \"<!-- [!code ++] -->\", \"<!-- [!code ++] [!code highlight:3] -->\"\n  new RegExp(`<!--${multiCodePattern.source}-->`, \"g\"),\n  // \"{/* [!code ++] */\", \"/* [!code ++] [!code highlight:3] */}\"\n  new RegExp(`[{]/[*]${multiCodePattern.source}[*]/[}]`, \"g\"),\n  // \"/* [!code ++] */\", \"/* [!code ++] [!code highlight:3] */\"\n  new RegExp(`/[*]${multiCodePattern.source}[*]/`, \"g\"),\n  // end-of line comments like \"// [!code ++]\", \"# [!code highlight:3]\", \"-- [!code word:Cache] [!code --]\"\"\n  new RegExp(`(//|[\"'#]|;{1,2}|%{1,2}|--)${multiCodePattern.source}$`, \"gm\"),\n];\nconst specialCommentPattern = new RegExp(\n  `(${patterns.map((p) => `(${p.source})`).join(\"|\")})`,\n  \"gm\"\n);\n\n/**\n * Applied to code blocks to preserve special comments like `// [!code ...]` on the same line.\n */\nfunction handleCodeBlockWithSpecialComments(node, path, options) {\n  // Check if this code block has special comments\n  const commentMatches = [...node.value.matchAll(specialCommentPattern)];\n  // Nothing to do.\n  if (commentMatches.length == 0) return null;\n\n  /** `true` if comment should be inline, `false` if it should be on a new line. */\n  const commentsInline = commentMatches.map((commentMatch) => {\n    for (\n      let index = commentMatch.index - 1, char = node.value[index];\n      index >= 0 && char !== \"\\n\";\n      char = node.value[--index]\n    ) {\n      const char = node.value[index];\n      if (char !== \" \" && char !== \"\\t\") {\n        return true;\n      }\n    }\n    return false;\n  });\n\n  // Use default formatting first\n  const defaultEmbed = markdown.printers.mdast.embed(path, options);\n  return async (textToDoc) => {\n    let stringResult = prettier.doc.printer.printDocToString(\n      await defaultEmbed(textToDoc),\n      options\n    ).formatted;\n\n    const formattedCommentMatches = [\n      ...stringResult.matchAll(specialCommentPattern),\n    ];\n\n    // Process each comment in reverse order to avoid index shifting\n    for (let i = formattedCommentMatches.length - 1; i >= 0; i--) {\n      const commentMatch = formattedCommentMatches[i];\n      const shouldBeInline = commentsInline[i];\n      if (!shouldBeInline) continue;\n\n      // Find the preceding non-whitespace character, starting from the comment position\n      let insertPos = commentMatch.index - 1;\n      while (insertPos >= 0 && /\\s/.test(stringResult[insertPos])) {\n        insertPos--;\n      }\n\n      stringResult =\n        stringResult.substring(0, insertPos + 1) +\n        stringResult.substring(commentMatch.index);\n    }\n\n    return stringResult;\n  };\n}\n\n/** @type {Plugin[\"printers\"]} */\nexport const printers = {\n  mdx3: {\n    ...markdown.printers.mdast,\n    embed(path, options) {\n      const node = path.node;\n\n      if (node.type === \"code\" && node.lang !== null) {\n        const result = handleCodeBlockWithSpecialComments(node, path, options);\n        if (result) return result;\n      }\n\n      if (node.type === \"jsx\") {\n        // If the node was parsed incorrectly because it followed the MDX3 format (no spacing around JSX tags),\n        // we will not try to format it as MDX, but instead return the original value.\n\n        // We detect that by looking at `value` - if it's only a starting or closing tag, it was parsed correctly.\n        const correctlyParsedMatch = node.value.match(/^(<\\/?[^>]*>)$/);\n        if (!correctlyParsedMatch)\n          return (\n            node.value\n              .split(\"\\n\")\n              // But we need to restore the original indentation\n              .map((line, idx) =>\n                idx === 0 ? line : (\n                  \" \".repeat(node.position.indent[idx - 1] - 1) + line\n                )\n              )\n              .join(\"\\n\")\n          );\n      }\n      return markdown.printers.mdast.embed(path, options);\n    },\n  },\n};\n"
  },
  {
    "path": "config/prettier/test.ts",
    "content": "import * as prettier from \"prettier\";\nconst code = `\n\\`\\`\\`ts\nconst client = new ApolloClient({\n  link: new HttpLink({ // [!code ++]\n    uri: \"https://example.com/graphql\",\n  }),\n});\n\\`\\`\\`\n`;\n\nconst result = await prettier.format(code, {\n  parser: \"mdx3\",\n  plugins: [\"./format-mdx3.js\"],\n});\n\nconsole.log(result);\n"
  },
  {
    "path": "config/processInvariants.ts",
    "content": "import * as fs from \"fs\";\nimport { join as osPathJoin, posix } from \"path\";\n\nimport type { ExpressionKind } from \"ast-types/lib/gen/kinds\";\nimport * as recast from \"recast\";\n\nimport type { BuildStepOptions } from \"./build.ts\";\nimport { applyRecast, reprint } from \"./helpers.ts\";\nconst b = recast.types.builders;\nconst n = recast.types.namedTypes;\ntype Node = recast.types.namedTypes.Node;\ntype CallExpression = recast.types.namedTypes.CallExpression;\ntype NewExpression = recast.types.namedTypes.NewExpression;\n\nexport async function processInvariants(options: BuildStepOptions) {\n  const program = b.program([]);\n  let nextErrorCode = 1;\n\n  const allExports = {\n    errorCodes: getExportObject(\"errorCodes\"),\n    devDebug: getExportObject(\"devDebug\"),\n    devLog: getExportObject(\"devLog\"),\n    devWarn: getExportObject(\"devWarn\"),\n    devError: getExportObject(\"devError\"),\n  };\n  type ExportName = keyof typeof allExports;\n\n  program.comments = [\n    b.commentLine(\n      \" This file is used by the error message display website and the\",\n      true\n    ),\n    b.commentLine(\" @apollo/client/includeErrors entry point.\", true),\n    b.commentLine(\" This file is not meant to be imported manually.\", true),\n  ];\n\n  if (options.type === \"cjs\") {\n    program.body.unshift(\n      b.expressionStatement(\n        b.callExpression(\n          b.memberExpression(\n            b.identifier(\"Object\"),\n            b.identifier(\"defineProperty\")\n          ),\n          [\n            b.identifier(\"exports\"),\n            b.stringLiteral(\"__esModule\"),\n            b.objectExpression([\n              b.property(\"init\", b.identifier(\"value\"), b.booleanLiteral(true)),\n            ]),\n          ]\n        )\n      ),\n      b.expressionStatement(\n        Object.keys(allExports).reduce<\n          | recast.types.namedTypes.UnaryExpression\n          | recast.types.namedTypes.AssignmentExpression\n        >(\n          (right, name) =>\n            b.assignmentExpression(\n              \"=\",\n              b.memberExpression(b.identifier(\"exports\"), b.identifier(name)),\n              right\n            ),\n          b.unaryExpression(\"void\", b.numericLiteral(0), true)\n        )\n      )\n    );\n  }\n\n  await applyRecast({\n    cwd: options.targetDir,\n    glob: `**/*.${options.jsExt}`,\n    transformStep: transform,\n  });\n\n  fs.writeFileSync(\n    osPathJoin(options.targetDir, `invariantErrorCodes.${options.jsExt}`),\n    recast.print(program, {\n      tabWidth: 2,\n    }).code + \"\\n\"\n  );\n\n  function getExportObject(exportName: string) {\n    const object = b.objectExpression([]);\n\n    if (options.type === \"esm\") {\n      program.body.push(\n        b.exportNamedDeclaration(\n          b.variableDeclaration(\"const\", [\n            b.variableDeclarator(b.identifier(exportName), object),\n          ])\n        )\n      );\n    } else {\n      program.body.push(\n        b.expressionStatement(\n          b.assignmentExpression(\n            \"=\",\n            b.memberExpression(\n              b.identifier(\"exports\"),\n              b.identifier(exportName)\n            ),\n            object\n          )\n        )\n      );\n    }\n    return object;\n  }\n\n  function getErrorCode(\n    file: string,\n    expr: CallExpression | NewExpression,\n    type: keyof typeof allExports\n  ): ExpressionKind {\n    if (isIdWithName(expr.callee, \"invariant\")) {\n      return extractString(\n        file,\n        allExports[type].properties,\n        expr.arguments[1],\n        expr.arguments[0]\n      );\n    } else {\n      return extractString(\n        file,\n        allExports[type].properties,\n        expr.arguments[0]\n      );\n    }\n\n    function extractString(\n      file: string,\n      target: (typeof allExports)[ExportName][\"properties\"],\n      message: recast.types.namedTypes.SpreadElement | ExpressionKind,\n      condition?: recast.types.namedTypes.SpreadElement | ExpressionKind\n    ): ExpressionKind {\n      if (message.type === \"ConditionalExpression\") {\n        return b.conditionalExpression(\n          message.test,\n          extractString(file, target, message.consequent, condition),\n          extractString(file, target, message.alternate, condition)\n        );\n      } else if (isStringOnly(message)) {\n        const messageText = reprint(message);\n        if (messageText.includes(\"Apollo DevTools\")) {\n          return message;\n        }\n\n        const obj = b.objectExpression([]);\n        const numLit = b.numericLiteral(nextErrorCode++);\n        target.push(b.property(\"init\", numLit, obj));\n\n        obj.properties.push(\n          b.property(\n            \"init\",\n            b.identifier(\"file\"),\n            b.stringLiteral(\n              options.targetDir.replace(/^dist/, \"@apollo/client\") + \"/\" + file\n            )\n          )\n        );\n        if (condition) {\n          obj.properties.push(\n            b.property(\n              \"init\",\n              b.identifier(\"condition\"),\n              b.stringLiteral(reprint(expr.arguments[0]))\n            )\n          );\n        }\n        obj.properties.push(\n          b.property(\"init\", b.identifier(\"message\"), message)\n        );\n\n        return numLit;\n      } else {\n        throw new Error(`invariant minification error: node cannot have dynamical error argument!\n        file: ${posix.join(options.targetDir, file)}:${expr.loc?.start.line}\n        code:\n\n        ${reprint(message)}\n      `);\n      }\n    }\n  }\n\n  function transform({\n    ast,\n    relativeSourcePath,\n  }: {\n    ast: recast.types.ASTNode;\n    relativeSourcePath: string;\n  }) {\n    let fileRequiresDevImport = false;\n    if (\n      relativeSourcePath !==\n      osPathJoin(`utilities`, `invariant`, `index.${options.jsExt}`)\n    )\n      recast.visit(ast, {\n        visitCallExpression(path) {\n          this.traverse(path);\n          const node = path.node;\n\n          if (isCallWithLength(node, \"invariant\", 1)) {\n            const newArgs = [...node.arguments];\n            newArgs.splice(\n              1,\n              1,\n              getErrorCode(relativeSourcePath, node, \"errorCodes\")\n            );\n\n            return b.callExpression.from({\n              ...node,\n              arguments: newArgs,\n            });\n          }\n\n          if (isCallWithLength(node, \"newInvariantError\", 0)) {\n            const newArgs = [...node.arguments];\n            newArgs.splice(\n              0,\n              1,\n              getErrorCode(relativeSourcePath, node, \"errorCodes\")\n            );\n\n            return b.callExpression.from({\n              ...node,\n              arguments: newArgs,\n            });\n          }\n\n          if (\n            node.callee.type === \"MemberExpression\" &&\n            isIdWithName(node.callee.object, \"invariant\") &&\n            isIdWithName(node.callee.property, \"debug\", \"log\", \"warn\", \"error\")\n          ) {\n            let newNode = node;\n            if (node.arguments[0].type !== \"Identifier\") {\n              const prop = node.callee.property;\n              if (!n.Identifier.check(prop)) throw new Error(\"unexpected type\");\n\n              const newArgs = [...node.arguments];\n              newArgs.splice(\n                0,\n                1,\n                getErrorCode(\n                  relativeSourcePath,\n                  node,\n                  (\"dev\" + capitalize(prop.name)) as ExportName\n                )\n              );\n              newNode = b.callExpression.from({\n                ...node,\n                arguments: newArgs,\n              });\n            }\n\n            if (\n              isDEVLogicalAnd(path.parent.node) ||\n              isIdWithName(node.callee.property, \"error\")\n            ) {\n              return newNode;\n            }\n            fileRequiresDevImport = true;\n            return b.logicalExpression(\"&&\", makeDEVExpr(), newNode);\n          }\n        },\n      });\n\n    if (fileRequiresDevImport) addDevImport(ast, options.type);\n\n    return { ast };\n  }\n\n  function _isIdWithName(node: Node | null | undefined, ...names: string[]) {\n    return (\n      node &&\n      n.Identifier.check(node) &&\n      names.some((name) => name === node.name)\n    );\n  }\n\n  /**\n   * wrapper around \\_isIdWithName that also checks for cjs-transpiled code-patterns:\n   *\n   * ```\n   * invariant(condition)\n   * ^^^^^^^^^\n   * in CJS:\n   * (0, index_js_1.invariant)(condition)\n   *                ^^^^^^^^^\n   * or index_js_2.invariant.warn\n   *               ^^^^^^^^^\n   * ```\n   */\n  function isIdWithName(node: Node | null | undefined, ...names: string[]) {\n    return (\n      _isIdWithName(node, ...names) ||\n      (n.SequenceExpression.check(node) &&\n        n.MemberExpression.check(node.expressions[1]) &&\n        _isIdWithName(node.expressions[1].property, ...names)) ||\n      (n.MemberExpression.check(node) && _isIdWithName(node.property, ...names))\n    );\n  }\n\n  function isCallWithLength(\n    node: CallExpression | NewExpression,\n    name: string,\n    length: number\n  ) {\n    return isIdWithName(node.callee, name) && node.arguments.length > length;\n  }\n\n  function isDEVLogicalAnd(node: Node) {\n    return (\n      n.LogicalExpression.check(node) &&\n      node.operator === \"&&\" &&\n      isDEVExpr(node.left)\n    );\n  }\n\n  function makeDEVExpr() {\n    return b.identifier(\"__DEV__\");\n  }\n\n  function isDEVExpr(node: Node) {\n    return isIdWithName(node, \"__DEV__\");\n  }\n\n  function isStringOnly(\n    node: recast.types.namedTypes.ASTNode\n  ): node is ExpressionKind {\n    switch (node.type) {\n      case \"StringLiteral\":\n      case \"Literal\":\n        return true;\n      case \"TemplateLiteral\":\n        return (node.expressions as recast.types.namedTypes.ASTNode[]).every(\n          isStringOnly\n        );\n      case \"BinaryExpression\":\n        return (\n          node.operator == \"+\" &&\n          isStringOnly(node.left) &&\n          isStringOnly(node.right)\n        );\n    }\n    return false;\n  }\n\n  function capitalize(str: string) {\n    return str[0].toUpperCase() + str.slice(1);\n  }\n}\nfunction addDevImport(ast: recast.types.ASTNode, type: \"esm\" | \"cjs\") {\n  let fileRequiresDevImport = true;\n  // check if a dev import is already present\n  recast.visit(ast, {\n    visitImportDeclaration(path) {\n      const node = path.node;\n      if (node.source.value === \"@apollo/client/utilities/environment\") {\n        if (\n          node.specifiers.some(\n            (s) => s.type === \"ImportSpecifier\" && s.imported.name === \"__DEV__\"\n          )\n        ) {\n          fileRequiresDevImport = false;\n          return this.abort();\n        }\n      }\n      return this.traverse(path);\n    },\n    visitProgram(path) {\n      const node = path.node;\n      if (\n        node.body.some(\n          (expr) =>\n            expr.type === \"VariableDeclaration\" &&\n            expr.declarations.some(\n              (declaration) =>\n                declaration.type === \"VariableDeclarator\" &&\n                ((declaration.id.type === \"ObjectPattern\" &&\n                  declaration.id.properties.some(\n                    (p) =>\n                      p.type === \"Property\" &&\n                      p.key.type === \"Identifier\" &&\n                      p.key.name === \"__DEV__\"\n                  )) ||\n                  (declaration.id.type === \"Identifier\" &&\n                    declaration.id.name === \"__DEV__\"))\n            )\n        )\n      ) {\n        fileRequiresDevImport = false;\n        return this.abort();\n      }\n      return this.traverse(path);\n    },\n  });\n\n  if (fileRequiresDevImport) {\n    recast.visit(ast, {\n      visitProgram(path) {\n        const node = path.node;\n        if (type === \"esm\") {\n          node.body.unshift(\n            b.importDeclaration(\n              [b.importSpecifier(b.identifier(\"__DEV__\"))],\n              b.literal(\"@apollo/client/utilities/environment\")\n            )\n          );\n        } else {\n          const identifier = b.identifier(\"__DEV__\");\n          node.body.unshift(\n            b.variableDeclaration(\"const\", [\n              b.variableDeclarator(\n                b.objectPattern([\n                  b.property.from({\n                    kind: \"init\",\n                    key: identifier,\n                    value: identifier,\n                    shorthand: true,\n                  }),\n                ]),\n                b.callExpression(b.identifier(\"require\"), [\n                  b.literal(\"@apollo/client/utilities/environment\"),\n                ])\n              ),\n            ])\n          );\n        }\n        return false;\n      },\n    });\n  }\n}\n"
  },
  {
    "path": "config/react-compiler.ts",
    "content": "import { readFileSync } from \"node:fs\";\nimport { cp, mkdir } from \"node:fs/promises\";\nimport { dirname, format, join, parse, resolve } from \"node:path\";\n\nimport { transformFromAstAsync } from \"@babel/core\";\nimport { visit } from \"recast\";\nimport { SourceMapConsumer } from \"source-map\";\n\nimport type { BuildStep } from \"./build.ts\";\nimport { applyRecast, updatePackageJson } from \"./helpers.ts\";\n\nexport const reactCompiler: BuildStep = async (options) => {\n  if (options.type !== \"esm\") {\n    return;\n  }\n  const cwd = join(options.targetDir, \"react\", \"hooks-compiled\");\n  await cp(join(options.targetDir, \"react\", \"hooks\"), cwd, { recursive: true });\n  await applyRecast({\n    glob: `**/*.${options.jsExt}`,\n    cwd,\n    async transformStep({ ast, sourceName, relativeSourcePath }) {\n      const mapPath = join(cwd, relativeSourcePath + \".map\");\n      const rawMap = JSON.parse(readFileSync(mapPath, \"utf-8\"));\n      let consumer: SourceMapConsumer | null = null;\n      const result = await transformFromAstAsync(ast as any, undefined, {\n        filename: sourceName,\n        sourceFileName: sourceName,\n        sourceMaps: true,\n        code: false,\n        ast: true,\n        cloneInputAst: false,\n        retainLines: true,\n        plugins: [\n          [\n            \"babel-plugin-react-compiler\",\n            {\n              target: \"17\",\n              // still too many errors to enable panicThreshold on any level\n              // panicThreshold: \"critical_errors\",\n              // panicThreshold: \"all_errors\",\n              logger: {\n                logEvent(_, event) {\n                  if (event.kind === \"CompileError\") {\n                    const loc =\n                      event.detail.primaryLocation?.() || event.detail.loc;\n\n                    let source = `${join(cwd, relativeSourcePath)}${\n                      loc ? `:${loc.start.line}:${loc.start.column}` : \"\"\n                    }`;\n\n                    if (loc) {\n                      const { line, column } = loc.start;\n                      consumer ||= new SourceMapConsumer(rawMap);\n                      const original = consumer.originalPositionFor({\n                        line,\n                        column,\n                      });\n                      if (original.source) {\n                        source += `, original source ${resolve(\n                          dirname(join(cwd, relativeSourcePath)),\n                          original.source\n                        )}:${original.line}:${original.column}`;\n                      }\n                    }\n\n                    console.error(`\\nCompilation failed: ${source}`);\n                    console.error(`Reason: ${event.detail.reason}`);\n\n                    if (event.detail.description) {\n                      console.error(`Details: ${event.detail.description}`);\n                    }\n\n                    if (event.detail.suggestions) {\n                      console.error(\"Suggestions:\", event.detail.suggestions);\n                    }\n                  }\n                },\n              },\n            },\n          ],\n          {\n            visitor: {\n              ImportDeclaration(path) {\n                // Rewrite imports for the React Compiler Runtime to our own copy\n                // until the upstream package is stable\n                if (path.node.source.value === \"react-compiler-runtime\") {\n                  path.node.source.value =\n                    \"@apollo/client/react/internal/compiler-runtime\";\n                }\n              },\n            },\n          },\n        ],\n      });\n      return { ast: result.ast!, map: result.map };\n    },\n  });\n\n  const compilerVersion = (\n    await import(\"babel-plugin-react-compiler/package.json\", {\n      with: { type: \"json\" },\n    })\n  ).default.version;\n\n  await applyRecast({\n    glob: \"index.{js,d.ts}\",\n    cwd: join(options.targetDir, \"react\"),\n    transformStep({ ast, sourceName }) {\n      return {\n        targetFileName: sourceName.replace(\"index.\", \"index.compiled.\"),\n        copy: true,\n        ast: visit(ast, {\n          visitExportNamedDeclaration(path) {\n            if (path.node.source) {\n              const source = path.node.source.value.toString();\n              if (source.startsWith(\"./hooks/\")) {\n                path.node.source.value = source.replace(\n                  \"./hooks/\",\n                  \"./hooks-compiled/\"\n                );\n              }\n            }\n            this.traverse(path);\n          },\n          visitVariableDeclarator(path) {\n            if (\n              path.node.id.type === \"Identifier\" &&\n              path.node.id.name === \"reactCompilerVersion\"\n            ) {\n              path.node.init = {\n                type: \"StringLiteral\",\n                value: compilerVersion,\n              };\n            }\n            this.traverse(path);\n          },\n        }),\n      };\n    },\n  });\n  await updatePackageJson(options.packageRoot, (pkg) => {\n    pkg.exports[\"./react/compiled\"] = \"./react/index.compiled.js\";\n  });\n\n  // add `react/compiled/index.js` entry point for `node10` resolution\n  await mkdir(join(options.targetDir, \"react\", \"compiled\"));\n  await applyRecast({\n    glob: \"index.{js,d.ts}\",\n    cwd: join(options.targetDir, \"react\"),\n    transformStep({ ast, sourceName }) {\n      const originalFileName = parse(sourceName);\n      const targetFileName = format({\n        ...originalFileName,\n        dir: join(originalFileName.dir, \"compiled\"),\n      });\n      return {\n        targetFileName,\n        copy: true,\n        ast: {\n          type: \"File\",\n          program: {\n            type: \"Program\",\n            sourceType: \"module\",\n            body: [\n              {\n                type: \"ExportAllDeclaration\",\n                source: {\n                  type: \"StringLiteral\",\n                  value: \"../index.compiled.js\",\n                },\n              },\n            ],\n          },\n        },\n      };\n    },\n  });\n};\n"
  },
  {
    "path": "config/schema.package.json.ts",
    "content": "/**\n * This file was automatically generated by json-schema-to-typescript\n * based on https://json.schemastore.org/package.json.\n * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,\n * and run json-schema-to-typescript to regenerate this file.\n */\n\nexport type JSONSchemaForNPMPackageJsonFiles = {\n  [k: string]: unknown;\n} & {\n  /**\n   * The name of the package.\n   */\n  name?: string;\n  /**\n   * Version must be parseable by node-semver, which is bundled with npm as a dependency.\n   */\n  version?: string;\n  /**\n   * This helps people discover your package, as it's listed in 'npm search'.\n   */\n  description?: string;\n  /**\n   * This helps people discover your package as it's listed in 'npm search'.\n   */\n  keywords?: string[];\n  /**\n   * The url to the project homepage.\n   */\n  homepage?: string;\n  /**\n   * The url to your project's issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.\n   */\n  bugs?:\n    | {\n        /**\n         * The url to your project's issue tracker.\n         */\n        url?: string;\n        /**\n         * The email address to which issues should be reported.\n         */\n        email?: string;\n        [k: string]: unknown;\n      }\n    | string;\n  /**\n   * You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you're placing on it.\n   */\n  license?:\n    | string\n    | (\n        | \"AGPL-3.0-only\"\n        | \"Apache-2.0\"\n        | \"BSD-2-Clause\"\n        | \"BSD-3-Clause\"\n        | \"BSL-1.0\"\n        | \"CC0-1.0\"\n        | \"CDDL-1.0\"\n        | \"CDDL-1.1\"\n        | \"EPL-1.0\"\n        | \"EPL-2.0\"\n        | \"GPL-2.0-only\"\n        | \"GPL-3.0-only\"\n        | \"ISC\"\n        | \"LGPL-2.0-only\"\n        | \"LGPL-2.1-only\"\n        | \"LGPL-2.1-or-later\"\n        | \"LGPL-3.0-only\"\n        | \"LGPL-3.0-or-later\"\n        | \"MIT\"\n        | \"MPL-2.0\"\n        | \"MS-PL\"\n        | \"UNLICENSED\"\n      );\n  /**\n   * DEPRECATED: Instead, use SPDX expressions, like this: { \"license\": \"ISC\" } or { \"license\": \"(MIT OR Apache-2.0)\" } see: 'https://docs.npmjs.com/files/package.json#license'.\n   */\n  licenses?: {\n    type?: License;\n    url?: string;\n    [k: string]: unknown;\n  }[];\n  author?: Person;\n  /**\n   * A list of people who contributed to this package.\n   */\n  contributors?: Person[];\n  /**\n   * A list of people who maintains this package.\n   */\n  maintainers?: Person[];\n  /**\n   * The 'files' field is an array of files to include in your project. If you name a folder in the array, then it will also include the files inside that folder.\n   */\n  files?: string[];\n  /**\n   * The main field is a module ID that is the primary entry point to your program.\n   */\n  main?: string;\n  /**\n   * The \"exports\" field is used to restrict external access to non-exported module files, also enables a module to import itself using \"name\".\n   */\n  exports?:\n    | (string | null)\n    | {\n        /**\n         * The module path that is resolved when the module specifier matches \"name\", shadows the \"main\" field.\n         */\n        \".\"?: PackageExportsEntry | PackageExportsFallback;\n        /**\n         * The module path prefix that is resolved when the module specifier starts with \"name/\", set to \"./\\*\" to allow external modules to import any subpath.\n         *\n         * This interface was referenced by `undefined`'s JSON-Schema definition\n         * via the `patternProperty` \"^\\./.+\".\n         */\n        [k: string]: PackageExportsEntry | PackageExportsFallback;\n      }\n    | PackageExportsEntryObject1\n    | PackageExportsFallback1;\n  /**\n   * The \"imports\" field is used to create private mappings that only apply to import specifiers from within the package itself.\n   */\n  imports?: {\n    /**\n     * The module path that is resolved when this environment matches the property name.\n     *\n     * This interface was referenced by `undefined`'s JSON-Schema definition\n     * via the `patternProperty` \"^#.+$\".\n     */\n    [k: string]: PackageImportsEntry | PackageImportsFallback;\n  };\n  bin?:\n    | string\n    | {\n        [k: string]: string;\n      };\n  /**\n   * When set to \"module\", the type field allows a package to specify all .js files within are ES modules. If the \"type\" field is omitted or set to \"commonjs\", all .js files are treated as CommonJS.\n   */\n  type?: \"commonjs\" | \"module\";\n  /**\n   * Set the types property to point to your bundled declaration file.\n   */\n  types?: string;\n  /**\n   * Note that the \"typings\" field is synonymous with \"types\", and could be used as well.\n   */\n  typings?: string;\n  /**\n   * The \"typesVersions\" field is used since TypeScript 3.1 to support features that were only made available in newer TypeScript versions.\n   */\n  typesVersions?: {\n    /**\n     * Contains overrides for the TypeScript version that matches the version range matching the property key.\n     */\n    [k: string]: {\n      /**\n       * Maps all file paths to the file paths specified in the array.\n       */\n      \"*\"?: string[];\n    };\n  };\n  /**\n   * Specify either a single file or an array of filenames to put in place for the man program to find.\n   */\n  man?: string[] | string;\n  directories?: {\n    /**\n     * If you specify a 'bin' directory, then all the files in that folder will be used as the 'bin' hash.\n     */\n    bin?: string;\n    /**\n     * Put markdown files in here. Eventually, these will be displayed nicely, maybe, someday.\n     */\n    doc?: string;\n    /**\n     * Put example scripts in here. Someday, it might be exposed in some clever way.\n     */\n    example?: string;\n    /**\n     * Tell people where the bulk of your library is. Nothing special is done with the lib folder in any way, but it's useful meta info.\n     */\n    lib?: string;\n    /**\n     * A folder that is full of man pages. Sugar to generate a 'man' array by walking the folder.\n     */\n    man?: string;\n    test?: string;\n    [k: string]: unknown;\n  };\n  /**\n   * Specify the place where your code lives. This is helpful for people who want to contribute.\n   */\n  repository?:\n    | {\n        type?: string;\n        url?: string;\n        directory?: string;\n        [k: string]: unknown;\n      }\n    | string;\n  funding?:\n    | FundingUrl\n    | FundingWay\n    | [FundingUrl | FundingWay, ...(FundingUrl | FundingWay)[]];\n  /**\n   * The 'scripts' member is an object hash of script commands that are run at various times in the lifecycle of your package. The key is the lifecycle event, and the value is the command to run at that point.\n   */\n  scripts?: {\n    /**\n     * Run code quality tools, e.g. ESLint, TSLint, etc.\n     */\n    lint?: string;\n    /**\n     * Run BEFORE the package is published (Also run on local npm install without any arguments).\n     */\n    prepublish?: string;\n    /**\n     * Run both BEFORE the package is packed and published, and on local npm install without any arguments. This is run AFTER prepublish, but BEFORE prepublishOnly.\n     */\n    prepare?: string;\n    /**\n     * Run BEFORE the package is prepared and packed, ONLY on npm publish.\n     */\n    prepublishOnly?: string;\n    /**\n     * run BEFORE a tarball is packed (on npm pack, npm publish, and when installing git dependencies).\n     */\n    prepack?: string;\n    /**\n     * Run AFTER the tarball has been generated and moved to its final destination.\n     */\n    postpack?: string;\n    /**\n     * Publishes a package to the registry so that it can be installed by name. See https://docs.npmjs.com/cli/v8/commands/npm-publish\n     */\n    publish?: string;\n    postpublish?: ScriptsPublishAfter;\n    /**\n     * Run BEFORE the package is installed.\n     */\n    preinstall?: string;\n    install?: ScriptsInstallAfter;\n    postinstall?: ScriptsInstallAfter;\n    preuninstall?: ScriptsUninstallBefore;\n    uninstall?: ScriptsUninstallBefore;\n    /**\n     * Run AFTER the package is uninstalled.\n     */\n    postuninstall?: string;\n    preversion?: ScriptsVersionBefore;\n    version?: ScriptsVersionBefore;\n    /**\n     * Run AFTER bump the package version.\n     */\n    postversion?: string;\n    pretest?: ScriptsTest;\n    test?: ScriptsTest;\n    posttest?: ScriptsTest;\n    prestop?: ScriptsStop;\n    stop?: ScriptsStop;\n    poststop?: ScriptsStop;\n    prestart?: ScriptsStart;\n    start?: ScriptsStart;\n    poststart?: ScriptsStart;\n    prerestart?: ScriptsRestart;\n    restart?: ScriptsRestart;\n    postrestart?: ScriptsRestart;\n    /**\n     * Start dev server to serve application files\n     */\n    serve?: string;\n    [k: string]: string | undefined;\n  };\n  /**\n   * A 'config' hash can be used to set configuration parameters used in package scripts that persist across upgrades.\n   */\n  config?: {\n    [k: string]: unknown;\n  };\n  dependencies?: Dependency;\n  devDependencies?: Dependency;\n  optionalDependencies?: Dependency;\n  peerDependencies?: Dependency;\n  peerDependenciesMeta?: PeerDependencyMeta;\n  /**\n   * Array of package names that will be bundled when publishing the package.\n   */\n  bundleDependencies?: string[] | boolean;\n  /**\n   * DEPRECATED: This field is honored, but \"bundleDependencies\" is the correct field name.\n   */\n  bundledDependencies?: string[] | boolean;\n  /**\n   * Resolutions is used to support selective version resolutions using yarn, which lets you define custom package versions or ranges inside your dependencies. For npm, use overrides instead. See: https://classic.yarnpkg.com/en/docs/selective-version-resolutions\n   */\n  resolutions?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Overrides is used to support selective version overrides using npm, which lets you define custom package versions or ranges inside your dependencies. For yarn, use resolutions instead. See: https://docs.npmjs.com/cli/v9/configuring-npm/package-json#overrides\n   */\n  overrides?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Defines which package manager is expected to be used when working on the current project. This field is currently experimental and needs to be opted-in; see https://nodejs.org/api/corepack.html\n   */\n  packageManager?: string;\n  engines?: {\n    node?: string;\n    [k: string]: string;\n  };\n  /**\n   * Defines which tools and versions are expected to be used when Volta is installed.\n   */\n  volta?: {\n    /**\n     * The value of that entry should be a path to another JSON file which also has a \"volta\" section\n     */\n    extends?: string;\n    /**\n     * This interface was referenced by `undefined`'s JSON-Schema definition\n     * via the `patternProperty` \"(node|npm|pnpm|yarn)\".\n     */\n    [k: string]: string;\n  };\n  engineStrict?: boolean;\n  /**\n   * Specify which operating systems your module will run on.\n   */\n  os?: string[];\n  /**\n   * Specify that your code only runs on certain cpu architectures.\n   */\n  cpu?: string[];\n  /**\n   * DEPRECATED: This option used to trigger an npm warning, but it will no longer warn. It is purely there for informational purposes. It is now recommended that you install any binaries as local devDependencies wherever possible.\n   */\n  preferGlobal?: boolean;\n  /**\n   * If set to true, then npm will refuse to publish it.\n   */\n  private?: boolean | (\"false\" | \"true\");\n  publishConfig?: {\n    access?: \"public\" | \"restricted\";\n    tag?: string;\n    registry?: string;\n    provenance?: boolean;\n    [k: string]: unknown;\n  };\n  dist?: {\n    shasum?: string;\n    tarball?: string;\n    [k: string]: unknown;\n  };\n  readme?: string;\n  /**\n   * An ECMAScript module ID that is the primary entry point to your program.\n   */\n  module?: string;\n  /**\n   * A module ID with untranspiled code that is the primary entry point to your program.\n   */\n  esnext?:\n    | string\n    | {\n        main?: string;\n        browser?: string;\n        [k: string]: string;\n      };\n  /**\n   * Allows packages within a directory to depend on one another using direct linking of local files. Additionally, dependencies within a workspace are hoisted to the workspace root when possible to reduce duplication. Note: It's also a good idea to set \"private\" to true when using this feature.\n   */\n  workspaces?:\n    | string[]\n    | {\n        /**\n         * Workspace package paths. Glob patterns are supported.\n         */\n        packages?: string[];\n        /**\n         * Packages to block from hoisting to the workspace root. Currently only supported in Yarn only.\n         */\n        nohoist?: string[];\n        [k: string]: unknown;\n      };\n  jspm?: JSONSchemaForNPMPackageJsonFiles;\n  eslintConfig?: JSONSchemaForESLintConfigurationFiles;\n  prettier?: SchemaForPrettierrc;\n  stylelint?: JSONSchemaForTheStylelintConfigurationFiles;\n  ava?: AVAConfigSchema;\n  release?: SemanticReleaseSchema;\n  jscpd?: HttpsJsonSchemastoreOrgJscpdJson;\n  /**\n   * Defines pnpm specific configuration.\n   */\n  pnpm?: {\n    /**\n     * Used to override any dependency in the dependency graph.\n     */\n    overrides?: {\n      [k: string]: unknown;\n    };\n    /**\n     * Used to extend the existing package definitions with additional information.\n     */\n    packageExtensions?: {\n      /**\n       * This interface was referenced by `undefined`'s JSON-Schema definition\n       * via the `patternProperty` \"^.+$\".\n       */\n      [k: string]: {\n        dependencies?: Dependency;\n        optionalDependencies?: Dependency;\n        peerDependencies?: Dependency;\n        peerDependenciesMeta?: PeerDependencyMeta;\n      };\n    };\n    peerDependencyRules?: {\n      /**\n       * pnpm will not print warnings about missing peer dependencies from this list.\n       */\n      ignoreMissing?: string[];\n      /**\n       * Unmet peer dependency warnings will not be printed for peer dependencies of the specified range.\n       */\n      allowedVersions?: {\n        [k: string]: unknown;\n      };\n      /**\n       * Any peer dependency matching the pattern will be resolved from any version, regardless of the range specified in \"peerDependencies\".\n       */\n      allowAny?: string[];\n    };\n    /**\n     * A list of dependencies to skip the builds.\n     */\n    neverBuiltDependencies?: string[];\n    /**\n     * A list of dependencies to skip the builds.\n     */\n    onlyBuiltDependencies?: string[];\n    /**\n     * Specifies a JSON file that lists the only packages permitted to run installation scripts during the pnpm install process.\n     */\n    onlyBuiltDependenciesFile?: string;\n    /**\n     * A list of deprecated versions that the warnings are suppressed.\n     */\n    allowedDeprecatedVersions?: {\n      [k: string]: unknown;\n    };\n    /**\n     * A list of dependencies that are patched.\n     */\n    patchedDependencies?: {\n      [k: string]: unknown;\n    };\n    /**\n     * When true, installation won't fail if some of the patches from the \"patchedDependencies\" field were not applied.\n     */\n    allowNonAppliedPatches?: boolean;\n    updateConfig?: {\n      /**\n       * A list of packages that should be ignored when running \"pnpm outdated\" or \"pnpm update --latest\".\n       */\n      ignoreDependencies?: string[];\n    };\n    auditConfig?: {\n      /**\n       * A list of CVE IDs that will be ignored by \"pnpm audit\".\n       */\n      ignoreCves?: string[];\n      /**\n       * A list of GHSA Codes that will be ignored by \"pnpm audit\".\n       */\n      ignoreGhsas?: string[];\n    };\n    /**\n     * A list of scripts that must exist in each project.\n     */\n    requiredScripts?: string[];\n    /**\n     * Specifies architectures for which you'd like to install optional dependencies, even if they don't match the architecture of the system running the install.\n     */\n    supportedArchitectures?: {\n      os?: string[];\n      cpu?: string[];\n      libc?: string[];\n    };\n    /**\n     * A list of optional dependencies that the install should be skipped.\n     */\n    ignoredOptionalDependencies?: string[];\n    executionEnv?: {\n      /**\n       * Specifies which exact Node.js version should be used for the project's runtime.\n       */\n      nodeVersion?: string;\n    };\n  };\n  /**\n   * Any property starting with \\_ is valid.\n   *\n   * This interface was referenced by `undefined`'s JSON-Schema definition\n   * via the `patternProperty` \"^\\_\".\n   */\n  [k: string]: any;\n};\nexport type License =\n  | string\n  | (\n      | \"AGPL-3.0-only\"\n      | \"Apache-2.0\"\n      | \"BSD-2-Clause\"\n      | \"BSD-3-Clause\"\n      | \"BSL-1.0\"\n      | \"CC0-1.0\"\n      | \"CDDL-1.0\"\n      | \"CDDL-1.1\"\n      | \"EPL-1.0\"\n      | \"EPL-2.0\"\n      | \"GPL-2.0-only\"\n      | \"GPL-3.0-only\"\n      | \"ISC\"\n      | \"LGPL-2.0-only\"\n      | \"LGPL-2.1-only\"\n      | \"LGPL-2.1-or-later\"\n      | \"LGPL-3.0-only\"\n      | \"LGPL-3.0-or-later\"\n      | \"MIT\"\n      | \"MPL-2.0\"\n      | \"MS-PL\"\n      | \"UNLICENSED\"\n    );\n/**\n * A person who has been involved in creating or maintaining this package.\n */\nexport type Person = {\n  name: string;\n  url?: string;\n  email?: string;\n  [k: string]: unknown;\n} & Person1;\nexport type Person1 =\n  | {\n      name: string;\n      url?: string;\n      email?: string;\n      [k: string]: unknown;\n    }\n  | string;\nexport type PackageExportsEntry =\n  | PackageExportsEntryPath\n  | PackageExportsEntryObject;\n/**\n * The module path that is resolved when this specifier is imported. Set to `null` to disallow importing this module.\n */\nexport type PackageExportsEntryPath = string | null;\n/**\n * Used to allow fallbacks in case this environment doesn't support the preceding entries.\n */\nexport type PackageExportsFallback = PackageExportsEntry[];\n/**\n * Used to allow fallbacks in case this environment doesn't support the preceding entries.\n */\nexport type PackageExportsFallback1 = PackageExportsEntry[];\nexport type PackageImportsEntry =\n  | PackageImportsEntryPath\n  | PackageImportsEntryObject;\n/**\n * The module path that is resolved when this specifier is imported. Set to `null` to disallow importing this module.\n */\nexport type PackageImportsEntryPath = string | null;\n/**\n * Used to allow fallbacks in case this environment doesn't support the preceding entries.\n */\nexport type PackageImportsFallback = PackageImportsEntry[];\n/**\n * URL to a website with details about how to fund the package.\n */\nexport type FundingUrl = string;\n/**\n * Run AFTER the package is published.\n */\nexport type ScriptsPublishAfter = string;\n/**\n * Run AFTER the package is installed.\n */\nexport type ScriptsInstallAfter = string;\n/**\n * Run BEFORE the package is uninstalled.\n */\nexport type ScriptsUninstallBefore = string;\n/**\n * Run BEFORE bump the package version.\n */\nexport type ScriptsVersionBefore = string;\n/**\n * Run by the 'npm test' command.\n */\nexport type ScriptsTest = string;\n/**\n * Run by the 'npm stop' command.\n */\nexport type ScriptsStop = string;\n/**\n * Run by the 'npm start' command.\n */\nexport type ScriptsStart = string;\n/**\n * Run by the 'npm restart' command. Note: 'npm restart' will run the stop and start scripts if no restart script is provided.\n */\nexport type ScriptsRestart = string;\n/**\n * ESLint supports the use of third-party plugins. Before using the plugin, you have to install it using npm.\n */\nexport type Plugins = string[];\n/**\n * ESLint comes with a large number of rules. You can modify which rules your project uses either using configuration comments or configuration files.\n */\nexport type Rules = PossibleErrors &\n  BestPractices &\n  StrictMode &\n  Variables &\n  NodeAndCommonJs &\n  StylisticIssues &\n  EcmaScript6 &\n  Legacy &\n  HttpsJsonSchemastoreOrgPartialEslintPluginsJson;\n/**\n * Allows to override configuration for files and folders, specified by glob patterns\n */\nexport type Overrides = {\n  /**\n   * Glob pattern for files to apply 'overrides' configuration, relative to the directory of the config file\n   */\n  files: string | [string, ...string[]];\n  /**\n   * If you want to extend a specific configuration file, you can use the extends property and specify the path to the file. The path can be either relative or absolute.\n   */\n  extends?: string | string[];\n  /**\n   * If a file matches any of the 'excludedFiles' glob patterns, the 'overrides' configuration won't apply\n   */\n  excludedFiles?: string | string[];\n  ecmaFeatures?: EcmaFeatures;\n  env?: Env;\n  globals?: Globals;\n  parser?: string;\n  parserOptions?: ParserOptions;\n  plugins?: Plugins;\n  /**\n   * To specify a processor, specify the plugin name and processor name joined by a forward slash\n   */\n  processor?: string;\n  rules?: Rules;\n  settings?: Settings;\n  overrides?: Overrides;\n}[];\nexport type SchemaForPrettierrc =\n  | (OptionsDefinition & OverridesDefinition)\n  | string;\n/**\n * Your configuration can extend an existing configuration(s) (whether your own or a third-party config)\n */\nexport type SimpleStringOrArrayStringRule = (string | SimpleArrayStringRule) &\n  (\n    | ((string | SimpleArrayStringRule) & string)\n    | ((string | SimpleArrayStringRule) & unknown[])\n  );\nexport type SimpleArrayStringRule = string[];\n/**\n * Plugins are rules or sets of rules built by the community that support methodologies, toolsets, non-standard CSS features, or very specific use cases\n */\nexport type SimpleArrayStringRule1 = string[];\nexport type AllRules = AtRule &\n  Block &\n  Color &\n  Comment &\n  CustomMedia &\n  CustomProperty &\n  Declaration &\n  DeclarationBlock &\n  Font &\n  Function &\n  GeneralSheet &\n  KeyframeDeclaration &\n  Length &\n  Lightness &\n  MediaFeature &\n  MediaQuery &\n  MediaQueryList &\n  Number &\n  Property &\n  RootRule &\n  Rule &\n  Selector &\n  SelectorList &\n  ShorthandProperty &\n  String &\n  StylelintDisableComment &\n  Time &\n  Unit &\n  Value &\n  ValueList;\n/**\n * Specify a blacklist of disallowed at-rules\n */\nexport type ArrayStringRule = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for at-rules names\n */\nexport type LowerUpperRule = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline after at-rule names\n */\nexport type AlwaysMultiLineRule = (\n  | null\n  | (\"always\" | \"always-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | [])\n          | [\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | [])\n        | [\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | [])\n        | [\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow vendor prefixes for at-rules\n */\nexport type BooleanRule = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed at-rules\n */\nexport type ArrayStringRule1 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the closing brace of blocks\n */\nexport type NewlineSpaceWithIgnoreRule = (\n  | null\n  | (\n      | \"always\"\n      | \"never\"\n      | \"always-single-line\"\n      | \"never-single-line\"\n      | \"always-multi-line\"\n      | \"never-multi-line\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"always\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\n            | \"always\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the closing brace of blocks\n */\nexport type NewlineRule = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the closing brace of blocks\n */\nexport type NewlineSpaceRule = (\n  | null\n  | (\n      | \"always\"\n      | \"never\"\n      | \"always-single-line\"\n      | \"never-single-line\"\n      | \"always-multi-line\"\n      | \"never-multi-line\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the closing brace of blocks\n */\nexport type NewlineSpaceRule1 = (\n  | null\n  | (\n      | \"always\"\n      | \"never\"\n      | \"always-single-line\"\n      | \"never-single-line\"\n      | \"always-multi-line\"\n      | \"never-multi-line\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow empty blocks\n */\nexport type BooleanRule1 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow single-line blocks\n */\nexport type BooleanRule2 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline after the opening brace of blocks\n */\nexport type NewlineRule1 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the opening brace of blocks\n */\nexport type NewlineSpaceRule2 = (\n  | null\n  | (\n      | \"always\"\n      | \"never\"\n      | \"always-single-line\"\n      | \"never-single-line\"\n      | \"always-multi-line\"\n      | \"never-multi-line\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the opening brace of blocks\n */\nexport type NewlineSpaceWithIgnoreRule1 = (\n  | null\n  | (\n      | \"always\"\n      | \"never\"\n      | \"always-single-line\"\n      | \"never-single-line\"\n      | \"always-multi-line\"\n      | \"never-multi-line\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"always\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\n            | \"always\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | {}\n          )\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"always\"\n            | \"never\"\n            | \"always-single-line\"\n            | \"never-single-line\"\n            | \"always-multi-line\"\n            | \"never-multi-line\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | \"always-multi-line\"\n                  | \"never-multi-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for hex colors\n */\nexport type LowerUpperRule1 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow hex colors\n */\nexport type BooleanRule3 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow invalid hex colors\n */\nexport type BooleanRule4 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow empty comments\n */\nexport type BooleanRule5 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow whitespace on the inside of comment markers\n */\nexport type AlwaysNeverRule = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a blacklist of disallowed words within comments\n */\nexport type ArrayStringRule2 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a pattern for custom media query names\n */\nexport type StringRule = (\n  | (null | string)\n  | [\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow custom properties outside of `:root` rules\n */\nexport type BooleanRule6 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a pattern for custom properties\n */\nexport type StringRule1 = (\n  | (null | string)\n  | [\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the bang of declarations\n */\nexport type AlwaysNeverRule1 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the bang of declarations\n */\nexport type AlwaysNeverRule2 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the colon of declarations\n */\nexport type AlwaysMultiLineRule1 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | [])\n          | [\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | [])\n        | [\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | [])\n        | [\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"always-multi-line\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"always-multi-line\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"always-multi-line\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the colon of declarations\n */\nexport type AlwaysNeverRule3 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow `!important` within declarations\n */\nexport type BooleanRule7 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\nexport type SimpleStringOrArrayStringRule1 = (string | SimpleArrayStringRule) &\n  (\n    | ((string | SimpleArrayStringRule) & string)\n    | ((string | SimpleArrayStringRule) & unknown[])\n  );\n/**\n * Disallow property values that are ignored due to another property value in the same rule\n */\nexport type BooleanRule8 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow shorthand properties that override related longhand properties\n */\nexport type BooleanRule9 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the semicolons of declaration blocks\n */\nexport type NewlineRule2 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the semicolons of declaration blocks\n */\nexport type NewlineRule3 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the semicolons of declaration blocks\n */\nexport type SpaceRule = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the semicolons of declaration blocks\n */\nexport type SpaceRule1 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of declaration within a single line declaration block\n */\nexport type IntegerRule = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow a trailing semicolon within declaration blocks\n */\nexport type AlwaysNeverRule4 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a blacklist of disallowed functions\n */\nexport type ArrayStringRule3 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow an unspaced operator within `calc` functions\n */\nexport type BooleanRule10 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the commas of functions\n */\nexport type NewlineRule4 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the commas of functions\n */\nexport type NewlineRule5 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the commas of functions\n */\nexport type SpaceRule2 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the commas of functions\n */\nexport type SpaceRule3 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow direction values in `linear-gradient()` calls that are not valid according to the standard syntax\n */\nexport type BooleanRule11 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of adjacent empty lines within functions\n */\nexport type IntegerRule1 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace on the inside of the parentheses of functions\n */\nexport type NewlineRule6 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace on the inside of the parentheses of functions\n */\nexport type SpaceRule4 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow data URIs for urls\n */\nexport type AlwaysNeverRule5 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow scheme-relative urls\n */\nexport type BooleanRule12 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow quotes for urls\n */\nexport type AlwaysNeverRule6 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed url schemes\n */\nexport type ArrayStringRule4 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed functions\n */\nexport type ArrayStringRule5 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow whitespace after functions\n */\nexport type AlwaysNeverRule7 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of adjacent empty lines\n */\nexport type IntegerRule2 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow selectors of lower specificity from coming after overriding selectors of higher specificity\n */\nexport type BooleanRule13 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow duplicate selectors within a stylesheet\n */\nexport type BooleanRule14 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow empty sources\n */\nexport type BooleanRule15 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow extra semicolons\n */\nexport type BooleanRule16 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow double-slash comments `(//...)` which are not supported by CSS and could lead to unexpected results\n */\nexport type BooleanRule17 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow missing end-of-source newlines\n */\nexport type BooleanRule18 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow animation names that do not correspond to a `@keyframes` declaration\n */\nexport type BooleanRule19 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow Unicode BOM\n */\nexport type AlwaysNeverRule8 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow !important within keyframe declarations\n */\nexport type BooleanRule20 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow units for zero lengths\n */\nexport type BooleanRule21 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the colon in media features\n */\nexport type AlwaysNeverRule9 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the colon in media features\n */\nexport type AlwaysNeverRule10 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for media feature names\n */\nexport type LowerUpperRule2 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow vendor prefixes for media feature names\n */\nexport type BooleanRule22 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow missing punctuation for non-boolean media features\n */\nexport type BooleanRule23 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace on the inside of the parentheses within media features\n */\nexport type AlwaysNeverRule11 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the range operator in media features\n */\nexport type AlwaysNeverRule12 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the range operator in media features\n */\nexport type AlwaysNeverRule13 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the commas of media query lists\n */\nexport type NewlineRule7 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the commas of media query lists\n */\nexport type NewlineRule8 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the commas of media query lists\n */\nexport type SpaceRule5 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the commas of media query lists\n */\nexport type SpaceRule6 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow a leading zero for fractional numbers less than 1\n */\nexport type AlwaysNeverRule14 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of decimal places allowed in numbers\n */\nexport type IntegerRule3 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow trailing zeros in numbers\n */\nexport type BooleanRule24 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a blacklist of disallowed properties\n */\nexport type ArrayStringRule6 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for properties\n */\nexport type LowerUpperRule3 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow vendor prefixes for properties\n */\nexport type BooleanRule25 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed properties\n */\nexport type ArrayStringRule7 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow standard properties inside `:root` rules\n */\nexport type BooleanRule26 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace on the inside of the brackets within attribute selector\n */\nexport type AlwaysNeverRule15 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a blacklist of disallowed attribute operators\n */\nexport type ArrayStringRule8 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after operators within attribute selectors\n */\nexport type AlwaysNeverRule16 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before operators within attribute selectors\n */\nexport type AlwaysNeverRule17 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed attribute operators\n */\nexport type ArrayStringRule9 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require or disallow quotes for attribute values\n */\nexport type AlwaysNeverRule18 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the combinators of selectors\n */\nexport type AlwaysNeverRule19 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the combinators of selectors\n */\nexport type AlwaysNeverRule20 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow non-space characters for descendant combinators of selectors\n */\nexport type BooleanRule27 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a pattern for id selectors\n */\nexport type StringRule2 = (\n  | (null | string)\n  | [\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of compound selectors in a selector\n */\nexport type IntegerRule4 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the specificity of selectors\n */\nexport type StringRule3 = (\n  | (null | string)\n  | [\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a pattern for the selectors of rules nested within rules\n */\nexport type StringRule4 = (\n  | (null | string)\n  | [\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n      (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)) &\n        (string | CoreRule) &\n        (((string | CoreRule) & string) | (string | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n            (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)) &\n              (string | CoreRule) &\n              (((string | CoreRule) & string) | (string | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow attribute selectors\n */\nexport type BooleanRule28 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow combinators in selectors\n */\nexport type BooleanRule29 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow id selectors\n */\nexport type BooleanRule30 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow the universal selector\n */\nexport type BooleanRule31 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow vendor prefixes for selectors\n */\nexport type BooleanRule32 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for pseudo-class selectors\n */\nexport type LowerUpperRule4 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace on the inside of the parentheses within pseudo-class selectors\n */\nexport type AlwaysNeverRule21 = (\n  | null\n  | (\"always\" | \"never\" | [])\n  | [\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n      ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ) &\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n        (\n          | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n          | ((\"always\" | \"never\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | [])\n        | [\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n            ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ) &\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n              (\n                | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                | ((\"always\" | \"never\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed pseudo-class selectors\n */\nexport type ArrayStringRule10 = (\n  | (null | string)\n  | [\n      (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ),\n      ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ) &\n        (([] | {}) | SimpleArrayStringRule | CoreRule) &\n        (\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n          | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n          | (([] | {}) | SimpleArrayStringRule | CoreRule)\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | string)\n          | [\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ),\n              ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ) &\n                (([] | {}) | SimpleArrayStringRule | CoreRule) &\n                (\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                  | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                  | (([] | {}) | SimpleArrayStringRule | CoreRule)\n                ))[],\n            ]\n        ))\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | (null | string)\n        | [\n            (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ),\n            ...((([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ) &\n              (([] | {}) | SimpleArrayStringRule | CoreRule) &\n              (\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & string)\n                | ((([] | {}) | SimpleArrayStringRule | CoreRule) & unknown[])\n                | (([] | {}) | SimpleArrayStringRule | CoreRule)\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for pseudo-element selectors\n */\nexport type LowerUpperRule5 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify single or double colon notation for applicable pseudo-elements\n */\nexport type SingleDoubleRule = (\n  | null\n  | (\"single\" | \"double\" | [])\n  | [\n      ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ) &\n        ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ),\n      ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ) &\n        ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"single\" | \"double\" | [])\n          | [\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ) &\n                ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ),\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ) &\n                ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"single\" | \"double\" | [])\n        | [\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"single\" | \"double\" | [])\n        | [\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow the composition of :root in selectors\n */\nexport type BooleanRule33 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for type selectors\n */\nexport type LowerUpperRule6 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of adjacent empty lines within selectors\n */\nexport type IntegerRule5 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the commas of selector lists\n */\nexport type NewlineRule9 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the commas of selector lists\n */\nexport type NewlineRule10 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the commas of selector lists\n */\nexport type SpaceRule7 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the commas of selector lists\n */\nexport type SpaceRule8 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow redundant values in shorthand properties\n */\nexport type BooleanRule34 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow (unescaped) newlines in strings\n */\nexport type BooleanRule35 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify single or double quotes around strings\n */\nexport type SingleDoubleRule1 = (\n  | null\n  | (\"single\" | \"double\" | [])\n  | [\n      ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ) &\n        ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ),\n      ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ) &\n        ((\"single\" | \"double\" | {}) | CoreRule) &\n        (\n          | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n          | ((\"single\" | \"double\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"single\" | \"double\" | [])\n          | [\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ) &\n                ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ),\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ) &\n                ((\"single\" | \"double\" | {}) | CoreRule) &\n                (\n                  | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                  | ((\"single\" | \"double\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"single\" | \"double\" | [])\n        | [\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"single\" | \"double\" | [])\n        | [\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n            ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ) &\n              ((\"single\" | \"double\" | {}) | CoreRule) &\n              (\n                | (((\"single\" | \"double\" | {}) | CoreRule) & string)\n                | ((\"single\" | \"double\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow `animation` and `transition` less than or equal to 100ms\n */\nexport type BooleanRule36 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a blacklist of disallowed units\n */\nexport type UnitRule = (\n  | null\n  | (\n      | \"em\"\n      | \"ex\"\n      | \"px\"\n      | \"%\"\n      | \"rem\"\n      | \"vw\"\n      | \"vh\"\n      | \"vm\"\n      | \"vmin\"\n      | \"vmax\"\n      | \"ch\"\n      | \"in\"\n      | \"cm\"\n      | \"mm\"\n      | \"q\"\n      | \"pt\"\n      | \"pc\"\n      | \"deg\"\n      | \"grad\"\n      | \"rad\"\n      | \"turn\"\n      | \"ms\"\n      | \"s\"\n      | \"Hz\"\n      | \"kHz\"\n      | \"dpi\"\n      | \"dpcm\"\n      | \"dppx\"\n      | \"fr\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n            | {}\n          )\n        | [\n            (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            ),\n            ...(\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            )[],\n          ]\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n              | {}\n            )\n          | [\n              (\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              ),\n              ...(\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              )[],\n            ]\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ),\n      ...((\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n            | {}\n          )\n        | [\n            (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            ),\n            ...(\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            )[],\n          ]\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n              | {}\n            )\n          | [\n              (\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              ),\n              ...(\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              )[],\n            ]\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                      | []\n                      | {}\n                    )\n                  | [\n                      (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      ),\n                      ...(\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      )[],\n                    ]\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ),\n              ...((\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                      | []\n                      | {}\n                    )\n                  | [\n                      (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      ),\n                      ...(\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      )[],\n                    ]\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ))[],\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ),\n            ...((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ),\n            ...((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify lowercase or uppercase for units\n */\nexport type LowerUpperRule7 = (\n  | null\n  | (\"lower\" | \"upper\" | [])\n  | [\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n      ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ) &\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n        (\n          | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n          | ((\"lower\" | \"upper\" | {}) | CoreRule)\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"lower\" | \"upper\" | [])\n        | [\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n            ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ) &\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n              (\n                | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                | ((\"lower\" | \"upper\" | {}) | CoreRule)\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Specify a whitelist of allowed units\n */\nexport type UnitRule1 = (\n  | null\n  | (\n      | \"em\"\n      | \"ex\"\n      | \"px\"\n      | \"%\"\n      | \"rem\"\n      | \"vw\"\n      | \"vh\"\n      | \"vm\"\n      | \"vmin\"\n      | \"vmax\"\n      | \"ch\"\n      | \"in\"\n      | \"cm\"\n      | \"mm\"\n      | \"q\"\n      | \"pt\"\n      | \"pc\"\n      | \"deg\"\n      | \"grad\"\n      | \"rad\"\n      | \"turn\"\n      | \"ms\"\n      | \"s\"\n      | \"Hz\"\n      | \"kHz\"\n      | \"dpi\"\n      | \"dpcm\"\n      | \"dppx\"\n      | \"fr\"\n      | []\n    )\n  | [\n      (\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n            | {}\n          )\n        | [\n            (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            ),\n            ...(\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            )[],\n          ]\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n              | {}\n            )\n          | [\n              (\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              ),\n              ...(\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              )[],\n            ]\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ),\n      ...((\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n            | {}\n          )\n        | [\n            (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            ),\n            ...(\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n            )[],\n          ]\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n              | {}\n            )\n          | [\n              (\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              ),\n              ...(\n                | \"em\"\n                | \"ex\"\n                | \"px\"\n                | \"%\"\n                | \"rem\"\n                | \"vw\"\n                | \"vh\"\n                | \"vm\"\n                | \"vmin\"\n                | \"vmax\"\n                | \"ch\"\n                | \"in\"\n                | \"cm\"\n                | \"mm\"\n                | \"q\"\n                | \"pt\"\n                | \"pc\"\n                | \"deg\"\n                | \"grad\"\n                | \"rad\"\n                | \"turn\"\n                | \"ms\"\n                | \"s\"\n                | \"Hz\"\n                | \"kHz\"\n                | \"dpi\"\n                | \"dpcm\"\n                | \"dppx\"\n                | \"fr\"\n              )[],\n            ]\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              string)\n          | ((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              unknown[])\n          | (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            )\n        ))[],\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"em\"\n              | \"ex\"\n              | \"px\"\n              | \"%\"\n              | \"rem\"\n              | \"vw\"\n              | \"vh\"\n              | \"vm\"\n              | \"vmin\"\n              | \"vmax\"\n              | \"ch\"\n              | \"in\"\n              | \"cm\"\n              | \"mm\"\n              | \"q\"\n              | \"pt\"\n              | \"pc\"\n              | \"deg\"\n              | \"grad\"\n              | \"rad\"\n              | \"turn\"\n              | \"ms\"\n              | \"s\"\n              | \"Hz\"\n              | \"kHz\"\n              | \"dpi\"\n              | \"dpcm\"\n              | \"dppx\"\n              | \"fr\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                      | []\n                      | {}\n                    )\n                  | [\n                      (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      ),\n                      ...(\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      )[],\n                    ]\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ),\n              ...((\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                      | []\n                      | {}\n                    )\n                  | [\n                      (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      ),\n                      ...(\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                      )[],\n                    ]\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                          | []\n                          | {}\n                        )\n                      | [\n                          (\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          ),\n                          ...(\n                            | \"em\"\n                            | \"ex\"\n                            | \"px\"\n                            | \"%\"\n                            | \"rem\"\n                            | \"vw\"\n                            | \"vh\"\n                            | \"vm\"\n                            | \"vmin\"\n                            | \"vmax\"\n                            | \"ch\"\n                            | \"in\"\n                            | \"cm\"\n                            | \"mm\"\n                            | \"q\"\n                            | \"pt\"\n                            | \"pc\"\n                            | \"deg\"\n                            | \"grad\"\n                            | \"rad\"\n                            | \"turn\"\n                            | \"ms\"\n                            | \"s\"\n                            | \"Hz\"\n                            | \"kHz\"\n                            | \"dpi\"\n                            | \"dpcm\"\n                            | \"dppx\"\n                            | \"fr\"\n                          )[],\n                        ]\n                      | CoreRule\n                    )\n                ))[],\n            ]\n        ))\n    | ((\n        | null\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ),\n            ...((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ))[],\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\n            | \"em\"\n            | \"ex\"\n            | \"px\"\n            | \"%\"\n            | \"rem\"\n            | \"vw\"\n            | \"vh\"\n            | \"vm\"\n            | \"vmin\"\n            | \"vmax\"\n            | \"ch\"\n            | \"in\"\n            | \"cm\"\n            | \"mm\"\n            | \"q\"\n            | \"pt\"\n            | \"pc\"\n            | \"deg\"\n            | \"grad\"\n            | \"rad\"\n            | \"turn\"\n            | \"ms\"\n            | \"s\"\n            | \"Hz\"\n            | \"kHz\"\n            | \"dpi\"\n            | \"dpcm\"\n            | \"dppx\"\n            | \"fr\"\n            | []\n          )\n        | [\n            (\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ),\n            ...((\n              | (\n                  | \"em\"\n                  | \"ex\"\n                  | \"px\"\n                  | \"%\"\n                  | \"rem\"\n                  | \"vw\"\n                  | \"vh\"\n                  | \"vm\"\n                  | \"vmin\"\n                  | \"vmax\"\n                  | \"ch\"\n                  | \"in\"\n                  | \"cm\"\n                  | \"mm\"\n                  | \"q\"\n                  | \"pt\"\n                  | \"pc\"\n                  | \"deg\"\n                  | \"grad\"\n                  | \"rad\"\n                  | \"turn\"\n                  | \"ms\"\n                  | \"s\"\n                  | \"Hz\"\n                  | \"kHz\"\n                  | \"dpi\"\n                  | \"dpcm\"\n                  | \"dppx\"\n                  | \"fr\"\n                  | []\n                  | {}\n                )\n              | [\n                  (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  ),\n                  ...(\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                  )[],\n                ]\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"em\"\n                    | \"ex\"\n                    | \"px\"\n                    | \"%\"\n                    | \"rem\"\n                    | \"vw\"\n                    | \"vh\"\n                    | \"vm\"\n                    | \"vmin\"\n                    | \"vmax\"\n                    | \"ch\"\n                    | \"in\"\n                    | \"cm\"\n                    | \"mm\"\n                    | \"q\"\n                    | \"pt\"\n                    | \"pc\"\n                    | \"deg\"\n                    | \"grad\"\n                    | \"rad\"\n                    | \"turn\"\n                    | \"ms\"\n                    | \"s\"\n                    | \"Hz\"\n                    | \"kHz\"\n                    | \"dpi\"\n                    | \"dpcm\"\n                    | \"dppx\"\n                    | \"fr\"\n                    | []\n                    | {}\n                  )\n                | [\n                    (\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    ),\n                    ...(\n                      | \"em\"\n                      | \"ex\"\n                      | \"px\"\n                      | \"%\"\n                      | \"rem\"\n                      | \"vw\"\n                      | \"vh\"\n                      | \"vm\"\n                      | \"vmin\"\n                      | \"vmax\"\n                      | \"ch\"\n                      | \"in\"\n                      | \"cm\"\n                      | \"mm\"\n                      | \"q\"\n                      | \"pt\"\n                      | \"pc\"\n                      | \"deg\"\n                      | \"grad\"\n                      | \"rad\"\n                      | \"turn\"\n                      | \"ms\"\n                      | \"s\"\n                      | \"Hz\"\n                      | \"kHz\"\n                      | \"dpi\"\n                      | \"dpcm\"\n                      | \"dppx\"\n                      | \"fr\"\n                    )[],\n                  ]\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    string)\n                | ((\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  ) &\n                    unknown[])\n                | (\n                    | (\n                        | \"em\"\n                        | \"ex\"\n                        | \"px\"\n                        | \"%\"\n                        | \"rem\"\n                        | \"vw\"\n                        | \"vh\"\n                        | \"vm\"\n                        | \"vmin\"\n                        | \"vmax\"\n                        | \"ch\"\n                        | \"in\"\n                        | \"cm\"\n                        | \"mm\"\n                        | \"q\"\n                        | \"pt\"\n                        | \"pc\"\n                        | \"deg\"\n                        | \"grad\"\n                        | \"rad\"\n                        | \"turn\"\n                        | \"ms\"\n                        | \"s\"\n                        | \"Hz\"\n                        | \"kHz\"\n                        | \"dpi\"\n                        | \"dpcm\"\n                        | \"dppx\"\n                        | \"fr\"\n                        | []\n                        | {}\n                      )\n                    | [\n                        (\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        ),\n                        ...(\n                          | \"em\"\n                          | \"ex\"\n                          | \"px\"\n                          | \"%\"\n                          | \"rem\"\n                          | \"vw\"\n                          | \"vh\"\n                          | \"vm\"\n                          | \"vmin\"\n                          | \"vmax\"\n                          | \"ch\"\n                          | \"in\"\n                          | \"cm\"\n                          | \"mm\"\n                          | \"q\"\n                          | \"pt\"\n                          | \"pc\"\n                          | \"deg\"\n                          | \"grad\"\n                          | \"rad\"\n                          | \"turn\"\n                          | \"ms\"\n                          | \"s\"\n                          | \"Hz\"\n                          | \"kHz\"\n                          | \"dpi\"\n                          | \"dpcm\"\n                          | \"dppx\"\n                          | \"fr\"\n                        )[],\n                      ]\n                    | CoreRule\n                  )\n              ))[],\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Disallow vendor prefixes for values\n */\nexport type BooleanRule37 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace after the commas of value lists\n */\nexport type NewlineRule11 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a newline or disallow whitespace before the commas of value lists\n */\nexport type NewlineRule12 = (\n  | null\n  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n  | [\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n      ((\"always\" | \"always-multi-line\" | \"never-multi-line\" | {}) | CoreRule) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ) &\n        (\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | [])\n        | [\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\"always\" | \"always-multi-line\" | \"never-multi-line\" | {})\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace after the commas of value lists\n */\nexport type SpaceRule9 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Require a single space or disallow whitespace before the commas of value lists\n */\nexport type SpaceRule10 = (\n  | null\n  | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n  | [\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n      (\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | {})\n        | CoreRule\n      ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ) &\n        (\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n        (\n          | ((\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              string)\n          | (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            )\n        ),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | (\n              | \"always\"\n              | \"never\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ))\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        string)\n    | ((\n        | null\n        | (\"always\" | \"never\" | \"always-single-line\" | \"never-single-line\" | [])\n        | [\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n            (\n              | (\n                  | \"always\"\n                  | \"never\"\n                  | \"always-single-line\"\n                  | \"never-single-line\"\n                  | {}\n                )\n              | CoreRule\n            ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ) &\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n              (\n                | ((\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                    string)\n                | (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  )\n              ),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Limit the number of adjacent empty lines within value lists\n */\nexport type IntegerRule6 = (\n  | (null | number)\n  | [\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n      ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)) &\n        ({} | CoreRule) &\n        ((({} | CoreRule) & number) | ({} | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | (number &\n        (\n          | (null | number)\n          | [\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n              ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)) &\n                ({} | CoreRule) &\n                ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ]\n        ))\n    | ((\n        | (null | number)\n        | [\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n            ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)) &\n              ({} | CoreRule) &\n              ((({} | CoreRule) & number) | ({} | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Provide a glob or array of globs to ignore specific files\n */\nexport type SimpleStringOrArrayStringRule2 = (string | SimpleArrayStringRule) &\n  (\n    | ((string | SimpleArrayStringRule) & string)\n    | ((string | SimpleArrayStringRule) & unknown[])\n  );\n/**\n * Report stylelint-disable comments without a description.\n */\nexport type BooleanRule38 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Report stylelint-disable comments that don't match rules that are specified in the configuration object.\n */\nexport type BooleanRule39 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * Report stylelint-disable comments that don't actually match any lints that need to be disabled\n */\nexport type BooleanRule40 = (\n  | null\n  | boolean\n  | [\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n      (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n        (boolean | CoreRule) &\n        (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n    ]\n) &\n  (\n    | (null &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | (boolean &\n        (\n          | null\n          | boolean\n          | [\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n              (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n                (boolean | CoreRule) &\n                (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            ]\n        ))\n    | ((\n        | null\n        | boolean\n        | [\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n            (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)) &\n              (boolean | CoreRule) &\n              (((boolean | CoreRule) & boolean) | (boolean | CoreRule)),\n          ]\n      ) &\n        unknown[])\n  );\n/**\n * An array of glob patterns to select test files. Files with an underscore prefix are ignored. By default only selects files with `cjs`, `mjs` & `js` extensions, even if the pattern matches other files. Specify `extensions` to allow other file extensions\n */\nexport type ArrayOfPaths = string[];\n/**\n * An array of glob patterns to match files that, even if changed, are ignored by the watcher\n */\nexport type ArrayOfPaths1 = string[];\n/**\n * Not typically useful in the `package.json` configuration, but equivalent to specifying `--match` on the CLI\n */\nexport type ArrayOfPaths2 = string[];\nexport type ArrayOfStrings = string[];\n/**\n * Extra modules to require before tests are run. Modules are required in the worker processes\n */\nexport type ArrayOfPaths3 = string[];\n/**\n * Configure Node.js arguments used to launch worker processes\n */\nexport type ArrayOfStrings1 = string[];\n/**\n * You can configure AVA to recognize additional file extensions as TypeScript (e.g., `[\"ts\", \"tsx\"]` to add partial JSX support). Note that the preserve mode for JSX is not (yet) supported. See also AVA's `extensions` object\n */\nexport type ArrayOfPaths4 = string[];\n\n/**\n * Used to specify conditional exports, note that Conditional exports are unsupported in older environments, so it's recommended to use the fallback array option if support for those environments is a concern.\n */\nexport interface PackageExportsEntryObject {\n  /**\n   * The module path that is resolved when this specifier is imported as a CommonJS module using the `require(...)` function.\n   */\n  require?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this specifier is imported as an ECMAScript module using an `import` declaration or the dynamic `import(...)` function.\n   */\n  import?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this environment is Node.js.\n   */\n  node?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when no other export type matches.\n   */\n  default?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved for TypeScript types when this specifier is imported. Should be listed before other conditions.\n   */\n  types?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this environment matches the property name.\n   *\n   * This interface was referenced by `PackageExportsEntryObject`'s JSON-Schema definition\n   * via the `patternProperty` \"^[^.0-9]+$\".\n   *\n   * This interface was referenced by `PackageExportsEntryObject1`'s JSON-Schema definition\n   * via the `patternProperty` \"^[^.0-9]+$\".\n   */\n  [k: string]: PackageExportsEntry | PackageExportsFallback;\n}\n/**\n * The module path that is resolved when the module specifier matches \"name\", shadows the \"main\" field.\n */\nexport interface PackageExportsEntryObject1 {\n  /**\n   * The module path that is resolved when this specifier is imported as a CommonJS module using the `require(...)` function.\n   */\n  require?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this specifier is imported as an ECMAScript module using an `import` declaration or the dynamic `import(...)` function.\n   */\n  import?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this environment is Node.js.\n   */\n  node?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when no other export type matches.\n   */\n  default?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved for TypeScript types when this specifier is imported. Should be listed before other conditions.\n   */\n  types?: PackageExportsEntry | PackageExportsFallback;\n  /**\n   * The module path that is resolved when this environment matches the property name.\n   *\n   * This interface was referenced by `PackageExportsEntryObject`'s JSON-Schema definition\n   * via the `patternProperty` \"^[^.0-9]+$\".\n   *\n   * This interface was referenced by `PackageExportsEntryObject1`'s JSON-Schema definition\n   * via the `patternProperty` \"^[^.0-9]+$\".\n   */\n  [k: string]: PackageExportsEntry | PackageExportsFallback;\n}\n/**\n * Used to specify conditional exports, note that Conditional exports are unsupported in older environments, so it's recommended to use the fallback array option if support for those environments is a concern.\n */\nexport interface PackageImportsEntryObject {\n  /**\n   * The module path that is resolved when this specifier is imported as a CommonJS module using the `require(...)` function.\n   */\n  require?: PackageImportsEntry | PackageImportsFallback;\n  /**\n   * The module path that is resolved when this specifier is imported as an ECMAScript module using an `import` declaration or the dynamic `import(...)` function.\n   */\n  import?: PackageImportsEntry | PackageImportsFallback;\n  /**\n   * The module path that is resolved when this environment is Node.js.\n   */\n  node?: PackageImportsEntry | PackageImportsFallback;\n  /**\n   * The module path that is resolved when no other export type matches.\n   */\n  default?: PackageImportsEntry | PackageImportsFallback;\n  /**\n   * The module path that is resolved for TypeScript types when this specifier is imported. Should be listed before other conditions.\n   */\n  types?: PackageImportsEntry | PackageImportsFallback;\n  /**\n   * The module path that is resolved when this environment matches the property name.\n   *\n   * This interface was referenced by `PackageImportsEntryObject`'s JSON-Schema definition\n   * via the `patternProperty` \"^[^.0-9]+$\".\n   */\n  [k: string]: PackageImportsEntry | PackageImportsFallback;\n}\n/**\n * Used to inform about ways to help fund development of the package.\n */\nexport interface FundingWay {\n  url: FundingUrl;\n  /**\n   * The type of funding or the platform through which funding can be provided, e.g. patreon, opencollective, tidelift or github.\n   */\n  type?: string;\n}\n/**\n * Dependencies are specified with a simple hash of package name to version range. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or git URL.\n */\nexport interface Dependency {\n  [k: string]: string;\n}\n/**\n * When a user installs your package, warnings are emitted if packages specified in \"peerDependencies\" are not already installed. The \"peerDependenciesMeta\" field serves to provide more information on how your peer dependencies are utilized. Most commonly, it allows peer dependencies to be marked as optional. Metadata for this field is specified with a simple hash of the package name to a metadata object.\n */\nexport interface PeerDependencyMeta {\n  [k: string]: {\n    /**\n     * Specifies that this peer dependency is optional and should not be installed automatically.\n     */\n    optional?: boolean;\n    [k: string]: unknown;\n  };\n}\nexport interface JSONSchemaForESLintConfigurationFiles {\n  ecmaFeatures?: EcmaFeatures;\n  env?: Env;\n  /**\n   * If you want to extend a specific configuration file, you can use the extends property and specify the path to the file. The path can be either relative or absolute.\n   */\n  extends?: string | string[];\n  globals?: Globals;\n  /**\n   * Prevent comments from changing config or rules\n   */\n  noInlineConfig?: boolean;\n  /**\n   * Report unused eslint-disable comments\n   */\n  reportUnusedDisableDirectives?: boolean;\n  parser?: string;\n  parserOptions?: ParserOptions;\n  plugins?: Plugins;\n  /**\n   * By default, ESLint will look for configuration files in all parent folders up to the root directory. This can be useful if you want all of your projects to follow a certain convention, but can sometimes lead to unexpected results. To limit ESLint to a specific project, set this to `true` in a configuration in the root of your project.\n   */\n  root?: boolean;\n  /**\n   * Tell ESLint to ignore specific files and directories. Each value uses the same pattern as the `.eslintignore` file.\n   */\n  ignorePatterns?: string | string[];\n  rules?: Rules;\n  settings?: Settings;\n  overrides?: Overrides;\n  [k: string]: unknown;\n}\n/**\n * By default, ESLint supports only ECMAScript 5 syntax. You can override that setting to enable support for ECMAScript 6 as well as JSX by using configuration settings.\n */\nexport interface EcmaFeatures {\n  arrowFunctions?: boolean;\n  binaryLiterals?: boolean;\n  blockBindings?: boolean;\n  classes?: boolean;\n  defaultParams?: boolean;\n  destructuring?: boolean;\n  /**\n   * Enables support for the experimental object rest/spread properties (IMPORTANT: This is an experimental feature that may change significantly in the future. It's recommended that you do not write rules relying on this functionality unless you are willing to incur maintenance cost when it changes.)\n   */\n  experimentalObjectRestSpread?: boolean;\n  forOf?: boolean;\n  generators?: boolean;\n  /**\n   * allow return statements in the global scope\n   */\n  globalReturn?: boolean;\n  /**\n   * enable global strict mode (if ecmaVersion is 5 or greater)\n   */\n  impliedStrict?: boolean;\n  /**\n   * enable JSX\n   */\n  jsx?: boolean;\n  modules?: boolean;\n  objectLiteralComputedProperties?: boolean;\n  objectLiteralDuplicateProperties?: boolean;\n  objectLiteralShorthandMethods?: boolean;\n  objectLiteralShorthandProperties?: boolean;\n  octalLiterals?: boolean;\n  regexUFlag?: boolean;\n  regexYFlag?: boolean;\n  restParams?: boolean;\n  spread?: boolean;\n  superInFunctions?: boolean;\n  templateStrings?: boolean;\n  unicodeCodePointEscapes?: boolean;\n  [k: string]: unknown;\n}\n/**\n * An environment defines global variables that are predefined.\n */\nexport interface Env {\n  /**\n   * defines require() and define() as global variables as per the amd spec\n   */\n  amd?: boolean;\n  /**\n   * AppleScript global variables\n   */\n  applescript?: boolean;\n  /**\n   * Atom test helper globals\n   */\n  atomtest?: boolean;\n  /**\n   * browser global variables\n   */\n  browser?: boolean;\n  /**\n   * CommonJS global variables and CommonJS scoping (use this for browser-only code that uses Browserify/WebPack)\n   */\n  commonjs?: boolean;\n  /**\n   * Globals common to both Node and Browser\n   */\n  \"shared-node-browser\"?: boolean;\n  /**\n   * Ember test helper globals\n   */\n  embertest?: boolean;\n  /**\n   * enable all ECMAScript 6 features except for modules\n   */\n  es6?: boolean;\n  /**\n   * GreaseMonkey globals\n   */\n  greasemonkey?: boolean;\n  /**\n   * adds all of the Jasmine testing global variables for version 1.3 and 2.0\n   */\n  jasmine?: boolean;\n  /**\n   * Jest global variables\n   */\n  jest?: boolean;\n  /**\n   * jQuery global variables\n   */\n  jquery?: boolean;\n  /**\n   * Meteor global variables\n   */\n  meteor?: boolean;\n  /**\n   * adds all of the Mocha test global variables\n   */\n  mocha?: boolean;\n  /**\n   * MongoDB global variables\n   */\n  mongo?: boolean;\n  /**\n   * Java 8 Nashorn global variables\n   */\n  nashorn?: boolean;\n  /**\n   * Node.js global variables and Node.js scoping\n   */\n  node?: boolean;\n  /**\n   * PhantomJS global variables\n   */\n  phantomjs?: boolean;\n  /**\n   * Prototype.js global variables\n   */\n  prototypejs?: boolean;\n  /**\n   * Protractor global variables\n   */\n  protractor?: boolean;\n  /**\n   * QUnit global variables\n   */\n  qunit?: boolean;\n  /**\n   * Service Worker global variables\n   */\n  serviceworker?: boolean;\n  /**\n   * ShellJS global variables\n   */\n  shelljs?: boolean;\n  /**\n   * WebExtensions globals\n   */\n  webextensions?: boolean;\n  /**\n   * web workers global variables\n   */\n  worker?: boolean;\n  [k: string]: unknown;\n}\n/**\n * Set each global variable name equal to true to allow the variable to be overwritten or false to disallow overwriting.\n */\nexport interface Globals {\n  [k: string]: (\"readonly\" | \"writable\" | \"off\") | boolean;\n}\n/**\n * The JavaScript language options to be supported\n */\nexport interface ParserOptions {\n  ecmaFeatures?: EcmaFeatures;\n  /**\n   * Set to 3, 5 (default), 6, 7, 8, 9, 10, 11, 12, 13, 14, or 15 to specify the version of ECMAScript syntax you want to use. You can also set it to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), 2021 (same as 12), 2022 (same as 13), 2023 (same as 14), or 2024 (same as 15) to use the year-based naming. You can also set \"latest\" to use the most recently supported version.\n   */\n  ecmaVersion?:\n    | 3\n    | 5\n    | 6\n    | 2015\n    | 7\n    | 2016\n    | 8\n    | 2017\n    | 9\n    | 2018\n    | 10\n    | 2019\n    | 11\n    | 2020\n    | 12\n    | 2021\n    | 13\n    | 2022\n    | 14\n    | 2023\n    | 15\n    | 2024\n    | \"latest\";\n  /**\n   * set to \"script\" (default), \"commonjs\", or \"module\" if your code is in ECMAScript modules\n   */\n  sourceType?: \"script\" | \"module\" | \"commonjs\";\n  [k: string]: unknown;\n}\nexport interface PossibleErrors {\n  /**\n   * Require or disallow trailing commas\n   */\n  \"comma-dangle\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce \"for\" loop update clause moving the counter in the right direction\n   */\n  \"for-direction\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce return statements in getters\n   */\n  \"getter-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow await inside of loops\n   */\n  \"no-await-in-loop\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow comparing against -0\n   */\n  \"no-compare-neg-zero\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow assignment operators in conditional expressions\n   */\n  \"no-cond-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of console\n   */\n  \"no-console\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow constant expressions in conditions\n   */\n  \"no-constant-condition\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow control characters in regular expressions\n   */\n  \"no-control-regex\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of debugger\n   */\n  \"no-debugger\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow duplicate arguments in function definitions\n   */\n  \"no-dupe-args\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow duplicate keys in object literals\n   */\n  \"no-dupe-keys\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow duplicate case labels\n   */\n  \"no-duplicate-case\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow empty block statements\n   */\n  \"no-empty\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow empty character classes in regular expressions\n   */\n  \"no-empty-character-class\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow reassigning exceptions in catch clauses\n   */\n  \"no-ex-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary boolean casts\n   */\n  \"no-extra-boolean-cast\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary parentheses\n   */\n  \"no-extra-parens\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary semicolons\n   */\n  \"no-extra-semi\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow reassigning function declarations\n   */\n  \"no-func-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow function or var declarations in nested blocks\n   */\n  \"no-inner-declarations\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow invalid regular expression strings in RegExp constructors\n   */\n  \"no-invalid-regexp\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow irregular whitespace outside of strings and comments\n   */\n  \"no-irregular-whitespace\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow negating the left operand in in expressions (deprecated)\n   */\n  \"no-negated-in-lhs\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow calling global object properties as functions\n   */\n  \"no-obj-calls\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow calling some Object.prototype methods directly on objects\n   */\n  \"no-prototype-builtins\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow multiple spaces in regular expressions\n   */\n  \"no-regex-spaces\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow sparse arrays\n   */\n  \"no-sparse-arrays\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow template literal placeholder syntax in regular strings\n   */\n  \"no-template-curly-in-string\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Disallow confusing multiline expressions\n   */\n  \"no-unexpected-multiline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unreachable code after return, throw, continue, and break statements\n   */\n  \"no-unreachable\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow control flow statements in finally blocks\n   */\n  \"no-unsafe-finally\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow negating the left operand of relational operators\n   */\n  \"no-unsafe-negation\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require calls to isNaN() when checking for NaN\n   */\n  \"use-isnan\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce valid JSDoc comments\n   */\n  \"valid-jsdoc\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce comparing typeof expressions against valid strings\n   */\n  \"valid-typeof\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface BestPractices {\n  /**\n   * Enforce getter and setter pairs in objects\n   */\n  \"accessor-pairs\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce return statements in callbacks of array methods\n   */\n  \"array-callback-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce the use of variables within the scope they are defined\n   */\n  \"block-scoped-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce that class methods utilize this\n   */\n  \"class-methods-use-this\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum cyclomatic complexity allowed in a program\n   */\n  complexity?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require return statements to either always or never specify values\n   */\n  \"consistent-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent brace style for all control statements\n   */\n  curly?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require default cases in switch statements\n   */\n  \"default-case\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent newlines before and after dots\n   */\n  \"dot-location\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce dot notation whenever possible\n   */\n  \"dot-notation\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require the use of === and !==\n   */\n  eqeqeq?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require for-in loops to include an if statement\n   */\n  \"guard-for-in\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of alert, confirm, and prompt\n   */\n  \"no-alert\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of arguments.caller or arguments.callee\n   */\n  \"no-caller\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow lexical declarations in case clauses\n   */\n  \"no-case-declarations\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow division operators explicitly at the beginning of regular expressions\n   */\n  \"no-div-regex\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow else blocks after return statements in if statements\n   */\n  \"no-else-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow empty functions\n   */\n  \"no-empty-function\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow empty destructuring patterns\n   */\n  \"no-empty-pattern\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow null comparisons without type-checking operators\n   */\n  \"no-eq-null\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of eval()\n   */\n  \"no-eval\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow extending native types\n   */\n  \"no-extend-native\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary calls to .bind()\n   */\n  \"no-extra-bind\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary labels\n   */\n  \"no-extra-label\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow fallthrough of case statements\n   */\n  \"no-fallthrough\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow leading or trailing decimal points in numeric literals\n   */\n  \"no-floating-decimal\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow assignments to native objects or read-only global variables\n   */\n  \"no-global-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow shorthand type conversions\n   */\n  \"no-implicit-coercion\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow var and named function declarations in the global scope\n   */\n  \"no-implicit-globals\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of eval()-like methods\n   */\n  \"no-implied-eval\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow this keywords outside of classes or class-like objects\n   */\n  \"no-invalid-this\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of the **iterator** property\n   */\n  \"no-iterator\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow labeled statements\n   */\n  \"no-labels\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary nested blocks\n   */\n  \"no-lone-blocks\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow function declarations and expressions inside loop statements\n   */\n  \"no-loop-func\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow magic numbers\n   */\n  \"no-magic-numbers\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow multiple spaces\n   */\n  \"no-multi-spaces\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow multiline strings\n   */\n  \"no-multi-str\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"no-native-reassign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow new operators outside of assignments or comparisons\n   */\n  \"no-new\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow new operators with the Function object\n   */\n  \"no-new-func\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow new operators with the String, Number, and Boolean objects\n   */\n  \"no-new-wrappers\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow octal literals\n   */\n  \"no-octal\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow octal escape sequences in string literals\n   */\n  \"no-octal-escape\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow reassigning function parameters\n   */\n  \"no-param-reassign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of the **proto** property\n   */\n  \"no-proto\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow var redeclaration\n   */\n  \"no-redeclare\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow certain properties on certain objects\n   */\n  \"no-restricted-properties\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow assignment operators in return statements\n   */\n  \"no-return-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary return await\n   */\n  \"no-return-await\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow javascript: urls\n   */\n  \"no-script-url\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow assignments where both sides are exactly the same\n   */\n  \"no-self-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow comparisons where both sides are exactly the same\n   */\n  \"no-self-compare\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow comma operators\n   */\n  \"no-sequences\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow throwing literals as exceptions\n   */\n  \"no-throw-literal\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unmodified loop conditions\n   */\n  \"no-unmodified-loop-condition\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Disallow unused expressions\n   */\n  \"no-unused-expressions\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unused labels\n   */\n  \"no-unused-labels\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary calls to .call() and .apply()\n   */\n  \"no-useless-call\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary concatenation of literals or template literals\n   */\n  \"no-useless-concat\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary escape characters\n   */\n  \"no-useless-escape\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow redundant return statements\n   */\n  \"no-useless-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow void operators\n   */\n  \"no-void\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified warning terms in comments\n   */\n  \"no-warning-comments\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow with statements\n   */\n  \"no-with\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require using Error objects as Promise rejection reasons\n   */\n  \"prefer-promise-reject-errors\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce the consistent use of the radix argument when using parseInt()\n   */\n  radix?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow async functions which have no await expression\n   */\n  \"require-await\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require var declarations be placed at the top of their containing scope\n   */\n  \"vars-on-top\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require parentheses around immediate function invocations\n   */\n  \"wrap-iife\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or Disallow \"Yoda\" conditions\n   */\n  yoda?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface StrictMode {\n  /**\n   * require or disallow strict mode directives\n   */\n  strict?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface Variables {\n  /**\n   * Require or disallow initialization in var declarations\n   */\n  \"init-declarations\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow catch clause parameters from shadowing variables in the outer scope\n   */\n  \"no-catch-shadow\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow deleting variables\n   */\n  \"no-delete-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow labels that share a name with a variable\n   */\n  \"no-label-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified global variables\n   */\n  \"no-restricted-globals\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow var declarations from shadowing variables in the outer scope\n   */\n  \"no-shadow\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow identifiers from shadowing restricted names\n   */\n  \"no-shadow-restricted-names\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Disallow the use of undeclared variables unless mentioned in /_global _ / comments\n   */\n  \"no-undef\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of undefined as an identifier\n   */\n  \"no-undefined\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow initializing variables to undefined\n   */\n  \"no-undef-init\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unused variables\n   */\n  \"no-unused-vars\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of variables before they are defined\n   */\n  \"no-use-before-define\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface NodeAndCommonJs {\n  /**\n   * Require return statements after callbacks\n   */\n  \"callback-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require require() calls to be placed at top-level module scope\n   */\n  \"global-require\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require error handling in callbacks\n   */\n  \"handle-callback-err\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow use of the Buffer() constructor\n   */\n  \"no-buffer-constructor\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow require calls to be mixed with regular var declarations\n   */\n  \"no-mixed-requires\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow new operators with calls to require\n   */\n  \"no-new-require\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow string concatenation with **dirname and **filename\n   */\n  \"no-path-concat\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of process.env\n   */\n  \"no-process-env\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the use of process.exit()\n   */\n  \"no-process-exit\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified modules when loaded by require\n   */\n  \"no-restricted-modules\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow synchronous methods\n   */\n  \"no-sync\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface StylisticIssues {\n  /**\n   * Enforce line breaks after opening and before closing array brackets\n   */\n  \"array-bracket-newline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing inside array brackets\n   */\n  \"array-bracket-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce line breaks after each array element\n   */\n  \"array-element-newline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing inside single-line blocks\n   */\n  \"block-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent brace style for blocks\n   */\n  \"brace-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce camelcase naming convention\n   */\n  camelcase?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce or disallow capitalization of the first letter of a comment\n   */\n  \"capitalized-comments\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow trailing commas\n   */\n  \"comma-dangle\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before and after commas\n   */\n  \"comma-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent comma style\n   */\n  \"comma-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing inside computed property brackets\n   */\n  \"computed-property-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent naming when capturing the current execution context\n   */\n  \"consistent-this\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce at least one newline at the end of files\n   */\n  \"eol-last\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow spacing between function identifiers and their invocations\n   */\n  \"func-call-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require function names to match the name of the variable or property to which they are assigned\n   */\n  \"func-name-matching\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow named function expressions\n   */\n  \"func-names\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce the consistent use of either function declarations or expressions\n   */\n  \"func-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce line breaks between arguments of a function call\n   */\n  \"function-call-argument-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce consistent line breaks inside function parentheses\n   */\n  \"function-paren-newline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified identifiers\n   */\n  \"id-blacklist\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce minimum and maximum identifier lengths\n   */\n  \"id-length\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require identifiers to match a specified regular expression\n   */\n  \"id-match\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce the location of arrow function bodies\n   */\n  \"implicit-arrow-linebreak\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent indentation\n   */\n  indent?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent indentation (legacy, deprecated)\n   */\n  \"indent-legacy\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce the consistent use of either double or single quotes in JSX attributes\n   */\n  \"jsx-quotes\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing between keys and values in object literal properties\n   */\n  \"key-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before and after keywords\n   */\n  \"keyword-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce position of line comments\n   */\n  \"line-comment-position\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow an empty line between class members\n   */\n  \"lines-between-class-members\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce consistent linebreak style\n   */\n  \"linebreak-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require empty lines around comments\n   */\n  \"lines-around-comment\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow newlines around directives\n   */\n  \"lines-around-directive\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum depth that blocks can be nested\n   */\n  \"max-depth\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum line length\n   */\n  \"max-len\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum number of lines per file\n   */\n  \"max-lines\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum depth that callbacks can be nested\n   */\n  \"max-nested-callbacks\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum number of parameters in function definitions\n   */\n  \"max-params\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum number of statements allowed in function blocks\n   */\n  \"max-statements\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a maximum number of statements allowed per line\n   */\n  \"max-statements-per-line\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce a particular style for multiline comments\n   */\n  \"multiline-comment-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce newlines between operands of ternary expressions\n   */\n  \"multiline-ternary\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require constructor function names to begin with a capital letter\n   */\n  \"new-cap\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow an empty line after var declarations\n   */\n  \"newline-after-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require an empty line before return statements\n   */\n  \"newline-before-return\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require a newline after each call in a method chain\n   */\n  \"newline-per-chained-call\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require parentheses when invoking a constructor with no arguments\n   */\n  \"new-parens\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow Array constructors\n   */\n  \"no-array-constructor\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow bitwise operators\n   */\n  \"no-bitwise\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow continue statements\n   */\n  \"no-continue\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow inline comments after code\n   */\n  \"no-inline-comments\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow if statements as the only statement in else blocks\n   */\n  \"no-lonely-if\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow mixed binary operators\n   */\n  \"no-mixed-operators\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow mixed spaces and tabs for indentation\n   */\n  \"no-mixed-spaces-and-tabs\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow use of chained assignment expressions\n   */\n  \"no-multi-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow multiple empty lines\n   */\n  \"no-multiple-empty-lines\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow negated conditions\n   */\n  \"no-negated-condition\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow nested ternary expressions\n   */\n  \"no-nested-ternary\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow Object constructors\n   */\n  \"no-new-object\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow the unary operators ++ and --\n   */\n  \"no-plusplus\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified syntax\n   */\n  \"no-restricted-syntax\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"no-spaced-func\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow tabs in file\n   */\n  \"no-tabs\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow ternary operators\n   */\n  \"no-ternary\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow trailing whitespace at the end of lines\n   */\n  \"no-trailing-spaces\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow dangling underscores in identifiers\n   */\n  \"no-underscore-dangle\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow ternary operators when simpler alternatives exist\n   */\n  \"no-unneeded-ternary\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow whitespace before properties\n   */\n  \"no-whitespace-before-property\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce the location of single-line statements\n   */\n  \"nonblock-statement-body-position\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce consistent line breaks inside braces\n   */\n  \"object-curly-newline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing inside braces\n   */\n  \"object-curly-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce placing object properties on separate lines\n   */\n  \"object-property-newline\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"object-shorthand\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce variables to be declared either together or separately in functions\n   */\n  \"one-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow newlines around var declarations\n   */\n  \"one-var-declaration-per-line\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Require or disallow assignment operator shorthand where possible\n   */\n  \"operator-assignment\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent linebreak style for operators\n   */\n  \"operator-linebreak\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow padding within blocks\n   */\n  \"padded-blocks\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow padding lines between statements\n   */\n  \"padding-line-between-statements\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Require quotes around object literal property names\n   */\n  \"quote-props\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce the consistent use of either backticks, double, or single quotes\n   */\n  quotes?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require JSDoc comments\n   */\n  \"require-jsdoc\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow semicolons instead of ASI\n   */\n  semi?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before and after semicolons\n   */\n  \"semi-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce location of semicolons\n   */\n  \"semi-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Requires object keys to be sorted\n   */\n  \"sort-keys\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require variables within the same declaration block to be sorted\n   */\n  \"sort-vars\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before blocks\n   */\n  \"space-before-blocks\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before function definition opening parenthesis\n   */\n  \"space-before-function-paren\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | unknown[];\n  /**\n   * Enforce consistent spacing after the // or /\\* in a comment\n   */\n  \"spaced-comment\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require spacing around operators\n   */\n  \"space-infix-ops\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing inside parentheses\n   */\n  \"space-in-parens\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before or after unary operators\n   */\n  \"space-unary-ops\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce spacing around colons of switch statements\n   */\n  \"switch-colon-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow spacing between template tags and their literals\n   */\n  \"template-tag-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow Unicode byte order mark (BOM)\n   */\n  \"unicode-bom\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require parenthesis around regex literals\n   */\n  \"wrap-regex\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface EcmaScript6 {\n  /**\n   * Require braces around arrow function bodies\n   */\n  \"arrow-body-style\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require parentheses around arrow function arguments\n   */\n  \"arrow-parens\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing before and after the arrow in arrow functions\n   */\n  \"arrow-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require super() calls in constructors\n   */\n  \"constructor-super\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce consistent spacing around \\* operators in generator functions\n   */\n  \"generator-star-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow reassigning class members\n   */\n  \"no-class-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow arrow functions where they could be confused with comparisons\n   */\n  \"no-confusing-arrow\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow reassigning const variables\n   */\n  \"no-const-assign\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow duplicate class members\n   */\n  \"no-dupe-class-members\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow duplicate module imports\n   */\n  \"no-duplicate-imports\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow new operators with the Symbol object\n   */\n  \"no-new-symbol\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow specified modules when loaded by import\n   */\n  \"no-restricted-imports\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow this/super before calling super() in constructors\n   */\n  \"no-this-before-super\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary computed property keys in object literals\n   */\n  \"no-useless-computed-key\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow unnecessary constructors\n   */\n  \"no-useless-constructor\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow renaming import, export, and destructured assignments to the same name\n   */\n  \"no-useless-rename\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require let or const instead of var\n   */\n  \"no-var\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow method and property shorthand syntax for object literals\n   */\n  \"object-shorthand\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require arrow functions as callbacks\n   */\n  \"prefer-arrow-callback\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require const declarations for variables that are never reassigned after declared\n   */\n  \"prefer-const\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require destructuring from arrays and/or objects\n   */\n  \"prefer-destructuring\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Disallow parseInt() in favor of binary, octal, and hexadecimal literals\n   */\n  \"prefer-numeric-literals\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require Reflect methods where applicable\n   */\n  \"prefer-reflect\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require rest parameters instead of arguments\n   */\n  \"prefer-rest-params\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require spread operators instead of .apply()\n   */\n  \"prefer-spread\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require template literals instead of string concatenation\n   */\n  \"prefer-template\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require generator functions to contain yield\n   */\n  \"require-yield\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce spacing between rest and spread operators and their expressions\n   */\n  \"rest-spread-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Enforce sorted import declarations within modules\n   */\n  \"sort-imports\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require symbol descriptions\n   */\n  \"symbol-description\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow spacing around embedded expressions of template strings\n   */\n  \"template-curly-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  /**\n   * Require or disallow spacing around the _ in yield_ expressions\n   */\n  \"yield-star-spacing\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface Legacy {\n  \"max-depth\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"max-len\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"max-params\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"max-statements\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"no-bitwise\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  \"no-plusplus\"?: number | (\"off\" | \"warn\" | \"error\") | unknown[];\n  [k: string]: unknown;\n}\nexport interface HttpsJsonSchemastoreOrgPartialEslintPluginsJson {\n  /**\n   * Classes decorated with @Component must have suffix \"Component\" (or custom) in their name. See more at https://angular.dev/style-guide#style-02-03\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/component-class-suffix.md\n   */\n  \"@angular-eslint/component-class-suffix\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          suffixes?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforces a maximum number of lines in inline template, styles and animations. See more at https://angular.dev/style-guide#style-05-04\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/component-max-inline-declarations.md\n   */\n  \"@angular-eslint/component-max-inline-declarations\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          template?: number;\n          styles?: number;\n          animations?: number;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Component selectors should follow given naming rules. See more at https://angular.dev/style-guide#style-02-07, https://angular.dev/style-guide#style-05-02\n   * and https://angular.dev/style-guide#style-05-03.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/component-selector.md\n   */\n  \"@angular-eslint/component-selector\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          type?: string | (\"element\" | \"attribute\")[];\n          prefix?: string | unknown[];\n          style?: \"camelCase\" | \"kebab-case\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures consistent usage of `styles`/`styleUrls`/`styleUrl` within Component metadata\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/consistent-component-styles.md\n   */\n  \"@angular-eslint/consistent-component-styles\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures that classes use contextual decorators in its body\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/contextual-decorator.md\n   */\n  \"@angular-eslint/contextual-decorator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that lifecycle methods are used in a correct context\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/contextual-lifecycle.md\n   */\n  \"@angular-eslint/contextual-lifecycle\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Classes decorated with @Directive must have suffix \"Directive\" (or custom) in their name. See more at https://angular.dev/style-guide#style-02-03\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/directive-class-suffix.md\n   */\n  \"@angular-eslint/directive-class-suffix\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          suffixes?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Directive selectors should follow given naming rules. See more at https://angular.dev/style-guide#style-02-06 and https://angular.dev/style-guide#style-02-08.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/directive-selector.md\n   */\n  \"@angular-eslint/directive-selector\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          type?: string | (\"element\" | \"attribute\")[];\n          prefix?: string | unknown[];\n          style?: \"camelCase\" | \"kebab-case\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Angular Lifecycle methods should not be async. Angular does not wait for async lifecycle but the code incorrectly suggests it does.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-async-lifecycle-method.md\n   */\n  \"@angular-eslint/no-async-lifecycle-method\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * The @Attribute decorator is used to obtain a single value for an attribute. This is a much less common use-case than getting a stream of values (using @Input), so often the @Attribute decorator is mistakenly used when @Input was what was intended. This rule disallows usage of @Attribute decorator altogether in order to prevent these mistakes.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-attribute-decorator.md\n   */\n  \"@angular-eslint/no-attribute-decorator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that directives not implement conflicting lifecycle interfaces.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-conflicting-lifecycle.md\n   */\n  \"@angular-eslint/no-conflicting-lifecycle\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that metadata arrays do not contain duplicate entries.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-duplicates-in-metadata-arrays.md\n   */\n  \"@angular-eslint/no-duplicates-in-metadata-arrays\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows declaring empty lifecycle methods\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-empty-lifecycle-method.md\n   */\n  \"@angular-eslint/no-empty-lifecycle-method\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows usage of `forwardRef` references for DI\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-forward-ref.md\n   */\n  \"@angular-eslint/no-forward-ref\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows usage of the `host` metadata property. NOTE: This used to be recommended by the Angular Team, but now they recommend the exact opposite: https://github.com/angular/angular/issues/54284\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-host-metadata-property.md\n   */\n  \"@angular-eslint/no-host-metadata-property\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowStatic?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures that input bindings, including aliases, are not named or prefixed by the configured disallowed prefixes\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-input-prefix.md\n   */\n  \"@angular-eslint/no-input-prefix\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          prefixes?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures that input bindings are not aliased\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-input-rename.md\n   */\n  \"@angular-eslint/no-input-rename\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * A list with allowed input names\n           */\n          allowedNames?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallows usage of the `inputs` metadata property. See more at https://angular.dev/style-guide#style-05-12\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-inputs-metadata-property.md\n   */\n  \"@angular-eslint/no-inputs-metadata-property\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows explicit calls to lifecycle methods\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-lifecycle-call.md\n   */\n  \"@angular-eslint/no-lifecycle-call\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that output bindings, including aliases, are not named as standard DOM events\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-output-native.md\n   */\n  \"@angular-eslint/no-output-native\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that output bindings, including aliases, are not named \"on\", nor prefixed with it. See more at https://angular.dev/style-guide#style-05-16\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-output-on-prefix.md\n   */\n  \"@angular-eslint/no-output-on-prefix\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that output bindings are not aliased\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-output-rename.md\n   */\n  \"@angular-eslint/no-output-rename\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows usage of the `outputs` metadata property. See more at https://angular.dev/style-guide#style-05-12\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-outputs-metadata-property.md\n   */\n  \"@angular-eslint/no-outputs-metadata-property\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows the declaration of impure pipes\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-pipe-impure.md\n   */\n  \"@angular-eslint/no-pipe-impure\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows usage of the `queries` metadata property. See more at https://angular.dev/style-guide#style-05-12.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/no-queries-metadata-property.md\n   */\n  \"@angular-eslint/no-queries-metadata-property\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent prefix for pipes.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/pipe-prefix.md\n   */\n  \"@angular-eslint/pipe-prefix\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          prefixes?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures component's `changeDetection` is set to `ChangeDetectionStrategy.OnPush`\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-on-push-component-change-detection.md\n   */\n  \"@angular-eslint/prefer-on-push-component-change-detection\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures component, directive and pipe `standalone` property is set to `true` in the component decorator\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-standalone.md\n   */\n  \"@angular-eslint/prefer-standalone\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures component `standalone` property is set to `true` in the component decorator\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-standalone-component.md\n   */\n  \"@angular-eslint/prefer-standalone-component\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer to declare `@Output` as `readonly` since they are not supposed to be reassigned\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/prefer-output-readonly.md\n   */\n  \"@angular-eslint/prefer-output-readonly\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * The ./ and ../ prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix. See more at https://angular.dev/style-guide#style-05-04\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/relative-url-prefix.md\n   */\n  \"@angular-eslint/relative-url-prefix\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that $localize tagged messages contain helpful metadata to aid with translations.\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/require-localize-metadata.md\n   */\n  \"@angular-eslint/require-localize-metadata\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          requireDescription?: boolean;\n          requireMeaning?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures that lifecycle methods are declared in order of execution\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/sort-lifecycle-methods.md\n   */\n  \"@angular-eslint/sort-lifecycle-methods\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures ASC alphabetical order for `NgModule` metadata arrays for easy visual scanning\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/sort-ngmodule-metadata-arrays.md\n   */\n  \"@angular-eslint/sort-ngmodule-metadata-arrays\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * A string with a BCP 47 language tag.\n           */\n          locale?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Component selector must be declared\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/use-component-selector.md\n   */\n  \"@angular-eslint/use-component-selector\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallows using `ViewEncapsulation.None`\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/use-component-view-encapsulation.md\n   */\n  \"@angular-eslint/use-component-view-encapsulation\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Using the `providedIn` property makes `Injectables` tree-shakable\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/use-injectable-provided-in.md\n   */\n  \"@angular-eslint/use-injectable-provided-in\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreClassNamePattern?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensures that classes implement lifecycle interfaces corresponding to the declared lifecycle methods. See more at https://angular.dev/style-guide#style-09-01\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/use-lifecycle-interface.md\n   */\n  \"@angular-eslint/use-lifecycle-interface\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensures that `Pipes` implement `PipeTransform` interface\n   * https://github.com/angular-eslint/angular-eslint/blob/main/packages/eslint-plugin/docs/rules/use-pipe-transform-interface.md\n   */\n  \"@angular-eslint/use-pipe-transform-interface\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensure imports point to a file/module that can be resolved.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-unresolved.md\n   */\n  \"eslint-plugin-import/no-unresolved\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          amd?: boolean;\n          esmodule?: boolean;\n          /**\n           * @minItems 1\n           */\n          ignore?: [string, ...string[]];\n          caseSensitive?: boolean;\n          caseSensitiveStrict?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensure named imports correspond to a named export in the remote file.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/named.md\n   */\n  \"eslint-plugin-import/named\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensure a default export is present, given a default import.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/default.md\n   */\n  \"eslint-plugin-import/default\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensure imported namespaces contain dereferenced properties as they are dereferenced.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/namespace.md\n   */\n  \"eslint-plugin-import/namespace\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * If `false`, will report computed (and thus, un-lintable) references to namespace members.\n           */\n          allowComputed?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid namespace (a.k.a. \"wildcard\" `*`) imports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-namespace.md\n   */\n  \"eslint-plugin-import/no-namespace\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignore?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid any invalid exports, i.e. re-export of the same name.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/export.md\n   */\n  \"eslint-plugin-import/export\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid the use of mutable exports with `var` or `let`.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-mutable-exports.md\n   */\n  \"eslint-plugin-import/no-mutable-exports\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensure consistent use of file extension within the import path.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/extensions.md\n   */\n  \"eslint-plugin-import/extensions\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce which files can be imported in a given folder.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-restricted-paths.md\n   */\n  \"eslint-plugin-import/no-restricted-paths\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           */\n          zones?: [\n            {\n              target?: string | [string, ...string[]];\n              from?: string | [string, ...string[]];\n              except?: string[];\n              message?: string;\n            },\n            ...{\n              target?: string | [string, ...string[]];\n              from?: string | [string, ...string[]];\n              except?: string[];\n              message?: string;\n            }[],\n          ];\n          basePath?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid importing the submodules of other modules.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-internal-modules.md\n   */\n  \"eslint-plugin-import/no-internal-modules\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer named exports to be grouped together in a single export declaration\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/group-exports.md\n   */\n  \"eslint-plugin-import/group-exports\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid importing packages through relative paths.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-relative-packages.md\n   */\n  \"eslint-plugin-import/no-relative-packages\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          amd?: boolean;\n          esmodule?: boolean;\n          /**\n           * @minItems 1\n           */\n          ignore?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid importing modules from parent directories.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-relative-parent-imports.md\n   */\n  \"eslint-plugin-import/no-relative-parent-imports\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          amd?: boolean;\n          esmodule?: boolean;\n          /**\n           * @minItems 1\n           */\n          ignore?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce or ban the use of inline type-only markers for named imports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/consistent-type-specifier-style.md\n   */\n  \"eslint-plugin-import/consistent-type-specifier-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid a module from importing itself.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-self-import.md\n   */\n  \"eslint-plugin-import/no-self-import\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid a module from importing a module with a dependency path back to itself.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-cycle.md\n   */\n  \"eslint-plugin-import/no-cycle\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          amd?: boolean;\n          esmodule?: boolean;\n          /**\n           * @minItems 1\n           */\n          ignore?: [string, ...string[]];\n          maxDepth?: number | \"∞\";\n          /**\n           * ignore external modules\n           */\n          ignoreExternal?: boolean;\n          /**\n           * Allow cyclic dependency if there is at least one dynamic import in the chain\n           */\n          allowUnsafeDynamicCyclicDependency?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid named default exports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-named-default.md\n   */\n  \"eslint-plugin-import/no-named-default\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid use of exported name as identifier of default export.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-named-as-default.md\n   */\n  \"eslint-plugin-import/no-named-as-default\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid use of exported name as property of default export.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-named-as-default-member.md\n   */\n  \"eslint-plugin-import/no-named-as-default-member\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid anonymous values as default exports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-anonymous-default-export.md\n   */\n  \"eslint-plugin-import/no-anonymous-default-export\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * If `false`, will report default export of an array\n           */\n          allowArray?: boolean;\n          /**\n           * If `false`, will report default export of an arrow function\n           */\n          allowArrowFunction?: boolean;\n          /**\n           * If `false`, will report default export of a function call\n           */\n          allowCallExpression?: boolean;\n          /**\n           * If `false`, will report default export of an anonymous class\n           */\n          allowAnonymousClass?: boolean;\n          /**\n           * If `false`, will report default export of an anonymous function\n           */\n          allowAnonymousFunction?: boolean;\n          /**\n           * If `false`, will report default export of a literal\n           */\n          allowLiteral?: boolean;\n          /**\n           * If `false`, will report default export of an object expression\n           */\n          allowObject?: boolean;\n          /**\n           * If `false`, will report default export of a class instantiation\n           */\n          allowNew?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid modules without exports, or exports without matching import in another module.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-unused-modules.md\n   */\n  \"eslint-plugin-import/no-unused-modules\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * files/paths to be analyzed (only for unused exports)\n           */\n          src?: string[];\n          /**\n           * files/paths for which unused exports will not be reported (e.g module entry points)\n           */\n          ignoreExports?: string[];\n          /**\n           * report modules without any exports\n           */\n          missingExports?: boolean;\n          /**\n           * report exports without any usage\n           */\n          unusedExports?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid CommonJS `require` calls and `module.exports` or `exports.*`.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-commonjs.md\n   */\n  \"eslint-plugin-import/no-commonjs\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid AMD `require` and `define` calls.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-amd.md\n   */\n  \"eslint-plugin-import/no-amd\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid repeated import of the same module in multiple places.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-duplicates.md\n   */\n  \"eslint-plugin-import/no-duplicates\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          considerQueryString?: boolean;\n          \"prefer-inline\"?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Ensure all imports appear before other statements.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/first.md\n   */\n  \"eslint-plugin-import/first\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce the maximum number of dependencies a module can have.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/max-dependencies.md\n   */\n  \"eslint-plugin-import/max-dependencies\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          max?: number;\n          ignoreTypeImports?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid the use of extraneous packages.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-extraneous-dependencies.md\n   */\n  \"eslint-plugin-import/no-extraneous-dependencies\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          devDependencies?: boolean | unknown[];\n          optionalDependencies?: boolean | unknown[];\n          peerDependencies?: boolean | unknown[];\n          bundledDependencies?: boolean | unknown[];\n          packageDir?: string | unknown[];\n          includeInternal?: boolean;\n          includeTypes?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid import of modules using absolute paths.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-absolute-path.md\n   */\n  \"eslint-plugin-import/no-absolute-path\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          amd?: boolean;\n          esmodule?: boolean;\n          /**\n           * @minItems 1\n           */\n          ignore?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid Node.js builtin modules.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-nodejs-modules.md\n   */\n  \"eslint-plugin-import/no-nodejs-modules\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid webpack loader syntax in imports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-webpack-loader-syntax.md\n   */\n  \"eslint-plugin-import/no-webpack-loader-syntax\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce a convention in module import order.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/order.md\n   */\n  \"eslint-plugin-import/order\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          groups?: unknown[];\n          pathGroupsExcludedImportTypes?: unknown[];\n          distinctGroup?: boolean;\n          pathGroups?: {\n            pattern: string;\n            patternOptions?: {\n              [k: string]: unknown;\n            };\n            group:\n              | \"builtin\"\n              | \"external\"\n              | \"internal\"\n              | \"unknown\"\n              | \"parent\"\n              | \"sibling\"\n              | \"index\"\n              | \"object\"\n              | \"type\";\n            position?: \"after\" | \"before\";\n          }[];\n          \"newlines-between\"?:\n            | \"ignore\"\n            | \"always\"\n            | \"always-and-inside-groups\"\n            | \"never\";\n          alphabetize?: {\n            caseInsensitive?: boolean;\n            order?: \"ignore\" | \"asc\" | \"desc\";\n            orderImportKind?: \"ignore\" | \"asc\" | \"desc\";\n          };\n          warnOnUnassignedImports?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce a newline after import statements.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/newline-after-import.md\n   */\n  \"eslint-plugin-import/newline-after-import\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          count?: number;\n          exactCount?: boolean;\n          considerComments?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer a default export if module exports a single name or multiple names.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/prefer-default-export.md\n   */\n  \"eslint-plugin-import/prefer-default-export\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          target?: \"single\" | \"any\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid default exports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-default-export.md\n   */\n  \"eslint-plugin-import/no-default-export\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid named exports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-named-export.md\n   */\n  \"eslint-plugin-import/no-named-export\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid `require()` calls with expressions.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-dynamic-require.md\n   */\n  \"eslint-plugin-import/no-dynamic-require\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          esmodule?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid potentially ambiguous parse goal (`script` vs. `module`).\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/unambiguous.md\n   */\n  \"eslint-plugin-import/unambiguous\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid unassigned imports\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-unassigned-import.md\n   */\n  \"eslint-plugin-import/no-unassigned-import\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          devDependencies?: boolean | unknown[];\n          optionalDependencies?: boolean | unknown[];\n          peerDependencies?: boolean | unknown[];\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid unnecessary path segments in import and require statements.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-useless-path-segments.md\n   */\n  \"eslint-plugin-import/no-useless-path-segments\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          commonjs?: boolean;\n          noUselessIndex?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce a leading comment with the webpackChunkName for dynamic imports.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/dynamic-import-chunkname.md\n   */\n  \"eslint-plugin-import/dynamic-import-chunkname\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          importFunctions?: string[];\n          webpackChunknameFormat?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid import statements with CommonJS module.exports.\n   */\n  \"eslint-plugin-import/no-import-module-exports\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          exceptions?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Forbid empty named import blocks.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-empty-named-blocks.md\n   */\n  \"eslint-plugin-import/no-empty-named-blocks\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Ensure all exports appear after other statements.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/exports-last.md\n   */\n  \"eslint-plugin-import/exports-last\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Forbid imported names marked with `@deprecated` documentation tag.\n   * https://github.com/import-js/eslint-plugin-import/blob/v2.29.1/docs/rules/no-deprecated.md\n   */\n  \"eslint-plugin-import/no-deprecated\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Replaced by `import/first`.\n   * https://github.com/import-js/eslint-plugin-import/blob/7b25c1cb95ee18acc1531002fd343e1e6031f9ed/docs/rules/imports-first.md\n   */\n  \"eslint-plugin-import/imports-first\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Improve regexes by making them shorter, consistent, and safer.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/better-regex.md\n   */\n  \"eslint-plugin-unicorn/better-regex\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          sortCharacterClasses?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce a specific parameter name in catch clauses.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/catch-error-name.md\n   */\n  \"eslint-plugin-unicorn/catch-error-name\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          name?: string;\n          ignore?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Use destructured variables over properties.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/consistent-destructuring.md\n   */\n  \"eslint-plugin-unicorn/consistent-destructuring\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer consistent types when spreading a ternary in an array literal.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/consistent-empty-array-spread.md\n   */\n  \"eslint-plugin-unicorn/consistent-empty-array-spread\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Move function definitions to the highest possible scope.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/consistent-function-scoping.md\n   */\n  \"eslint-plugin-unicorn/consistent-function-scoping\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkArrowFunctions?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce correct `Error` subclassing.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/custom-error-definition.md\n   */\n  \"eslint-plugin-unicorn/custom-error-definition\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce no spaces between braces.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/empty-brace-spaces.md\n   */\n  \"eslint-plugin-unicorn/empty-brace-spaces\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce passing a `message` value when creating a built-in error.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/error-message.md\n   */\n  \"eslint-plugin-unicorn/error-message\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require escape sequences to use uppercase values.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/escape-case.md\n   */\n  \"eslint-plugin-unicorn/escape-case\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Add expiration conditions to TODO comments.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/expiring-todo-comments.md\n   */\n  \"eslint-plugin-unicorn/expiring-todo-comments\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          terms?: string[];\n          ignore?: unknown[];\n          ignoreDatesOnPullRequests?: boolean;\n          allowWarningComments?: boolean;\n          date?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce explicitly comparing the `length` or `size` property of a value.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/explicit-length-check.md\n   */\n  \"eslint-plugin-unicorn/explicit-length-check\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          \"non-zero\"?: \"greater-than\" | \"not-equal\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce a case style for filenames.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/filename-case.md\n   */\n  \"eslint-plugin-unicorn/filename-case\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce specific import styles per module.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/import-style.md\n   */\n  \"eslint-plugin-unicorn/import-style\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of `new` for all builtins, except `String`, `Number`, `Boolean`, `Symbol` and `BigInt`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/new-for-builtins.md\n   */\n  \"eslint-plugin-unicorn/new-for-builtins\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce specifying rules to disable in `eslint-disable` comments.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-abusive-eslint-disable.md\n   */\n  \"eslint-plugin-unicorn/no-abusive-eslint-disable\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow anonymous functions and classes as the default export.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-anonymous-default-export.md\n   */\n  \"eslint-plugin-unicorn/no-anonymous-default-export\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prevent passing a function reference directly to iterator methods.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-array-callback-reference.md\n   */\n  \"eslint-plugin-unicorn/no-array-callback-reference\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `for…of` over the `forEach` method.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-array-for-each.md\n   */\n  \"eslint-plugin-unicorn/no-array-for-each\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow using the `this` argument in array methods.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-array-method-this-argument.md\n   */\n  \"eslint-plugin-unicorn/no-array-method-this-argument\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce combining multiple `Array#push()` into one call.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-array-push-push.md\n   */\n  \"eslint-plugin-unicorn/no-array-push-push\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignore?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow `Array#reduce()` and `Array#reduceRight()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-array-reduce.md\n   */\n  \"eslint-plugin-unicorn/no-array-reduce\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowSimpleOperations?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow member access from await expression.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-await-expression-member.md\n   */\n  \"eslint-plugin-unicorn/no-await-expression-member\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow using `await` in `Promise` method parameters.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-await-in-promise-methods.md\n   */\n  \"eslint-plugin-unicorn/no-await-in-promise-methods\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Do not use leading/trailing space between `console.log` parameters.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-console-spaces.md\n   */\n  \"eslint-plugin-unicorn/no-console-spaces\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Do not use `document.cookie` directly.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-document-cookie.md\n   */\n  \"eslint-plugin-unicorn/no-document-cookie\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow empty files.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-empty-file.md\n   */\n  \"eslint-plugin-unicorn/no-empty-file\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Do not use a `for` loop that can be replaced with a `for-of` loop.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-for-loop.md\n   */\n  \"eslint-plugin-unicorn/no-for-loop\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of Unicode escapes instead of hexadecimal escapes.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-hex-escape.md\n   */\n  \"eslint-plugin-unicorn/no-hex-escape\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require `Array.isArray()` instead of `instanceof Array`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-instanceof-array.md\n   */\n  \"eslint-plugin-unicorn/no-instanceof-array\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow invalid options in `fetch()` and `new Request()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-invalid-fetch-options.md\n   */\n  \"eslint-plugin-unicorn/no-invalid-fetch-options\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prevent calling `EventTarget#removeEventListener()` with the result of an expression.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-invalid-remove-event-listener.md\n   */\n  \"eslint-plugin-unicorn/no-invalid-remove-event-listener\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow identifiers starting with `new` or `class`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-keyword-prefix.md\n   */\n  \"eslint-plugin-unicorn/no-keyword-prefix\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           * @maxItems 1\n           */\n          disallowedPrefixes?: [string];\n          checkProperties?: boolean;\n          onlyCamelCase?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow `if` statements as the only statement in `if` blocks without `else`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-lonely-if.md\n   */\n  \"eslint-plugin-unicorn/no-lonely-if\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow a magic number as the `depth` argument in `Array#flat(…).`\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-magic-array-flat-depth.md\n   */\n  \"eslint-plugin-unicorn/no-magic-array-flat-depth\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow negated conditions.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-negated-condition.md\n   */\n  \"eslint-plugin-unicorn/no-negated-condition\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow negated expression in equality check.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-negation-in-equality-check.md\n   */\n  \"eslint-plugin-unicorn/no-negation-in-equality-check\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow nested ternary expressions.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-nested-ternary.md\n   */\n  \"eslint-plugin-unicorn/no-nested-ternary\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow `new Array()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-new-array.md\n   */\n  \"eslint-plugin-unicorn/no-new-array\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of `Buffer.from()` and `Buffer.alloc()` instead of the deprecated `new Buffer()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-new-buffer.md\n   */\n  \"eslint-plugin-unicorn/no-new-buffer\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow the use of the `null` literal.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-null.md\n   */\n  \"eslint-plugin-unicorn/no-null\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkStrictEquality?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow the use of objects as default parameters.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-object-as-default-parameter.md\n   */\n  \"eslint-plugin-unicorn/no-object-as-default-parameter\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow `process.exit()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-process-exit.md\n   */\n  \"eslint-plugin-unicorn/no-process-exit\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow passing single-element arrays to `Promise` methods.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-single-promise-in-promise-methods.md\n   */\n  \"eslint-plugin-unicorn/no-single-promise-in-promise-methods\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow classes that only have static members.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-static-only-class.md\n   */\n  \"eslint-plugin-unicorn/no-static-only-class\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow `then` property.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-thenable.md\n   */\n  \"eslint-plugin-unicorn/no-thenable\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow assigning `this` to a variable.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-this-assignment.md\n   */\n  \"eslint-plugin-unicorn/no-this-assignment\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow comparing `undefined` using `typeof`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-typeof-undefined.md\n   */\n  \"eslint-plugin-unicorn/no-typeof-undefined\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkGlobalVariables?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow awaiting non-promise values.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-unnecessary-await.md\n   */\n  \"eslint-plugin-unicorn/no-unnecessary-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of built-in methods instead of unnecessary polyfills.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-unnecessary-polyfills.md\n   */\n  \"eslint-plugin-unicorn/no-unnecessary-polyfills\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          targets?:\n            | string\n            | unknown[]\n            | {\n                [k: string]: unknown;\n              };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unreadable array destructuring.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-unreadable-array-destructuring.md\n   */\n  \"eslint-plugin-unicorn/no-unreadable-array-destructuring\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unreadable IIFEs.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-unreadable-iife.md\n   */\n  \"eslint-plugin-unicorn/no-unreadable-iife\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unused object properties.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-unused-properties.md\n   */\n  \"eslint-plugin-unicorn/no-unused-properties\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow useless fallback when spreading in object literals.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-fallback-in-spread.md\n   */\n  \"eslint-plugin-unicorn/no-useless-fallback-in-spread\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow useless array length check.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-length-check.md\n   */\n  \"eslint-plugin-unicorn/no-useless-length-check\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow returning/yielding `Promise.resolve/reject()` in async functions or promise callbacks\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-promise-resolve-reject.md\n   */\n  \"eslint-plugin-unicorn/no-useless-promise-resolve-reject\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary spread.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-spread.md\n   */\n  \"eslint-plugin-unicorn/no-useless-spread\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow useless case in switch statements.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-switch-case.md\n   */\n  \"eslint-plugin-unicorn/no-useless-switch-case\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow useless `undefined`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-useless-undefined.md\n   */\n  \"eslint-plugin-unicorn/no-useless-undefined\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkArguments?: boolean;\n          checkArrowFunctionBody?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow number literals with zero fractions or dangling dots.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/no-zero-fractions.md\n   */\n  \"eslint-plugin-unicorn/no-zero-fractions\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce proper case for numeric literals.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/number-literal-case.md\n   */\n  \"eslint-plugin-unicorn/number-literal-case\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the style of numeric separators by correctly grouping digits.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/numeric-separators-style.md\n   */\n  \"eslint-plugin-unicorn/numeric-separators-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          binary?: {\n            onlyIfContainsSeparator?: boolean;\n            minimumDigits?: number;\n            groupLength?: number;\n          };\n          octal?: {\n            onlyIfContainsSeparator?: boolean;\n            minimumDigits?: number;\n            groupLength?: number;\n          };\n          hexadecimal?: {\n            onlyIfContainsSeparator?: boolean;\n            minimumDigits?: number;\n            groupLength?: number;\n          };\n          number?: {\n            onlyIfContainsSeparator?: boolean;\n            minimumDigits?: number;\n            groupLength?: number;\n          };\n          onlyIfContainsSeparator?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `.addEventListener()` and `.removeEventListener()` over `on`-functions.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-add-event-listener.md\n   */\n  \"eslint-plugin-unicorn/prefer-add-event-listener\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          excludedPackages?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `.find(…)` and `.findLast(…)` over the first or last element from `.filter(…)`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-array-find.md\n   */\n  \"eslint-plugin-unicorn/prefer-array-find\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkFromLast?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `.flatMap(…)` over `.map(…).flat()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-array-flat-map.md\n   */\n  \"eslint-plugin-unicorn/prefer-array-flat-map\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Array#flat()` over legacy techniques to flatten arrays.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-array-flat.md\n   */\n  \"eslint-plugin-unicorn/prefer-array-flat\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          functions?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `Array#{indexOf,lastIndexOf}()` over `Array#{findIndex,findLastIndex}()` when looking for the index of an item.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-array-index-of.md\n   */\n  \"eslint-plugin-unicorn/prefer-array-index-of\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `.some(…)` over `.filter(…).length` check and `.{find,findLast,findIndex,findLastIndex}(…)`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-array-some.md\n   */\n  \"eslint-plugin-unicorn/prefer-array-some\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `.at()` method for index access and `String#charAt()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-at.md\n   */\n  \"eslint-plugin-unicorn/prefer-at\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          getLastElementFunctions?: unknown[];\n          checkAllIndexAccess?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `Blob#arrayBuffer()` over `FileReader#readAsArrayBuffer(…)` and `Blob#text()` over `FileReader#readAsText(…)`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-blob-reading-methods.md\n   */\n  \"eslint-plugin-unicorn/prefer-blob-reading-methods\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `String#codePointAt(…)` over `String#charCodeAt(…)` and `String.fromCodePoint(…)` over `String.fromCharCode(…)`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-code-point.md\n   */\n  \"eslint-plugin-unicorn/prefer-code-point\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Date.now()` to get the number of milliseconds since the Unix Epoch.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-date-now.md\n   */\n  \"eslint-plugin-unicorn/prefer-date-now\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer default parameters over reassignment.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-default-parameters.md\n   */\n  \"eslint-plugin-unicorn/prefer-default-parameters\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Node#append()` over `Node#appendChild()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-dom-node-append.md\n   */\n  \"eslint-plugin-unicorn/prefer-dom-node-append\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using `.dataset` on DOM elements over calling attribute methods.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-dom-node-dataset.md\n   */\n  \"eslint-plugin-unicorn/prefer-dom-node-dataset\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `childNode.remove()` over `parentNode.removeChild(childNode)`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-dom-node-remove.md\n   */\n  \"eslint-plugin-unicorn/prefer-dom-node-remove\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `.textContent` over `.innerText`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-dom-node-text-content.md\n   */\n  \"eslint-plugin-unicorn/prefer-dom-node-text-content\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `EventTarget` over `EventEmitter`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-event-target.md\n   */\n  \"eslint-plugin-unicorn/prefer-event-target\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `export…from` when re-exporting.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-export-from.md\n   */\n  \"eslint-plugin-unicorn/prefer-export-from\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreUsedVariables?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `.includes()` over `.indexOf()`, `.lastIndexOf()`, and `Array#some()` when checking for existence or non-existence.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-includes.md\n   */\n  \"eslint-plugin-unicorn/prefer-includes\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer reading a JSON file as a buffer.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-json-parse-buffer.md\n   */\n  \"eslint-plugin-unicorn/prefer-json-parse-buffer\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `KeyboardEvent#key` over `KeyboardEvent#keyCode`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-keyboard-event-key.md\n   */\n  \"eslint-plugin-unicorn/prefer-keyboard-event-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using a logical operator over a ternary.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-logical-operator-over-ternary.md\n   */\n  \"eslint-plugin-unicorn/prefer-logical-operator-over-ternary\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of `Math.trunc` instead of bitwise operators.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-math-trunc.md\n   */\n  \"eslint-plugin-unicorn/prefer-math-trunc\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `.before()` over `.insertBefore()`, `.replaceWith()` over `.replaceChild()`, prefer one of `.before()`, `.after()`, `.append()` or `.prepend()` over `insertAdjacentText()` and `insertAdjacentElement()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-modern-dom-apis.md\n   */\n  \"eslint-plugin-unicorn/prefer-modern-dom-apis\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer modern `Math` APIs over legacy patterns.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-modern-math-apis.md\n   */\n  \"eslint-plugin-unicorn/prefer-modern-math-apis\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer JavaScript modules (ESM) over CommonJS.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-module.md\n   */\n  \"eslint-plugin-unicorn/prefer-module\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using `String`, `Number`, `BigInt`, `Boolean`, and `Symbol` directly.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-native-coercion-functions.md\n   */\n  \"eslint-plugin-unicorn/prefer-native-coercion-functions\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer negative index over `.length - index` when possible.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-negative-index.md\n   */\n  \"eslint-plugin-unicorn/prefer-negative-index\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using the `node:` protocol when importing Node.js builtin modules.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-node-protocol.md\n   */\n  \"eslint-plugin-unicorn/prefer-node-protocol\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Number` static properties over global ones.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-number-properties.md\n   */\n  \"eslint-plugin-unicorn/prefer-number-properties\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkInfinity?: boolean;\n          checkNaN?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer using `Object.fromEntries(…)` to transform a list of key-value pairs into an object.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-object-from-entries.md\n   */\n  \"eslint-plugin-unicorn/prefer-object-from-entries\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          functions?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer omitting the `catch` binding parameter.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-optional-catch-binding.md\n   */\n  \"eslint-plugin-unicorn/prefer-optional-catch-binding\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer borrowing methods from the prototype instead of the instance.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-prototype-methods.md\n   */\n  \"eslint-plugin-unicorn/prefer-prototype-methods\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `.querySelector()` over `.getElementById()`, `.querySelectorAll()` over `.getElementsByClassName()` and `.getElementsByTagName()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-query-selector.md\n   */\n  \"eslint-plugin-unicorn/prefer-query-selector\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Reflect.apply()` over `Function#apply()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-reflect-apply.md\n   */\n  \"eslint-plugin-unicorn/prefer-reflect-apply\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `RegExp#test()` over `String#match()` and `RegExp#exec()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-regexp-test.md\n   */\n  \"eslint-plugin-unicorn/prefer-regexp-test\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `Set#has()` over `Array#includes()` when checking for existence or non-existence.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-set-has.md\n   */\n  \"eslint-plugin-unicorn/prefer-set-has\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using `Set#size` instead of `Array#length`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-set-size.md\n   */\n  \"eslint-plugin-unicorn/prefer-set-size\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer the spread operator over `Array.from(…)`, `Array#concat(…)`, `Array#{slice,toSpliced}()` and `String#split('')`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-spread.md\n   */\n  \"eslint-plugin-unicorn/prefer-spread\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using the `String.raw` tag to avoid escaping `\\`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-string-raw.md\n   */\n  \"eslint-plugin-unicorn/prefer-string-raw\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `String#replaceAll()` over regex searches with the global flag.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-string-replace-all.md\n   */\n  \"eslint-plugin-unicorn/prefer-string-replace-all\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `String#slice()` over `String#substr()` and `String#substring()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-string-slice.md\n   */\n  \"eslint-plugin-unicorn/prefer-string-slice\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `String#startsWith()` & `String#endsWith()` over `RegExp#test()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-string-starts-ends-with.md\n   */\n  \"eslint-plugin-unicorn/prefer-string-starts-ends-with\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer `String#trimStart()` / `String#trimEnd()` over `String#trimLeft()` / `String#trimRight()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-string-trim-start-end.md\n   */\n  \"eslint-plugin-unicorn/prefer-string-trim-start-end\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prefer using `structuredClone` to create a deep clone.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-structured-clone.md\n   */\n  \"eslint-plugin-unicorn/prefer-structured-clone\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          functions?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer `switch` over multiple `else-if`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-switch.md\n   */\n  \"eslint-plugin-unicorn/prefer-switch\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          minimumCases?: number;\n          emptyDefaultCase?:\n            | \"no-default-comment\"\n            | \"do-nothing-comment\"\n            | \"no-default-case\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer ternary expressions over simple `if-else` statements.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-ternary.md\n   */\n  \"eslint-plugin-unicorn/prefer-ternary\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Prefer top-level await over top-level promises and async function calls.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-top-level-await.md\n   */\n  \"eslint-plugin-unicorn/prefer-top-level-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce throwing `TypeError` in type checking conditions.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prefer-type-error.md\n   */\n  \"eslint-plugin-unicorn/prefer-type-error\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Prevent abbreviations.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/prevent-abbreviations.md\n   */\n  \"eslint-plugin-unicorn/prevent-abbreviations\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent relative URL style.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/relative-url-style.md\n   */\n  \"eslint-plugin-unicorn/relative-url-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce using the separator argument with `Array#join()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/require-array-join-separator.md\n   */\n  \"eslint-plugin-unicorn/require-array-join-separator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce using the digits argument with `Number#toFixed()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/require-number-to-fixed-digits-argument.md\n   */\n  \"eslint-plugin-unicorn/require-number-to-fixed-digits-argument\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce using the `targetOrigin` argument with `window.postMessage()`.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/require-post-message-target-origin.md\n   */\n  \"eslint-plugin-unicorn/require-post-message-target-origin\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce better string content.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/string-content.md\n   */\n  \"eslint-plugin-unicorn/string-content\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          patterns?: {\n            [k: string]:\n              | string\n              | {\n                  suggest: string;\n                  fix?: boolean;\n                  message?: string;\n                };\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent brace style for `case` clauses.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/switch-case-braces.md\n   */\n  \"eslint-plugin-unicorn/switch-case-braces\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Fix whitespace-insensitive template indentation.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/template-indent.md\n   */\n  \"eslint-plugin-unicorn/template-indent\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          indent?: string | number;\n          tags?: string[];\n          functions?: string[];\n          selectors?: string[];\n          comments?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent case for text encoding identifiers.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/text-encoding-identifier-case.md\n   */\n  \"eslint-plugin-unicorn/text-encoding-identifier-case\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require `new` when creating an error.\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/rules/throw-new-error.md\n   */\n  \"eslint-plugin-unicorn/throw-new-error\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#import-index\n   */\n  \"eslint-plugin-unicorn/import-index\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#no-array-instanceof\n   */\n  \"eslint-plugin-unicorn/no-array-instanceof\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#no-fn-reference-in-iterator\n   */\n  \"eslint-plugin-unicorn/no-fn-reference-in-iterator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#no-reduce\n   */\n  \"eslint-plugin-unicorn/no-reduce\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#no-unsafe-regex\n   */\n  \"eslint-plugin-unicorn/no-unsafe-regex\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-dataset\n   */\n  \"eslint-plugin-unicorn/prefer-dataset\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-event-key\n   */\n  \"eslint-plugin-unicorn/prefer-event-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-exponentiation-operator\n   */\n  \"eslint-plugin-unicorn/prefer-exponentiation-operator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-flat-map\n   */\n  \"eslint-plugin-unicorn/prefer-flat-map\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-node-append\n   */\n  \"eslint-plugin-unicorn/prefer-node-append\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-node-remove\n   */\n  \"eslint-plugin-unicorn/prefer-node-remove\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-object-has-own\n   */\n  \"eslint-plugin-unicorn/prefer-object-has-own\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-replace-all\n   */\n  \"eslint-plugin-unicorn/prefer-replace-all\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-starts-ends-with\n   */\n  \"eslint-plugin-unicorn/prefer-starts-ends-with\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-text-content\n   */\n  \"eslint-plugin-unicorn/prefer-text-content\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#prefer-trim-start-end\n   */\n  \"eslint-plugin-unicorn/prefer-trim-start-end\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * https://github.com/sindresorhus/eslint-plugin-unicorn/blob/v54.0.0/docs/deprecated-rules.md#regex-shorthand\n   */\n  \"eslint-plugin-unicorn/regex-shorthand\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce linebreaks after opening and before closing array brackets in `<template>`\n   * https://eslint.vuejs.org/rules/array-bracket-newline.html\n   */\n  \"eslint-plugin-vue/array-bracket-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing inside array brackets in `<template>`\n   * https://eslint.vuejs.org/rules/array-bracket-spacing.html\n   */\n  \"eslint-plugin-vue/array-bracket-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce line breaks after each array element in `<template>`\n   * https://eslint.vuejs.org/rules/array-element-newline.html\n   */\n  \"eslint-plugin-vue/array-element-newline\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing before and after the arrow in arrow functions in `<template>`\n   * https://eslint.vuejs.org/rules/arrow-spacing.html\n   */\n  \"eslint-plugin-vue/arrow-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce attribute naming style on custom components in template\n   * https://eslint.vuejs.org/rules/attribute-hyphenation.html\n   */\n  \"eslint-plugin-vue/attribute-hyphenation\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce order of attributes\n   * https://eslint.vuejs.org/rules/attributes-order.html\n   */\n  \"eslint-plugin-vue/attributes-order\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          order?: (\n            | (\n                | \"DEFINITION\"\n                | \"LIST_RENDERING\"\n                | \"CONDITIONALS\"\n                | \"RENDER_MODIFIERS\"\n                | \"GLOBAL\"\n                | \"UNIQUE\"\n                | \"SLOT\"\n                | \"TWO_WAY_BINDING\"\n                | \"OTHER_DIRECTIVES\"\n                | \"OTHER_ATTR\"\n                | \"ATTR_STATIC\"\n                | \"ATTR_DYNAMIC\"\n                | \"ATTR_SHORTHAND_BOOL\"\n                | \"EVENTS\"\n                | \"CONTENT\"\n              )\n            | (\n                | \"DEFINITION\"\n                | \"LIST_RENDERING\"\n                | \"CONDITIONALS\"\n                | \"RENDER_MODIFIERS\"\n                | \"GLOBAL\"\n                | \"UNIQUE\"\n                | \"SLOT\"\n                | \"TWO_WAY_BINDING\"\n                | \"OTHER_DIRECTIVES\"\n                | \"OTHER_ATTR\"\n                | \"ATTR_STATIC\"\n                | \"ATTR_DYNAMIC\"\n                | \"ATTR_SHORTHAND_BOOL\"\n                | \"EVENTS\"\n                | \"CONTENT\"\n              )[]\n          )[];\n          alphabetical?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow use other than available `lang`\n   * https://eslint.vuejs.org/rules/block-lang.html\n   */\n  \"eslint-plugin-vue/block-lang\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce order of component top-level elements\n   * https://eslint.vuejs.org/rules/block-order.html\n   */\n  \"eslint-plugin-vue/block-order\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          order?: (string | string[])[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow or enforce spaces inside of blocks after opening block and before closing block in `<template>`\n   * https://eslint.vuejs.org/rules/block-spacing.html\n   */\n  \"eslint-plugin-vue/block-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce line breaks after opening and before closing block-level tags\n   * https://eslint.vuejs.org/rules/block-tag-newline.html\n   */\n  \"eslint-plugin-vue/block-tag-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          singleline?: \"always\" | \"never\" | \"consistent\" | \"ignore\";\n          multiline?: \"always\" | \"never\" | \"consistent\" | \"ignore\";\n          maxEmptyLines?: number;\n          blocks?: {\n            /**\n             * This interface was referenced by `undefined`'s JSON-Schema definition\n             * via the `patternProperty` \"^(?:\\S+)$\".\n             */\n            [k: string]: {\n              singleline?: \"always\" | \"never\" | \"consistent\" | \"ignore\";\n              multiline?: \"always\" | \"never\" | \"consistent\" | \"ignore\";\n              maxEmptyLines?: number;\n            };\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent brace style for blocks in `<template>`\n   * https://eslint.vuejs.org/rules/brace-style.html\n   */\n  \"eslint-plugin-vue/brace-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce camelcase naming convention in `<template>`\n   * https://eslint.vuejs.org/rules/camelcase.html\n   */\n  \"eslint-plugin-vue/camelcase\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreDestructuring?: boolean;\n          ignoreImports?: boolean;\n          ignoreGlobals?: boolean;\n          properties?: \"always\" | \"never\";\n          /**\n           * @minItems 0\n           */\n          allow?: [] | [string];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow trailing commas in `<template>`\n   * https://eslint.vuejs.org/rules/comma-dangle.html\n   */\n  \"eslint-plugin-vue/comma-dangle\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing before and after commas in `<template>`\n   * https://eslint.vuejs.org/rules/comma-spacing.html\n   */\n  \"eslint-plugin-vue/comma-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent comma style in `<template>`\n   * https://eslint.vuejs.org/rules/comma-style.html\n   */\n  \"eslint-plugin-vue/comma-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * support comment-directives in `<template>`\n   * https://eslint.vuejs.org/rules/comment-directive.html\n   */\n  \"eslint-plugin-vue/comment-directive\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          reportUnusedDisableDirectives?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce component API style\n   * https://eslint.vuejs.org/rules/component-api-style.html\n   */\n  \"eslint-plugin-vue/component-api-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce specific casing for component definition name\n   * https://eslint.vuejs.org/rules/component-definition-name-casing.html\n   */\n  \"eslint-plugin-vue/component-definition-name-casing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce specific casing for the component naming style in template\n   * https://eslint.vuejs.org/rules/component-name-in-template-casing.html\n   */\n  \"eslint-plugin-vue/component-name-in-template-casing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce the casing of component name in `components` options\n   * https://eslint.vuejs.org/rules/component-options-name-casing.html\n   */\n  \"eslint-plugin-vue/component-options-name-casing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce order of component top-level elements\n   * https://eslint.vuejs.org/rules/component-tags-order.html\n   */\n  \"eslint-plugin-vue/component-tags-order\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          order?: (string | string[])[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce specific casing for custom event name\n   * https://eslint.vuejs.org/rules/custom-event-name-casing.html\n   */\n  \"eslint-plugin-vue/custom-event-name-casing\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce declaration style of `defineEmits`\n   * https://eslint.vuejs.org/rules/define-emits-declaration.html\n   */\n  \"eslint-plugin-vue/define-emits-declaration\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce order of `defineEmits` and `defineProps` compiler macros\n   * https://eslint.vuejs.org/rules/define-macros-order.html\n   */\n  \"eslint-plugin-vue/define-macros-order\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          order?: (\n            | \"defineEmits\"\n            | \"defineProps\"\n            | \"defineOptions\"\n            | \"defineSlots\"\n            | \"defineModel\"\n          )[];\n          defineExposeLast?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce declaration style of `defineProps`\n   * https://eslint.vuejs.org/rules/define-props-declaration.html\n   */\n  \"eslint-plugin-vue/define-props-declaration\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent newlines before and after dots in `<template>`\n   * https://eslint.vuejs.org/rules/dot-location.html\n   */\n  \"eslint-plugin-vue/dot-location\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce dot notation whenever possible in `<template>`\n   * https://eslint.vuejs.org/rules/dot-notation.html\n   */\n  \"eslint-plugin-vue/dot-notation\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowKeywords?: boolean;\n          allowPattern?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce or forbid the use of the `scoped` and `module` attributes in SFC top level style tags\n   * https://eslint.vuejs.org/rules/enforce-style-attribute.html\n   */\n  \"eslint-plugin-vue/enforce-style-attribute\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           */\n          allow?: [\n            \"plain\" | \"scoped\" | \"module\",\n            ...(\"plain\" | \"scoped\" | \"module\")[],\n          ];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require the use of `===` and `!==` in `<template>`\n   * https://eslint.vuejs.org/rules/eqeqeq.html\n   */\n  \"eslint-plugin-vue/eqeqeq\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce the location of first attribute\n   * https://eslint.vuejs.org/rules/first-attribute-linebreak.html\n   */\n  \"eslint-plugin-vue/first-attribute-linebreak\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          multiline?: \"below\" | \"beside\" | \"ignore\";\n          singleline?: \"below\" | \"beside\" | \"ignore\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow spacing between function identifiers and their invocations in `<template>`\n   * https://eslint.vuejs.org/rules/func-call-spacing.html\n   */\n  \"eslint-plugin-vue/func-call-spacing\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow usage of button without an explicit type attribute\n   * https://eslint.vuejs.org/rules/html-button-has-type.html\n   */\n  \"eslint-plugin-vue/html-button-has-type\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          button?: boolean;\n          submit?: boolean;\n          reset?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require or disallow a line break before tag's closing brackets\n   * https://eslint.vuejs.org/rules/html-closing-bracket-newline.html\n   */\n  \"eslint-plugin-vue/html-closing-bracket-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          singleline?: \"always\" | \"never\";\n          multiline?: \"always\" | \"never\";\n          selfClosingTag?: {\n            singleline?: \"always\" | \"never\";\n            multiline?: \"always\" | \"never\";\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require or disallow a space before tag's closing brackets\n   * https://eslint.vuejs.org/rules/html-closing-bracket-spacing.html\n   */\n  \"eslint-plugin-vue/html-closing-bracket-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          startTag?: \"always\" | \"never\";\n          endTag?: \"always\" | \"never\";\n          selfClosingTag?: \"always\" | \"never\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce unified line brake in HTML comments\n   * https://eslint.vuejs.org/rules/html-comment-content-newline.html\n   */\n  \"eslint-plugin-vue/html-comment-content-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce unified spacing in HTML comments\n   * https://eslint.vuejs.org/rules/html-comment-content-spacing.html\n   */\n  \"eslint-plugin-vue/html-comment-content-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce consistent indentation in HTML comments\n   * https://eslint.vuejs.org/rules/html-comment-indent.html\n   */\n  \"eslint-plugin-vue/html-comment-indent\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce end tag style\n   * https://eslint.vuejs.org/rules/html-end-tags.html\n   */\n  \"eslint-plugin-vue/html-end-tags\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce consistent indentation in `<template>`\n   * https://eslint.vuejs.org/rules/html-indent.html\n   */\n  \"eslint-plugin-vue/html-indent\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce quotes style of HTML attributes\n   * https://eslint.vuejs.org/rules/html-quotes.html\n   */\n  \"eslint-plugin-vue/html-quotes\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce self-closing style\n   * https://eslint.vuejs.org/rules/html-self-closing.html\n   */\n  \"eslint-plugin-vue/html-self-closing\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * prevent variables used in JSX to be marked as unused\n   * https://eslint.vuejs.org/rules/jsx-uses-vars.html\n   */\n  \"eslint-plugin-vue/jsx-uses-vars\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing between keys and values in object literal properties in `<template>`\n   * https://eslint.vuejs.org/rules/key-spacing.html\n   */\n  \"eslint-plugin-vue/key-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing before and after keywords in `<template>`\n   * https://eslint.vuejs.org/rules/keyword-spacing.html\n   */\n  \"eslint-plugin-vue/keyword-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          overrides?: {\n            abstract?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            as?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            async?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            await?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            boolean?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            break?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            byte?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            case?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            catch?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            char?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            class?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            const?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            continue?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            debugger?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            default?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            delete?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            do?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            double?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            else?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            enum?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            export?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            extends?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            false?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            final?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            finally?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            float?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            for?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            from?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            function?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            get?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            goto?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            if?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            implements?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            import?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            in?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            instanceof?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            int?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            interface?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            let?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            long?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            native?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            new?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            null?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            of?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            package?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            private?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            protected?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            public?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            return?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            set?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            short?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            static?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            super?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            switch?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            synchronized?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            this?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            throw?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            throws?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            transient?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            true?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            try?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            typeof?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            var?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            void?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            volatile?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            while?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            with?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            yield?: {\n              before?: boolean;\n              after?: boolean;\n            };\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require component name property to match its file name\n   * https://eslint.vuejs.org/rules/match-component-file-name.html\n   */\n  \"eslint-plugin-vue/match-component-file-name\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          extensions?: string[];\n          shouldMatchCase?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require the registered component name to match the imported component name\n   * https://eslint.vuejs.org/rules/match-component-import-name.html\n   */\n  \"eslint-plugin-vue/match-component-import-name\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce the maximum number of attributes per line\n   * https://eslint.vuejs.org/rules/max-attributes-per-line.html\n   */\n  \"eslint-plugin-vue/max-attributes-per-line\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          singleline?:\n            | number\n            | {\n                max?: number;\n              };\n          multiline?:\n            | number\n            | {\n                max?: number;\n              };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce a maximum line length in `.vue` files\n   * https://eslint.vuejs.org/rules/max-len.html\n   */\n  \"eslint-plugin-vue/max-len\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce maximum number of lines in Vue SFC blocks\n   * https://eslint.vuejs.org/rules/max-lines-per-block.html\n   */\n  \"eslint-plugin-vue/max-lines-per-block\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          style?: number;\n          template?: number;\n          script?: number;\n          skipBlankLines?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require component names to be always multi-word\n   * https://eslint.vuejs.org/rules/multi-word-component-names.html\n   */\n  \"eslint-plugin-vue/multi-word-component-names\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignores?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require a line break before and after the contents of a multiline element\n   * https://eslint.vuejs.org/rules/multiline-html-element-content-newline.html\n   */\n  \"eslint-plugin-vue/multiline-html-element-content-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreWhenEmpty?: boolean;\n          ignores?: string[];\n          allowEmptyLines?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce newlines between operands of ternary expressions in `<template>`\n   * https://eslint.vuejs.org/rules/multiline-ternary.html\n   */\n  \"eslint-plugin-vue/multiline-ternary\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce unified spacing in mustache interpolations\n   * https://eslint.vuejs.org/rules/mustache-interpolation-spacing.html\n   */\n  \"eslint-plugin-vue/mustache-interpolation-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce new lines between multi-line properties in Vue components\n   * https://eslint.vuejs.org/rules/new-line-between-multi-line-property.html\n   */\n  \"eslint-plugin-vue/new-line-between-multi-line-property\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          minLineOfMultilineProperty?: number;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce Promise or callback style in `nextTick`\n   * https://eslint.vuejs.org/rules/next-tick-style.html\n   */\n  \"eslint-plugin-vue/next-tick-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow using arrow functions to define watcher\n   * https://eslint.vuejs.org/rules/no-arrow-functions-in-watch.html\n   */\n  \"eslint-plugin-vue/no-arrow-functions-in-watch\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow asynchronous actions in computed properties\n   * https://eslint.vuejs.org/rules/no-async-in-computed-properties.html\n   */\n  \"eslint-plugin-vue/no-async-in-computed-properties\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow the use of bare strings in `<template>`\n   * https://eslint.vuejs.org/rules/no-bare-strings-in-template.html\n   */\n  \"eslint-plugin-vue/no-bare-strings-in-template\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowlist?: string[];\n          attributes?: {\n            /**\n             * This interface was referenced by `undefined`'s JSON-Schema definition\n             * via the `patternProperty` \"^(?:\\S+|/._\\/[a-z]_)$\".\n             */\n            [k: string]: string[];\n          };\n          directives?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow boolean defaults\n   * https://eslint.vuejs.org/rules/no-boolean-default.html\n   */\n  \"eslint-plugin-vue/no-boolean-default\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow element's child contents which would be overwritten by a directive like `v-html` or `v-text`\n   * https://eslint.vuejs.org/rules/no-child-content.html\n   */\n  \"eslint-plugin-vue/no-child-content\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           */\n          additionalDirectives?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow accessing computed properties in `data`.\n   * https://eslint.vuejs.org/rules/no-computed-properties-in-data.html\n   */\n  \"eslint-plugin-vue/no-computed-properties-in-data\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow the use of `console` in `<template>`\n   * https://eslint.vuejs.org/rules/no-console.html\n   */\n  \"eslint-plugin-vue/no-console\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           */\n          allow?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow constant expressions in conditions in `<template>`\n   * https://eslint.vuejs.org/rules/no-constant-condition.html\n   */\n  \"eslint-plugin-vue/no-constant-condition\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkLoops?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow custom modifiers on v-model used on the component\n   * https://eslint.vuejs.org/rules/no-custom-modifiers-on-v-model.html\n   */\n  \"eslint-plugin-vue/no-custom-modifiers-on-v-model\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated object declaration on data (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-data-object-declaration.html\n   */\n  \"eslint-plugin-vue/no-deprecated-data-object-declaration\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `destroyed` and `beforeDestroy` lifecycle hooks (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-destroyed-lifecycle.html\n   */\n  \"eslint-plugin-vue/no-deprecated-destroyed-lifecycle\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `$listeners` (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-dollar-listeners-api.html\n   */\n  \"eslint-plugin-vue/no-deprecated-dollar-listeners-api\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `$scopedSlots` (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-dollar-scopedslots-api.html\n   */\n  \"eslint-plugin-vue/no-deprecated-dollar-scopedslots-api\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated events api (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-events-api.html\n   */\n  \"eslint-plugin-vue/no-deprecated-events-api\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated filters syntax (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-filter.html\n   */\n  \"eslint-plugin-vue/no-deprecated-filter\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated the `functional` template (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-functional-template.html\n   */\n  \"eslint-plugin-vue/no-deprecated-functional-template\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated the `is` attribute on HTML elements (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-html-element-is.html\n   */\n  \"eslint-plugin-vue/no-deprecated-html-element-is\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `inline-template` attribute (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-inline-template.html\n   */\n  \"eslint-plugin-vue/no-deprecated-inline-template\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow deprecated `model` definition (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-model-definition.html\n   */\n  \"eslint-plugin-vue/no-deprecated-model-definition\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowVue3Compat?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow deprecated `this` access in props default function (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-props-default-this.html\n   */\n  \"eslint-plugin-vue/no-deprecated-props-default-this\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `tag` property on `RouterLink` (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-router-link-tag-prop.html\n   */\n  \"eslint-plugin-vue/no-deprecated-router-link-tag-prop\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 1\n           */\n          components?: [string, ...string[]];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow deprecated `scope` attribute (in Vue.js 2.5.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-scope-attribute.html\n   */\n  \"eslint-plugin-vue/no-deprecated-scope-attribute\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow deprecated `slot` attribute (in Vue.js 2.6.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-slot-attribute.html\n   */\n  \"eslint-plugin-vue/no-deprecated-slot-attribute\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignore?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow deprecated `slot-scope` attribute (in Vue.js 2.6.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-slot-scope-attribute.html\n   */\n  \"eslint-plugin-vue/no-deprecated-slot-scope-attribute\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow use of deprecated `.sync` modifier on `v-bind` directive (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-v-bind-sync.html\n   */\n  \"eslint-plugin-vue/no-deprecated-v-bind-sync\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow deprecated `v-is` directive (in Vue.js 3.1.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-v-is.html\n   */\n  \"eslint-plugin-vue/no-deprecated-v-is\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `.native` modifiers (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-v-on-native-modifier.html\n   */\n  \"eslint-plugin-vue/no-deprecated-v-on-native-modifier\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated number (keycode) modifiers (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-v-on-number-modifiers.html\n   */\n  \"eslint-plugin-vue/no-deprecated-v-on-number-modifiers\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using deprecated `Vue.config.keyCodes` (in Vue.js 3.0.0+)\n   * https://eslint.vuejs.org/rules/no-deprecated-vue-config-keycodes.html\n   */\n  \"eslint-plugin-vue/no-deprecated-vue-config-keycodes\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow duplication of field names\n   * https://eslint.vuejs.org/rules/no-dupe-keys.html\n   */\n  \"eslint-plugin-vue/no-dupe-keys\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          groups?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow duplicate conditions in `v-if` / `v-else-if` chains\n   * https://eslint.vuejs.org/rules/no-dupe-v-else-if.html\n   */\n  \"eslint-plugin-vue/no-dupe-v-else-if\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce `inheritAttrs` to be set to `false` when using `v-bind=\"$attrs\"`\n   * https://eslint.vuejs.org/rules/no-duplicate-attr-inheritance.html\n   */\n  \"eslint-plugin-vue/no-duplicate-attr-inheritance\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow duplication of attributes\n   * https://eslint.vuejs.org/rules/no-duplicate-attributes.html\n   */\n  \"eslint-plugin-vue/no-duplicate-attributes\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowCoexistClass?: boolean;\n          allowCoexistStyle?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow the `<template>` `<script>` `<style>` block to be empty\n   * https://eslint.vuejs.org/rules/no-empty-component-block.html\n   */\n  \"eslint-plugin-vue/no-empty-component-block\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow empty destructuring patterns in `<template>`\n   * https://eslint.vuejs.org/rules/no-empty-pattern.html\n   */\n  \"eslint-plugin-vue/no-empty-pattern\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowObjectPatternsAsParameters?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow `export` in `<script setup>`\n   * https://eslint.vuejs.org/rules/no-export-in-script-setup.html\n   */\n  \"eslint-plugin-vue/no-export-in-script-setup\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow asynchronously registered `expose`\n   * https://eslint.vuejs.org/rules/no-expose-after-await.html\n   */\n  \"eslint-plugin-vue/no-expose-after-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary parentheses in `<template>`\n   * https://eslint.vuejs.org/rules/no-extra-parens.html\n   */\n  \"eslint-plugin-vue/no-extra-parens\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require valid keys in model option\n   * https://eslint.vuejs.org/rules/no-invalid-model-keys.html\n   */\n  \"eslint-plugin-vue/no-invalid-model-keys\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow irregular whitespace in `.vue` files\n   * https://eslint.vuejs.org/rules/no-irregular-whitespace.html\n   */\n  \"eslint-plugin-vue/no-irregular-whitespace\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          skipComments?: boolean;\n          skipStrings?: boolean;\n          skipTemplates?: boolean;\n          skipRegExps?: boolean;\n          skipHTMLAttributeValues?: boolean;\n          skipHTMLTextContents?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow asynchronously registered lifecycle hooks\n   * https://eslint.vuejs.org/rules/no-lifecycle-after-await.html\n   */\n  \"eslint-plugin-vue/no-lifecycle-after-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow unnecessary `<template>`\n   * https://eslint.vuejs.org/rules/no-lone-template.html\n   */\n  \"eslint-plugin-vue/no-lone-template\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreAccessible?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow literal numbers that lose precision in `<template>`\n   * https://eslint.vuejs.org/rules/no-loss-of-precision.html\n   */\n  \"eslint-plugin-vue/no-loss-of-precision\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow multiple spaces\n   * https://eslint.vuejs.org/rules/no-multi-spaces.html\n   */\n  \"eslint-plugin-vue/no-multi-spaces\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreProperties?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow to pass multiple objects into array to class\n   * https://eslint.vuejs.org/rules/no-multiple-objects-in-class.html\n   */\n  \"eslint-plugin-vue/no-multiple-objects-in-class\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow to pass multiple arguments to scoped slots\n   * https://eslint.vuejs.org/rules/no-multiple-slot-args.html\n   */\n  \"eslint-plugin-vue/no-multiple-slot-args\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow adding multiple root nodes to the template\n   * https://eslint.vuejs.org/rules/no-multiple-template-root.html\n   */\n  \"eslint-plugin-vue/no-multiple-template-root\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow mutation of component props\n   * https://eslint.vuejs.org/rules/no-mutating-props.html\n   */\n  \"eslint-plugin-vue/no-mutating-props\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          shallowOnly?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow parsing errors in `<template>`\n   * https://eslint.vuejs.org/rules/no-parsing-error.html\n   */\n  \"eslint-plugin-vue/no-parsing-error\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          \"abrupt-closing-of-empty-comment\"?: boolean;\n          \"absence-of-digits-in-numeric-character-reference\"?: boolean;\n          \"cdata-in-html-content\"?: boolean;\n          \"character-reference-outside-unicode-range\"?: boolean;\n          \"control-character-in-input-stream\"?: boolean;\n          \"control-character-reference\"?: boolean;\n          \"eof-before-tag-name\"?: boolean;\n          \"eof-in-cdata\"?: boolean;\n          \"eof-in-comment\"?: boolean;\n          \"eof-in-tag\"?: boolean;\n          \"incorrectly-closed-comment\"?: boolean;\n          \"incorrectly-opened-comment\"?: boolean;\n          \"invalid-first-character-of-tag-name\"?: boolean;\n          \"missing-attribute-value\"?: boolean;\n          \"missing-end-tag-name\"?: boolean;\n          \"missing-semicolon-after-character-reference\"?: boolean;\n          \"missing-whitespace-between-attributes\"?: boolean;\n          \"nested-comment\"?: boolean;\n          \"noncharacter-character-reference\"?: boolean;\n          \"noncharacter-in-input-stream\"?: boolean;\n          \"null-character-reference\"?: boolean;\n          \"surrogate-character-reference\"?: boolean;\n          \"surrogate-in-input-stream\"?: boolean;\n          \"unexpected-character-in-attribute-name\"?: boolean;\n          \"unexpected-character-in-unquoted-attribute-value\"?: boolean;\n          \"unexpected-equals-sign-before-attribute-name\"?: boolean;\n          \"unexpected-null-character\"?: boolean;\n          \"unexpected-question-mark-instead-of-tag-name\"?: boolean;\n          \"unexpected-solidus-in-tag\"?: boolean;\n          \"unknown-named-character-reference\"?: boolean;\n          \"end-tag-with-attributes\"?: boolean;\n          \"duplicate-attribute\"?: boolean;\n          \"end-tag-with-trailing-solidus\"?: boolean;\n          \"non-void-html-element-start-tag-with-trailing-solidus\"?: boolean;\n          \"x-invalid-end-tag\"?: boolean;\n          \"x-invalid-namespace\"?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow a potential typo in your component property\n   * https://eslint.vuejs.org/rules/no-potential-component-option-typo.html\n   */\n  \"eslint-plugin-vue/no-potential-component-option-typo\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * @minItems 0\n           */\n          presets?: (\"all\" | \"vue\" | \"vue-router\" | \"nuxt\")[];\n          /**\n           * @minItems 0\n           */\n          custom?: string[];\n          threshold?: number;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow use of value wrapped by `ref()` (Composition API) as an operand\n   * https://eslint.vuejs.org/rules/no-ref-as-operand.html\n   */\n  \"eslint-plugin-vue/no-ref-as-operand\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow usages of ref objects that can lead to loss of reactivity\n   * https://eslint.vuejs.org/rules/no-ref-object-destructure.html\n   */\n  \"eslint-plugin-vue/no-ref-object-destructure\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow usages of ref objects that can lead to loss of reactivity\n   * https://eslint.vuejs.org/rules/no-ref-object-reactivity-loss.html\n   */\n  \"eslint-plugin-vue/no-ref-object-reactivity-loss\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce props with default values to be optional\n   * https://eslint.vuejs.org/rules/no-required-prop-with-default.html\n   */\n  \"eslint-plugin-vue/no-required-prop-with-default\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          autofix?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow the use of reserved names in component definitions\n   * https://eslint.vuejs.org/rules/no-reserved-component-names.html\n   */\n  \"eslint-plugin-vue/no-reserved-component-names\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          disallowVueBuiltInComponents?: boolean;\n          disallowVue3BuiltInComponents?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow overwriting reserved keys\n   * https://eslint.vuejs.org/rules/no-reserved-keys.html\n   */\n  \"eslint-plugin-vue/no-reserved-keys\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          reserved?: unknown[];\n          groups?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow reserved names in props\n   * https://eslint.vuejs.org/rules/no-reserved-props.html\n   */\n  \"eslint-plugin-vue/no-reserved-props\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          vueVersion?: 2 | 3;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow specific block\n   * https://eslint.vuejs.org/rules/no-restricted-block.html\n   */\n  \"eslint-plugin-vue/no-restricted-block\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow asynchronously called restricted methods\n   * https://eslint.vuejs.org/rules/no-restricted-call-after-await.html\n   */\n  \"eslint-plugin-vue/no-restricted-call-after-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific classes in Vue components\n   * https://eslint.vuejs.org/rules/no-restricted-class.html\n   */\n  \"eslint-plugin-vue/no-restricted-class\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific component names\n   * https://eslint.vuejs.org/rules/no-restricted-component-names.html\n   */\n  \"eslint-plugin-vue/no-restricted-component-names\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific component option\n   * https://eslint.vuejs.org/rules/no-restricted-component-options.html\n   */\n  \"eslint-plugin-vue/no-restricted-component-options\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific custom event\n   * https://eslint.vuejs.org/rules/no-restricted-custom-event.html\n   */\n  \"eslint-plugin-vue/no-restricted-custom-event\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific HTML elements\n   * https://eslint.vuejs.org/rules/no-restricted-html-elements.html\n   */\n  \"eslint-plugin-vue/no-restricted-html-elements\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific props\n   * https://eslint.vuejs.org/rules/no-restricted-props.html\n   */\n  \"eslint-plugin-vue/no-restricted-props\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific attribute\n   * https://eslint.vuejs.org/rules/no-restricted-static-attribute.html\n   */\n  \"eslint-plugin-vue/no-restricted-static-attribute\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow specified syntax in `<template>`\n   * https://eslint.vuejs.org/rules/no-restricted-syntax.html\n   */\n  \"eslint-plugin-vue/no-restricted-syntax\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific argument in `v-bind`\n   * https://eslint.vuejs.org/rules/no-restricted-v-bind.html\n   */\n  \"eslint-plugin-vue/no-restricted-v-bind\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow specific argument in `v-on`\n   * https://eslint.vuejs.org/rules/no-restricted-v-on.html\n   */\n  \"eslint-plugin-vue/no-restricted-v-on\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow `v-if` directives on root element\n   * https://eslint.vuejs.org/rules/no-root-v-if.html\n   */\n  \"eslint-plugin-vue/no-root-v-if\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow usages that lose the reactivity of `props` passed to `setup`\n   * https://eslint.vuejs.org/rules/no-setup-props-destructure.html\n   */\n  \"eslint-plugin-vue/no-setup-props-destructure\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow usages that lose the reactivity of `props` passed to `setup`\n   * https://eslint.vuejs.org/rules/no-setup-props-reactivity-loss.html\n   */\n  \"eslint-plugin-vue/no-setup-props-reactivity-loss\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce component's data property to be a function\n   * https://eslint.vuejs.org/rules/no-shared-component-data.html\n   */\n  \"eslint-plugin-vue/no-shared-component-data\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow side effects in computed properties\n   * https://eslint.vuejs.org/rules/no-side-effects-in-computed-properties.html\n   */\n  \"eslint-plugin-vue/no-side-effects-in-computed-properties\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow spaces around equal signs in attribute\n   * https://eslint.vuejs.org/rules/no-spaces-around-equal-signs-in-attribute.html\n   */\n  \"eslint-plugin-vue/no-spaces-around-equal-signs-in-attribute\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow sparse arrays in `<template>`\n   * https://eslint.vuejs.org/rules/no-sparse-arrays.html\n   */\n  \"eslint-plugin-vue/no-sparse-arrays\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow static inline `style` attributes\n   * https://eslint.vuejs.org/rules/no-static-inline-styles.html\n   */\n  \"eslint-plugin-vue/no-static-inline-styles\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowBinding?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow `key` attribute on `<template>`\n   * https://eslint.vuejs.org/rules/no-template-key.html\n   */\n  \"eslint-plugin-vue/no-template-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow variable declarations from shadowing variables declared in the outer scope\n   * https://eslint.vuejs.org/rules/no-template-shadow.html\n   */\n  \"eslint-plugin-vue/no-template-shadow\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow target=\"\\_blank\" attribute without rel=\"noopener noreferrer\"\n   * https://eslint.vuejs.org/rules/no-template-target-blank.html\n   */\n  \"eslint-plugin-vue/no-template-target-blank\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowReferrer?: boolean;\n          enforceDynamicLinks?: \"always\" | \"never\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow mustaches in `<textarea>`\n   * https://eslint.vuejs.org/rules/no-textarea-mustache.html\n   */\n  \"eslint-plugin-vue/no-textarea-mustache\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow `this` usage in a `beforeRouteEnter` method\n   * https://eslint.vuejs.org/rules/no-this-in-before-route-enter.html\n   */\n  \"eslint-plugin-vue/no-this-in-before-route-enter\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow use of undefined components in `<template>`\n   * https://eslint.vuejs.org/rules/no-undef-components.html\n   */\n  \"eslint-plugin-vue/no-undef-components\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignorePatterns?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow undefined properties\n   * https://eslint.vuejs.org/rules/no-undef-properties.html\n   */\n  \"eslint-plugin-vue/no-undef-properties\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignores?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow unsupported Vue.js syntax on the specified version\n   * https://eslint.vuejs.org/rules/no-unsupported-features.html\n   */\n  \"eslint-plugin-vue/no-unsupported-features\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          version?: string;\n          ignores?: (\n            | \"slot-scope-attribute\"\n            | \"dynamic-directive-arguments\"\n            | \"v-slot\"\n            | \"script-setup\"\n            | \"style-css-vars-injection\"\n            | \"v-model-argument\"\n            | \"v-model-custom-modifiers\"\n            | \"v-is\"\n            | \"is-attribute-with-vue-prefix\"\n            | \"v-memo\"\n            | \"v-bind-prop-modifier-shorthand\"\n            | \"v-bind-attr-modifier\"\n            | \"define-options\"\n            | \"define-slots\"\n            | \"define-model\"\n            | \"v-bind-same-name-shorthand\"\n          )[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow registering components that are not used inside templates\n   * https://eslint.vuejs.org/rules/no-unused-components.html\n   */\n  \"eslint-plugin-vue/no-unused-components\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreWhenBindingPresent?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow unused emit declarations\n   * https://eslint.vuejs.org/rules/no-unused-emit-declarations.html\n   */\n  \"eslint-plugin-vue/no-unused-emit-declarations\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow unused properties\n   * https://eslint.vuejs.org/rules/no-unused-properties.html\n   */\n  \"eslint-plugin-vue/no-unused-properties\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          groups?: (\n            | \"props\"\n            | \"data\"\n            | \"asyncData\"\n            | \"computed\"\n            | \"methods\"\n            | \"setup\"\n          )[];\n          deepData?: boolean;\n          ignorePublicMembers?: boolean;\n          unreferencedOptions?: (\n            | \"unknownMemberAsUnreferenced\"\n            | \"returnAsUnreferenced\"\n          )[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow unused refs\n   * https://eslint.vuejs.org/rules/no-unused-refs.html\n   */\n  \"eslint-plugin-vue/no-unused-refs\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow unused variable definitions of v-for directives or scope attributes\n   * https://eslint.vuejs.org/rules/no-unused-vars.html\n   */\n  \"eslint-plugin-vue/no-unused-vars\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignorePattern?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow use computed property like method\n   * https://eslint.vuejs.org/rules/no-use-computed-property-like-method.html\n   */\n  \"eslint-plugin-vue/no-use-computed-property-like-method\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using `v-else-if`/`v-else` on the same element as `v-for`\n   * https://eslint.vuejs.org/rules/no-use-v-else-with-v-for.html\n   */\n  \"eslint-plugin-vue/no-use-v-else-with-v-for\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow using `v-if` on the same element as `v-for`\n   * https://eslint.vuejs.org/rules/no-use-v-if-with-v-for.html\n   */\n  \"eslint-plugin-vue/no-use-v-if-with-v-for\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowUsingIterationVar?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unnecessary concatenation of literals or template literals in `<template>`\n   * https://eslint.vuejs.org/rules/no-useless-concat.html\n   */\n  \"eslint-plugin-vue/no-useless-concat\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow unnecessary mustache interpolations\n   * https://eslint.vuejs.org/rules/no-useless-mustaches.html\n   */\n  \"eslint-plugin-vue/no-useless-mustaches\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreIncludesComment?: boolean;\n          ignoreStringEscape?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow useless attribute on `<template>`\n   * https://eslint.vuejs.org/rules/no-useless-template-attributes.html\n   */\n  \"eslint-plugin-vue/no-useless-template-attributes\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow unnecessary `v-bind` directives\n   * https://eslint.vuejs.org/rules/no-useless-v-bind.html\n   */\n  \"eslint-plugin-vue/no-useless-v-bind\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreIncludesComment?: boolean;\n          ignoreStringEscape?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow key of `<template v-for>` placed on child elements\n   * https://eslint.vuejs.org/rules/no-v-for-template-key-on-child.html\n   */\n  \"eslint-plugin-vue/no-v-for-template-key-on-child\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow `key` attribute on `<template v-for>`\n   * https://eslint.vuejs.org/rules/no-v-for-template-key.html\n   */\n  \"eslint-plugin-vue/no-v-for-template-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow use of v-html to prevent XSS attack\n   * https://eslint.vuejs.org/rules/no-v-html.html\n   */\n  \"eslint-plugin-vue/no-v-html\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow adding an argument to `v-model` used in custom component\n   * https://eslint.vuejs.org/rules/no-v-model-argument.html\n   */\n  \"eslint-plugin-vue/no-v-model-argument\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow v-text / v-html on component\n   * https://eslint.vuejs.org/rules/no-v-text-v-html-on-component.html\n   */\n  \"eslint-plugin-vue/no-v-text-v-html-on-component\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow use of v-text\n   * https://eslint.vuejs.org/rules/no-v-text.html\n   */\n  \"eslint-plugin-vue/no-v-text\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * disallow asynchronously registered `watch`\n   * https://eslint.vuejs.org/rules/no-watch-after-await.html\n   */\n  \"eslint-plugin-vue/no-watch-after-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent line breaks after opening and before closing braces in `<template>`\n   * https://eslint.vuejs.org/rules/object-curly-newline.html\n   */\n  \"eslint-plugin-vue/object-curly-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing inside braces in `<template>`\n   * https://eslint.vuejs.org/rules/object-curly-spacing.html\n   */\n  \"eslint-plugin-vue/object-curly-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce placing object properties on separate lines in `<template>`\n   * https://eslint.vuejs.org/rules/object-property-newline.html\n   */\n  \"eslint-plugin-vue/object-property-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowAllPropertiesOnSameLine?: boolean;\n          allowMultiplePropertiesPerLine?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow method and property shorthand syntax for object literals in `<template>`\n   * https://eslint.vuejs.org/rules/object-shorthand.html\n   */\n  \"eslint-plugin-vue/object-shorthand\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce that each component should be in its own file\n   * https://eslint.vuejs.org/rules/one-component-per-file.html\n   */\n  \"eslint-plugin-vue/one-component-per-file\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent linebreak style for operators in `<template>`\n   * https://eslint.vuejs.org/rules/operator-linebreak.html\n   */\n  \"eslint-plugin-vue/operator-linebreak\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce order of properties in components\n   * https://eslint.vuejs.org/rules/order-in-components.html\n   */\n  \"eslint-plugin-vue/order-in-components\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          order?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require or disallow padding lines between blocks\n   * https://eslint.vuejs.org/rules/padding-line-between-blocks.html\n   */\n  \"eslint-plugin-vue/padding-line-between-blocks\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require or disallow newlines between sibling tags in template\n   * https://eslint.vuejs.org/rules/padding-line-between-tags.html\n   */\n  \"eslint-plugin-vue/padding-line-between-tags\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require or disallow padding lines in component definition\n   * https://eslint.vuejs.org/rules/padding-lines-in-component-definition.html\n   */\n  \"eslint-plugin-vue/padding-lines-in-component-definition\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce use of `defineOptions` instead of default export.\n   * https://eslint.vuejs.org/rules/prefer-define-options.html\n   */\n  \"eslint-plugin-vue/prefer-define-options\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce import from 'vue' instead of import from '@vue/\\*'\n   * https://eslint.vuejs.org/rules/prefer-import-from-vue.html\n   */\n  \"eslint-plugin-vue/prefer-import-from-vue\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce `Boolean` comes first in component prop types\n   * https://eslint.vuejs.org/rules/prefer-prop-type-boolean-first.html\n   */\n  \"eslint-plugin-vue/prefer-prop-type-boolean-first\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require static class names in template to be in a separate `class` attribute\n   * https://eslint.vuejs.org/rules/prefer-separate-static-class.html\n   */\n  \"eslint-plugin-vue/prefer-separate-static-class\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require template literals instead of string concatenation in `<template>`\n   * https://eslint.vuejs.org/rules/prefer-template.html\n   */\n  \"eslint-plugin-vue/prefer-template\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require shorthand form attribute when `v-bind` value is `true`\n   * https://eslint.vuejs.org/rules/prefer-true-attribute-shorthand.html\n   */\n  \"eslint-plugin-vue/prefer-true-attribute-shorthand\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce specific casing for the Prop name in Vue components\n   * https://eslint.vuejs.org/rules/prop-name-casing.html\n   */\n  \"eslint-plugin-vue/prop-name-casing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require quotes around object literal property names in `<template>`\n   * https://eslint.vuejs.org/rules/quote-props.html\n   */\n  \"eslint-plugin-vue/quote-props\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require `v-bind:is` of `<component>` elements\n   * https://eslint.vuejs.org/rules/require-component-is.html\n   */\n  \"eslint-plugin-vue/require-component-is\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require default value for props\n   * https://eslint.vuejs.org/rules/require-default-prop.html\n   */\n  \"eslint-plugin-vue/require-default-prop\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require the component to be directly exported\n   * https://eslint.vuejs.org/rules/require-direct-export.html\n   */\n  \"eslint-plugin-vue/require-direct-export\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          disallowFunctionalComponentFunction?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require type definitions in emits\n   * https://eslint.vuejs.org/rules/require-emit-validator.html\n   */\n  \"eslint-plugin-vue/require-emit-validator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require `emits` option with name triggered by `$emit()`\n   * https://eslint.vuejs.org/rules/require-explicit-emits.html\n   */\n  \"eslint-plugin-vue/require-explicit-emits\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowProps?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require slots to be explicitly defined\n   * https://eslint.vuejs.org/rules/require-explicit-slots.html\n   */\n  \"eslint-plugin-vue/require-explicit-slots\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require declare public properties using `expose`\n   * https://eslint.vuejs.org/rules/require-expose.html\n   */\n  \"eslint-plugin-vue/require-expose\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require a certain macro variable name\n   * https://eslint.vuejs.org/rules/require-macro-variable-name.html\n   */\n  \"eslint-plugin-vue/require-macro-variable-name\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          defineProps?: string;\n          defineEmits?: string;\n          defineSlots?: string;\n          useSlots?: string;\n          useAttrs?: string;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require a name property in Vue components\n   * https://eslint.vuejs.org/rules/require-name-property.html\n   */\n  \"eslint-plugin-vue/require-name-property\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require props to have a comment\n   * https://eslint.vuejs.org/rules/require-prop-comment.html\n   */\n  \"eslint-plugin-vue/require-prop-comment\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          type?: \"JSDoc\" | \"line\" | \"block\" | \"any\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require prop type to be a constructor\n   * https://eslint.vuejs.org/rules/require-prop-type-constructor.html\n   */\n  \"eslint-plugin-vue/require-prop-type-constructor\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require type definitions in props\n   * https://eslint.vuejs.org/rules/require-prop-types.html\n   */\n  \"eslint-plugin-vue/require-prop-types\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce render function to always return value\n   * https://eslint.vuejs.org/rules/require-render-return.html\n   */\n  \"eslint-plugin-vue/require-render-return\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce properties of `$slots` to be used as a function\n   * https://eslint.vuejs.org/rules/require-slots-as-functions.html\n   */\n  \"eslint-plugin-vue/require-slots-as-functions\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require control the display of the content inside `<transition>`\n   * https://eslint.vuejs.org/rules/require-toggle-inside-transition.html\n   */\n  \"eslint-plugin-vue/require-toggle-inside-transition\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce adding type declarations to object props\n   * https://eslint.vuejs.org/rules/require-typed-object-prop.html\n   */\n  \"eslint-plugin-vue/require-typed-object-prop\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require `ref` and `shallowRef` functions to be strongly typed\n   * https://eslint.vuejs.org/rules/require-typed-ref.html\n   */\n  \"eslint-plugin-vue/require-typed-ref\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require `v-bind:key` with `v-for` directives\n   * https://eslint.vuejs.org/rules/require-v-for-key.html\n   */\n  \"eslint-plugin-vue/require-v-for-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce props default values to be valid\n   * https://eslint.vuejs.org/rules/require-valid-default-prop.html\n   */\n  \"eslint-plugin-vue/require-valid-default-prop\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce that a return statement is present in computed property\n   * https://eslint.vuejs.org/rules/return-in-computed-property.html\n   */\n  \"eslint-plugin-vue/return-in-computed-property\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          treatUndefinedAsUnspecified?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce that a return statement is present in emits validator\n   * https://eslint.vuejs.org/rules/return-in-emits-validator.html\n   */\n  \"eslint-plugin-vue/return-in-emits-validator\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce consistent indentation in `<script>`\n   * https://eslint.vuejs.org/rules/script-indent.html\n   */\n  \"eslint-plugin-vue/script-indent\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * prevent `<script setup>` variables used in `<template>` to be marked as unused\n   * https://eslint.vuejs.org/rules/script-setup-uses-vars.html\n   */\n  \"eslint-plugin-vue/script-setup-uses-vars\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require a line break before and after the contents of a singleline element\n   * https://eslint.vuejs.org/rules/singleline-html-element-content-newline.html\n   */\n  \"eslint-plugin-vue/singleline-html-element-content-newline\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreWhenNoAttributes?: boolean;\n          ignoreWhenEmpty?: boolean;\n          ignores?: string[];\n          externalIgnores?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce sort-keys in a manner that is compatible with order-in-components\n   * https://eslint.vuejs.org/rules/sort-keys.html\n   */\n  \"eslint-plugin-vue/sort-keys\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing inside parentheses in `<template>`\n   * https://eslint.vuejs.org/rules/space-in-parens.html\n   */\n  \"eslint-plugin-vue/space-in-parens\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require spacing around infix operators in `<template>`\n   * https://eslint.vuejs.org/rules/space-infix-ops.html\n   */\n  \"eslint-plugin-vue/space-infix-ops\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          int32Hint?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing before or after unary operators in `<template>`\n   * https://eslint.vuejs.org/rules/space-unary-ops.html\n   */\n  \"eslint-plugin-vue/space-unary-ops\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          words?: boolean;\n          nonwords?: boolean;\n          overrides?: {\n            [k: string]: boolean;\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce static class names order\n   * https://eslint.vuejs.org/rules/static-class-names-order.html\n   */\n  \"eslint-plugin-vue/static-class-names-order\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require or disallow spacing around embedded expressions of template strings in `<template>`\n   * https://eslint.vuejs.org/rules/template-curly-spacing.html\n   */\n  \"eslint-plugin-vue/template-curly-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * disallow usage of `this` in template\n   * https://eslint.vuejs.org/rules/this-in-template.html\n   */\n  \"eslint-plugin-vue/this-in-template\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce usage of `exact` modifier on `v-on`\n   * https://eslint.vuejs.org/rules/use-v-on-exact.html\n   */\n  \"eslint-plugin-vue/use-v-on-exact\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce `v-bind` directive style\n   * https://eslint.vuejs.org/rules/v-bind-style.html\n   */\n  \"eslint-plugin-vue/v-bind-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce `v-for` directive's delimiter style\n   * https://eslint.vuejs.org/rules/v-for-delimiter-style.html\n   */\n  \"eslint-plugin-vue/v-for-delimiter-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require key attribute for conditionally rendered repeated components\n   * https://eslint.vuejs.org/rules/v-if-else-key.html\n   */\n  \"eslint-plugin-vue/v-if-else-key\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce v-on event naming style on custom components in template\n   * https://eslint.vuejs.org/rules/v-on-event-hyphenation.html\n   */\n  \"eslint-plugin-vue/v-on-event-hyphenation\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce or forbid parentheses after method calls without arguments in `v-on` directives\n   * https://eslint.vuejs.org/rules/v-on-function-call.html\n   */\n  \"eslint-plugin-vue/v-on-function-call\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce writing style for handlers in `v-on` directives\n   * https://eslint.vuejs.org/rules/v-on-handler-style.html\n   */\n  \"eslint-plugin-vue/v-on-handler-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce `v-on` directive style\n   * https://eslint.vuejs.org/rules/v-on-style.html\n   */\n  \"eslint-plugin-vue/v-on-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce `v-slot` directive style\n   * https://eslint.vuejs.org/rules/v-slot-style.html\n   */\n  \"eslint-plugin-vue/v-slot-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * require valid attribute names\n   * https://eslint.vuejs.org/rules/valid-attribute-name.html\n   */\n  \"eslint-plugin-vue/valid-attribute-name\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `defineEmits` compiler macro\n   * https://eslint.vuejs.org/rules/valid-define-emits.html\n   */\n  \"eslint-plugin-vue/valid-define-emits\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `defineOptions` compiler macro\n   * https://eslint.vuejs.org/rules/valid-define-options.html\n   */\n  \"eslint-plugin-vue/valid-define-options\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `defineProps` compiler macro\n   * https://eslint.vuejs.org/rules/valid-define-props.html\n   */\n  \"eslint-plugin-vue/valid-define-props\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * require valid keys in model option\n   * https://eslint.vuejs.org/rules/valid-model-definition.html\n   */\n  \"eslint-plugin-vue/valid-model-definition\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `nextTick` function calls\n   * https://eslint.vuejs.org/rules/valid-next-tick.html\n   */\n  \"eslint-plugin-vue/valid-next-tick\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid template root\n   * https://eslint.vuejs.org/rules/valid-template-root.html\n   */\n  \"eslint-plugin-vue/valid-template-root\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `.sync` modifier on `v-bind` directives\n   * https://eslint.vuejs.org/rules/valid-v-bind-sync.html\n   */\n  \"eslint-plugin-vue/valid-v-bind-sync\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-bind` directives\n   * https://eslint.vuejs.org/rules/valid-v-bind.html\n   */\n  \"eslint-plugin-vue/valid-v-bind\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-cloak` directives\n   * https://eslint.vuejs.org/rules/valid-v-cloak.html\n   */\n  \"eslint-plugin-vue/valid-v-cloak\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-else-if` directives\n   * https://eslint.vuejs.org/rules/valid-v-else-if.html\n   */\n  \"eslint-plugin-vue/valid-v-else-if\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-else` directives\n   * https://eslint.vuejs.org/rules/valid-v-else.html\n   */\n  \"eslint-plugin-vue/valid-v-else\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-for` directives\n   * https://eslint.vuejs.org/rules/valid-v-for.html\n   */\n  \"eslint-plugin-vue/valid-v-for\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-html` directives\n   * https://eslint.vuejs.org/rules/valid-v-html.html\n   */\n  \"eslint-plugin-vue/valid-v-html\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-if` directives\n   * https://eslint.vuejs.org/rules/valid-v-if.html\n   */\n  \"eslint-plugin-vue/valid-v-if\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-is` directives\n   * https://eslint.vuejs.org/rules/valid-v-is.html\n   */\n  \"eslint-plugin-vue/valid-v-is\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-memo` directives\n   * https://eslint.vuejs.org/rules/valid-v-memo.html\n   */\n  \"eslint-plugin-vue/valid-v-memo\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-model` directives\n   * https://eslint.vuejs.org/rules/valid-v-model.html\n   */\n  \"eslint-plugin-vue/valid-v-model\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-on` directives\n   * https://eslint.vuejs.org/rules/valid-v-on.html\n   */\n  \"eslint-plugin-vue/valid-v-on\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          modifiers?: unknown[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce valid `v-once` directives\n   * https://eslint.vuejs.org/rules/valid-v-once.html\n   */\n  \"eslint-plugin-vue/valid-v-once\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-pre` directives\n   * https://eslint.vuejs.org/rules/valid-v-pre.html\n   */\n  \"eslint-plugin-vue/valid-v-pre\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-show` directives\n   * https://eslint.vuejs.org/rules/valid-v-show.html\n   */\n  \"eslint-plugin-vue/valid-v-show\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * enforce valid `v-slot` directives\n   * https://eslint.vuejs.org/rules/valid-v-slot.html\n   */\n  \"eslint-plugin-vue/valid-v-slot\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowModifiers?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * enforce valid `v-text` directives\n   * https://eslint.vuejs.org/rules/valid-v-text.html\n   */\n  \"eslint-plugin-vue/valid-v-text\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require that function overload signatures be consecutive\n   * https://typescript-eslint.io/rules/adjacent-overload-signatures\n   */\n  \"@typescript-eslint/adjacent-overload-signatures\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require consistently using either `T[]` or `Array<T>` for arrays\n   * https://typescript-eslint.io/rules/array-type\n   */\n  \"@typescript-eslint/array-type\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * The array type expected for mutable cases.\n           */\n          default?: {\n            [k: string]: unknown;\n          };\n          /**\n           * The array type expected for readonly cases. If omitted, the value for `default` will be used.\n           */\n          readonly?: {\n            [k: string]: unknown;\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow awaiting a value that is not a Thenable\n   * https://typescript-eslint.io/rules/await-thenable\n   */\n  \"@typescript-eslint/await-thenable\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow `@ts-<directive>` comments or require descriptions after directives\n   * https://typescript-eslint.io/rules/ban-ts-comment\n   */\n  \"@typescript-eslint/ban-ts-comment\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          \"ts-expect-error\"?: unknown;\n          \"ts-ignore\"?: unknown;\n          \"ts-nocheck\"?: unknown;\n          \"ts-check\"?: unknown;\n          minimumDescriptionLength?: number;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow `// tslint:<rule-flag>` comments\n   * https://typescript-eslint.io/rules/ban-tslint-comment\n   */\n  \"@typescript-eslint/ban-tslint-comment\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow certain types\n   * https://typescript-eslint.io/rules/ban-types\n   */\n  \"@typescript-eslint/ban-types\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          types?: {\n            [k: string]: unknown;\n          };\n          extendDefaults?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow or enforce spaces inside of blocks after opening block and before closing block\n   * https://typescript-eslint.io/rules/block-spacing\n   */\n  \"@typescript-eslint/block-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent brace style for blocks\n   * https://typescript-eslint.io/rules/brace-style\n   */\n  \"@typescript-eslint/brace-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce that literals on classes are exposed in a consistent style\n   * https://typescript-eslint.io/rules/class-literal-property-style\n   */\n  \"@typescript-eslint/class-literal-property-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce that class methods utilize `this`\n   * https://typescript-eslint.io/rules/class-methods-use-this\n   */\n  \"@typescript-eslint/class-methods-use-this\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Allows specified method names to be ignored with this rule\n           */\n          exceptMethods?: string[];\n          /**\n           * Enforces that functions used as instance field initializers utilize `this`\n           */\n          enforceForClassFields?: boolean;\n          /**\n           * Ignore members marked with the `override` modifier\n           */\n          ignoreOverrideMethods?: boolean;\n          /**\n           * Ignore classes that specifically implement some interface\n           */\n          ignoreClassesThatImplementAnInterface?: boolean | \"public-fields\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow trailing commas\n   * https://typescript-eslint.io/rules/comma-dangle\n   */\n  \"@typescript-eslint/comma-dangle\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing before and after commas\n   * https://typescript-eslint.io/rules/comma-spacing\n   */\n  \"@typescript-eslint/comma-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce specifying generic type arguments on type annotation or constructor name of a constructor call\n   * https://typescript-eslint.io/rules/consistent-generic-constructors\n   */\n  \"@typescript-eslint/consistent-generic-constructors\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow the `Record` type\n   * https://typescript-eslint.io/rules/consistent-indexed-object-style\n   */\n  \"@typescript-eslint/consistent-indexed-object-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [number | (\"off\" | \"warn\" | \"error\"), \"record\" | \"index-signature\"];\n  /**\n   * Require `return` statements to either always or never specify values\n   * https://typescript-eslint.io/rules/consistent-return\n   */\n  \"@typescript-eslint/consistent-return\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          treatUndefinedAsUnspecified?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent usage of type assertions\n   * https://typescript-eslint.io/rules/consistent-type-assertions\n   */\n  \"@typescript-eslint/consistent-type-assertions\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce type definitions to consistently use either `interface` or `type`\n   * https://typescript-eslint.io/rules/consistent-type-definitions\n   */\n  \"@typescript-eslint/consistent-type-definitions\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [number | (\"off\" | \"warn\" | \"error\"), \"interface\" | \"type\"];\n  /**\n   * Enforce consistent usage of type exports\n   * https://typescript-eslint.io/rules/consistent-type-exports\n   */\n  \"@typescript-eslint/consistent-type-exports\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          fixMixedExportsWithInlineTypeSpecifier?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent usage of type imports\n   * https://typescript-eslint.io/rules/consistent-type-imports\n   */\n  \"@typescript-eslint/consistent-type-imports\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          disallowTypeAnnotations?: boolean;\n          fixStyle?: \"separate-type-imports\" | \"inline-type-imports\";\n          prefer?: \"type-imports\" | \"no-type-imports\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce default parameters to be last\n   * https://typescript-eslint.io/rules/default-param-last\n   */\n  \"@typescript-eslint/default-param-last\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce dot notation whenever possible\n   * https://typescript-eslint.io/rules/dot-notation\n   */\n  \"@typescript-eslint/dot-notation\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowKeywords?: boolean;\n          allowPattern?: string;\n          allowPrivateClassPropertyAccess?: boolean;\n          allowProtectedClassPropertyAccess?: boolean;\n          allowIndexSignaturePropertyAccess?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require explicit return types on functions and class methods\n   * https://typescript-eslint.io/rules/explicit-function-return-type\n   */\n  \"@typescript-eslint/explicit-function-return-type\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow arrow functions that start with the `void` keyword.\n           */\n          allowConciseArrowFunctionExpressionsStartingWithVoid?: boolean;\n          /**\n           * Whether to ignore function expressions (functions which are not part of a declaration).\n           */\n          allowExpressions?: boolean;\n          /**\n           * Whether to ignore functions immediately returning another function expression.\n           */\n          allowHigherOrderFunctions?: boolean;\n          /**\n           * Whether to ignore type annotations on the variable of function expressions.\n           */\n          allowTypedFunctionExpressions?: boolean;\n          /**\n           * Whether to ignore arrow functions immediately returning a `as const` value.\n           */\n          allowDirectConstAssertionInArrowFunctions?: boolean;\n          /**\n           * Whether to ignore functions that don't have generic type parameters.\n           */\n          allowFunctionsWithoutTypeParameters?: boolean;\n          /**\n           * An array of function/method names that will not have their arguments or return values checked.\n           */\n          allowedNames?: string[];\n          /**\n           * Whether to ignore immediately invoked function expressions (IIFEs).\n           */\n          allowIIFEs?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require explicit accessibility modifiers on class properties and methods\n   * https://typescript-eslint.io/rules/explicit-member-accessibility\n   */\n  \"@typescript-eslint/explicit-member-accessibility\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          accessibility?: unknown;\n          overrides?: {\n            accessors?: unknown;\n            constructors?: unknown;\n            methods?: unknown;\n            properties?: unknown;\n            parameterProperties?: unknown;\n          };\n          ignoredMethodNames?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require explicit return and argument types on exported functions' and classes' public class methods\n   * https://typescript-eslint.io/rules/explicit-module-boundary-types\n   */\n  \"@typescript-eslint/explicit-module-boundary-types\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to ignore arguments that are explicitly typed as `any`.\n           */\n          allowArgumentsExplicitlyTypedAsAny?: boolean;\n          /**\n           * Whether to ignore return type annotations on body-less arrow functions that return an `as const` type assertion.\n           * You must still type the parameters of the function.\n           */\n          allowDirectConstAssertionInArrowFunctions?: boolean;\n          /**\n           * An array of function/method names that will not have their arguments or return values checked.\n           */\n          allowedNames?: string[];\n          /**\n           * Whether to ignore return type annotations on functions immediately returning another function expression.\n           * You must still type the parameters of the function.\n           */\n          allowHigherOrderFunctions?: boolean;\n          /**\n           * Whether to ignore type annotations on the variable of a function expression.\n           */\n          allowTypedFunctionExpressions?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow spacing between function identifiers and their invocations\n   * https://typescript-eslint.io/rules/func-call-spacing\n   */\n  \"@typescript-eslint/func-call-spacing\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent indentation\n   * https://typescript-eslint.io/rules/indent\n   */\n  \"@typescript-eslint/indent\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow initialization in variable declarations\n   * https://typescript-eslint.io/rules/init-declarations\n   */\n  \"@typescript-eslint/init-declarations\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing between property names and type annotations in types and interfaces\n   * https://typescript-eslint.io/rules/key-spacing\n   */\n  \"@typescript-eslint/key-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing before and after keywords\n   * https://typescript-eslint.io/rules/keyword-spacing\n   */\n  \"@typescript-eslint/keyword-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          overrides?: {\n            abstract?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            as?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            async?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            await?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            boolean?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            break?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            byte?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            case?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            catch?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            char?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            class?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            const?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            continue?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            debugger?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            default?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            delete?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            do?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            double?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            else?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            enum?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            export?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            extends?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            false?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            final?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            finally?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            float?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            for?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            from?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            function?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            get?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            goto?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            if?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            implements?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            import?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            in?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            instanceof?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            int?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            interface?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            let?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            long?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            native?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            new?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            null?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            of?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            package?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            private?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            protected?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            public?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            return?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            set?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            short?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            static?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            super?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            switch?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            synchronized?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            this?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            throw?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            throws?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            transient?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            true?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            try?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            typeof?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            var?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            void?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            volatile?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            while?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            with?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            yield?: {\n              before?: boolean;\n              after?: boolean;\n            };\n            type?: {\n              before?: boolean;\n              after?: boolean;\n            };\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require empty lines around comments\n   * https://typescript-eslint.io/rules/lines-around-comment\n   */\n  \"@typescript-eslint/lines-around-comment\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          beforeBlockComment?: boolean;\n          afterBlockComment?: boolean;\n          beforeLineComment?: boolean;\n          afterLineComment?: boolean;\n          allowBlockStart?: boolean;\n          allowBlockEnd?: boolean;\n          allowClassStart?: boolean;\n          allowClassEnd?: boolean;\n          allowObjectStart?: boolean;\n          allowObjectEnd?: boolean;\n          allowArrayStart?: boolean;\n          allowArrayEnd?: boolean;\n          allowInterfaceStart?: boolean;\n          allowInterfaceEnd?: boolean;\n          allowTypeStart?: boolean;\n          allowTypeEnd?: boolean;\n          allowEnumStart?: boolean;\n          allowEnumEnd?: boolean;\n          allowModuleStart?: boolean;\n          allowModuleEnd?: boolean;\n          ignorePattern?: string;\n          applyDefaultIgnorePatterns?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow an empty line between class members\n   * https://typescript-eslint.io/rules/lines-between-class-members\n   */\n  \"@typescript-eslint/lines-between-class-members\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce a maximum number of parameters in function definitions\n   * https://typescript-eslint.io/rules/max-params\n   */\n  \"@typescript-eslint/max-params\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          maximum?: number;\n          max?: number;\n          countVoidThis?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require a specific member delimiter style for interfaces and type literals\n   * https://typescript-eslint.io/rules/member-delimiter-style\n   */\n  \"@typescript-eslint/member-delimiter-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          multiline?: {\n            delimiter?: unknown;\n            requireLast?: boolean;\n          };\n          singleline?: {\n            delimiter?: unknown;\n            requireLast?: boolean;\n          };\n          overrides?: {\n            interface?: unknown;\n            typeLiteral?: unknown;\n          };\n          multilineDetection?: \"brackets\" | \"last-member\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require a consistent member declaration order\n   * https://typescript-eslint.io/rules/member-ordering\n   */\n  \"@typescript-eslint/member-ordering\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          default?: unknown;\n          classes?: unknown;\n          classExpressions?: unknown;\n          interfaces?: unknown;\n          typeLiterals?: unknown;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce using a particular method signature syntax\n   * https://typescript-eslint.io/rules/method-signature-style\n   */\n  \"@typescript-eslint/method-signature-style\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce naming conventions for everything across a codebase\n   * https://typescript-eslint.io/rules/naming-convention\n   */\n  \"@typescript-eslint/naming-convention\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow generic `Array` constructors\n   * https://typescript-eslint.io/rules/no-array-constructor\n   */\n  \"@typescript-eslint/no-array-constructor\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow using the `delete` operator on array values\n   * https://typescript-eslint.io/rules/no-array-delete\n   */\n  \"@typescript-eslint/no-array-delete\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require `.toString()` to only be called on objects which provide useful information when stringified\n   * https://typescript-eslint.io/rules/no-base-to-string\n   */\n  \"@typescript-eslint/no-base-to-string\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoredTypeNames?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow non-null assertion in locations that may be confusing\n   * https://typescript-eslint.io/rules/no-confusing-non-null-assertion\n   */\n  \"@typescript-eslint/no-confusing-non-null-assertion\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require expressions of type void to appear in statement position\n   * https://typescript-eslint.io/rules/no-confusing-void-expression\n   */\n  \"@typescript-eslint/no-confusing-void-expression\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreArrowShorthand?: boolean;\n          ignoreVoidOperator?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow duplicate class members\n   * https://typescript-eslint.io/rules/no-dupe-class-members\n   */\n  \"@typescript-eslint/no-dupe-class-members\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow duplicate enum member values\n   * https://typescript-eslint.io/rules/no-duplicate-enum-values\n   */\n  \"@typescript-eslint/no-duplicate-enum-values\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow duplicate constituents of union or intersection types\n   * https://typescript-eslint.io/rules/no-duplicate-type-constituents\n   */\n  \"@typescript-eslint/no-duplicate-type-constituents\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreIntersections?: boolean;\n          ignoreUnions?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow using the `delete` operator on computed key expressions\n   * https://typescript-eslint.io/rules/no-dynamic-delete\n   */\n  \"@typescript-eslint/no-dynamic-delete\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow empty functions\n   * https://typescript-eslint.io/rules/no-empty-function\n   */\n  \"@typescript-eslint/no-empty-function\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: (\n            | \"functions\"\n            | \"arrowFunctions\"\n            | \"generatorFunctions\"\n            | \"methods\"\n            | \"generatorMethods\"\n            | \"getters\"\n            | \"setters\"\n            | \"constructors\"\n            | \"private-constructors\"\n            | \"protected-constructors\"\n            | \"asyncFunctions\"\n            | \"asyncMethods\"\n            | \"decoratedFunctions\"\n            | \"overrideMethods\"\n          )[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow the declaration of empty interfaces\n   * https://typescript-eslint.io/rules/no-empty-interface\n   */\n  \"@typescript-eslint/no-empty-interface\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowSingleExtends?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow the `any` type\n   * https://typescript-eslint.io/rules/no-explicit-any\n   */\n  \"@typescript-eslint/no-explicit-any\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to enable auto-fixing in which the `any` type is converted to the `unknown` type.\n           */\n          fixToUnknown?: boolean;\n          /**\n           * Whether to ignore rest parameter arrays.\n           */\n          ignoreRestArgs?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow extra non-null assertions\n   * https://typescript-eslint.io/rules/no-extra-non-null-assertion\n   */\n  \"@typescript-eslint/no-extra-non-null-assertion\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary parentheses\n   * https://typescript-eslint.io/rules/no-extra-parens\n   */\n  \"@typescript-eslint/no-extra-parens\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary semicolons\n   * https://typescript-eslint.io/rules/no-extra-semi\n   */\n  \"@typescript-eslint/no-extra-semi\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow classes used as namespaces\n   * https://typescript-eslint.io/rules/no-extraneous-class\n   */\n  \"@typescript-eslint/no-extraneous-class\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow extraneous classes that contain only a constructor.\n           */\n          allowConstructorOnly?: boolean;\n          /**\n           * Whether to allow extraneous classes that have no body (i.e. are empty).\n           */\n          allowEmpty?: boolean;\n          /**\n           * Whether to allow extraneous classes that only contain static members.\n           */\n          allowStaticOnly?: boolean;\n          /**\n           * Whether to allow extraneous classes that include a decorator.\n           */\n          allowWithDecorator?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require Promise-like statements to be handled appropriately\n   * https://typescript-eslint.io/rules/no-floating-promises\n   */\n  \"@typescript-eslint/no-floating-promises\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to ignore `void` expressions.\n           */\n          ignoreVoid?: boolean;\n          /**\n           * Whether to ignore async IIFEs (Immediately Invoked Function Expressions).\n           */\n          ignoreIIFE?: boolean;\n          allowForKnownSafePromises?: (\n            | string\n            | {\n                from: \"file\";\n                name: string | [string, ...string[]];\n                path?: string;\n              }\n            | {\n                from: \"lib\";\n                name: string | [string, ...string[]];\n              }\n            | {\n                from: \"package\";\n                name: string | [string, ...string[]];\n                package: string;\n              }\n          )[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow iterating over an array with a for-in loop\n   * https://typescript-eslint.io/rules/no-for-in-array\n   */\n  \"@typescript-eslint/no-for-in-array\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow the use of `eval()`-like methods\n   * https://typescript-eslint.io/rules/no-implied-eval\n   */\n  \"@typescript-eslint/no-implied-eval\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of top-level import type qualifier when an import only has specifiers with inline type qualifiers\n   * https://typescript-eslint.io/rules/no-import-type-side-effects\n   */\n  \"@typescript-eslint/no-import-type-side-effects\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow explicit type declarations for variables or parameters initialized to a number, string, or boolean\n   * https://typescript-eslint.io/rules/no-inferrable-types\n   */\n  \"@typescript-eslint/no-inferrable-types\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          ignoreParameters?: boolean;\n          ignoreProperties?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow `this` keywords outside of classes or class-like objects\n   * https://typescript-eslint.io/rules/no-invalid-this\n   */\n  \"@typescript-eslint/no-invalid-this\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          capIsConstructor?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow `void` type outside of generic or return types\n   * https://typescript-eslint.io/rules/no-invalid-void-type\n   */\n  \"@typescript-eslint/no-invalid-void-type\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowInGenericTypeArguments?: boolean | [string, ...string[]];\n          allowAsThisParameter?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow function declarations that contain unsafe references inside loop statements\n   * https://typescript-eslint.io/rules/no-loop-func\n   */\n  \"@typescript-eslint/no-loop-func\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow literal numbers that lose precision\n   * https://typescript-eslint.io/rules/no-loss-of-precision\n   */\n  \"@typescript-eslint/no-loss-of-precision\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow magic numbers\n   * https://typescript-eslint.io/rules/no-magic-numbers\n   */\n  \"@typescript-eslint/no-magic-numbers\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          detectObjects?: boolean;\n          enforceConst?: boolean;\n          ignore?: (number | string)[];\n          ignoreArrayIndexes?: boolean;\n          ignoreDefaultValues?: boolean;\n          ignoreClassFieldInitialValues?: boolean;\n          ignoreNumericLiteralTypes?: boolean;\n          ignoreEnums?: boolean;\n          ignoreReadonlyClassProperties?: boolean;\n          ignoreTypeIndexes?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow the `void` operator except when used to discard a value\n   * https://typescript-eslint.io/rules/no-meaningless-void-operator\n   */\n  \"@typescript-eslint/no-meaningless-void-operator\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checkNever?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce valid definition of `new` and `constructor`\n   * https://typescript-eslint.io/rules/no-misused-new\n   */\n  \"@typescript-eslint/no-misused-new\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow Promises in places not designed to handle them\n   * https://typescript-eslint.io/rules/no-misused-promises\n   */\n  \"@typescript-eslint/no-misused-promises\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          checksConditionals?: boolean;\n          checksVoidReturn?:\n            | boolean\n            | {\n                arguments?: boolean;\n                attributes?: boolean;\n                properties?: boolean;\n                returns?: boolean;\n                variables?: boolean;\n              };\n          checksSpreads?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow enums from having both number and string members\n   * https://typescript-eslint.io/rules/no-mixed-enums\n   */\n  \"@typescript-eslint/no-mixed-enums\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow TypeScript namespaces\n   * https://typescript-eslint.io/rules/no-namespace\n   */\n  \"@typescript-eslint/no-namespace\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow `declare` with custom TypeScript namespaces.\n           */\n          allowDeclarations?: boolean;\n          /**\n           * Whether to allow `declare` with custom TypeScript namespaces inside definition files.\n           */\n          allowDefinitionFiles?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow non-null assertions in the left operand of a nullish coalescing operator\n   * https://typescript-eslint.io/rules/no-non-null-asserted-nullish-coalescing\n   */\n  \"@typescript-eslint/no-non-null-asserted-nullish-coalescing\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow non-null assertions after an optional chain expression\n   * https://typescript-eslint.io/rules/no-non-null-asserted-optional-chain\n   */\n  \"@typescript-eslint/no-non-null-asserted-optional-chain\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow non-null assertions using the `!` postfix operator\n   * https://typescript-eslint.io/rules/no-non-null-assertion\n   */\n  \"@typescript-eslint/no-non-null-assertion\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow variable redeclaration\n   * https://typescript-eslint.io/rules/no-redeclare\n   */\n  \"@typescript-eslint/no-redeclare\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          builtinGlobals?: boolean;\n          ignoreDeclarationMerge?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow members of unions and intersections that do nothing or override type information\n   * https://typescript-eslint.io/rules/no-redundant-type-constituents\n   */\n  \"@typescript-eslint/no-redundant-type-constituents\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow invocation of `require()`\n   * https://typescript-eslint.io/rules/no-require-imports\n   */\n  \"@typescript-eslint/no-require-imports\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Patterns of import paths to allow requiring from.\n           */\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow specified modules when loaded by `import`\n   * https://typescript-eslint.io/rules/no-restricted-imports\n   */\n  \"@typescript-eslint/no-restricted-imports\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow variable declarations from shadowing variables declared in the outer scope\n   * https://typescript-eslint.io/rules/no-shadow\n   */\n  \"@typescript-eslint/no-shadow\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          builtinGlobals?: boolean;\n          hoist?: \"all\" | \"functions\" | \"never\";\n          allow?: string[];\n          ignoreOnInitialization?: boolean;\n          ignoreTypeValueShadow?: boolean;\n          ignoreFunctionTypeParameterNameValueShadow?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow aliasing `this`\n   * https://typescript-eslint.io/rules/no-this-alias\n   */\n  \"@typescript-eslint/no-this-alias\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to ignore destructurings, such as `const { props, state } = this`.\n           */\n          allowDestructuring?: boolean;\n          /**\n           * Names to ignore, such as [\"self\"] for `const self = this;`.\n           */\n          allowedNames?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow throwing literals as exceptions\n   * https://typescript-eslint.io/rules/no-throw-literal\n   */\n  \"@typescript-eslint/no-throw-literal\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowThrowingAny?: boolean;\n          allowThrowingUnknown?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow type aliases\n   * https://typescript-eslint.io/rules/no-type-alias\n   */\n  \"@typescript-eslint/no-type-alias\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow direct one-to-one type aliases.\n           */\n          allowAliases?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases for callbacks.\n           */\n          allowCallbacks?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases for conditional types.\n           */\n          allowConditionalTypes?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases with constructors.\n           */\n          allowConstructors?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases with object literal types.\n           */\n          allowLiterals?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases with mapped types.\n           */\n          allowMappedTypes?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases with tuple types.\n           */\n          allowTupleTypes?: {\n            [k: string]: unknown;\n          };\n          /**\n           * Whether to allow type aliases with generic types.\n           */\n          allowGenerics?: {\n            [k: string]: unknown;\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unnecessary equality comparisons against boolean literals\n   * https://typescript-eslint.io/rules/no-unnecessary-boolean-literal-compare\n   */\n  \"@typescript-eslint/no-unnecessary-boolean-literal-compare\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow comparisons between nullable boolean variables and `true`.\n           */\n          allowComparingNullableBooleansToTrue?: boolean;\n          /**\n           * Whether to allow comparisons between nullable boolean variables and `false`.\n           */\n          allowComparingNullableBooleansToFalse?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow conditionals where the type is always truthy or always falsy\n   * https://typescript-eslint.io/rules/no-unnecessary-condition\n   */\n  \"@typescript-eslint/no-unnecessary-condition\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to ignore constant loop conditions, such as `while (true)`.\n           */\n          allowConstantLoopConditions?: boolean;\n          /**\n           * Whether to not error when running with a tsconfig that has strictNullChecks turned.\n           */\n          allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unnecessary namespace qualifiers\n   * https://typescript-eslint.io/rules/no-unnecessary-qualifier\n   */\n  \"@typescript-eslint/no-unnecessary-qualifier\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary template expressions\n   * https://typescript-eslint.io/rules/no-unnecessary-template-expression\n   */\n  \"@typescript-eslint/no-unnecessary-template-expression\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow type arguments that are equal to the default\n   * https://typescript-eslint.io/rules/no-unnecessary-type-arguments\n   */\n  \"@typescript-eslint/no-unnecessary-type-arguments\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow type assertions that do not change the type of an expression\n   * https://typescript-eslint.io/rules/no-unnecessary-type-assertion\n   */\n  \"@typescript-eslint/no-unnecessary-type-assertion\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * A list of type names to ignore.\n           */\n          typesToIgnore?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unnecessary constraints on generic types\n   * https://typescript-eslint.io/rules/no-unnecessary-type-constraint\n   */\n  \"@typescript-eslint/no-unnecessary-type-constraint\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow calling a function with a value with type `any`\n   * https://typescript-eslint.io/rules/no-unsafe-argument\n   */\n  \"@typescript-eslint/no-unsafe-argument\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow assigning a value with type `any` to variables and properties\n   * https://typescript-eslint.io/rules/no-unsafe-assignment\n   */\n  \"@typescript-eslint/no-unsafe-assignment\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow calling a value with type `any`\n   * https://typescript-eslint.io/rules/no-unsafe-call\n   */\n  \"@typescript-eslint/no-unsafe-call\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unsafe declaration merging\n   * https://typescript-eslint.io/rules/no-unsafe-declaration-merging\n   */\n  \"@typescript-eslint/no-unsafe-declaration-merging\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow comparing an enum value with a non-enum value\n   * https://typescript-eslint.io/rules/no-unsafe-enum-comparison\n   */\n  \"@typescript-eslint/no-unsafe-enum-comparison\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow member access on a value with type `any`\n   * https://typescript-eslint.io/rules/no-unsafe-member-access\n   */\n  \"@typescript-eslint/no-unsafe-member-access\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow returning a value with type `any` from a function\n   * https://typescript-eslint.io/rules/no-unsafe-return\n   */\n  \"@typescript-eslint/no-unsafe-return\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require unary negation to take a number\n   * https://typescript-eslint.io/rules/no-unsafe-unary-minus\n   */\n  \"@typescript-eslint/no-unsafe-unary-minus\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unused expressions\n   * https://typescript-eslint.io/rules/no-unused-expressions\n   */\n  \"@typescript-eslint/no-unused-expressions\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowShortCircuit?: boolean;\n          allowTernary?: boolean;\n          allowTaggedTemplates?: boolean;\n          enforceForJSX?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unused variables\n   * https://typescript-eslint.io/rules/no-unused-vars\n   */\n  \"@typescript-eslint/no-unused-vars\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow the use of variables before they are defined\n   * https://typescript-eslint.io/rules/no-use-before-define\n   */\n  \"@typescript-eslint/no-use-before-define\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow unnecessary constructors\n   * https://typescript-eslint.io/rules/no-useless-constructor\n   */\n  \"@typescript-eslint/no-useless-constructor\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow empty exports that don't change anything in a module file\n   * https://typescript-eslint.io/rules/no-useless-empty-export\n   */\n  \"@typescript-eslint/no-useless-empty-export\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow unnecessary template expressions\n   * https://typescript-eslint.io/rules/no-useless-template-literals\n   */\n  \"@typescript-eslint/no-useless-template-literals\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Disallow `require` statements except in import statements\n   * https://typescript-eslint.io/rules/no-var-requires\n   */\n  \"@typescript-eslint/no-var-requires\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Patterns of import paths to allow requiring from.\n           */\n          allow?: string[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce non-null assertions over explicit type casts\n   * https://typescript-eslint.io/rules/non-nullable-type-assertion-style\n   */\n  \"@typescript-eslint/non-nullable-type-assertion-style\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce consistent spacing inside braces\n   * https://typescript-eslint.io/rules/object-curly-spacing\n   */\n  \"@typescript-eslint/object-curly-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow throwing non-`Error` values as exceptions\n   * https://typescript-eslint.io/rules/only-throw-error\n   */\n  \"@typescript-eslint/only-throw-error\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowThrowingAny?: boolean;\n          allowThrowingUnknown?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require or disallow padding lines between statements\n   * https://typescript-eslint.io/rules/padding-line-between-statements\n   */\n  \"@typescript-eslint/padding-line-between-statements\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require or disallow parameter properties in class constructors\n   * https://typescript-eslint.io/rules/parameter-properties\n   */\n  \"@typescript-eslint/parameter-properties\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: unknown[];\n          prefer?: \"class-property\" | \"parameter-property\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce the use of `as const` over literal type\n   * https://typescript-eslint.io/rules/prefer-as-const\n   */\n  \"@typescript-eslint/prefer-as-const\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require destructuring from arrays and/or objects\n   * https://typescript-eslint.io/rules/prefer-destructuring\n   */\n  \"@typescript-eslint/prefer-destructuring\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require each enum member value to be explicitly initialized\n   * https://typescript-eslint.io/rules/prefer-enum-initializers\n   */\n  \"@typescript-eslint/prefer-enum-initializers\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result\n   * https://typescript-eslint.io/rules/prefer-find\n   */\n  \"@typescript-eslint/prefer-find\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce the use of `for-of` loop over the standard `for` loop where possible\n   * https://typescript-eslint.io/rules/prefer-for-of\n   */\n  \"@typescript-eslint/prefer-for-of\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce using function types instead of interfaces with call signatures\n   * https://typescript-eslint.io/rules/prefer-function-type\n   */\n  \"@typescript-eslint/prefer-function-type\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce `includes` method over `indexOf` method\n   * https://typescript-eslint.io/rules/prefer-includes\n   */\n  \"@typescript-eslint/prefer-includes\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require all enum members to be literal values\n   * https://typescript-eslint.io/rules/prefer-literal-enum-member\n   */\n  \"@typescript-eslint/prefer-literal-enum-member\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowBitwiseExpressions?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require using `namespace` keyword over `module` keyword to declare custom TypeScript modules\n   * https://typescript-eslint.io/rules/prefer-namespace-keyword\n   */\n  \"@typescript-eslint/prefer-namespace-keyword\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce using the nullish coalescing operator instead of logical assignments or chaining\n   * https://typescript-eslint.io/rules/prefer-nullish-coalescing\n   */\n  \"@typescript-eslint/prefer-nullish-coalescing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;\n          ignoreConditionalTests?: boolean;\n          ignoreMixedLogicalExpressions?: boolean;\n          ignorePrimitives?:\n            | {\n                bigint?: boolean;\n                boolean?: boolean;\n                number?: boolean;\n                string?: boolean;\n                [k: string]: unknown;\n              }\n            | true;\n          ignoreTernaryTests?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce using concise optional chain expressions instead of chained logical ands, negated logical ors, or empty objects\n   * https://typescript-eslint.io/rules/prefer-optional-chain\n   */\n  \"@typescript-eslint/prefer-optional-chain\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Check operands that are typed as `any` when inspecting \"loose boolean\" operands.\n           */\n          checkAny?: boolean;\n          /**\n           * Check operands that are typed as `unknown` when inspecting \"loose boolean\" operands.\n           */\n          checkUnknown?: boolean;\n          /**\n           * Check operands that are typed as `string` when inspecting \"loose boolean\" operands.\n           */\n          checkString?: boolean;\n          /**\n           * Check operands that are typed as `number` when inspecting \"loose boolean\" operands.\n           */\n          checkNumber?: boolean;\n          /**\n           * Check operands that are typed as `boolean` when inspecting \"loose boolean\" operands.\n           */\n          checkBoolean?: boolean;\n          /**\n           * Check operands that are typed as `bigint` when inspecting \"loose boolean\" operands.\n           */\n          checkBigInt?: boolean;\n          /**\n           * Skip operands that are not typed with `null` and/or `undefined` when inspecting \"loose boolean\" operands.\n           */\n          requireNullish?: boolean;\n          /**\n           * Allow autofixers that will change the return type of the expression. This option is considered unsafe as it may break the build.\n           */\n          allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require using Error objects as Promise rejection reasons\n   * https://typescript-eslint.io/rules/prefer-promise-reject-errors\n   */\n  \"@typescript-eslint/prefer-promise-reject-errors\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowEmptyReject?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require private members to be marked as `readonly` if they're never modified outside of the constructor\n   * https://typescript-eslint.io/rules/prefer-readonly\n   */\n  \"@typescript-eslint/prefer-readonly\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          onlyInlineLambdas?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require function parameters to be typed as `readonly` to prevent accidental mutation of inputs\n   * https://typescript-eslint.io/rules/prefer-readonly-parameter-types\n   */\n  \"@typescript-eslint/prefer-readonly-parameter-types\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allow?: (\n            | string\n            | {\n                from: \"file\";\n                name: string | [string, ...string[]];\n                path?: string;\n              }\n            | {\n                from: \"lib\";\n                name: string | [string, ...string[]];\n              }\n            | {\n                from: \"package\";\n                name: string | [string, ...string[]];\n                package: string;\n              }\n          )[];\n          checkParameterProperties?: boolean;\n          ignoreInferredTypes?: boolean;\n          treatMethodsAsReadonly?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce using type parameter when calling `Array#reduce` instead of casting\n   * https://typescript-eslint.io/rules/prefer-reduce-type-parameter\n   */\n  \"@typescript-eslint/prefer-reduce-type-parameter\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce `RegExp#exec` over `String#match` if no global flag is provided\n   * https://typescript-eslint.io/rules/prefer-regexp-exec\n   */\n  \"@typescript-eslint/prefer-regexp-exec\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce that `this` is used when only `this` type is returned\n   * https://typescript-eslint.io/rules/prefer-return-this-type\n   */\n  \"@typescript-eslint/prefer-return-this-type\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce using `String#startsWith` and `String#endsWith` over other equivalent methods of checking substrings\n   * https://typescript-eslint.io/rules/prefer-string-starts-ends-with\n   */\n  \"@typescript-eslint/prefer-string-starts-ends-with\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow equality checks against the first or last element of a string.\n           */\n          allowSingleElementEquality?: \"always\" | \"never\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce using `@ts-expect-error` over `@ts-ignore`\n   * https://typescript-eslint.io/rules/prefer-ts-expect-error\n   */\n  \"@typescript-eslint/prefer-ts-expect-error\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require any function or method that returns a Promise to be marked async\n   * https://typescript-eslint.io/rules/promise-function-async\n   */\n  \"@typescript-eslint/promise-function-async\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to consider `any` and `unknown` to be Promises.\n           */\n          allowAny?: boolean;\n          /**\n           * Any extra names of classes or interfaces to be considered Promises.\n           */\n          allowedPromiseNames?: string[];\n          checkArrowFunctions?: boolean;\n          checkFunctionDeclarations?: boolean;\n          checkFunctionExpressions?: boolean;\n          checkMethodDeclarations?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce the consistent use of either backticks, double, or single quotes\n   * https://typescript-eslint.io/rules/quotes\n   */\n  \"@typescript-eslint/quotes\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [number | (\"off\" | \"warn\" | \"error\"), \"double\" | \"single\" | \"backtick\"]\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        \"double\" | \"single\" | \"backtick\",\n        {\n          /**\n           * allows strings to use single-quotes or double-quotes so long as the string contains a quote that would have to be escaped otherwise\n           */\n          avoidEscape?: boolean;\n          /**\n           * allows strings to use backticks\n           */\n          allowTemplateLiterals?: boolean;\n          /**\n           * Deprecated: The object property avoid-escape is deprecated; please use the object property avoidEscape instead.\n           */\n          \"avoid-escape\"?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require `Array#sort` and `Array#toSorted` calls to always provide a `compareFunction`\n   * https://typescript-eslint.io/rules/require-array-sort-compare\n   */\n  \"@typescript-eslint/require-array-sort-compare\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to ignore arrays in which all elements are strings.\n           */\n          ignoreStringArrays?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow async functions which do not return promises and have no `await` expression\n   * https://typescript-eslint.io/rules/require-await\n   */\n  \"@typescript-eslint/require-await\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Require both operands of addition to be the same type and be `bigint`, `number`, or `string`\n   * https://typescript-eslint.io/rules/restrict-plus-operands\n   */\n  \"@typescript-eslint/restrict-plus-operands\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow `any` typed values.\n           */\n          allowAny?: boolean;\n          /**\n           * Whether to allow `boolean` typed values.\n           */\n          allowBoolean?: boolean;\n          /**\n           * Whether to allow potentially `null` or `undefined` typed values.\n           */\n          allowNullish?: boolean;\n          /**\n           * Whether to allow `bigint`/`number` typed values and `string` typed values to be added together.\n           */\n          allowNumberAndString?: boolean;\n          /**\n           * Whether to allow `regexp` typed values.\n           */\n          allowRegExp?: boolean;\n          /**\n           * Whether to skip compound assignments such as `+=`.\n           */\n          skipCompoundAssignments?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce template literal expressions to be of `string` type\n   * https://typescript-eslint.io/rules/restrict-template-expressions\n   */\n  \"@typescript-eslint/restrict-template-expressions\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to allow `any` typed values in template expressions.\n           */\n          allowAny?: boolean;\n          /**\n           * Whether to allow `array` typed values in template expressions.\n           */\n          allowArray?: boolean;\n          /**\n           * Whether to allow `boolean` typed values in template expressions.\n           */\n          allowBoolean?: boolean;\n          /**\n           * Whether to allow `nullish` typed values in template expressions.\n           */\n          allowNullish?: boolean;\n          /**\n           * Whether to allow `number` typed values in template expressions.\n           */\n          allowNumber?: boolean;\n          /**\n           * Whether to allow `regexp` typed values in template expressions.\n           */\n          allowRegExp?: boolean;\n          /**\n           * Whether to allow `never` typed values in template expressions.\n           */\n          allowNever?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent awaiting of returned promises\n   * https://typescript-eslint.io/rules/return-await\n   */\n  \"@typescript-eslint/return-await\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        \"never\" | \"error-handling-correctness-only\" | \"in-try-catch\" | \"always\",\n      ];\n  /**\n   * Require or disallow semicolons instead of ASI\n   * https://typescript-eslint.io/rules/semi\n   */\n  \"@typescript-eslint/semi\"?: {\n    [k: string]: unknown;\n  };\n  /**\n   * Enforce constituents of a type union/intersection to be sorted alphabetically\n   * https://typescript-eslint.io/rules/sort-type-constituents\n   */\n  \"@typescript-eslint/sort-type-constituents\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to check intersection types.\n           */\n          checkIntersections?: boolean;\n          /**\n           * Whether to check union types.\n           */\n          checkUnions?: boolean;\n          /**\n           * Whether to sort using case sensitive sorting.\n           */\n          caseSensitive?: boolean;\n          /**\n           * Ordering of the groups.\n           */\n          groupOrder?: (\n            | \"conditional\"\n            | \"function\"\n            | \"import\"\n            | \"intersection\"\n            | \"keyword\"\n            | \"nullish\"\n            | \"literal\"\n            | \"named\"\n            | \"object\"\n            | \"operator\"\n            | \"tuple\"\n            | \"union\"\n          )[];\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing before blocks\n   * https://typescript-eslint.io/rules/space-before-blocks\n   */\n  \"@typescript-eslint/space-before-blocks\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce consistent spacing before function parenthesis\n   * https://typescript-eslint.io/rules/space-before-function-paren\n   */\n  \"@typescript-eslint/space-before-function-paren\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require spacing around infix operators\n   * https://typescript-eslint.io/rules/space-infix-ops\n   */\n  \"@typescript-eslint/space-infix-ops\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          int32Hint?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow certain types in boolean expressions\n   * https://typescript-eslint.io/rules/strict-boolean-expressions\n   */\n  \"@typescript-eslint/strict-boolean-expressions\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          allowString?: boolean;\n          allowNumber?: boolean;\n          allowNullableObject?: boolean;\n          allowNullableBoolean?: boolean;\n          allowNullableString?: boolean;\n          allowNullableNumber?: boolean;\n          allowNullableEnum?: boolean;\n          allowAny?: boolean;\n          allowRuleToRunWithoutStrictNullChecksIKnowWhatIAmDoing?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require switch-case statements to be exhaustive\n   * https://typescript-eslint.io/rules/switch-exhaustiveness-check\n   */\n  \"@typescript-eslint/switch-exhaustiveness-check\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * If 'true', allow 'default' cases on switch statements with exhaustive cases.\n           */\n          allowDefaultCaseForExhaustiveSwitch?: boolean;\n          /**\n           * If 'true', require a 'default' clause for switches on non-union types.\n           */\n          requireDefaultForNonUnion?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow certain triple slash directives in favor of ES6-style import declarations\n   * https://typescript-eslint.io/rules/triple-slash-reference\n   */\n  \"@typescript-eslint/triple-slash-reference\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          lib?: \"always\" | \"never\";\n          path?: \"always\" | \"never\";\n          types?: \"always\" | \"never\" | \"prefer-import\";\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require consistent spacing around type annotations\n   * https://typescript-eslint.io/rules/type-annotation-spacing\n   */\n  \"@typescript-eslint/type-annotation-spacing\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          before?: boolean;\n          after?: boolean;\n          overrides?: {\n            colon?: unknown;\n            arrow?: unknown;\n            variable?: unknown;\n            parameter?: unknown;\n            property?: unknown;\n            returnType?: unknown;\n          };\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Require type annotations in certain places\n   * https://typescript-eslint.io/rules/typedef\n   */\n  \"@typescript-eslint/typedef\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          arrayDestructuring?: boolean;\n          arrowParameter?: boolean;\n          memberVariableDeclaration?: boolean;\n          objectDestructuring?: boolean;\n          parameter?: boolean;\n          propertyDeclaration?: boolean;\n          variableDeclaration?: boolean;\n          variableDeclarationIgnoreFunction?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce unbound methods are called with their expected scope\n   * https://typescript-eslint.io/rules/unbound-method\n   */\n  \"@typescript-eslint/unbound-method\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether to skip checking whether `static` methods are correctly bound.\n           */\n          ignoreStatic?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Disallow two overloads that could be unified into one with a union or an optional/rest parameter\n   * https://typescript-eslint.io/rules/unified-signatures\n   */\n  \"@typescript-eslint/unified-signatures\"?:\n    | number\n    | (\"off\" | \"warn\" | \"error\")\n    | [\n        number | (\"off\" | \"warn\" | \"error\"),\n        {\n          /**\n           * Whether two parameters with different names at the same index should be considered different even if their types are the same.\n           */\n          ignoreDifferentlyNamedParameters?: boolean;\n          [k: string]: unknown;\n        },\n      ];\n  /**\n   * Enforce typing arguments in `.catch()` callbacks as `unknown`\n   * https://typescript-eslint.io/rules/use-unknown-in-catch-callback-variable\n   */\n  \"@typescript-eslint/use-unknown-in-catch-callback-variable\"?: {\n    [k: string]: unknown;\n  };\n  [k: string]: unknown;\n}\n/**\n * ESLint supports adding shared settings into configuration file. You can add settings object to ESLint configuration file and it will be supplied to every rule that will be executed. This may be useful if you are adding custom rules and want them to have access to the same information and be easily configurable.\n */\nexport interface Settings {\n  [k: string]: unknown;\n}\nexport interface OptionsDefinition {\n  /**\n   * Include parentheses around a sole arrow function parameter.\n   */\n  arrowParens?: \"always\" | \"avoid\";\n  /**\n   * Put > of opening tags on the last line instead of on a new line.\n   */\n  bracketSameLine?: boolean;\n  /**\n   * Print spaces between brackets.\n   */\n  bracketSpacing?: boolean;\n  /**\n   * Print (to stderr) where a cursor at the given position would move to after formatting.\n   */\n  cursorOffset?: number;\n  /**\n   * Control how Prettier formats quoted code embedded in the file.\n   */\n  embeddedLanguageFormatting?: \"auto\" | \"off\";\n  /**\n   * Which end of line characters to apply.\n   */\n  endOfLine?: \"lf\" | \"crlf\" | \"cr\" | \"auto\";\n  /**\n   * Use curious ternaries, with the question mark after the condition.\n   */\n  experimentalTernaries?: boolean;\n  /**\n   * Specify the input filepath. This will be used to do parser inference.\n   */\n  filepath?: string;\n  /**\n   * How to handle whitespaces in HTML.\n   */\n  htmlWhitespaceSensitivity?: \"css\" | \"strict\" | \"ignore\";\n  /**\n   * Insert @format pragma into file's first docblock comment.\n   */\n  insertPragma?: boolean;\n  /**\n   * Use single quotes in JSX.\n   */\n  jsxSingleQuote?: boolean;\n  /**\n   * Which parser to use.\n   */\n  parser?:\n    | \"flow\"\n    | \"babel\"\n    | \"babel-flow\"\n    | \"babel-ts\"\n    | \"typescript\"\n    | \"acorn\"\n    | \"espree\"\n    | \"meriyah\"\n    | \"css\"\n    | \"less\"\n    | \"scss\"\n    | \"json\"\n    | \"json5\"\n    | \"jsonc\"\n    | \"json-stringify\"\n    | \"graphql\"\n    | \"markdown\"\n    | \"mdx\"\n    | \"vue\"\n    | \"yaml\"\n    | \"glimmer\"\n    | \"html\"\n    | \"angular\"\n    | \"lwc\"\n    | string;\n  /**\n   * Add a plugin. Multiple plugins can be passed as separate `--plugin`s.\n   */\n  plugins?: string[];\n  /**\n   * The line length where Prettier will try wrap.\n   */\n  printWidth?: number;\n  /**\n   * How to wrap prose.\n   */\n  proseWrap?: \"always\" | \"never\" | \"preserve\";\n  /**\n   * Change when properties in objects are quoted.\n   */\n  quoteProps?: \"as-needed\" | \"consistent\" | \"preserve\";\n  /**\n   * Format code ending at a given character offset (exclusive).\n   * The range will extend forwards to the end of the selected statement.\n   */\n  rangeEnd?: number;\n  /**\n   * Format code starting at a given character offset.\n   * The range will extend backwards to the start of the first line containing the selected statement.\n   */\n  rangeStart?: number;\n  /**\n   * Require either '@prettier' or '@format' to be present in the file's first docblock comment\n   * in order for it to be formatted.\n   */\n  requirePragma?: boolean;\n  /**\n   * Print semicolons.\n   */\n  semi?: boolean;\n  /**\n   * Enforce single attribute per line in HTML, Vue and JSX.\n   */\n  singleAttributePerLine?: boolean;\n  /**\n   * Use single quotes instead of double quotes.\n   */\n  singleQuote?: boolean;\n  /**\n   * Number of spaces per indentation level.\n   */\n  tabWidth?: number;\n  /**\n   * Print trailing commas wherever possible when multi-line.\n   */\n  trailingComma?: \"all\" | \"es5\" | \"none\";\n  /**\n   * Indent with tabs instead of spaces.\n   */\n  useTabs?: boolean;\n  /**\n   * Indent script and style tags in Vue files.\n   */\n  vueIndentScriptAndStyle?: boolean;\n  [k: string]: unknown;\n}\nexport interface OverridesDefinition {\n  /**\n   * Provide a list of patterns to override prettier configuration.\n   */\n  overrides?: {\n    /**\n     * Include these files in this override.\n     */\n    files: string | string[];\n    /**\n     * Exclude these files from this override.\n     */\n    excludeFiles?: string | string[];\n    options?: OptionsDefinition1;\n  }[];\n  [k: string]: unknown;\n}\n/**\n * The options to apply for this override.\n */\nexport interface OptionsDefinition1 {\n  /**\n   * Include parentheses around a sole arrow function parameter.\n   */\n  arrowParens?: \"always\" | \"avoid\";\n  /**\n   * Put > of opening tags on the last line instead of on a new line.\n   */\n  bracketSameLine?: boolean;\n  /**\n   * Print spaces between brackets.\n   */\n  bracketSpacing?: boolean;\n  /**\n   * Print (to stderr) where a cursor at the given position would move to after formatting.\n   */\n  cursorOffset?: number;\n  /**\n   * Control how Prettier formats quoted code embedded in the file.\n   */\n  embeddedLanguageFormatting?: \"auto\" | \"off\";\n  /**\n   * Which end of line characters to apply.\n   */\n  endOfLine?: \"lf\" | \"crlf\" | \"cr\" | \"auto\";\n  /**\n   * Use curious ternaries, with the question mark after the condition.\n   */\n  experimentalTernaries?: boolean;\n  /**\n   * Specify the input filepath. This will be used to do parser inference.\n   */\n  filepath?: string;\n  /**\n   * How to handle whitespaces in HTML.\n   */\n  htmlWhitespaceSensitivity?: \"css\" | \"strict\" | \"ignore\";\n  /**\n   * Insert @format pragma into file's first docblock comment.\n   */\n  insertPragma?: boolean;\n  /**\n   * Use single quotes in JSX.\n   */\n  jsxSingleQuote?: boolean;\n  /**\n   * Which parser to use.\n   */\n  parser?:\n    | \"flow\"\n    | \"babel\"\n    | \"babel-flow\"\n    | \"babel-ts\"\n    | \"typescript\"\n    | \"acorn\"\n    | \"espree\"\n    | \"meriyah\"\n    | \"css\"\n    | \"less\"\n    | \"scss\"\n    | \"json\"\n    | \"json5\"\n    | \"jsonc\"\n    | \"json-stringify\"\n    | \"graphql\"\n    | \"markdown\"\n    | \"mdx\"\n    | \"vue\"\n    | \"yaml\"\n    | \"glimmer\"\n    | \"html\"\n    | \"angular\"\n    | \"lwc\"\n    | string;\n  /**\n   * Add a plugin. Multiple plugins can be passed as separate `--plugin`s.\n   */\n  plugins?: string[];\n  /**\n   * The line length where Prettier will try wrap.\n   */\n  printWidth?: number;\n  /**\n   * How to wrap prose.\n   */\n  proseWrap?: \"always\" | \"never\" | \"preserve\";\n  /**\n   * Change when properties in objects are quoted.\n   */\n  quoteProps?: \"as-needed\" | \"consistent\" | \"preserve\";\n  /**\n   * Format code ending at a given character offset (exclusive).\n   * The range will extend forwards to the end of the selected statement.\n   */\n  rangeEnd?: number;\n  /**\n   * Format code starting at a given character offset.\n   * The range will extend backwards to the start of the first line containing the selected statement.\n   */\n  rangeStart?: number;\n  /**\n   * Require either '@prettier' or '@format' to be present in the file's first docblock comment\n   * in order for it to be formatted.\n   */\n  requirePragma?: boolean;\n  /**\n   * Print semicolons.\n   */\n  semi?: boolean;\n  /**\n   * Enforce single attribute per line in HTML, Vue and JSX.\n   */\n  singleAttributePerLine?: boolean;\n  /**\n   * Use single quotes instead of double quotes.\n   */\n  singleQuote?: boolean;\n  /**\n   * Number of spaces per indentation level.\n   */\n  tabWidth?: number;\n  /**\n   * Print trailing commas wherever possible when multi-line.\n   */\n  trailingComma?: \"all\" | \"es5\" | \"none\";\n  /**\n   * Indent with tabs instead of spaces.\n   */\n  useTabs?: boolean;\n  /**\n   * Indent script and style tags in Vue files.\n   */\n  vueIndentScriptAndStyle?: boolean;\n  [k: string]: unknown;\n}\nexport interface JSONSchemaForTheStylelintConfigurationFiles {\n  extends?: SimpleStringOrArrayStringRule;\n  plugins?: SimpleArrayStringRule1;\n  /**\n   * Specify a custom syntax to use on your code.\n   */\n  customSyntax?: string;\n  /**\n   * Provide rule and behavior overrides for files that match particular glob patterns.\n   */\n  overrides?: {\n    files?: string[];\n    customSyntax?: string;\n    rules?: AllRules;\n    [k: string]: unknown;\n  }[];\n  /**\n   * Processors are functions that hook into stylelint's pipeline, modifying code on its way into stylelint and modifying results on their way out\n   */\n  processors?: (\n    | string\n    | []\n    | [\n        string,\n        ...{\n          [k: string]: unknown;\n        }[],\n      ]\n  )[];\n  /**\n   * Ignore stylelint-disable (e.g. /_ stylelint-disable block-no-empty _ /) comments.\n   */\n  ignoreDisables?: boolean;\n  ignoreFiles?: SimpleStringOrArrayStringRule2;\n  /**\n   * The default severity level for all rules that do not have a severity specified in their secondary options\n   */\n  defaultSeverity?: \"warning\" | \"error\";\n  reportDescriptionlessDisables?: BooleanRule38;\n  reportInvalidScopeDisables?: BooleanRule39;\n  reportNeedlessDisables?: BooleanRule40;\n  rules?: AllRules;\n  [k: string]: unknown;\n}\nexport interface AtRule {\n  \"at-rule-blacklist\"?: ArrayStringRule;\n  /**\n   * Require or disallow an empty line before at-rules\n   */\n  \"at-rule-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | [])\n    | [\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"never\" | [])\n            | [\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"at-rule-name-case\"?: LowerUpperRule;\n  \"at-rule-name-newline-after\"?: AlwaysMultiLineRule;\n  /**\n   * Require a single space after at-rule names\n   */\n  \"at-rule-name-space-after\"?: (\n    | null\n    | (\"always\" | \"always-single-line\" | [])\n    | [\n        ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"always-single-line\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"always-single-line\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"always-single-line\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"always-single-line\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"always-single-line\" | [])\n            | [\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"always-single-line\" | [])\n          | [\n              ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"always-single-line\" | [])\n          | [\n              ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"always-single-line\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always\" | \"always-single-line\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Disallow unknown at-rules\n   */\n  \"at-rule-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"at-rule-no-vendor-prefix\"?: BooleanRule;\n  /**\n   * Require a newline after the semicolon of at-rules\n   */\n  \"at-rule-semicolon-newline-after\"?: (\n    | null\n    | (\"always\" | [])\n    | [\n        ((\"always\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | {}) | CoreRule) & string)\n            | ((\"always\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | {}) | CoreRule) & string)\n            | ((\"always\" | {}) | CoreRule)\n          ),\n        ((\"always\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | {}) | CoreRule) & string)\n            | ((\"always\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | {}) | CoreRule) & string)\n            | ((\"always\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | [])\n            | [\n                ((\"always\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | {}) | CoreRule) & string)\n                    | ((\"always\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | {}) | CoreRule) & string)\n                    | ((\"always\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | {}) | CoreRule) & string)\n                    | ((\"always\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | {}) | CoreRule) & string)\n                    | ((\"always\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | [])\n          | [\n              ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ),\n              ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | [])\n          | [\n              ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ),\n              ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | {}) | CoreRule) & string)\n                  | ((\"always\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * @deprecated\n   * Require a single space or disallow whitespace before the semicolons of at-rules\n   */\n  \"at-rule-semicolon-space-before\"?: {\n    [k: string]: unknown;\n  };\n  \"at-rule-whitelist\"?: ArrayStringRule1;\n  [k: string]: unknown;\n}\nexport interface CoreRule {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n  [k: string]: unknown;\n}\nexport interface Block {\n  /**\n   * Require or disallow an empty line before the closing brace of blocks\n   */\n  \"block-closing-brace-empty-line-before\"?: (\n    | null\n    | (\"always-multi-line\" | \"never\" | [])\n    | [\n        ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always-multi-line\" | \"never\" | [])\n            | [\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always-multi-line\" | \"never\" | [])\n          | [\n              ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always-multi-line\" | \"never\" | [])\n          | [\n              ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-multi-line\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-multi-line\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always-multi-line\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"block-closing-brace-newline-after\"?: NewlineSpaceWithIgnoreRule;\n  \"block-closing-brace-newline-before\"?: NewlineRule;\n  \"block-closing-brace-space-after\"?: NewlineSpaceRule;\n  \"block-closing-brace-space-before\"?: NewlineSpaceRule1;\n  \"block-no-empty\"?: BooleanRule1;\n  \"block-no-single-line\"?: BooleanRule2;\n  \"block-opening-brace-newline-after\"?: NewlineRule1;\n  /**\n   * Require a newline or disallow whitespace before the opening brace of blocks\n   */\n  \"block-opening-brace-newline-before\"?: (\n    | null\n    | (\n        | \"always\"\n        | \"always-single-line\"\n        | \"never-single-line\"\n        | \"always-multi-line\"\n        | \"never-multi-line\"\n        | []\n      )\n    | [\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"always-single-line\"\n                | \"never-single-line\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n        (\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | {}\n            )\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"always-single-line\"\n                | \"never-single-line\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\n                | \"always\"\n                | \"always-single-line\"\n                | \"never-single-line\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | []\n              )\n            | [\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"always-single-line\"\n                        | \"never-single-line\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"always-single-line\"\n                            | \"never-single-line\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\n              | \"always\"\n              | \"always-single-line\"\n              | \"never-single-line\"\n              | \"always-multi-line\"\n              | \"never-multi-line\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"always-single-line\"\n                    | \"never-single-line\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"always-single-line\"\n                      | \"never-single-line\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"always-single-line\"\n                          | \"never-single-line\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"block-opening-brace-space-after\"?: NewlineSpaceRule2;\n  \"block-opening-brace-space-before\"?: NewlineSpaceWithIgnoreRule1;\n  [k: string]: unknown;\n}\nexport interface Color {\n  \"color-hex-case\"?: LowerUpperRule1;\n  /**\n   * Specify short or long notation for hex colors\n   */\n  \"color-hex-length\"?: (\n    | null\n    | (\"short\" | \"long\" | [])\n    | [\n        ((\"short\" | \"long\" | {}) | CoreRule) &\n          (\n            | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n            | ((\"short\" | \"long\" | {}) | CoreRule)\n          ) &\n          ((\"short\" | \"long\" | {}) | CoreRule) &\n          (\n            | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n            | ((\"short\" | \"long\" | {}) | CoreRule)\n          ),\n        ((\"short\" | \"long\" | {}) | CoreRule) &\n          (\n            | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n            | ((\"short\" | \"long\" | {}) | CoreRule)\n          ) &\n          ((\"short\" | \"long\" | {}) | CoreRule) &\n          (\n            | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n            | ((\"short\" | \"long\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"short\" | \"long\" | [])\n            | [\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                  (\n                    | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                    | ((\"short\" | \"long\" | {}) | CoreRule)\n                  ) &\n                  ((\"short\" | \"long\" | {}) | CoreRule) &\n                  (\n                    | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                    | ((\"short\" | \"long\" | {}) | CoreRule)\n                  ),\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                  (\n                    | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                    | ((\"short\" | \"long\" | {}) | CoreRule)\n                  ) &\n                  ((\"short\" | \"long\" | {}) | CoreRule) &\n                  (\n                    | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                    | ((\"short\" | \"long\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"short\" | \"long\" | [])\n          | [\n              ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ) &\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ),\n              ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ) &\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"short\" | \"long\" | [])\n          | [\n              ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ) &\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ),\n              ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ) &\n                ((\"short\" | \"long\" | {}) | CoreRule) &\n                (\n                  | (((\"short\" | \"long\" | {}) | CoreRule) & string)\n                  | ((\"short\" | \"long\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Require (where possible) or disallow named colors\n   */\n  \"color-named\"?: (\n    | null\n    | (\"always-where-possible\" | \"never\" | [])\n    | [\n        ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always-where-possible\" | \"never\" | [])\n            | [\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always-where-possible\" | \"never\" | [])\n          | [\n              ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always-where-possible\" | \"never\" | [])\n          | [\n              ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always-where-possible\" | \"never\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-where-possible\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"color-no-hex\"?: BooleanRule3;\n  \"color-no-invalid-hex\"?: BooleanRule4;\n  [k: string]: unknown;\n}\nexport interface Comment {\n  /**\n   * Require or disallow an empty line before comments\n   */\n  \"comment-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | [])\n    | [\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"never\" | [])\n            | [\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"comment-no-empty\"?: BooleanRule5;\n  \"comment-whitespace-inside\"?: AlwaysNeverRule;\n  \"comment-word-blacklist\"?: ArrayStringRule2;\n  [k: string]: unknown;\n}\nexport interface CustomMedia {\n  \"custom-media-pattern\"?: StringRule;\n  /**\n   * Disallow unknown custom media queries\n   */\n  \"no-unknown-custom-media\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule1];\n  [k: string]: unknown;\n}\nexport interface CoreRule1 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface CustomProperty {\n  /**\n   * Require or disallow an empty line before custom properties\n   */\n  \"custom-property-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | [])\n    | [\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"never\" | [])\n            | [\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"custom-property-no-outside-root\"?: BooleanRule6;\n  \"custom-property-pattern\"?: StringRule1;\n  /**\n   * Disallow unknown custom properties\n   */\n  \"no-unknown-custom-properties\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule2];\n  [k: string]: unknown;\n}\nexport interface CoreRule2 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface Declaration {\n  \"declaration-bang-space-after\"?: AlwaysNeverRule1;\n  \"declaration-bang-space-before\"?: AlwaysNeverRule2;\n  \"declaration-colon-newline-after\"?: AlwaysMultiLineRule1;\n  /**\n   * Require a single space or disallow whitespace after the colon of declarations\n   */\n  \"declaration-colon-space-after\"?: (\n    | null\n    | (\"always\" | \"never\" | \"always-single-line\" | [])\n    | [\n        ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                string)\n            | ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                string)\n            | ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                string)\n            | ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                string)\n            | ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"never\" | \"always-single-line\" | [])\n            | [\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | ((\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\"always\" | \"never\" | \"always-single-line\" | {})\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      )\n                  ),\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                  (\n                    | ((\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\"always\" | \"never\" | \"always-single-line\" | {})\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\"always\" | \"never\" | \"always-single-line\" | {})\n                        | CoreRule\n                      )\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-single-line\" | [])\n          | [\n              ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ) &\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ),\n              ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ) &\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-single-line\" | [])\n          | [\n              ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ) &\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ),\n              ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ) &\n                ((\"always\" | \"never\" | \"always-single-line\" | {}) | CoreRule) &\n                (\n                  | ((\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\"always\" | \"never\" | \"always-single-line\" | {})\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"declaration-colon-space-before\"?: AlwaysNeverRule3;\n  /**\n   * Require or disallow an empty line before declarations\n   */\n  \"declaration-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | [])\n    | [\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n        ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ) &\n          ((\"always\" | \"never\" | {}) | CoreRule) &\n          (\n            | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n            | ((\"always\" | \"never\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always\" | \"never\" | [])\n            | [\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ) &\n                  ((\"always\" | \"never\" | {}) | CoreRule) &\n                  (\n                    | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                    | ((\"always\" | \"never\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | [])\n          | [\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n              ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ) &\n                ((\"always\" | \"never\" | {}) | CoreRule) &\n                (\n                  | (((\"always\" | \"never\" | {}) | CoreRule) & string)\n                  | ((\"always\" | \"never\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"declaration-no-important\"?: BooleanRule7;\n  /**\n   * Specify a blacklist of disallowed property and unit pairs within declarations\n   */\n  \"declaration-property-unit-blacklist\"?:\n    | null\n    | {\n        [k: string]: SimpleStringOrArrayStringRule1;\n      }\n    | [\n        {\n          [k: string]: SimpleStringOrArrayStringRule1;\n        },\n        CoreRule,\n      ];\n  /**\n   * Specify a whitelist of allowed property and unit pairs within declarations\n   */\n  \"declaration-property-unit-whitelist\"?:\n    | null\n    | {\n        [k: string]: SimpleStringOrArrayStringRule1;\n      }\n    | [\n        {\n          [k: string]: SimpleStringOrArrayStringRule1;\n        },\n        CoreRule,\n      ];\n  /**\n   * Specify a blacklist of disallowed property and value pairs within declarations\n   */\n  \"declaration-property-value-blacklist\"?:\n    | null\n    | {\n        [k: string]: SimpleStringOrArrayStringRule1;\n      }\n    | [\n        {\n          [k: string]: SimpleStringOrArrayStringRule1;\n        },\n        CoreRule,\n      ];\n  /**\n   * Disallow unknown values for properties within declarations\n   */\n  \"declaration-property-value-no-unknown\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule];\n  /**\n   * Specify a whitelist of allowed property and value pairs within declarations\n   */\n  \"declaration-property-value-whitelist\"?:\n    | null\n    | {\n        [k: string]: SimpleStringOrArrayStringRule1;\n      }\n    | [\n        {\n          [k: string]: SimpleStringOrArrayStringRule1;\n        },\n        CoreRule,\n      ];\n  [k: string]: unknown;\n}\nexport interface DeclarationBlock {\n  /**\n   * Disallow duplicate properties within declaration blocks\n   */\n  \"declaration-block-no-duplicate-properties\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"declaration-block-no-ignored-properties\"?: BooleanRule8;\n  /**\n   * Disallow longhand properties that can be combined into one shorthand property\n   */\n  \"declaration-block-no-redundant-longhand-properties\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"declaration-block-no-shorthand-property-overrides\"?: BooleanRule9;\n  /**\n   * Specify the order of properties within declaration blocks\n   */\n  \"declaration-block-properties-order\"?: (\n    | null\n    | (\"alphabetical\" | [])\n    | [\n        (\n          | (\"alphabetical\" | [] | {})\n          | string\n          | SimpleArrayStringRule\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                string)\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                unknown[])\n            | (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              )\n          ) &\n          (\n            | (\"alphabetical\" | [] | {})\n            | string\n            | SimpleArrayStringRule\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                string)\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                unknown[])\n            | (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              )\n          ),\n        ...((\n          | (\"alphabetical\" | [] | {})\n          | string\n          | SimpleArrayStringRule\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                string)\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                unknown[])\n            | (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              )\n          ) &\n          (\n            | (\"alphabetical\" | [] | {})\n            | string\n            | SimpleArrayStringRule\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                string)\n            | ((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                unknown[])\n            | (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              )\n          ))[],\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"alphabetical\" | [])\n            | [\n                (\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        string)\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        unknown[])\n                    | (\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\"alphabetical\" | [] | {})\n                    | string\n                    | SimpleArrayStringRule\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        string)\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        unknown[])\n                    | (\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      )\n                  ),\n                ...((\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        string)\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        unknown[])\n                    | (\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\"alphabetical\" | [] | {})\n                    | string\n                    | SimpleArrayStringRule\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        string)\n                    | ((\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      ) &\n                        unknown[])\n                    | (\n                        | (\"alphabetical\" | [] | {})\n                        | string\n                        | SimpleArrayStringRule\n                        | CoreRule\n                      )\n                  ))[],\n              ]\n          ))\n      | ((\n          | null\n          | (\"alphabetical\" | [])\n          | [\n              (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ),\n              ...((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ))[],\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"alphabetical\" | [])\n          | [\n              (\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ),\n              ...((\n                | (\"alphabetical\" | [] | {})\n                | string\n                | SimpleArrayStringRule\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\"alphabetical\" | [] | {})\n                  | string\n                  | SimpleArrayStringRule\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      string)\n                  | ((\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    ) &\n                      unknown[])\n                  | (\n                      | (\"alphabetical\" | [] | {})\n                      | string\n                      | SimpleArrayStringRule\n                      | CoreRule\n                    )\n                ))[],\n            ]\n        ) &\n          unknown[])\n    );\n  \"declaration-block-semicolon-newline-after\"?: NewlineRule2;\n  \"declaration-block-semicolon-newline-before\"?: NewlineRule3;\n  \"declaration-block-semicolon-space-after\"?: SpaceRule;\n  \"declaration-block-semicolon-space-before\"?: SpaceRule1;\n  \"declaration-block-single-line-max-declarations\"?: IntegerRule;\n  \"declaration-block-trailing-semicolon\"?: AlwaysNeverRule4;\n  [k: string]: unknown;\n}\nexport interface Font {\n  /**\n   * Specify whether or not quotation marks should be used around font family names\n   */\n  \"font-family-name-quotes\"?: (\n    | null\n    | (\n        | \"always-where-required\"\n        | \"always-where-recommended\"\n        | \"always-unless-keyword\"\n        | []\n      )\n    | [\n        (\n          | (\n              | \"always-where-required\"\n              | \"always-where-recommended\"\n              | \"always-unless-keyword\"\n              | {}\n            )\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always-where-required\"\n                | \"always-where-recommended\"\n                | \"always-unless-keyword\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n        (\n          | (\n              | \"always-where-required\"\n              | \"always-where-recommended\"\n              | \"always-unless-keyword\"\n              | {}\n            )\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always-where-required\"\n                | \"always-where-recommended\"\n                | \"always-unless-keyword\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\n                | \"always-where-required\"\n                | \"always-where-recommended\"\n                | \"always-unless-keyword\"\n                | []\n              )\n            | [\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always-where-required\"\n                        | \"always-where-recommended\"\n                        | \"always-unless-keyword\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always-where-required\"\n                        | \"always-where-recommended\"\n                        | \"always-unless-keyword\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always-where-required\"\n                            | \"always-where-recommended\"\n                            | \"always-unless-keyword\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\n              | \"always-where-required\"\n              | \"always-where-recommended\"\n              | \"always-unless-keyword\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\n              | \"always-where-required\"\n              | \"always-where-recommended\"\n              | \"always-unless-keyword\"\n              | []\n            )\n          | [\n              (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always-where-required\"\n                    | \"always-where-recommended\"\n                    | \"always-unless-keyword\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always-where-required\"\n                      | \"always-where-recommended\"\n                      | \"always-unless-keyword\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always-where-required\"\n                          | \"always-where-recommended\"\n                          | \"always-unless-keyword\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Require numeric or named (where possible) `font-weight` values. Also, when named values are expected, require only valid names\n   */\n  \"font-weight-notation\"?: (\n    | null\n    | (\"numeric\" | \"named-where-possible\" | [])\n    | [\n        ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n          (\n            | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) & string)\n            | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n          ) &\n          ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n          (\n            | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) & string)\n            | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n          ),\n        ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n          (\n            | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) & string)\n            | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n          ) &\n          ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n          (\n            | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) & string)\n            | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"numeric\" | \"named-where-possible\" | [])\n            | [\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                  (\n                    | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                        string)\n                    | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                  ) &\n                  ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                  (\n                    | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                        string)\n                    | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                  ),\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                  (\n                    | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                        string)\n                    | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                  ) &\n                  ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                  (\n                    | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                        string)\n                    | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"numeric\" | \"named-where-possible\" | [])\n          | [\n              ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ) &\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ),\n              ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ) &\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"numeric\" | \"named-where-possible\" | [])\n          | [\n              ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ) &\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ),\n              ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ) &\n                ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                (\n                  | (((\"numeric\" | \"named-where-possible\" | {}) | CoreRule) &\n                      string)\n                  | ((\"numeric\" | \"named-where-possible\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  [k: string]: unknown;\n}\nexport interface Function {\n  \"function-blacklist\"?: ArrayStringRule3;\n  \"function-calc-no-unspaced-operator\"?: BooleanRule10;\n  \"function-comma-newline-after\"?: NewlineRule4;\n  \"function-comma-newline-before\"?: NewlineRule5;\n  \"function-comma-space-after\"?: SpaceRule2;\n  \"function-comma-space-before\"?: SpaceRule3;\n  \"function-linear-gradient-no-nonstandard-direction\"?: BooleanRule11;\n  \"function-max-empty-lines\"?: IntegerRule1;\n  /**\n   * Specify lowercase or uppercase for function names\n   */\n  \"function-name-case\"?: (\n    | null\n    | (\"lower\" | \"upper\" | [])\n    | [\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ) &\n          ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ),\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ) &\n          ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"lower\" | \"upper\" | [])\n            | [\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ) &\n                  ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ),\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ) &\n                  ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"function-parentheses-newline-inside\"?: NewlineRule6;\n  \"function-parentheses-space-inside\"?: SpaceRule4;\n  \"function-url-data-uris\"?: AlwaysNeverRule5;\n  \"function-url-no-scheme-relative\"?: BooleanRule12;\n  \"function-url-quotes\"?: AlwaysNeverRule6;\n  \"function-url-scheme-whitelist\"?: ArrayStringRule4;\n  \"function-whitelist\"?: ArrayStringRule5;\n  \"function-whitespace-after\"?: AlwaysNeverRule7;\n  [k: string]: unknown;\n}\nexport interface GeneralSheet {\n  /**\n   * Specify indentation\n   */\n  indentation?: (\n    | (null | number)\n    | (\"tab\" | [])\n    | [number, ...number[]]\n    | [\n        (number | (\"tab\" | {}) | CoreRule) &\n          (\n            | ((number | (\"tab\" | {}) | CoreRule) & number)\n            | ((number | (\"tab\" | {}) | CoreRule) & string)\n            | (number | (\"tab\" | {}) | CoreRule)\n          ) &\n          (number | (\"tab\" | {}) | CoreRule) &\n          (\n            | ((number | (\"tab\" | {}) | CoreRule) & number)\n            | ((number | (\"tab\" | {}) | CoreRule) & string)\n            | (number | (\"tab\" | {}) | CoreRule)\n          ),\n        (number | (\"tab\" | {}) | CoreRule) &\n          (\n            | ((number | (\"tab\" | {}) | CoreRule) & number)\n            | ((number | (\"tab\" | {}) | CoreRule) & string)\n            | (number | (\"tab\" | {}) | CoreRule)\n          ) &\n          (number | (\"tab\" | {}) | CoreRule) &\n          (\n            | ((number | (\"tab\" | {}) | CoreRule) & number)\n            | ((number | (\"tab\" | {}) | CoreRule) & string)\n            | (number | (\"tab\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | (null | number)\n            | (\"tab\" | [])\n            | [number, ...number[]]\n            | [\n                (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ) &\n                  (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ),\n                (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ) &\n                  (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (number &\n          (\n            | (null | number)\n            | (\"tab\" | [])\n            | [number, ...number[]]\n            | [\n                (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ) &\n                  (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ),\n                (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ) &\n                  (number | (\"tab\" | {}) | CoreRule) &\n                  (\n                    | ((number | (\"tab\" | {}) | CoreRule) & number)\n                    | ((number | (\"tab\" | {}) | CoreRule) & string)\n                    | (number | (\"tab\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | (null | number)\n          | (\"tab\" | [])\n          | [number, ...number[]]\n          | [\n              (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ) &\n                (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ),\n              (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ) &\n                (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | (null | number)\n          | (\"tab\" | [])\n          | [number, ...number[]]\n          | [\n              (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ) &\n                (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ),\n              (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ) &\n                (number | (\"tab\" | {}) | CoreRule) &\n                (\n                  | ((number | (\"tab\" | {}) | CoreRule) & number)\n                  | ((number | (\"tab\" | {}) | CoreRule) & string)\n                  | (number | (\"tab\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * @deprecated\n   * Specify unix or windows linebreaks\n   */\n  linebreaks?: {\n    [k: string]: unknown;\n  };\n  \"max-empty-lines\"?: IntegerRule2;\n  /**\n   * Limit the length of a line\n   */\n  \"max-line-length\"?: (\n    | (null | number)\n    | [\n        (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)) &\n          (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)),\n        (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)) &\n          (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | (null | number)\n            | [\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n              ]\n          ))\n      | (number &\n          (\n            | (null | number)\n            | [\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n              ]\n          ))\n      | ((\n          | (null | number)\n          | [\n              (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)) &\n                (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)),\n              (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)) &\n                (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Limit the allowed nesting depth\n   */\n  \"max-nesting-depth\"?: (\n    | (null | number)\n    | [\n        (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)) &\n          (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)),\n        (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)) &\n          (number | CoreRule) &\n          (((number | CoreRule) & number) | (number | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | (null | number)\n            | [\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n              ]\n          ))\n      | (number &\n          (\n            | (null | number)\n            | [\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n                (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)) &\n                  (number | CoreRule) &\n                  (((number | CoreRule) & number) | (number | CoreRule)),\n              ]\n          ))\n      | ((\n          | (null | number)\n          | [\n              (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)) &\n                (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)),\n              (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)) &\n                (number | CoreRule) &\n                (((number | CoreRule) & number) | (number | CoreRule)),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Disallow browser hacks that are irrelevant to the browsers you are targeting\n   */\n  \"no-browser-hacks\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"no-descending-specificity\"?: BooleanRule13;\n  \"no-duplicate-selectors\"?: BooleanRule14;\n  /**\n   * @deprecated\n   * Disallow empty first lines\n   */\n  \"no-empty-first-line\"?: {\n    [k: string]: unknown;\n  };\n  \"no-empty-source\"?: BooleanRule15;\n  /**\n   * Disallow end-of-line whitespace\n   */\n  \"no-eol-whitespace\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"no-extra-semicolons\"?: BooleanRule16;\n  /**\n   * Disallow colors that are suspiciously close to being identical\n   */\n  \"no-indistinguishable-colors\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"no-invalid-double-slash-comments\"?: BooleanRule17;\n  \"no-missing-end-of-source-newline\"?: BooleanRule18;\n  \"no-unknown-animations\"?: BooleanRule19;\n  \"unicode-bom\"?: AlwaysNeverRule8;\n  /**\n   * Disallow features that are unsupported by the browsers that you are targeting\n   */\n  \"no-unsupported-browser-features\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  [k: string]: unknown;\n}\nexport interface KeyframeDeclaration {\n  \"keyframe-declaration-no-important\"?: BooleanRule20;\n  [k: string]: unknown;\n}\nexport interface Length {\n  \"length-zero-no-unit\"?: BooleanRule21;\n  [k: string]: unknown;\n}\nexport interface Lightness {\n  /**\n   * Specify number or percentage notation for lightness\n   */\n  \"lightness-notation\"?:\n    | ((\"percentage\" | \"number\") | null)\n    | [(\"percentage\" | \"number\") | null]\n    | [(\"percentage\" | \"number\") | null, CoreRule3];\n  [k: string]: unknown;\n}\nexport interface CoreRule3 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface MediaFeature {\n  \"media-feature-colon-space-after\"?: AlwaysNeverRule9;\n  \"media-feature-colon-space-before\"?: AlwaysNeverRule10;\n  \"media-feature-name-case\"?: LowerUpperRule2;\n  /**\n   * Disallow unknown media feature names\n   */\n  \"media-feature-name-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Disallow unknown values for media features\n   */\n  \"media-feature-name-value-no-unknown\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule4];\n  \"media-feature-name-no-vendor-prefix\"?: BooleanRule22;\n  /**\n   * Specify a list of allowed name and unit pairs within media features\n   */\n  \"media-feature-name-unit-allowed-list\"?:\n    | ({\n        [k: string]: string | string[];\n      } | null)\n    | [\n        {\n          [k: string]: string | string[];\n        } | null,\n      ]\n    | [\n        {\n          [k: string]: string | string[];\n        } | null,\n        CoreRule5,\n      ];\n  \"media-feature-no-missing-punctuation\"?: BooleanRule23;\n  \"media-feature-parentheses-space-inside\"?: AlwaysNeverRule11;\n  /**\n   * Specify context or prefix notation for media feature ranges\n   */\n  \"media-feature-range-notation\"?:\n    | ((\"prefix\" | \"context\") | null)\n    | [(\"prefix\" | \"context\") | null]\n    | [(\"prefix\" | \"context\") | null, CoreRule6];\n  \"media-feature-range-operator-space-after\"?: AlwaysNeverRule12;\n  \"media-feature-range-operator-space-before\"?: AlwaysNeverRule13;\n  [k: string]: unknown;\n}\nexport interface CoreRule4 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface CoreRule5 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface CoreRule6 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface MediaQuery {\n  /**\n   * Disallow invalid media queries\n   */\n  \"media-query-no-invalid\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule7];\n  [k: string]: unknown;\n}\nexport interface CoreRule7 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface MediaQueryList {\n  \"media-query-list-comma-newline-after\"?: NewlineRule7;\n  \"media-query-list-comma-newline-before\"?: NewlineRule8;\n  \"media-query-list-comma-space-after\"?: SpaceRule5;\n  \"media-query-list-comma-space-before\"?: SpaceRule6;\n  [k: string]: unknown;\n}\nexport interface Number {\n  \"number-leading-zero\"?: AlwaysNeverRule14;\n  \"number-max-precision\"?: IntegerRule3;\n  \"number-no-trailing-zeros\"?: BooleanRule24;\n  [k: string]: unknown;\n}\nexport interface Property {\n  \"property-blacklist\"?: ArrayStringRule6;\n  \"property-case\"?: LowerUpperRule3;\n  /**\n   * Disallow unknown properties\n   */\n  \"property-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"property-no-vendor-prefix\"?: BooleanRule25;\n  \"property-whitelist\"?: ArrayStringRule7;\n  [k: string]: unknown;\n}\nexport interface RootRule {\n  \"root-no-standard-properties\"?: BooleanRule26;\n  [k: string]: unknown;\n}\nexport interface Rule {\n  /**\n   * Require or disallow an empty line before nested rules\n   */\n  \"rule-nested-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n    | [\n        (\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n        (\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | []\n              )\n            | [\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Require or disallow an empty line before non-nested rules\n   */\n  \"rule-non-nested-empty-line-before\"?: (\n    | null\n    | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n    | [\n        (\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n        (\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | {})\n          | CoreRule\n        ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ) &\n          (\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | {}\n              )\n            | CoreRule\n          ) &\n          (\n            | ((\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                string)\n            | (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              )\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\n                | \"always\"\n                | \"never\"\n                | \"always-multi-line\"\n                | \"never-multi-line\"\n                | []\n              )\n            | [\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ) &\n                  (\n                    | (\n                        | \"always\"\n                        | \"never\"\n                        | \"always-multi-line\"\n                        | \"never-multi-line\"\n                        | {}\n                      )\n                    | CoreRule\n                  ) &\n                  (\n                    | ((\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      ) &\n                        string)\n                    | (\n                        | (\n                            | \"always\"\n                            | \"never\"\n                            | \"always-multi-line\"\n                            | \"never-multi-line\"\n                            | {}\n                          )\n                        | CoreRule\n                      )\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always\" | \"never\" | \"always-multi-line\" | \"never-multi-line\" | [])\n          | [\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n              (\n                | (\n                    | \"always\"\n                    | \"never\"\n                    | \"always-multi-line\"\n                    | \"never-multi-line\"\n                    | {}\n                  )\n                | CoreRule\n              ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ) &\n                (\n                  | (\n                      | \"always\"\n                      | \"never\"\n                      | \"always-multi-line\"\n                      | \"never-multi-line\"\n                      | {}\n                    )\n                  | CoreRule\n                ) &\n                (\n                  | ((\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    ) &\n                      string)\n                  | (\n                      | (\n                          | \"always\"\n                          | \"never\"\n                          | \"always-multi-line\"\n                          | \"never-multi-line\"\n                          | {}\n                        )\n                      | CoreRule\n                    )\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  [k: string]: unknown;\n}\nexport interface Selector {\n  /**\n   * Disallow unmatchable An+B selectors\n   */\n  \"selector-anb-no-unmatchable\"?:\n    | (true | null)\n    | [true | null]\n    | [true | null, CoreRule8];\n  \"selector-attribute-brackets-space-inside\"?: AlwaysNeverRule15;\n  \"selector-attribute-operator-blacklist\"?: ArrayStringRule8;\n  \"selector-attribute-operator-space-after\"?: AlwaysNeverRule16;\n  \"selector-attribute-operator-space-before\"?: AlwaysNeverRule17;\n  \"selector-attribute-operator-whitelist\"?: ArrayStringRule9;\n  \"selector-attribute-quotes\"?: AlwaysNeverRule18;\n  /**\n   * Specify a pattern for class selectors\n   */\n  \"selector-class-pattern\"?: (\n    | (null | string)\n    | [\n        (string | CoreRule) &\n          (((string | CoreRule) & string) | (string | CoreRule)) &\n          (string | CoreRule) &\n          (((string | CoreRule) & string) | (string | CoreRule)),\n        (string | CoreRule) &\n          (((string | CoreRule) & string) | (string | CoreRule)) &\n          (string | CoreRule) &\n          (((string | CoreRule) & string) | (string | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | (null | string)\n            | [\n                (string | CoreRule) &\n                  (((string | CoreRule) & string) | (string | CoreRule)) &\n                  (string | CoreRule) &\n                  (((string | CoreRule) & string) | (string | CoreRule)),\n                (string | CoreRule) &\n                  (((string | CoreRule) & string) | (string | CoreRule)) &\n                  (string | CoreRule) &\n                  (((string | CoreRule) & string) | (string | CoreRule)),\n              ]\n          ))\n      | ((\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ) &\n          string)\n      | ((\n          | (null | string)\n          | [\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n              (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)) &\n                (string | CoreRule) &\n                (((string | CoreRule) & string) | (string | CoreRule)),\n            ]\n        ) &\n          unknown[])\n    );\n  \"selector-combinator-space-after\"?: AlwaysNeverRule19;\n  \"selector-combinator-space-before\"?: AlwaysNeverRule20;\n  \"selector-descendant-combinator-no-non-space\"?: BooleanRule27;\n  \"selector-id-pattern\"?: StringRule2;\n  \"selector-max-compound-selectors\"?: IntegerRule4;\n  \"selector-max-specificity\"?: StringRule3;\n  \"selector-nested-pattern\"?: StringRule4;\n  \"selector-no-attribute\"?: BooleanRule28;\n  \"selector-no-combinator\"?: BooleanRule29;\n  \"selector-no-id\"?: BooleanRule30;\n  /**\n   * Disallow qualifying a selector by type\n   */\n  \"selector-no-qualifying-type\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  /**\n   * Disallow type selectors\n   */\n  \"selector-no-type\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"selector-no-universal\"?: BooleanRule31;\n  \"selector-no-vendor-prefix\"?: BooleanRule32;\n  \"selector-pseudo-class-case\"?: LowerUpperRule4;\n  /**\n   * Disallow unknown pseudo-class selectors\n   */\n  \"selector-pseudo-class-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"selector-pseudo-class-parentheses-space-inside\"?: AlwaysNeverRule21;\n  \"selector-pseudo-class-whitelist\"?: ArrayStringRule10;\n  \"selector-pseudo-element-case\"?: LowerUpperRule5;\n  \"selector-pseudo-element-colon-notation\"?: SingleDoubleRule;\n  /**\n   * Disallow unknown pseudo-element selectors\n   */\n  \"selector-pseudo-element-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"selector-root-no-composition\"?: BooleanRule33;\n  \"selector-type-case\"?: LowerUpperRule6;\n  /**\n   * Disallow unknown type selectors\n   */\n  \"selector-type-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"selector-max-empty-lines\"?: IntegerRule5;\n  [k: string]: unknown;\n}\nexport interface CoreRule8 {\n  disableFix?: boolean;\n  /**\n   * Custom message that will be used in errors and warnings\n   */\n  message?: string;\n  reportDisables?: boolean;\n  /**\n   * Message status\n   */\n  severity?: \"warning\" | \"error\";\n  url?: string;\n}\nexport interface SelectorList {\n  \"selector-list-comma-newline-after\"?: NewlineRule9;\n  \"selector-list-comma-newline-before\"?: NewlineRule10;\n  \"selector-list-comma-space-after\"?: SpaceRule7;\n  \"selector-list-comma-space-before\"?: SpaceRule8;\n  [k: string]: unknown;\n}\nexport interface ShorthandProperty {\n  \"shorthand-property-no-redundant-values\"?: BooleanRule34;\n  [k: string]: unknown;\n}\nexport interface String {\n  \"string-no-newline\"?: BooleanRule35;\n  \"string-quotes\"?: SingleDoubleRule1;\n  [k: string]: unknown;\n}\nexport interface StylelintDisableComment {\n  /**\n   * Require a reason comment before or after `stylelint-disable` comments\n   */\n  \"stylelint-disable-reason\"?: (\n    | null\n    | (\"always-before\" | \"always-after\" | [])\n    | [\n        ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n          (\n            | (((\"always-before\" | \"always-after\" | {}) | CoreRule) & string)\n            | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n          ) &\n          ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n          (\n            | (((\"always-before\" | \"always-after\" | {}) | CoreRule) & string)\n            | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n          ),\n        ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n          (\n            | (((\"always-before\" | \"always-after\" | {}) | CoreRule) & string)\n            | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n          ) &\n          ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n          (\n            | (((\"always-before\" | \"always-after\" | {}) | CoreRule) & string)\n            | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"always-before\" | \"always-after\" | [])\n            | [\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                  ),\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                  ) &\n                  ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                  (\n                    | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                        string)\n                    | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"always-before\" | \"always-after\" | [])\n          | [\n              ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ) &\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ),\n              ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ) &\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"always-before\" | \"always-after\" | [])\n          | [\n              ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ) &\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ),\n              ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ) &\n                ((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                (\n                  | (((\"always-before\" | \"always-after\" | {}) | CoreRule) &\n                      string)\n                  | ((\"always-before\" | \"always-after\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  [k: string]: unknown;\n}\nexport interface Time {\n  \"time-no-imperceptible\"?: BooleanRule36;\n  [k: string]: unknown;\n}\nexport interface Unit {\n  \"unit-blacklist\"?: UnitRule;\n  \"unit-case\"?: LowerUpperRule7;\n  /**\n   * Disallow unknown units\n   */\n  \"unit-no-unknown\"?: (\n    | null\n    | (true | [])\n    | [\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n        ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)) &\n          ((true | {}) | CoreRule) &\n          ((((true | {}) | CoreRule) & boolean) | ((true | {}) | CoreRule)),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | (boolean &\n          (\n            | null\n            | (true | [])\n            | [\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n                ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ) &\n                  ((true | {}) | CoreRule) &\n                  (\n                    | (((true | {}) | CoreRule) & boolean)\n                    | ((true | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (true | [])\n          | [\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n              ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ) &\n                ((true | {}) | CoreRule) &\n                (\n                  | (((true | {}) | CoreRule) & boolean)\n                  | ((true | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"unit-whitelist\"?: UnitRule1;\n  [k: string]: unknown;\n}\nexport interface Value {\n  /**\n   * Specify lowercase or uppercase for keywords values\n   */\n  \"value-keyword-case\"?: (\n    | null\n    | (\"lower\" | \"upper\" | [])\n    | [\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ) &\n          ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ),\n        ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ) &\n          ((\"lower\" | \"upper\" | {}) | CoreRule) &\n          (\n            | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n            | ((\"lower\" | \"upper\" | {}) | CoreRule)\n          ),\n      ]\n  ) &\n    (\n      | (null &\n          (\n            | null\n            | (\"lower\" | \"upper\" | [])\n            | [\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ) &\n                  ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ),\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ) &\n                  ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                  (\n                    | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                    | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                  ),\n              ]\n          ))\n      | ((\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          string)\n      | ((\n          | null\n          | (\"lower\" | \"upper\" | [])\n          | [\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n              ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ) &\n                ((\"lower\" | \"upper\" | {}) | CoreRule) &\n                (\n                  | (((\"lower\" | \"upper\" | {}) | CoreRule) & string)\n                  | ((\"lower\" | \"upper\" | {}) | CoreRule)\n                ),\n            ]\n        ) &\n          unknown[])\n    );\n  \"value-no-vendor-prefix\"?: BooleanRule37;\n  [k: string]: unknown;\n}\nexport interface ValueList {\n  \"value-list-comma-newline-after\"?: NewlineRule11;\n  \"value-list-comma-newline-before\"?: NewlineRule12;\n  \"value-list-comma-space-after\"?: SpaceRule9;\n  \"value-list-comma-space-before\"?: SpaceRule10;\n  \"value-list-max-empty-lines\"?: IntegerRule6;\n  [k: string]: unknown;\n}\n/**\n * Configuration Schema for the JavaScript test runner AVA\n */\nexport interface AVAConfigSchema {\n  files?: ArrayOfPaths;\n  ignoredByWatcher?: ArrayOfPaths1;\n  match?: ArrayOfPaths2;\n  /**\n   * Defaults to `true` to cache compiled files under `node_modules/.cache/ava.` If `false`, files are cached in a temporary directory instead\n   */\n  cache?: boolean;\n  /**\n   * Max number of test files running at the same time (default: CPU cores)\n   */\n  concurrency?: number;\n  /**\n   * Use worker threads to run tests (enabled by default). If `false`, tests will run in child processes\n   */\n  workerThreads?: boolean;\n  /**\n   * Stop running further tests once a test fails\n   */\n  failFast?: boolean;\n  /**\n   * If `false`, does not fail a test if it doesn't run assertions\n   */\n  failWithoutAssertions?: boolean;\n  environmentVariables?: EnvironmentVariables;\n  /**\n   * if `true`, prevents parallel execution of tests within a file\n   */\n  serial?: boolean;\n  /**\n   * If `true`, enables the TAP reporter\n   */\n  tap?: boolean;\n  /**\n   * If `true`, enables verbose output (though currently non-verbose output is not supported)\n   */\n  verbose?: boolean;\n  /**\n   * Specifies a fixed location for storing snapshot files. Use this if your snapshots are ending up in the wrong location\n   */\n  snapshotDir?: string;\n  /**\n   * Extensions of test files. Setting this overrides the default `[\"cjs\", \"mjs\", \"js\"]` value, so make sure to include those extensions in the list. Experimentally you can configure how files are loaded\n   */\n  extensions?: ArrayOfStrings | Extensions;\n  require?: ArrayOfPaths3;\n  /**\n   * Timeouts in AVA behave differently than in other test frameworks. AVA resets a timer after each test, forcing tests to quit if no new test results were received within the specified timeout. This can be used to handle stalled tests. See our timeout documentation for more options\n   */\n  timeout?: number | string;\n  nodeArguments?: ArrayOfStrings1;\n  /**\n   * If `false`, disable parallel builds (default: `true`)\n   */\n  utilizeParallelBuilds?: boolean;\n  typescript?: Configuration;\n}\n/**\n * Specifies environment variables to be made available to the tests. The environment variables defined here override the ones from `process.env`\n */\nexport interface EnvironmentVariables {\n  [k: string]: string;\n}\nexport interface Extensions {\n  [k: string]: \"commonjs\" | \"module\";\n}\n/**\n * Configures @ava/typescript for projects that precompile TypeScript. Alternatively, you can use `ts-node` to do live testing without transpiling, in which case you shouldn't use the `typescript` property\n */\nexport interface Configuration {\n  extensions?: ArrayOfPaths4;\n  rewritePaths?: Paths;\n  /**\n   * If `false`, AVA will assume you have already compiled your project. If set to `'tsc'`, AVA will run the TypeScript compiler before running your tests. This can be inefficient when using AVA in watch mode\n   */\n  compile?: false | \"tsc\";\n  [k: string]: unknown;\n}\n/**\n * AVA searches your entire project for `*.js`, `*.cjs`, `*.mjs` and `*.ts` files (or other extensions you've configured). It will ignore such files found in the `rewritePaths` targets (e.g. `build/`). If you use more specific paths, for instance `build/main/`, you may need to change AVA's `files` configuration to ignore other directories. Paths are relative to your project directory\n */\nexport interface Paths {\n  /**\n   * This interface was referenced by `Paths`'s JSON-Schema definition\n   * via the `patternProperty` \"/$\".\n   */\n  [k: string]: string;\n}\nexport interface SemanticReleaseSchema {\n  /**\n   * List of modules or file paths containing a shareable configuration. If multiple shareable configurations are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration\n   */\n  extends?: string | string[];\n  /**\n   * The branches on which releases should happen.\n   */\n  branches?: string | BranchObject | (string | BranchObject)[];\n  /**\n   * The git repository URL\n   */\n  repositoryUrl?: string;\n  /**\n   * The Git tag format used by semantic-release to identify releases. The tag name is generated with Lodash template and will be compiled with the version variable.\n   */\n  tagFormat?: string;\n  /**\n   * Define the list of plugins to use. Plugins will run in series, in the order defined\n   */\n  plugins?: (string | unknown[])[];\n  /**\n   * The objective of the dry-run mode is to get a preview of the pending release. Dry-run mode skips the following steps: prepare, publish, success and fail. In addition to this it prints the next version and release notes to the console\n   */\n  dryRun?: boolean;\n  /**\n   * Set to false to skip Continuous Integration environment verifications. This allows for making releases from a local machine\n   */\n  ci?: boolean;\n  [k: string]: unknown;\n}\nexport interface BranchObject {\n  name: string;\n  channel?: string;\n  range?: string;\n  prerelease?: boolean | string;\n}\nexport interface HttpsJsonSchemastoreOrgJscpdJson {\n  /**\n   * minimum size of code block in lines to check for duplication\n   */\n  minLines?: number;\n  /**\n   * maximum size of source file in lines to check for duplication\n   */\n  maxLines?: number;\n  /**\n   * maximum size of source file in bytes to check for duplication (e.g.,: 1kb, 1mb, 120kb)\n   */\n  maxSize?: string | number;\n  /**\n   * minimum size of code block in tokens to check for duplication\n   */\n  minTokens?: number;\n  /**\n   * maximum allowed duplicate lines expressed as a percentage; exit with error and exit code 1 when threshold exceeded\n   */\n  threshold?: number;\n  /**\n   * custom mapping from formats to file extensions (default: https://github.com/kucherenko/jscpd/blob/master/packages/tokenizer/src/formats.ts); see https://github.com/kucherenko/jscpd/blob/master/supported_formats.md\n   */\n  formatsExts?: {\n    [k: string]: string[];\n  };\n  /**\n   * path to directory for non-console reports\n   */\n  output?: string;\n  /**\n   * paths that should be included in duplicate detection (default: [process.cwd()])\n   */\n  path?: string[];\n  /**\n   * glob pattern for files that should be included in duplicate detection (e.g., \\*_ /_.txt); only used to filter directories configured via path option\n   */\n  pattern?: string;\n  /**\n   * ignore code blocks matching these regular expressions\n   */\n  ignorePattern?: string[];\n  /**\n   * mode of detection quality; see https://github.com/kucherenko/jscpd/blob/master/packages/jscpd/README.md#mode\n   */\n  mode?: \"mild\" | \"strict\" | \"weak\";\n  /**\n   * glob pattern for files that should be excluded from duplicate detection\n   */\n  ignore?: string[];\n  /**\n   * list of formats for which to detect duplication (default: all); see https://github.com/kucherenko/jscpd/blob/master/supported_formats.md\n   */\n  format?: (\n    | \"abap\"\n    | \"actionscript\"\n    | \"ada\"\n    | \"apacheconf\"\n    | \"apl\"\n    | \"applescript\"\n    | \"arduino\"\n    | \"arff\"\n    | \"asciidoc\"\n    | \"asm6502\"\n    | \"aspnet\"\n    | \"autohotkey\"\n    | \"autoit\"\n    | \"bash\"\n    | \"basic\"\n    | \"batch\"\n    | \"bison\"\n    | \"brainfuck\"\n    | \"bro\"\n    | \"c\"\n    | \"c-header\"\n    | \"clike\"\n    | \"clojure\"\n    | \"coffeescript\"\n    | \"comments\"\n    | \"cpp\"\n    | \"cpp-header\"\n    | \"crystal\"\n    | \"csharp\"\n    | \"csp\"\n    | \"css-extras\"\n    | \"css\"\n    | \"d\"\n    | \"dart\"\n    | \"diff\"\n    | \"django\"\n    | \"docker\"\n    | \"eiffel\"\n    | \"elixir\"\n    | \"elm\"\n    | \"erb\"\n    | \"erlang\"\n    | \"flow\"\n    | \"fortran\"\n    | \"fsharp\"\n    | \"gedcom\"\n    | \"gherkin\"\n    | \"git\"\n    | \"glsl\"\n    | \"go\"\n    | \"graphql\"\n    | \"groovy\"\n    | \"haml\"\n    | \"handlebars\"\n    | \"haskell\"\n    | \"haxe\"\n    | \"hpkp\"\n    | \"hsts\"\n    | \"http\"\n    | \"ichigojam\"\n    | \"icon\"\n    | \"inform7\"\n    | \"ini\"\n    | \"io\"\n    | \"j\"\n    | \"java\"\n    | \"javascript\"\n    | \"jolie\"\n    | \"json\"\n    | \"jsx\"\n    | \"julia\"\n    | \"keymap\"\n    | \"kotlin\"\n    | \"latex\"\n    | \"less\"\n    | \"liquid\"\n    | \"lisp\"\n    | \"livescript\"\n    | \"lolcode\"\n    | \"lua\"\n    | \"makefile\"\n    | \"markdown\"\n    | \"markup\"\n    | \"matlab\"\n    | \"mel\"\n    | \"mizar\"\n    | \"monkey\"\n    | \"n4js\"\n    | \"nasm\"\n    | \"nginx\"\n    | \"nim\"\n    | \"nix\"\n    | \"nsis\"\n    | \"objectivec\"\n    | \"ocaml\"\n    | \"opencl\"\n    | \"oz\"\n    | \"parigp\"\n    | \"pascal\"\n    | \"perl\"\n    | \"php\"\n    | \"plsql\"\n    | \"powershell\"\n    | \"processing\"\n    | \"prolog\"\n    | \"properties\"\n    | \"protobuf\"\n    | \"pug\"\n    | \"puppet\"\n    | \"pure\"\n    | \"python\"\n    | \"q\"\n    | \"qore\"\n    | \"r\"\n    | \"reason\"\n    | \"renpy\"\n    | \"rest\"\n    | \"rip\"\n    | \"roboconf\"\n    | \"ruby\"\n    | \"rust\"\n    | \"sas\"\n    | \"sass\"\n    | \"scala\"\n    | \"scheme\"\n    | \"scss\"\n    | \"smalltalk\"\n    | \"smarty\"\n    | \"soy\"\n    | \"sql\"\n    | \"stylus\"\n    | \"swift\"\n    | \"tap\"\n    | \"tcl\"\n    | \"textile\"\n    | \"tsx\"\n    | \"tt2\"\n    | \"twig\"\n    | \"typescript\"\n    | \"vbnet\"\n    | \"velocity\"\n    | \"verilog\"\n    | \"vhdl\"\n    | \"vim\"\n    | \"visual-basic\"\n    | \"wasm\"\n    | \"url\"\n    | \"wiki\"\n    | \"xeora\"\n    | \"xojo\"\n    | \"xquery\"\n    | \"yaml\"\n  )[];\n  /**\n   * store used to collect information about code (default: in-memory store); install @jscpd/leveldb-store and use leveldb for big repositories\n   */\n  store?: \"leveldb\" | \"redis\";\n  /**\n   * a list of reporters to use to output information about duplication; see https://github.com/kucherenko/jscpd/blob/master/packages/jscpd/README.md#reporters\n   */\n  reporters?: (\n    | \"xml\"\n    | \"json\"\n    | \"csv\"\n    | \"markdown\"\n    | \"consoleFull\"\n    | \"html\"\n    | \"console\"\n    | \"silent\"\n    | \"threshold\"\n    | \"xcode\"\n  )[];\n  /**\n   * get information about authors and dates of duplicated blocks from Git\n   */\n  blame?: boolean;\n  /**\n   * do not write duplicate detection progress and result to console\n   */\n  silent?: boolean;\n  /**\n   * show full information during duplicate detection\n   */\n  verbose?: boolean;\n  /**\n   * use absolute paths in reports\n   */\n  absolute?: boolean;\n  /**\n   * do not follow symlinks\n   */\n  noSymlinks?: boolean;\n  /**\n   * skip duplicates within folders; just detect cross-folder duplicates\n   */\n  skipLocal?: boolean;\n  /**\n   * ignore case of symbols in code (experimental)\n   */\n  ignoreCase?: boolean;\n  /**\n   * ignore all files from .gitignore file\n   */\n  gitignore?: boolean;\n  reportersOptions?: {\n    badge?: {\n      /**\n       * output path for duplication level badge (default: path.join(output, 'jscpd-badge.svg'))\n       */\n      path?: string;\n      /**\n       * badge subject text (URL-encoding needed for spaces or special characters)\n       */\n      label?: string;\n      /**\n       * badge label color (name or RGB code without #); see https://github.com/badgen/badgen/blob/master/src/color-presets.ts\n       */\n      labelColor?:\n        | (\n            | \"green\"\n            | \"blue\"\n            | \"red\"\n            | \"yellow\"\n            | \"orange\"\n            | \"purple\"\n            | \"pink\"\n            | \"grey\"\n            | \"gray\"\n            | \"cyan\"\n            | \"black\"\n          )\n        | string;\n      /**\n       * badge value text (URL-encoding needed for spaces or special characters, default: duplication %)\n       */\n      status?: string;\n      /**\n       * badge color (name or RGB code without #, default: green if beneath threshold, red if above threshold, grey if threshold not set); see https://github.com/badgen/badgen/blob/master/src/color-presets.ts\n       */\n      color?:\n        | (\n            | \"green\"\n            | \"blue\"\n            | \"red\"\n            | \"yellow\"\n            | \"orange\"\n            | \"purple\"\n            | \"pink\"\n            | \"grey\"\n            | \"gray\"\n            | \"cyan\"\n            | \"black\"\n          )\n        | string;\n      /**\n       * badge look: flat or classic\n       */\n      style?: \"flat\" | \"classic\";\n      /**\n       * URL for icon to display in front of badge subject text (e.g., data:image/svg+xml;base64,...)\n       */\n      icon?: string;\n      /**\n       * SVG width of icon to display in front of badge subject text; set this if icon is not square\n       */\n      iconWidth?: number;\n      /**\n       * size of badge relative to default of 1\n       */\n      scale?: number;\n    };\n  };\n  /**\n   * exit code to use when at least one duplicate code block is detected but threshold is not exceeded\n   */\n  exitCode?: number;\n}\n"
  },
  {
    "path": "config/size-limit/index.js",
    "content": "// @ts-check\n\nimport { mkdir, symlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * @typedef Config\n * @property {string} cwd\n * @property {string} configPath\n * @property {boolean} why\n * @property {string} saveBundle\n * @property {boolean} cleanDir\n * @property {Check[]} checks\n */\n\n/** @typedef {import('size-limit').Check} Check */\n\n/**\n * @typedef EsbuildCheck\n * @property {string} esbuildOutfile\n */\n\nexport default {\n  name: \"size-limit-apollo-plugin\",\n  async before(/** @type {Config} */ config) {\n    const originalChecks = /** @type {Check[]} */ (\n      (await import(join(config.cwd, config.configPath))).default\n    );\n\n    for (const i in originalChecks) {\n      // undo all the resolution logic going on in https://github.com/ai/size-limit/blob/058b1f132c4e51272e94e9d3650e480b3e0d6851/packages/size-limit/get-config.js#L217-L228\n      config.checks[i].import = originalChecks[i].import;\n    }\n  },\n  async step21(\n    /** @type {Config} */ config,\n    /** @type {Check & EsbuildCheck} */ check\n  ) {\n    await mkdir(join(check.esbuildOutfile, \"node_modules\", \"@apollo\"), {\n      recursive: true,\n    });\n    await symlink(\n      join(config.cwd, \"dist\"),\n      join(check.esbuildOutfile, \"node_modules\", \"@apollo\", \"client\")\n    );\n  },\n};\n"
  },
  {
    "path": "config/size-limit/package.json",
    "content": "{\n  \"name\": \"size-limit-apollo-plugin\",\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": \"./index.js\",\n    \"./package.json\": \"./package.json\"\n  }\n}\n"
  },
  {
    "path": "config/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"outDir\": \".ignore\",\n    \"target\": \"esnext\",\n    \"module\": \"nodenext\",\n    \"allowJs\": true,\n    \"allowImportingTsExtensions\": true,\n    \"rewriteRelativeImportExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"./**/*.ts\", \"./**/*.cts\", \"./**/*.cjs\"]\n}\n"
  },
  {
    "path": "config/verifySourceMaps.ts",
    "content": "import * as assert from \"node:assert\";\nimport { glob, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { SourceMapConsumer } from \"source-map\";\nimport validate from \"sourcemap-validator\";\n\nimport type { BuildStep } from \"./build.ts\";\n\nexport const verifySourceMaps: BuildStep = async (options) => {\n  // this only checks source maps for JavaScript files, not TypeScript declarations\n  // as we won't ship declaration maps in the end\n  for await (const file of glob(`${options.targetDir}/**/*.{js,cjs}`, {\n    withFileTypes: true,\n    exclude(fileName) {\n      return fileName.parentPath.indexOf(\"legacyEntryPoints\") !== -1;\n    },\n  })) {\n    const filePath = join(file.parentPath, file.name);\n    const distFileContents = await readFile(filePath, \"utf-8\");\n\n    if (isEmptyFile(distFileContents)) {\n      continue;\n    }\n\n    const sourceMapPath = filePath + \".map\";\n    const rawSourceMap = await readFile(sourceMapPath, \"utf-8\");\n    const sourceMap = JSON.parse(rawSourceMap);\n    const parsed = new SourceMapConsumer(sourceMap);\n\n    const originalFileName = sourceMap.sources[0];\n    if (!originalFileName) {\n      // a generated file\n      continue;\n    }\n    const originalFilePath = join(file.parentPath, originalFileName);\n    const originalFileContents = await readFile(originalFilePath, \"utf-8\");\n    const parsedContents = parsed.sourceContentFor(originalFileName, true);\n\n    assert.notEqual(\n      parsedContents,\n      null,\n      `No original contents for ${originalFileName} found in ${sourceMapPath}`\n    );\n\n    assert.equal(\n      parsed.sourceContentFor(originalFileName, true),\n      originalFileContents,\n      `Original file contents in source map for ${originalFileName} do not match actual file contents`\n    );\n\n    // sourcemap-validator really just does a basic sanity check,\n    // it doesn't actually compare the original file contents\n    // or anything like that - but it's the best tool I could find.\n    validate(\n      await readFile(filePath, { encoding: \"utf-8\" }),\n      await readFile(filePath + \".map\", { encoding: \"utf-8\" }),\n      {\n        [originalFileName]: originalFileContents,\n      }\n    );\n  }\n};\n\nfunction isEmptyFile(file: string) {\n  return (\n    file.split(\"\\n\").filter(\n      (line) =>\n        // skip a few things that TypeScript adds on transpilation, even to an empty file\n        line.trim() !== `\"use strict\";` &&\n        line.trim() !== `export {};` &&\n        line.trim() !==\n          `Object.defineProperty(exports, \"__esModule\", { value: true });` &&\n        !line.trim().startsWith(`//# sourceMappingURL=`) &&\n        line.trim() !== \"\"\n    ).length === 0\n  );\n}\n"
  },
  {
    "path": "config/version.ts",
    "content": "import assert from \"node:assert\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\n\nimport { visit } from \"recast\";\n\nimport pkgJson from \"../package.json\" with { type: \"json\" };\n\nimport type { BuildStep } from \"./build.ts\";\nimport { applyRecast } from \"./helpers.ts\";\n\nconst require = createRequire(import.meta.url);\n\nconst { version } = pkgJson;\nassert.strictEqual(\n  typeof version,\n  \"string\",\n  '\"version\" field missing from package.json'\n);\n\nexport const updateVersion: BuildStep = async (options) => {\n  await applyRecast({\n    glob: `version.${options.jsExt}`,\n    cwd: options.targetDir,\n    transformStep({ ast }) {\n      return {\n        ast: visit(ast, {\n          visitStringLiteral(path) {\n            const node = path.node;\n            if (node.value === \"local\") {\n              node.value = version;\n            }\n            if (node.value === \"source\") {\n              node.value = options.type;\n            }\n            this.traverse(path);\n          },\n        }),\n      };\n    },\n  });\n};\n\nexport const verifyVersion: BuildStep = async (options) => {\n  const { ApolloClient, InMemoryCache } = require(\n    path.join(\n      options.rootDir,\n      options.targetDir,\n      \"core\",\n      `index.${options.jsExt}`\n    )\n  );\n\n  // Though this may seem like overkill, verifying that ApolloClient is\n  // constructible in Node.js is actually pretty useful, too!\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n  });\n\n  // Probably not necessary, but it seems wise to clean up any resources\n  // the client might have acquired during its construction.\n  client.stop();\n\n  // The CommonJS dist/core/core.cjs file is generated from ESM modules\n  // generated by tsc, including dist/version.js, so verifying core.cjs\n  // exports an ApolloClient class that defines client.version also serves to\n  // verify that dist/version.js must have been correctly updated, which is\n  // convenient because dist/version.js uses ECMAScript module syntax, and is\n  // thus not importable in all versions of Node.js.\n  assert.strictEqual(\n    client.version,\n    version,\n    \"Failed to update dist/version.js and dist/core/core.cjs\"\n  );\n};\n"
  },
  {
    "path": "docs/README.md",
    "content": "# Documentation\n\nThis is the documentation **source** for this repository.\n\nThe **deployed** version of the documentation for this repository is available at:\n\n- https://www.apollographql.com/docs/react/\n\nFor general local installation and development instructions, see the [docs site README](https://github.com/apollographql/docs).\n\nIn order to build and develop the Apollo Client docs locally, you will need to follow these additional steps:\n\n1. Clone the docs site repository ([https://github.com/apollographql/docs](https://github.com/apollographql/docs)) in a sibling directory to your local copy of the [`apollo-client`](https://github.com/apollographql/apollo-client) repository.\n2. `cd docs && npm i`\n3. Open a new terminal, `cd apollo-client`, make changes to the docs and run `npm run docmodel`\n4. Back in the terminal window where you've checked out and cd'd into the `docs` repository, run `DOCS_MODE='local' npm run start:local -- ../apollo-client`\n5. Open a browser and visit `http://localhost:3000`\n6. Note: you'll need to manually remove the `/react` segment of the URL from the path inside the browser\n"
  },
  {
    "path": "docs/shared/MdxProvidedComponents.ts",
    "content": "import type * as React from \"react\";\n\ndeclare module \"react\" {\n  namespace React {\n    interface HTMLAttributes<T> {\n      class?: string | undefined;\n    }\n  }\n}\n\n/**\n * The `summary`, `remarks`, `example`, and `deprecated` sections reference their respective sections in the DocBlock.\n */\ndeclare const DocBlock: React.FC<{\n  /** canonical reference for the content displayed by this component */\n  canonicalReference: string;\n  /** defaults to `true`, can be set to `false` to hide the summary section */\n  summary?: boolean;\n  /** defaults to `false`, can be set to `show` to show the remarks section */\n  remarks?: boolean;\n  /** defaults to `false`, can be set to `true` to show the example section */\n  example?: boolean;\n  /** defaults to `false`, can be set to `true` to make the `remarks` section collapsible */\n  remarksCollapsible?: boolean;\n  /** defaults to `false`, can be set to `true` to information about deprecation status */\n  deprecated?: boolean;\n  /** defaults to `false`, can be set to `true` to include a <MinVersion> tag */\n  releaseTag?: boolean;\n  /** provides a custom order to render each section */\n  customOrder?: Array<\n    \"summary\" | \"remarks\" | \"example\" | \"deprecated\" | \"releaseTag\"\n  >;\n}>;\ndeclare const Example: React.FC<{\n  /** canonical reference for the content displayed by this component */\n  canonicalReference: string;\n  collapsible?: boolean | undefined;\n  /** describes the nesting depth of the main heading for the markdown generated by this codeblock */\n  headingLevel?: number | undefined;\n  index?: number | undefined;\n}>;\n/**\n * This tag will create documentation like this:\n *\n * ````md\n * ### getCurrentResult\n *\n *   <DocBlock deprecated remarks releaseTag />\n *   #### Example (if available in the DocBlock)\n *   ```ts\n *   [example code here]\n *   ```\n *   #### Signature\n *   ```ts\n *   [the function signature here]\n *   ```\n *   #### Parameters\n *   [a table of parameters with types and descriptions]\n *   #### Result\n *   [the type of the result]\n * ````\n */\ndeclare const FunctionDetails: React.FC<{\n  /** canonical reference of the DocBlock to include. */\n  canonicalReference: string;\n  /** can be used to override the heading, which would usually just be the name of the function. This is useful if the interface name only makes sense in the context of a class, such as `client.refetchResult` or `ApolloClient.refetchResult` instead of `refetchResult`, which would be too generic */\n  displayName?: string;\n  /** describes the nesting depth of the main heading for the markdown generated by this codeblock */\n  headingLevel: number;\n  /** can be set to `false` to hide the result and parameters sections in the generated Docs page - this is useful if the parameters are not well documented */\n  parameters?: boolean;\n  /** can be set to `false` to hide the result and parameters sections in the generated Docs page - this is useful if the parameters are not well documented */\n  result?: boolean;\n  /** can be used to override the autogenerated rendered content of the `result` section */\n  children?: React.ReactNode;\n}>;\ndeclare const InterfaceDetails: React.FC<{\n  /** canonical reference for the content displayed by this component */\n  canonicalReference: string;\n  /** describes the nesting depth of the main heading for the markdown generated by this codeblock */\n  headingLevel: number;\n  /** an array of property names that should be displayed in the order they are defined, instead of the default alphabetical order */\n  customPropertyOrder?: string[];\n  /** can be used to override the heading, which would usually just be the name of the interface. This is useful if the interface name only makes sense in the context of a namespace, such as `useQuery.Result` instead of `Result`, which would be too generic */\n  displayName?: string;\n}>;\ndeclare const PropertySignatureTable: React.FC<{\n  /** canonical reference for the content displayed by this component */\n  canonicalReference: string;\n  idPrefix: string;\n  prefix?: string | undefined;\n  customOrder?: string[] | undefined;\n  display?: \"parent\" | \"child\" | undefined;\n  showHeaders?: boolean | undefined;\n  genericNames?: string[] | undefined;\n}>;\ndeclare const EnumDetails: React.FC<{\n  /** canonical reference for the content displayed by this component */\n  canonicalReference: string;\n  /** describes the nesting depth of the main heading for the markdown generated by this codeblock */\n  headingLevel: number;\n}>;\ndeclare const ExpansionPanel: React.FC<\n  React.PropsWithChildren<{\n    title?: string | undefined;\n    trackingId?: string | undefined;\n    isPrimary?: boolean | undefined;\n  }>\n>;\ndeclare const Tip: React.FC<React.PropsWithChildren<{}>>;\ndeclare const Caution: React.FC<React.PropsWithChildren<{}>>;\ndeclare const Note: React.FC<\n  React.PropsWithChildren<{\n    title?: string | undefined;\n  }>\n>;\ndeclare const MinVersion: React.FC<\n  React.PropsWithChildren<{\n    version: string;\n  }>\n>;\ndeclare const MultiCodeBlock: React.FC<React.PropsWithChildren<{}>>;\n\ndeclare const ManualTupleItem: React.FC<\n  React.PropsWithChildren<{\n    name: string;\n    type: string;\n    idPrefix?: string;\n  }>\n>;\ndeclare const ManualTuple: React.FC<React.PropsWithChildren>;\ndeclare const Remarks: React.FC<{\n  itemJson: string;\n  canonicalReference: string;\n  summary?: boolean | undefined;\n  releaseTag?: boolean | undefined;\n  remarks?: boolean | undefined;\n  example?: boolean | undefined;\n  remarksCollapsible?: boolean | undefined;\n  deprecated?: boolean | undefined;\n}>;\ndeclare const YouTube: React.FC<{\n  youTubeId: string;\n}>;\ndeclare const ButtonLink: React.FC<{\n  href: string;\n  style?: any;\n  size?: string | undefined;\n  colorScheme?: string | undefined;\n}>;\ntype AllComponents = {\n  DocBlock: typeof DocBlock;\n  Example: typeof Example;\n  FunctionDetails: typeof FunctionDetails;\n  InterfaceDetails: typeof InterfaceDetails;\n  PropertySignatureTable: typeof PropertySignatureTable;\n  EnumDetails: typeof EnumDetails;\n  ExpansionPanel: typeof ExpansionPanel;\n  Tip: typeof Tip;\n  Caution: typeof Caution;\n  Note: typeof Note;\n  MinVersion: typeof MinVersion;\n  MultiCodeBlock: typeof MultiCodeBlock;\n  ManualTupleItem: typeof ManualTupleItem;\n  ManualTuple: typeof ManualTuple;\n  Remarks: typeof Remarks;\n  YouTube: typeof YouTube;\n  ClientPQIntro: React.FC;\n  ClientPQDifferences: React.FC;\n  ClientPQImplementation: React.FC;\n  PublishPQMs: React.FC;\n  ButtonLink: typeof ButtonLink;\n};\n\nexport type { AllComponents as MDXProvidedComponents };\ndeclare global {\n  type MDXProvidedComponents = AllComponents;\n}\n"
  },
  {
    "path": "docs/source/_sidebar.yaml",
    "content": "switcher:\n  heading: \"Apollo Client (Web)\"\n  versions:\n    - label: v4\n      latest: true\n      href: ./\n    - label: v3\n      href: ./v3\n    - label: v2\n      href: ./v2\nitems:\n  - label: Introduction\n    href: \".\"\n  - label: Why Apollo Client?\n    href: ./why-apollo\n  - label: Get started\n    href: ./get-started\n  - label: Core concepts\n    children:\n      - label: Queries\n        href: ./data/queries\n      - label: Suspense\n        href: ./data/suspense\n      - label: Fragments\n        href: ./data/fragments\n      - label: Mutations\n        href: ./data/mutations\n      - label: TypeScript\n        href: ./data/typescript\n      - label: Refetching\n        href: ./data/refetching\n      - label: Subscriptions\n        href: ./data/subscriptions\n      - label: Directives\n        href: ./data/directives\n      - label: Error handling\n        href: ./data/error-handling\n      - label: Persisted queries\n        href: ./data/persisted-queries\n      - label: Document transforms\n        href: ./data/document-transforms\n      - label: Deferring response data\n        href: ./data/defer\n      - label: Best practices\n        href: ./data/operation-best-practices\n  - label: Caching\n    children:\n      - label: Overview\n        href: ./caching/overview\n      - label: Configuration\n        href: ./caching/cache-configuration\n      - label: Reading and writing\n        href: ./caching/cache-interaction\n      - label: Garbage collection and eviction\n        href: ./caching/garbage-collection\n      - label: Customizing field behavior\n        href: ./caching/cache-field-behavior\n      - label: Memory Management\n        href: ./caching/memory-management\n      - label: Advanced topics\n        href: ./caching/advanced-topics\n  - label: Pagination\n    children:\n      - label: Overview\n        href: ./pagination/overview\n      - label: Core API\n        href: ./pagination/core-api\n      - label: Offset-based\n        href: ./pagination/offset-based\n      - label: Cursor-based\n        href: ./pagination/cursor-based\n      - label: keyArgs\n        href: ./pagination/key-args\n  - label: Local State\n    children:\n      - label: Overview\n        href: ./local-state/local-state-management\n      - label: Local-only fields\n        href: ./local-state/managing-state-with-field-policies\n      - label: Reactive variables\n        href: ./local-state/reactive-variables\n      - label: Local resolvers\n        href: ./local-state/local-resolvers\n  - label: Development & Testing\n    children:\n      - label: Developer tools\n        href: ./development-testing/developer-tooling\n      - label: GraphQL Codegen\n        href: ./development-testing/graphql-codegen\n      - label: Testing React components\n        href: ./development-testing/testing\n      - label: Schema-driven testing\n        href: ./development-testing/schema-driven-testing\n      - label: Mocking schema capabilities\n        href: ./development-testing/client-schema-mocking\n      - label: Reducing bundle size\n        href: ./development-testing/reducing-bundle-size\n  - label: Performance\n    children:\n      - label: Improving performance\n        href: ./performance/performance\n      - label: Optimistic mutation results\n        href: ./performance/optimistic-ui\n      - label: Server-side rendering\n        href: ./performance/server-side-rendering\n      - label: Compiling queries with Babel\n        href: ./performance/babel\n  - label: Integrations\n    children:\n      - label: Using Apollo Client with your view layer\n        href: ./integrations/integrations\n      - label: Next.js App Router\n        href: ./integrations/nextjs\n      - label: React Router framework mode\n        href: ./integrations/react-router\n      - label: TanStack Start\n        href: ./integrations/tanstack-start\n      - label: Integrating with React Native\n        href: ./integrations/react-native\n      - label: Loading queries with Webpack\n        href: ./integrations/webpack\n  - label: Networking\n    children:\n      - label: Basic HTTP networking\n        href: ./networking/basic-http-networking\n      - label: Advanced HTTP networking\n        href: ./networking/advanced-http-networking\n      - label: Authentication\n        href: ./networking/authentication\n  - label: API Reference\n    children:\n      - label: Core\n        children:\n          - label: ApolloClient\n            href: ./api/core/ApolloClient\n          - label: InMemoryCache\n            href: ./api/cache/InMemoryCache\n          - label: ObservableQuery\n            href: ./api/core/ObservableQuery\n      - label: Errors\n        children:\n          - label: CombinedGraphQLErrors\n            href: ./api/errors/CombinedGraphQLErrors\n          - label: CombinedProtocolErrors\n            href: ./api/errors/CombinedProtocolErrors\n          - label: LinkError\n            href: ./api/errors/LinkError\n          - label: LocalStateError\n            href: ./api/errors/LocalStateError\n          - label: ServerError\n            href: ./api/errors/ServerError\n          - label: ServerParseError\n            href: ./api/errors/ServerParseError\n          - label: UnconventionalError\n            href: ./api/errors/UnconventionalError\n      - label: React\n        children:\n          - label: ApolloProvider\n            href: ./api/react/ApolloProvider\n          - label: useQuery\n            href: ./api/react/useQuery\n          - label: useLazyQuery\n            href: ./api/react/useLazyQuery\n          - label: useMutation\n            href: ./api/react/useMutation\n          - label: useSubscription\n            href: ./api/react/useSubscription\n          - label: useFragment\n            href: ./api/react/useFragment\n          - label: useApolloClient\n            href: ./api/react/useApolloClient\n          - label: useReactiveVar\n            href: ./api/react/useReactiveVar\n          - label: useSuspenseQuery\n            href: ./api/react/useSuspenseQuery\n          - label: useBackgroundQuery\n            href: ./api/react/useBackgroundQuery\n          - label: useReadQuery\n            href: ./api/react/useReadQuery\n          - label: useLoadableQuery\n            href: ./api/react/useLoadableQuery\n          - label: useQueryRefHandlers\n            href: ./api/react/useQueryRefHandlers\n          - label: skipToken\n            href: ./api/react/skipToken\n          - label: createQueryPreloader\n            href: ./api/react/preloading\n          - label: MockProvider\n            href: ./api/react/testing\n          - label: SSR\n            href: ./api/react/ssr\n      - label: Apollo Link\n        children:\n          - label: Overview\n            href: ./api/link/introduction\n          - label: ApolloLink\n            href: ./api/link/apollo-link\n          - label: BaseHttpLink\n            href: ./api/link/apollo-link-base-http\n          - label: BaseBatchHttpLink\n            href: ./api/link/apollo-link-base-batch-http\n          - label: BatchHttpLink\n            href: ./api/link/apollo-link-batch-http\n          - label: BatchLink\n            href: ./api/link/apollo-link-batch\n          - label: ClientAwarenessLink\n            href: ./api/link/apollo-link-client-awareness\n          - label: ErrorLink\n            href: ./api/link/apollo-link-error\n          - label: GraphQLWsLink\n            href: ./api/link/apollo-link-subscriptions\n          - label: HttpLink\n            href: ./api/link/apollo-link-http\n          - label: PersistedQueryLink\n            href: ./api/link/apollo-link-persisted-queries\n          - label: RemoveTypenameFromVariablesLink\n            href: ./api/link/apollo-link-remove-typename\n          - label: RetryLink\n            href: ./api/link/apollo-link-retry\n          - label: SchemaLink\n            href: ./api/link/apollo-link-schema\n          - label: SetContextLink\n            href: ./api/link/apollo-link-context\n          - label: WebSocketLink (deprecated)\n            href: ./api/link/apollo-link-ws\n          - label: Community links\n            href: ./api/link/community-links\n  - label: Changelog\n    href: https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md\n  - label: Migrating to Apollo Client 4.0\n    href: ./migrating/apollo-client-4-migration\n  - label: Versioning Policy\n    href: ./versioning-policy\n"
  },
  {
    "path": "docs/source/api/cache/InMemoryCache.mdx",
    "content": "---\ntitle: class InMemoryCache\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nMethods of the `InMemoryCache` class (the cache used by almost every instance of [`ApolloClient`](../core/ApolloClient/)) are documented here.\n\n> Before reading about individual methods, see [Caching in Apollo Client](../../caching/overview/).\n\n## `readQuery`\n\nExecutes a GraphQL query directly against the cache and returns its result (or `null` if the query cannot be fulfilled):\n\n```js\n// Query a cached Todo object with id 5\nconst { todo } = cache.readQuery({\n  query: gql`\n    query ReadTodo {\n      todo(id: 5) {\n        id\n        text\n        completed\n      }\n    }\n  `,\n});\n```\n\nFor usage instructions, see [Interacting with cached data: `readQuery`](../../caching/cache-interaction/#readquery).\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `options`\n\n`Object`\n\n</td>\n<td>\n\n**Required.** Provides configuration options for the query, including the actual query to execute.\n\nSupported fields are listed below.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `optimistic`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, `readQuery` returns optimistic results.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `query`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** The GraphQL query to execute, created by wrapping a query string in the `gql` template literal.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `query`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\nThe root `id` to use for the query.\n\nThe default value is `ROOT_QUERY`, which is the ID of the root query object.\n\nBy specifying the ID of another cached object, you can query arbitrary cached data without conforming to the structure of your schema's supported queries. This enables `readQuery` to behave similarly to [`readFragment`](#readfragment).\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\nreadQuery<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.ReadQueryOptions<TData, TVariables>,\n  optimistic: boolean = false,\n): Unmasked<TData> | null\n```\n\n## `writeQuery`\n\nWrites data to the cache in the shape of a provided GraphQL query. Returns a `Reference` to the written object or `undefined` if the write failed.\n\n```js\n// Create or modify a cached Todo object with id 5\ncache.writeQuery({\n  query: gql`\n    query ReadTodo($id: ID!) {\n      todo(id: $id) {\n        id\n        text\n        completed\n      }\n    }\n  `,\n  data: {\n    todo: {\n      __typename: \"Todo\",\n      id: 5,\n      text: \"Buy grapes 🍇\",\n      completed: false,\n    },\n  },\n  variables: {\n    id: 5,\n  },\n});\n```\n\nFor usage instructions, see [Interacting with cached data: `writeQuery`](../../caching/cache-interaction/#writequery).\n\nTakes an `options` object as a parameter. Supported fields of this object are described below.\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `query`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** The GraphQL query that defines the shape of the data to write. Created by wrapping a query string in the `gql` template literal.\n\n</td>\n</tr>\n\n<tr class=\"required\">\n<td>\n\n###### `data`\n\n`Object`\n\n</td>\n<td>\n\n**Required.** The data to write to the cache. This object's fields must conform to the shape defined by `query`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `query`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\nThe `id` of the root object to use with `query`.\n\nThe default value is `ROOT_QUERY`, which is the ID of the root query object.\n\nBy specifying the ID of another cached object, you can modify arbitrary cached data without conforming to the structure of your schema's supported queries. This enables `writeQuery` to behave similarly to [`writeFragment`](#writefragment).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's modified by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `overwrite`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, ignore existing cache data when calling `merge` functions, allowing incoming data to replace existing data, without warnings about data loss.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\nwriteQuery<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.WriteQueryOptions<TData, TVariables>,\n): Reference | undefined\n```\n\n## `updateQuery`\n\nFetches data from the cache in the shape of a provided GraphQL query, then _updates_ that cached data according to a provided update function.\n\nReturns the updated result or `null` if the update failed.\n\n```js\n// Fetches a Todo object with id 5 and flips its `completed` boolean\ncache.updateQuery(\n  // options object\n  {\n    query: gql`\n      query ReadTodo($id: ID!) {\n        todo(id: $id) {\n          id\n          text\n          completed\n        }\n      }\n    `,\n    variables: {\n      id: 5,\n    },\n  },\n  // update function\n  (data) => ({\n    todo: {\n      ...data.todo,\n      completed: !data.todo.completed,\n    },\n  })\n);\n```\n\nTakes an `options` object and an update function as parameters (both described below).\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `query`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** The GraphQL query that defines the shape of the data to fetch. Created by wrapping a query string in the `gql` template literal.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `query`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\nThe `id` of the root object to use with `query`.\n\nThe default value is `ROOT_QUERY`, which is the ID of the root query object.\n\nBy specifying the ID of another cached object, you can modify arbitrary cached data without conforming to the structure of your schema's supported queries. This enables `updateQuery` to behave similarly to [`updateFragment`](#updatefragment).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's modified by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `overwrite`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, ignore existing cache data when calling `merge` functions, allowing incoming data to replace existing data, without warnings about data loss.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### `updateQuery` update function\n\nThe update function of `updateQuery` takes a query's current cached value and returns the value that should replace it (or `undefined` if no change should be made).\n\nThe returned value is automatically passed to [`writeQuery`](#writequery), which modifies the cached data.\n\nPlease note the `update` function has to calculate the new value in an immutable way. You can read more about immutable updates in the [React documentation](https://beta.reactjs.org/learn/updating-objects-in-state).\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\npublic updateQuery<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.UpdateQueryOptions<TData, TVariables>,\n  update: (data: TData | null) => TData | null | void,\n): TData | null\n```\n\n## `readFragment`\n\nReads data from the cache in the shape of a provided GraphQL fragment:\n\n```js\nconst todo = cache.readFragment({\n  id: \"5\", // The value of the to-do item's unique identifier\n  fragment: gql`\n    fragment MyTodo on Todo {\n      id\n      text\n      completed\n    }\n  `,\n});\n```\n\nReturns the requested data or `null` if data is not available in the cache.\n\nFor usage instructions, see [Interacting with cached data: `readFragment`](../../caching/cache-interaction/#readfragment).\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `options`\n\n`Object`\n\n</td>\n<td>\n\n**Required.** Provides configuration options, including the actual fragment to use.\n\nSupported fields are listed below.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `optimistic`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, `readFragment` returns optimistic results.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\n**Required.** The ID of the cached object that this call is reading a fragment of.\n\nIf the cache does not contain an object with the specified ID, `readFragment` returns `null`.\n\n</td>\n</tr>\n\n<tr class=\"required\">\n<td>\n\n###### `fragment`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** A GraphQL document created with the `gql` template literal tag that includes the fragment to read.\n\nIf the document includes more than one fragment, you must also provide [`fragmentName`](#fragmentname) to indicate which to use.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `fragmentName`\n\n`String`\n\n</td>\n<td>\n\nThe name of the fragment defined in the `fragment` document to use in the call.\n\nYou don't need to provide this value if the `fragment` document includes only one fragment.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `fragment`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\nreadFragment<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.ReadFragmentOptions<TData, TVariables>,\n  optimistic: boolean = false,\n): Unmasked<TData> | null\n```\n\n## `writeFragment`\n\nWrites data to the cache in the shape of the provided GraphQL fragment. Returns a `Reference` to the written object or `undefined` if the write failed.\n\n```js\nclient.writeFragment({\n  id: \"Todo:5\",\n  fragment: gql`\n    fragment MyTodo on Todo {\n      completed\n    }\n  `,\n  data: {\n    completed: true,\n  },\n});\n```\n\nFor usage instructions, see [Interacting with cached data: `writeFragment`](../../caching/cache-interaction/#writefragment).\n\nTakes an `options` object as a parameter. Supported fields of this object are described below.\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\n**Required.** The ID of the cached object that this call is writing a fragment to.\n\nIf the cache does not contain an object with the specified ID, `writeFragment` returns `null`.\n\n</td>\n</tr>\n\n<tr class=\"required\">\n<td>\n\n###### `fragment`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** A GraphQL document created with the `gql` template literal tag that includes the fragment to write.\n\nIf the document includes more than one fragment, you must also provide [`fragmentName`](#fragmentname) to indicate which to use.\n\n</td>\n</tr>\n\n<tr class=\"required\">\n<td>\n\n###### `data`\n\n`Object`\n\n</td>\n<td>\n\n**Required.** The data to write to the cache. This object's fields must conform to the shape defined by `fragment`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `fragmentName`\n\n`String`\n\n</td>\n<td>\n\nThe name of the fragment defined in the `fragment` document to use in the call.\n\nYou don't need to provide this value if the `fragment` document includes only one fragment.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `fragment`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's modified by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `overwrite`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, ignore existing cache data when calling `merge` functions, allowing incoming data to replace existing data, without warnings about data loss.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\nwriteFragment<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.WriteFragmentOptions<TData, TVariables>,\n): Reference | undefined\n```\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#watchFragment:member(1)\"\n  headingLevel={2}\n/>\n\n## `updateFragment`\n\nFetches data from the cache in the shape of a provided GraphQL fragment, then _updates_ that cached data according to a provided update function.\n\nReturns the updated result or `null` if the update failed.\n\n```js\n// Fetches a Todo object with id 5 and sets its `completed` boolean to true\nconst todo = cache.updateFragment(\n  // options object\n  {\n    id: \"5\", // The value of the to-do item's unique identifier\n    fragment: gql`\n      fragment MyTodo on Todo {\n        completed\n      }\n    `,\n  },\n  // update function\n  (data) => ({ ...data, completed: true })\n);\n```\n\nTakes an `options` object and an update function as parameters (both described below).\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\n**Required.** The ID of the cached object that this call is reading a fragment of.\n\nIf the cache does not contain an object with the specified ID, `updateFragment` returns `null`.\n\n</td>\n</tr>\n\n<tr class=\"required\">\n<td>\n\n###### `fragment`\n\n`DocumentNode`\n\n</td>\n<td>\n\n**Required.** A GraphQL document created with the `gql` template literal tag that includes the fragment to read.\n\nIf the document includes more than one fragment, you must also provide [`fragmentName`](#fragmentname) to indicate which to use.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `fragmentName`\n\n`String`\n\n</td>\n<td>\n\nThe name of the fragment defined in the `fragment` document to use in the call.\n\nYou don't need to provide this value if the `fragment` document includes only one fragment.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `variables`\n\n`Object`\n\n</td>\n<td>\n\nA map of any GraphQL variable names and values required by `fragment`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's modified by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `overwrite`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, ignore existing cache data when calling `merge` functions, allowing incoming data to replace existing data, without warnings about data loss.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### `updateFragment` update function\n\nThe update function of `updateFragment` takes a fragment's current cached value and returns the value that should replace it (or `undefined` if no change should be made).\n\nThe returned value is automatically passed to [`writeFragment`](#writefragment), which modifies the cached data.\n\nPlease note the `update` function has to calculate the new value in an immutable way. You can read more about immutable updates in the [React documentation](https://beta.reactjs.org/learn/updating-objects-in-state).\n\n### Signature\n\n```ts title=\"src/cache/core/cache.ts\"\npublic updateFragment<TData = unknown, TVariables = OperationVariables>(\n  options: Cache.UpdateFragmentOptions<TData, TVariables>,\n  update: (data: TData | null) => TData | null | void,\n): TData | null\n```\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!InMemoryCache#batch:member(1)\"\n  headingLevel={2}\n  result={false}\n/>\n\n## `identify`\n\nReturns the canonical ID for a specified cached object.\n\nYou can provide either an object or an object _reference_ to this function:\n\n- If you provide an object, `identify` returns the object's string-based ID (e.g., `Car:1`).\n- If you provide a reference, `identify` return the reference's `__ref` ID string.\n\nFor usage instructions, see [Interacting with cached data: Identify cached entities](../../caching/cache-interaction/#obtaining-an-objects-cache-id).\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `object`\n\n`StoreObject` or `Reference`\n\n</td>\n<td>\n\n**Required.** The cached object (or object reference) to obtain the canonical ID for.\n\n</td>\n</tr>\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nidentify(object: StoreObject | Reference): string | undefined\n```\n\n## `modify`\n\nModifies one or more field values of a cached object. Must provide a **modifier function** for each field to modify. A modifier function takes a cached field's current value and returns the value that should replace it.\n\nReturns `true` if the cache was modified successfully and `false` otherwise.\n\nFor usage instructions, see [Using `cache.modify`](../../caching/cache-interaction/#using-cachemodify).\n\nTakes an `options` object as a parameter. Supported fields of this object are described below.\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `fields`\n\n`Object`\n\n</td>\n<td>\n\n**Required.** A map that specifies the modifier function to call for each modified field of the cached object.\n\nSee [Modifier function API](#modifier-function-api) below.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `id`\n\n`string`\n\n</td>\n<td>\n\nThe ID of the cached object to modify.\n\nThe default value is `ROOT_QUERY` (the ID of the root query singleton object).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `optimistic`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, also modifies the optimistically cached values for included fields.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's modified by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n#### Modifier function API\n\nA modifier function takes a cached field's current value and returns the value that should replace it, or the [`DELETE` sentinel object](#delete) to delete the field entirely.\n\nThe first parameter passed to a modifier function is the current cached value of the field being modified.\n\nThe second parameter is a helper object that contains the following utilities:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr>\n<td>\n\n###### `fieldName`\n\n`String`\n\n</td>\n<td>\n\nThe name of the field being modified.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `storeFieldName`\n\n`String`\n\n</td>\n<td>\n\nThe full key for the field used internally, including serialized key arguments.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `readField`\n\n`Function`\n\n</td>\n<td>\n\nA helper function for reading other fields on the object passed to the modifier function as the first parameter.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `canRead`\n\n`Function`\n\n</td>\n<td>\n\nA helper function that returns `true` for non-normalized `StoreObject`s and non-dangling `Reference`s. This indicates that `readField(name, objOrRef)` has a chance of working.\n\nUseful for filtering dangling references out of lists.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `isReference`\n\n`Function`\n\n</td>\n<td>\n\nA helper function that returns `true` if a particular object is a reference to a cached entity.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `DELETE`\n\n`Object`\n\n</td>\n<td>\n\nA sentinel object that you can return from a modifier function to indicate that the field should be deleted entirely.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nmodify(options: Cache.ModifyOptions): boolean\n```\n\n## `gc`\n\nPerforms garbage collection of unreachable normalized objects in the cache:\n\n```js\ncache.gc();\n```\n\nReturns an array containing the IDs of all objects removed from the cache.\n\nFor usage instructions, see [`cache.gc`](../../caching/garbage-collection/#cachegc).\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\ngc();\n```\n\n## `evict`\n\nEither removes a normalized object from the cache or removes a specific field from a normalized object in the cache:\n\n```js\ncache.evict({ id: \"my-object-id\", fieldName: \"myFieldName\" });\n```\n\nReturns `true` if data was removed from the cache, `false` otherwise.\n\nFor usage instructions, see [`cache.evict`](../../caching/garbage-collection/#cacheevict).\n\nTakes an `options` object as a parameter. Supported fields of this object are described below.\n\n### Options\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr>\n<td>\n\n###### `id`\n\n`String`\n\n</td>\n<td>\n\nThe ID of the cached object to remove (or remove a field from).\n\nThe default value is `ROOT_QUERY`, which is the ID of the root query object.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `fieldName`\n\n`String`\n\n</td>\n<td>\n\nThe name of the field to remove from the cached object.\n\nOmit this option if you are removing the entire object.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `args`\n\n`Record<string, any>`\n\n</td>\n<td>\n\nIf provided with `fieldName`, only instances of the field with the specified arguments are removed from the cache.\n\nOtherwise, all instances of the field are removed for the cached object.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `broadcast`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, automatically refresh all active queries that depend on at least one field that's removed by this call. If `false`, silences the broadcast of cache updates and prevents automatic query refresh.\n\nThe default value is `true`.\n\n</td>\n</tr>\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nevict(options: Cache.EvictOptions): boolean\n```\n\n## `extract`\n\nReturns a serialized representation of the cache's current contents as a `NormalizedCacheObject`.\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr>\n<td>\n\n###### `optimistic`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, optimistic data is included in the serialization.\n\nThe default value is `false`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nextract(optimistic: boolean = false): NormalizedCacheObject\n```\n\n## `restore`\n\nRestores the cache's state from a serialized `NormalizedCacheObject` (such as one returned by [`extract`](#extract)). This removes all existing data from the cache.\n\nReturns the `InMemoryCache` instance it's called on.\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr class=\"required\">\n<td>\n\n###### `data`\n\n`NormalizedCacheObject`\n\n</td>\n<td>\n\n**Required.** The serialization to restore the cache from.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nrestore(data: NormalizedCacheObject): this\n```\n\n## `makeVar`\n\nCreates a reactive variable with an optional initial value:\n\n```js\nconst cartItems = makeVar([]);\n```\n\nReturns the reactive variable function you use to read or modify the variable's value.\n\nFor usage instructions, see [Reactive variables](../../local-state/reactive-variables/).\n\nAccepts the following parameters:\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n\n<tr>\n<td>\n\n###### `value`\n\nAny\n\n</td>\n<td>\n\nThe reactive variable's initial value.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n### Signature\n\n```ts title=\"src/cache/inmemory/inMemoryCache.ts\"\nmakeVar<T>(value: T): ReactiveVar<T>\n```\n"
  },
  {
    "path": "docs/source/api/core/ApolloClient.mdx",
    "content": "---\ntitle: class ApolloClient\ndescription: API reference\norder: 11\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nThe `ApolloClient` class encapsulates Apollo's core client-side API. It backs all available view-layer integrations (React, iOS, and so on).\n\n## The `ApolloClient` constructor\n\n<DocBlock canonicalReference={\"@apollo/client!ApolloClient:constructor(1)\"} />\n\nTakes an `ApolloClientOptions` parameter that supports the [fields listed below](#apolloclientoptions).\n\nReturns an initialized `ApolloClient` object.\n\n#### Example\n\n<Example canonicalReference=\"@apollo/client!ApolloClient:constructor(1)\" />\n\nFor more information on the `defaultOptions` object, see the [Default Options](#defaultoptions) section below.\n\n## Functions\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#watchQuery:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#query:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#mutate:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#subscribe:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#readQuery:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#readFragment:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#writeQuery:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#writeFragment:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#watchFragment:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#resetStore:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#onResetStore:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#clearStore:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#onClearStore:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#stop:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#refetchObservableQueries:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#refetchQueries:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#getObservableQueries:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#extract:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#restore:member(1)\"\n  headingLevel={3}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#setLink:member(1)\"\n  headingLevel={3}\n/>\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!ApolloClient.Options:interface\"\n  headingLevel={3}\n  displayName=\"ApolloClient.Options\"\n  customPropertyOrder={[\n    \"cache\",\n    \"link\",\n    \"uri\",\n    \"connectToDevTools\",\n    \"defaultOptions\",\n    \"name\",\n    \"version\",\n  ]}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!ApolloClient.DefaultOptions:interface\"\n  headingLevel={3}\n  displayName=\"ApolloClient.DefaultOptions\"\n/>\n\n##### Example `defaultOptions` object\n\n```js\nconst defaultOptions = {\n  watchQuery: {\n    fetchPolicy: \"cache-and-network\",\n    errorPolicy: \"ignore\",\n  },\n  query: {\n    fetchPolicy: \"network-only\",\n    errorPolicy: \"all\",\n  },\n  mutate: {\n    errorPolicy: \"all\",\n  },\n};\n```\n\nYou can override any default option you specify in this object by providing a\ndifferent value for the same option in individual function calls.\n\n> **Note:** The `useQuery` hook uses Apollo Client's `watchQuery` function. To set `defaultOptions` when using the `useQuery` hook, make sure to set them under the `defaultOptions.watchQuery` property.\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!ApolloClient.DevtoolsOptions:interface\"\n  headingLevel={3}\n  displayName=\"ApolloClient.DevtoolsOptions\"\n/>\n"
  },
  {
    "path": "docs/source/api/core/ObservableQuery.mdx",
    "content": "---\ntitle: ObservableQuery\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nAn `ObservableQuery` is created by calling the `client.watchQuery` method.\nIt represents a query that can be observed for changes, allowing you to reactively update your UI.\n\n## Key Behaviors\n\n### RxJS Integration\n\n`ObservableQuery` implements the [RxJS](https://rxjs.dev/) `InteropObservable` interface which means you can convert it into an RxJS `Observable` via `from(observableQuery)`.\nIt also provides the `subscribe` and `pipe` functions like an RxJS `Observable`.\nRefer to the [RxJS documentation](https://rxjs.dev/guide/overview) for additional context and API options.\n\nTo get a single result from an `ObservableQuery` as a Promise, use the `firstValueFrom` helper:\n\n```ts\nimport { firstValueFrom, from } from \"rxjs\";\n\n// The `from` is necessary to turn `observableQuery` into an RxJS observable\nconst result = await firstValueFrom(from(observableQuery));\n```\n\n### Subscription Lifecycle\n\n- `ObservableQuery` instances are only registered with `ApolloClient` while they have active subscribers\n- Unsubscribing from an `ObservableQuery` while a request is in flight does not terminate the request\n- Unsubscribing before any value has been emitted removes the query from the tracked list and makes it ineligible for query deduplication\n\n### Error Handling\n\n- `ObservableQuery` does not terminate on errors - instead it emits a `next` value with an `error` property. This ensures `ObservableQuery` subscriptions can continue receiving updates after errors without resubscription.\n\n### Loading States\n\n- When `notifyOnNetworkStatusChange` is `true` (the default), an initial loading state is emitted when subscribing\n- `ObservableQuery` preserves `data` when emitting a loading state unless `query` or `variables` changed (note: `@export` variables are not considered for this check)\n- When the query can be fulfilled by the cache or when the link chain responds synchronously, a loading state is omitted\n- `cache-only` queries initialize with `networkStatus: NetworkStatus.ready` when there is no data in the cache\n- `standby` queries initialize with `networkStatus: NetworkStatus.ready` before subscribing to the query\n\n### Promise-returning Methods and retention\n\n- `refetch()` and `reobserve()` return a `ResultPromise` with an additional `.retain()` method\n- By default, the network operation is cancelled when `ObservableQuery` no longer requires the result, such as when `ObservableQuery` is unsubscribed or variables change, and the returned `Promise` will reject with an `AbortError`\n- Calling `.retain()` keeps the network operation running even when the `ObservableQuery` no longer requires the result\n- `setVariables()` and `refetch()` guarantee that a value will be emitted from the observable, even when the result is deeply equal to the previous result\n\n### Active vs Inactive Queries\n\n- **Active queries**: Have at least one subscriber and are not skipped or have a `fetchPolicy` of `standby`\n- **Inactive queries**: Have a subscriber but are either skipped or have a `fetchPolicy` of `standby`\n- `ObservableQuery`s without subscribers but with an active network request are handled as if they had a subscriber for the duration of the query\n- Only queries with subscribers can be refetched using `ApolloClient.refetchQueries`\n\n## `ObservableQuery` functions\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#getCurrentResult:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery.DocumentationTypes.ObservableMethods#pipe:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery.DocumentationTypes.ObservableMethods#subscribe:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={true}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#refetch:member(1)\"\n  headingLevel={3}\n  result={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#fetchMore:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#subscribeToMore:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#stop:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#setVariables:member(1)\"\n  headingLevel={3}\n  result={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#updateQuery:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#startPolling:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#stopPolling:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ObservableQuery#reobserve:member(1)\"\n  headingLevel={3}\n  result={false}\n  parameters={false}\n/>\n\n## Types\n\n<EnumDetails\n  canonicalReference=\"@apollo/client!NetworkStatus:enum\"\n  headingLevel={3}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/utilities/internal!DocumentationTypes.ApolloQueryResult:interface\"\n  headingLevel={3}\n/>\n"
  },
  {
    "path": "docs/source/api/errors/CombinedGraphQLErrors.mdx",
    "content": "---\ntitle: CombinedGraphQLErrors\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Providing a custom message formatter\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.MessageFormatter:type\"\n  customOrder={[\"summary\", \"example\", \"remarks\"]}\n/>\n\n### Using the default message formatter\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.MessageFormatterOptions#defaultFormatMessage:member\"\n  customOrder={[\"remarks\", \"example\"]}\n/>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n\nSee the [instance properties](#instance-properties) for more details about the available properties provided by the `CombinedGraphQLErrors` object.\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.DocumentationTypes.formatMessage:function(1)\"\n  headingLevel={3}\n  result={false}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.MessageFormatterOptions:interface\"\n  headingLevel={4}\n  displayName=\"CombinedGraphQLErrors.MessageFormatterOptions\"\n/>\n\n## Instance properties\n\nThese properties are specific to the `CombinedGraphQLErrors` object. Standard error [instance properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#instance_properties) are also available.\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!CombinedGraphQLErrors.DocumentationTypes.InstanceProperties:interface\"\n  idPrefix=\"instanceproperties\"\n/>\n"
  },
  {
    "path": "docs/source/api/errors/CombinedProtocolErrors.mdx",
    "content": "---\ntitle: CombinedProtocolErrors\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Providing a custom message formatter\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.MessageFormatter:type\"\n  customOrder={[\"summary\", \"example\", \"remarks\"]}\n/>\n\n### Using the default message formatter\n\n<DocBlock\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.MessageFormatterOptions#defaultFormatMessage:member\"\n  customOrder={[\"remarks\", \"example\"]}\n/>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n\nSee the [instance properties](#instance-properties) for more details about the available properties provided by the `CombinedProtocolErrors` object.\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.DocumentationTypes.formatMessage:function(1)\"\n  headingLevel={3}\n  result={false}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.MessageFormatterOptions:interface\"\n  headingLevel={4}\n  displayName=\"CombinedProtocolErrors.MessageFormatterOptions\"\n/>\n\n## Instance properties\n\nThese properties are specific to the `CombinedProtocolErrors` object. Standard error [instance properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#instance_properties) are also available.\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!CombinedProtocolErrors.DocumentationTypes.InstanceProperties:interface\"\n  idPrefix=\"instanceproperties\"\n/>\n"
  },
  {
    "path": "docs/source/api/errors/LinkError.mdx",
    "content": "---\ntitle: LinkError\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nA facade error type that keeps a registry of errors emitted from the link chain. `LinkError` is not an error class itself but rather a utility to detect whether an error originated from the link chain.\n\nUse `LinkError` to distinguish between errors from the link chain and custom errors. This is helpful for retrying an operation at the call site only when the error originates from the link chain.\n\nThe following example creates a custom wrapped query function that detects whether the query includes an operation name and throws if not.\n\n```ts\nimport { LinkError } from \"@apollo/client/errors\";\n\nasync function runQuery<TData>(query: TypedDocumentNode<TData>) {\n  if (!hasOperationName(query)) {\n    throw new Error(\"Queries should have operation names.\");\n  }\n\n  return client.watchQuery({ query });\n}\n\ntry {\n  const result = await runQuery(query);\n} catch (error) {\n  // Only log the error if the error wasn't our own custom thrown error\n  if (LinkError.is(error)) {\n    console.log(\"Got network error:\", error.message);\n  }\n}\n```\n\nHere `LinkError` detects whether the caught `error` originated from the link chain or is the custom error thrown by `runQuery`. This avoids the need for more complex code, such as a custom error class, to distinguish between error types.\n\n## Static methods\n\n### `is`\n\nA function that determines whether an error originated from the link chain. `is` does not provide any type narrowing.\n\n```ts\nif (LinkError.is(error)) {\n  // The error originated from the link chain\n  console.log(\"Got network error:\", error.message);\n}\n```\n"
  },
  {
    "path": "docs/source/api/errors/LocalStateError.mdx",
    "content": "---\ntitle: LocalStateError\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!LocalStateError:class\"\n  customOrder={[\"summary\", \"example\"]}\n/>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!LocalStateError.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n\nSee the [instance properties](#instance-properties) for more details about the available properties provided by the `LocalStateError` object.\n\n## Instance properties\n\nThese properties are specific to the `LocalStateError` object. Standard error [instance properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#instance_properties) are also available.\n\n<Tip>\n  The `cause` property contains the original error thrown by local resolvers\n  when exporting variables for [`@export`](../../data/directives#export)\n  directive fields.\n</Tip>\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!LocalStateError.DocumentationTypes.InstanceProperties:interface\"\n  idPrefix=\"instanceproperties\"\n/>\n"
  },
  {
    "path": "docs/source/api/errors/ServerError.mdx",
    "content": "---\ntitle: ServerError\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!ServerError:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ServerError.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n\nSee the [instance properties](#instance-properties) for more details about the available properties provided by the `ServerError` object.\n\n## Instance properties\n\nThese properties are specific to the `ServerError` object. Standard error [instance properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#instance_properties) are also available.\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!ServerError.DocumentationTypes.InstanceProperties:interface\"\n  idPrefix=\"instanceproperties\"\n/>\n"
  },
  {
    "path": "docs/source/api/errors/ServerParseError.mdx",
    "content": "---\ntitle: ServerParseError\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!ServerParseError:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ServerParseError.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n\nSee the [instance properties](#instance-properties) for more details about the available properties provided by the `ServerParseError` object.\n\n## Instance properties\n\nThese properties are specific to the `ServerParseError` object. Standard error [instance properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#instance_properties) are also available.\n\n<Tip>\n  Use the `cause` property to access the original parse error thrown by\n  `JSON.parse()`.\n</Tip>\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!ServerParseError.DocumentationTypes.InstanceProperties:interface\"\n  idPrefix=\"instanceproperties\"\n/>\n"
  },
  {
    "path": "docs/source/api/errors/UnconventionalError.mdx",
    "content": "---\ntitle: UnconventionalError\ndescription: API reference\n---\n\n{/* * @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client!UnconventionalError:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Common scenarios\n\n`UnconventionalError` is typically encountered when custom link implementations, provided either by third-party libraries or your own link implementations, throw symbols, arrays, or other non-Error objects.\n\nBy wrapping these unconventional error types, Apollo Client ensures consistent error handling throughout the system while preserving the original error information.\n\n<Note>\n  Apollo Client itself does not throw or emit non-Error objects. Unless you're\n  using third-party packages integrated with Apollo Client, you will not\n  encounter this error type.\n</Note>\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!UnconventionalError.is:member(1)\"\n  headingLevel={3}\n  parameters={false}\n  result={false}\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-base-batch-http.mdx",
    "content": "---\ntitle: BaseBatchHttpLink\ndescription: Batch multiple operations into a single HTTP request\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/batch-http!BaseBatchHttpLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options: BaseBatchHttpLink.Options = {}\n): BaseBatchHttpLink\n```\n\n## Usage\n\nSee the [`BatchHttpLink` documentation](./apollo-link-batch-http) for more information on\nhow to use `BaseBatchHttpLink`.\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/batch-http!BaseBatchHttpLink.ContextOptions:interface\"\n  headingLevel={3}\n  displayName=\"BaseBatchHttpLink.ContextOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/batch-http!BaseBatchHttpLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"BaseBatchHttpLink.Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-base-http.mdx",
    "content": "---\ntitle: BaseHttpLink\ndescription: Get GraphQL results over a network using HTTP fetch\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/http!BaseHttpLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options: BaseHttpLink.Options = {}\n): BaseHttpLink\n```\n\n## Usage\n\nSee the [`HttpLink` documentation](./apollo-link-http) for more information on\nhow to use `BaseHttpLink`.\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/http!BaseHttpLink.ContextOptions:interface\"\n  headingLevel={3}\n  displayName=\"BaseHttpLink.ContextOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/http!BaseHttpLink.HttpOptions:interface\"\n  headingLevel={3}\n  displayName=\"BaseHttpLink.HttpOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/http!BaseHttpLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"BaseHttpLink.Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-batch-http.mdx",
    "content": "---\ntitle: BatchHttpLink\ndescription: Batch multiple operations into a single HTTP request\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/batch-http!BatchHttpLink:class\"\n  customOrder={[\"summary\", \"example\", \"remarks\"]}\n/>\n\n## Constructor signature\n\n{/* TODO: Remove the custom signature once documentation supports rendering constructor functions */}\n\n```ts\nconstructor(\n  options: BatchHttpLink.Options & ClientAwarenessLink.Options = {}\n): BatchHttpLink\n```\n\n## Context\n\nThe batch HTTP link currently uses the context in two different ways, per batch and per query. The context fields below are used per batch and taken from the first operation in the batch.\n\n| Option         | Description                                                              |\n| -------------- | ------------------------------------------------------------------------ |\n| `headers`      | An object representing values to be sent as headers on the request       |\n| `credentials`  | A string representing the credentials policy you want for the fetch call |\n| `uri`          | A string of the endpoint you want to fetch from                          |\n| `fetchOptions` | Any overrides of the fetch options argument to pass to the fetch call    |\n\nFor each query, the `http` field is used to modify each individual query in the batch, such as persisted queries (see below).\n\n## Operation results\n\nAfter your GraphQL endpoint successfully responds with the result of an operation, `BatchHttpLink` sets the `Response` object as the `response` field of the operation `context`. This enables each previous link in your link chain to interact with the response.\n\n## Custom fetching\n\nSee [Customizing `fetch`](apollo-link-http/#customizing-fetch).\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/batch-http!BatchHttpLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"BatchHttpLink.Options\"\n  customPropertyOrder={[\"uri\", \"headers\", \"credentials\", \"fetchOptions\"]}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/batch-http!BatchHttpLink.ContextOptions:interface\"\n  headingLevel={3}\n  displayName=\"BatchHttpLink.ContextOptions\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-batch.mdx",
    "content": "---\ntitle: BatchLink\ndescription: Core batching functionality for grouping multiple GraphQL operations\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/batch!BatchLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options?: BatchLink.Options\n): BatchLink\n```\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/batch!BatchLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"BatchLink.Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-client-awareness.mdx",
    "content": "---\ntitle: ClientAwarenessLink\ndescription: API reference\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/client-awareness!ClientAwarenessLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options?: ClientAwarenessLink.Options\n): ClientAwarenessLink\n```\n\n## Configuring client awareness\n\nClient awareness can be configured in various ways in Apollo Client.\n\n### Configuring with Apollo Client\n\nYou can configure client awareness when initializing your Apollo Client instance using the `clientAwareness` and `enhancedClientAwareness` options. Options configured with the `ClientAwarenessLink` constructor, `HttpLink` constructor, or [request context](./introduction#managing-context) take precedence.\n\n```ts\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  clientAwareness: {\n    name: \"My Client\",\n    version: \"my_client_version\",\n  },\n  enhancedClientAwareness: {\n    transport: \"extensions\",\n  },\n});\n```\n\n### Configuring with `HttpLink`\n\nYou can configure client awareness when initializing an `HttpLink` using the `clientAwareness` and `enhancedClientAwareness` options. These options take precedence over options provided to the `ApolloClient` constructor but can be overridden by [request context](./introduction#managing-context).\n\n```ts\nimport { ApolloClient, HttpLink } from \"@apollo/client\";\n\nconst link = new HttpLink({\n  clientAwareness: {\n    name: \"My Client\",\n    version: \"my_client_version\",\n  },\n  enhancedClientAwareness: {\n    transport: \"extensions\",\n  },\n});\n\nconst client = new ApolloClient({\n  link,\n  // additional options\n});\n```\n\n<Note>\n\nIf you use `BaseHttpLink`, add `ClientAwarenessLink` to your link chain manually to enable client awareness. `HttpLink` includes `ClientAwarenessLink` by default.\n\n</Note>\n\n### Configuring with request context\n\nConfigure client awareness on a per-request basis by providing the `clientAwareness` field in the request's `context`. These values take precedence over all other configurations.\n\n<Note>\n\nThe `enhancedClientAwareness` field is not supported in request context. Configure this feature at the client or link level instead.\n\n</Note>\n\n```ts\nconst client = new ApolloClient(/* ... */);\n\nfunction MyComponent() {\n  const { data } = useQuery(query, {\n    context: {\n      clientAwareness: {\n        name: \"My Client\",\n        version: \"my_client_version\",\n      },\n    },\n  });\n\n  // ...\n}\n```\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/client-awareness!ClientAwarenessLink.ContextOptions:interface\"\n  headingLevel={3}\n  displayName=\"ClientAwarenessLink.ContextOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/client-awareness!ClientAwarenessLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"ClientAwarenessLink.Options\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/client-awareness!ClientAwarenessLink.ClientAwarenessOptions:interface\"\n  headingLevel={3}\n  displayName=\"ClientAwarenessLink.ClientAwarenessOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/client-awareness!ClientAwarenessLink.EnhancedClientAwarenessOptions:interface\"\n  headingLevel={3}\n  displayName=\"ClientAwarenessLink.EnhancedClientAwarenessOptions\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-context.mdx",
    "content": "---\ntitle: SetContextLink\ndescription: Easily set a context on your operation, which is used by other links further down the chain.\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/context!SetContextLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  setter: SetContextLink.ContextSetter\n): SetContextLink\n```\n\n## Usage examples\n\n### Authentication\n\nThe most common use case is adding authentication headers to requests:\n\n```ts\nconst authLink = new SetContextLink((prevContext, operation) => {\n  const token = getAuthToken();\n\n  return {\n    headers: {\n      ...prevContext.headers,\n      authorization: token ? `Bearer ${token}` : \"\",\n    },\n  };\n});\n```\n\n### Asynchronous token lookup\n\nYou can also perform asynchronous operations to fetch tokens or other data:\n\n```ts\nconst asyncAuthLink = new SetContextLink(async (prevContext, operation) => {\n  const token = await fetchAuthToken();\n\n  return {\n    headers: {\n      ...prevContext.headers,\n      authorization: `Bearer ${token}`,\n    },\n  };\n});\n```\n\n## Caching lookups\n\nTypically async actions can be expensive and may not need to be called for every request, especially when a lot of request are happening at once. You can setup your own caching and invalidation outside of the link, to make it faster but still flexible.\n\nTake for example a user auth token being found, cached, then removed on a 401 response:\n\n```js\nimport { ServerError } from \"@apollo/client\";\nimport { SetContextLink } from \"@apollo/client/link/context\";\nimport { ErrorLink } from \"@apollo/client/link/error\";\n\n// cached storage for the user token\nlet token;\nconst withToken = new SetContextLink(async (prevContext, operation) => {\n  // if you have a cached value, return it immediately\n  if (token) {\n    return {\n      headers: {\n        ...prevContext.headers,\n        authorization: `Bearer ${token}`,\n      },\n    };\n  }\n\n  const userToken = await AsyncTokenLookup();\n  token = userToken;\n  return {\n    headers: {\n      ...prevContext.headers,\n      authorization: `Bearer ${token}`,\n    },\n  };\n});\n\nconst resetToken = new ErrorLink(({ error }) => {\n  if (ServerError.is(error) && error.statusCode === 401) {\n    // remove cached token on 401 from the server\n    token = null;\n  }\n});\n\nconst authFlowLink = withToken.concat(resetToken);\n```\n\n## Types\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/context!SetContextLink.SetContextLinkDocumentationTypes.ContextSetter:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"SetContextLink.ContextSetter\"\n/>\n\n### `SetContextLink.SetContextOperation`\n\n<DocBlock canonicalReference=\"@apollo/client/link/context!SetContextLink.SetContextOperation:type\" />\n\n#### Signature\n\n```ts\ntype SetContextOperation = Omit<\n  ApolloLink.Operation,\n  \"getContext\" | \"setContext\"\n>;\n```\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-error.mdx",
    "content": "---\ntitle: ErrorLink\ndescription: Handle and inspect errors in your GraphQL network stack.\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/error!ErrorLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n{/* TODO: Remove the custom signature once documentation supports rendering constructor functions */}\n\n```ts\nconstructor(\n  errorHandler: ErrorLink.ErrorHandler\n): ErrorLink\n```\n\n## Types\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/error!ErrorLink.ErrorLinkDocumentationTypes.ErrorHandler:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"ErrorLink.ErrorHandler\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/error!ErrorLink.ErrorHandlerOptions:interface\"\n  headingLevel={3}\n  displayName=\"ErrorLink.ErrorHandlerOptions\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-http.mdx",
    "content": "---\ntitle: HttpLink\ndescription: Get GraphQL results over a network using HTTP fetch.\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/http!HttpLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n{/* TODO: Remove the custom signature once documentation supports rendering constructor functions */}\n\n```ts\nconstructor(\n  options: HttpLink.Options = {}\n): HttpLink\n```\n\n## Operation results\n\nAfter your GraphQL endpoint successfully responds with the result of an operation, `HttpLink` sets the `Response` object as the `response` field of the operation `context`. This enables each previous link in your link chain to interact with the response.\n\n## Customizing `fetch`\n\nProvide a custom [`fetch` option](#options-fetch) to the `HttpLink` constructor if you need fine-grained control over the underlying `fetch` call. The function should behave identically to the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch).\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/http!HttpLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"HttpLink.Options\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/http!HttpLink.ContextOptions:interface\"\n  headingLevel={3}\n  displayName=\"HttpLink.ContextOptions\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-persisted-queries.mdx",
    "content": "---\ntitle: PersistedQueryLink\ndescription: Secure your graph while minimizing request latency\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\nRead the [Persisted queries](../../data/persisted-queries) guide to learn how to use persisted queries with Apollo Client.\n\n## Constructor signature\n\n```ts\nconstructor(\n  options: PersistedQueryLink.Options\n): PersistedQueryLink\n```\n\n#### `PersistedQueryLink` options\n\nThe `PersistedQueryLink` class takes a configuration object:\n\n- `sha256`: a SHA-256 hashing function. Can be sync or async. Providing a SHA-256 hashing function is required, unless you're defining a fully custom hashing approach via `generateHash`.\n- `generateHash`: an optional function that takes the query document and returns the hash. If provided this custom function will override the default hashing approach that uses the supplied `sha256` function. If not provided, the persisted queries link will use a fallback hashing approach leveraging the `sha256` function.\n- `useGETForHashedQueries`: set to `true` to use the HTTP `GET` method when sending the hashed version of queries (but not for mutations). `GET` requests are not compatible with `@apollo/client/link/batch-http`.\n  > If you want to use `GET` for non-mutation queries whether or not they are hashed, pass `useGETForQueries: true` option to `HttpLink` instead. If you want to use `GET` for all requests, pass `fetchOptions: {method: 'GET'}` to `HttpLink`.\n- `disable`: a function which takes a [`PersistedQueryLink.DisableFunctionOptions`](#persistedquerylinkdisablefunctionoptions) object and returns a boolean to disable any future persisted queries for that session. This defaults to disabling on `PersistedQueryNotSupported` error.\n- `retry`: a function which takes a [`PersistedQueryLink.RetryFunctionOptions`](#persistedquerylinkretryfunctionoptions) object and returns a boolean to retry the request with the full query text included. This defaults to `true` on `PersistedQueryNotSupported` or `PersistedQueryNotFound` errors.\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.DisableFunctionOptions:interface\"\n  headingLevel={3}\n  displayName=\"PersistedQueryLink.DisableFunctionOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.ErrorMeta:interface\"\n  headingLevel={3}\n  displayName=\"PersistedQueryLink.ErrorMeta\"\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.PersistedQueryLinkDocumentationTypes.GenerateHashFunction:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"PersistedQueryLink.GenerateHashFunction\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.GenerateHashOptions:interface\"\n  headingLevel={3}\n  displayName=\"PersistedQueryLink.GenerateHashOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.RetryFunctionOptions:interface\"\n  headingLevel={3}\n  displayName=\"PersistedQueryLink.RetryFunctionOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/persisted-queries!PersistedQueryLink.SHA256Options:interface\"\n  headingLevel={3}\n  displayName=\"PersistedQueryLink.SHA256Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-remove-typename.mdx",
    "content": "---\ntitle: RemoveTypenameFromVariablesLink\ndescription: Automatically remove __typename fields from variables.\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/remove-typename!RemoveTypenameFromVariablesLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options?: RemoveTypenameFromVariablesLink.Options\n): RemoveTypenameFromVariablesLink\n```\n\n## Use case\n\nAs an example, take the following query. Apollo Client automatically adds `__typename` fields for each field selection set.\n\n```ts\nconst query = gql`\n  query DashboardQuery($id: ID!) {\n    dashboard(id: $id) {\n      id\n      name\n    }\n  }\n`;\n\nconst { data } = await client.query({ query, variables: { id: 1 } });\n// {\n//   \"dashboard\": {\n//     \"__typename\": \"Dashboard\",\n//     \"id\": 1,\n//     \"name\": \"My Dashboard\"\n//   }\n// }\n```\n\nNow let's update this dashboard by sending a mutation to our server. We'll use the `dashboard` returned from the previous query as input to our mutation.\n\n```ts\nconst mutation = gql`\n  mutation UpdateDashboardMutation($dashboard: DashboardInput!) {\n    updateDashboard(dashboard: $dashboard) {\n      id\n      name\n    }\n  }\n`;\n\nawait client.mutate({\n  mutation,\n  variables: {\n    dashboard: { ...data.dashboard, name: \"My Updated Dashboard\" },\n  },\n});\n```\n\nWithout the use of `RemoveTypenameFromVariablesLink`, the server will return an error because `data.dashboard` still contains the `__typename` field.\n\n## Usage\n\nInclude `RemoveTypenameFromVariablesLink` anywhere in your [link chain](./introduction/#composing-a-link-chain) before your [terminating link](./introduction#the-terminating-link)\nto remove `__typename` fields from variables for all operations.\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\nimport { RemoveTypenameFromVariablesLink } from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink();\nconst link = ApolloLink.from([removeTypenameLink, httpLink]);\n\nconst client = new ApolloClient({\n  link,\n  // ... other options\n});\n```\n\nIf you're using [directional composition](/react/api/link/introduction#directional-composition),\nfor example, to [send a subscription to a websocket connection](/react/data/subscriptions#3-split-communication-by-operation-recommended),\nplace `RemoveTypenameFromVariablesLink` before the split link to remove `__typename` from variables for all operations.\n\n```ts\nimport { OperationTypeNode } from \"graphql\";\nimport { ApolloLink } from \"@apollo/client\";\nimport { RemoveTypenameFromVariablesLink } from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink();\n\nconst splitLink = ApolloLink.split(\n  ({ operationType }) => {\n    return operationType === OperationTypeNode.SUBSCRIPTION;\n  },\n  wsLink,\n  httpLink\n);\n\nconst link = ApolloLink.from([removeTypenameLink, splitLink]);\n\nconst client = new ApolloClient({\n  link,\n  // ... other options\n});\n```\n\n## Keep `__typename` in JSON scalars\n\nYou may need to retain the `__typename` field from a query's response—for example, in the case of [JSON scalar](https://github.com/taion/graphql-type-json) input fields.\n\nWhile the [GraphQL type validation spec](https://spec.graphql.org/October2021/#sec-Input-Objects.Type-Validation) disallows input fields that begin with two underscores (`__`), this restriction doesn't apply when the input field is a [JSON scalar](https://github.com/taion/graphql-type-json). (A JSON scalar type accepts raw JSON as input.) You can configure `RemoveTypenameFromVariablesLink` link to retain `__typename` for certain `JSON` scalars.\n\nTo do so, provide an `except` option when instantiating `RemoveTypenameFromVariablesLink` and use the `KEEP` sentinel to denote which variables types should keep `__typename`. Each key in the `except` option should correspond to an input type in your GraphQL schema.\n\nFor example, suppose your schema includes a `ConfigureDashboardMutation` mutation that takes a `JSON` type variable named `$dashboardConfig`:\n\n```graphql\nmutation ConfigureDashboardMutation($dashboardConfig: JSON) {\n  configureDashboard(config: $dashboardConfig) {\n    id\n  }\n}\n```\n\nYou tell `RemoveTypenameFromVariablesLink` to keep all `__typename` fields for any variable declared as a `JSON` type with the `KEEP` sentinel. Variable types are inferred from the GraphQL query.\n\n```ts\nimport {\n  RemoveTypenameFromVariablesLink,\n  KEEP,\n} from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink({\n  except: {\n    JSON: KEEP,\n  },\n});\n```\n\nWhen the query moves through `RemoveTypenameFromVariablesLink`, the `dashboardConfig` variable will be detected as a `JSON` scalar type and all `__typename` fields are kept intact.\n\n<Note>\n\nThe JSON scalar type does not need to be literally named `JSON` to be considered a JSON scalar.\n\n</Note>\n\n### Nested JSON scalar fields in input variables\n\nNot all top-level variables may map to a JSON scalar type. For more complex input object types, the JSON scalar may be found on a nested field. The `except` option lets you configure nested fields within these types to keep `__typename` intact.\n\n```ts\nimport {\n  RemoveTypenameFromVariablesLink,\n  KEEP,\n} from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink({\n  except: {\n    DashboardInput: {\n      config: KEEP,\n    },\n  },\n});\n```\n\nVariables declared as type `DashboardInput` will have all top-level `__typename` fields removed, but keep `__typename` for the `config` field.\n\nThis nesting can be as deep as needed and include as many fields as necessary. Use the `KEEP` sentinel to determine where `__typename` should be kept.\n\n```ts\nimport {\n  RemoveTypenameFromVariablesLink,\n  KEEP,\n} from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink({\n  except: {\n    // Keep __typename for `bar` and `baz` fields on any variable\n    // declared as a `FooInput` type\n    FooInput: {\n      bar: KEEP,\n      baz: KEEP,\n    },\n\n    // Keep __typename for the `baz.qux` field on any variable\n    // declared as a `BarInput` type\n    BarInput: {\n      baz: {\n        qux: KEEP,\n      },\n    },\n\n    // Keep __typename on `bar.baz` and `bar.qux.foo` fields for any\n    // variable declared as a `BazInput` type\n    BazInput: {\n      bar: {\n        baz: KEEP,\n        qux: {\n          foo: KEEP,\n        },\n      },\n    },\n  },\n});\n```\n\nTo keep `__typename` for nested fields in arrays, use the same object notation as if the field were an object type.\n\n```ts\nimport {\n  RemoveTypenameFromVariablesLink,\n  KEEP,\n} from \"@apollo/client/link/remove-typename\";\n\nconst removeTypenameLink = new RemoveTypenameFromVariablesLink({\n  except: {\n    // Keep __typename on the `config` field for each widget\n    // in the `widgets` array for variables declared as\n    // a `DashboardInput` type\n    DashboardInput: {\n      widgets: {\n        config: KEEP,\n      },\n    },\n  },\n});\n```\n\n## Types\n\n### `RemoveTypenameFromVariablesLink.KeepTypenameConfig`\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/remove-typename!RemoveTypenameFromVariablesLink.KeepTypenameConfig:interface\"\n  example\n  remarks\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/remove-typename!RemoveTypenameFromVariablesLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"RemoveTypenameFromVariablesLink.Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-retry.mdx",
    "content": "---\ntitle: RetryLink\ndescription: Attempt an operation multiple times if it fails due to network or server errors.\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/retry!RetryLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options?: RetryLink.Options\n): RetryLink\n```\n\n## Avoiding thundering herd\n\nStarting with `initialDelay`, the delay of each subsequent retry is increased exponentially, meaning it's multiplied by 2 each time. For example, if `initialDelay` is 100, additional retries will occur after delays of 200, 400, 800, etc.\n\nWith the `jitter` option enabled, delays are randomized anywhere between 0ms (instant), and 2x the configured delay. This way you get the same result on average, but with random delays.\n\nThese two features are combined to help alleviate [the thundering herd problem](https://en.wikipedia.org/wiki/Thundering_herd_problem), by distributing load during major outages. Without these strategies, when your server comes back up it will be hit by all of your clients at once, possibly causing it to go down again.\n\n## Custom strategies\n\nInstead of the options object, you may pass a function for `delay` and/or `attempts`, which implement custom strategies for each. In both cases the function is given the same arguments (`attempt`, `operation`, `error`).\n\nThe `attempts` function should return a `boolean` (or a `Promise` which resolves to a `boolean`) indicating whether the response should be retried. If yes, the `delay` function is then called, and should return the number of milliseconds to delay by.\n\n```ts\nimport { RetryLink } from \"@apollo/client/link/retry\";\n\nconst link = new RetryLink({\n  attempts: (attempt, operation, error) => {\n    return !!error && operation.operationName != \"specialCase\";\n  },\n  delay: (attempt, operation, error) => {\n    return attempt * 1000 * Math.random();\n  },\n});\n```\n\n## Types\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/retry!RetryLink.RetryLinkDocumentationTypes.AttemptsFunction:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"RetryLink.AttemptsFunction\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/retry!RetryLink.AttemptsOptions:interface\"\n  headingLevel={3}\n  displayName=\"RetryLink.AttemptsOptions\"\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/retry!RetryLink.RetryLinkDocumentationTypes.DelayFunction:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"RetryLink.DelayFunction\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/retry!RetryLink.DelayOptions:interface\"\n  headingLevel={3}\n  displayName=\"RetryLink.DelayOptions\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/retry!RetryLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"RetryLink.Options\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-schema.mdx",
    "content": "---\ntitle: SchemaLink\ndescription: Assists with mocking and server-side rendering\n---\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/schema!SchemaLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  options: SchemaLink.Options\n): SchemaLink\n```\n\n## Usage examples\n\n### Server Side Rendering\n\nWhen performing SSR _on the same server_, you can use this library to avoid making network calls.\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { SchemaLink } from \"@apollo/client/link/schema\";\n\nimport schema from \"./path/to/your/schema\";\n\nconst graphqlClient = new ApolloClient({\n  cache: new InMemoryCache(),\n  ssrMode: true,\n  link: new SchemaLink({ schema }),\n});\n```\n\n### Mocking\n\nFor more detailed information about mocking, refer to the [graphql-tools documentation](https://www.graphql-tools.com/docs/graphql-tools/mocking).\n\n```js\nimport { ApolloClient, InMemoryCache } from '@apollo/client';\nimport { SchemaLink } from '@apollo/client/link/schema';\nimport { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';\n\nconst typeDefs = `\n  Query {\n  ...\n  }\n`;\n\nconst mocks = {\n  Query: () => ...,\n  Mutation: () => ...\n};\n\nconst schema = makeExecutableSchema({ typeDefs });\nconst schemaWithMocks = addMockFunctionsToSchema({\n  schema,\n  mocks\n});\n\nconst apolloCache = new InMemoryCache(window.__APOLLO_STATE__);\n\nconst graphqlClient = new ApolloClient({\n  cache: apolloCache,\n  link: new SchemaLink({ schema: schemaWithMocks })\n});\n```\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/schema!SchemaLink.Options:interface\"\n  headingLevel={3}\n  displayName=\"SchemaLink.Options\"\n/>\n\n### `SchemaLink.ResolverContext`\n\n<DocBlock canonicalReference=\"@apollo/client/link/schema!SchemaLink.ResolverContext:type\" />\n\n#### Signature\n\n```ts\ntype ResolverContext = Record<string, any>;\n```\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link/schema!SchemaLink.SchemaLinkDocumentationTypes.ResolverContextFunction:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"SchemaLink.ResolverContextFunction\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-subscriptions.mdx",
    "content": "---\ntitle: GraphQLWsLink\ndescription: Execute subscriptions (or other operations) over WebSocket with the graphql-ws library\n---\n\n<DocBlock canonicalReference=\"@apollo/client/link/subscriptions!GraphQLWsLink:class\" />\n\n`GraphQLWsLink` requires the [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) library. Install it in your project like so:\n\n```shell\nnpm install graphql-ws\n```\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/subscriptions!GraphQLWsLink:class\"\n  customOrder={[\"example\"]}\n/>\n\n## Constructor signature\n\n{/* TODO: Remove the custom signature once documentation supports rendering constructor functions */}\n\n```js\nconstructor(\n  client: Client\n): GraphQLWsLink\n```\n\n### Options\n\nThe `GraphQLWsLink` constructor takes a single argument: a `Client` instance from the `graphql-ws` library. To create this instance, call the library's [`createClient`](https://the-guild.dev/graphql/ws/docs/client/functions/createClient) function. This function requires a `url` option, which is the URL to your WebSocket server. WebSocket URLs typically start with `ws://` or `wss://`.\n\nSee the [`ClientOptions`](https://the-guild.dev/graphql/ws/docs/client/interfaces/ClientOptions) documentation for more details on the supported options provided to the `createClient` function.\n\n#### Retrying failed connections\n\nSee the [`graphql-ws` recipes](https://the-guild.dev/graphql/ws/recipes) for strategies on retrying failed connections from the client. We generally recommend this approach over retrying failed connections from the link chain or your components because it provides more detailed information on why the connection failed.\n\nAlternatively, you can handle retries more generically within the link chain by using [`RetryLink`](./apollo-link-retry). This link resends the operation to the terminating link upon failure.\n\n## Usage\n\nSee [Subscriptions](../../data/subscriptions/) for more information on using subscription operations in Apollo Client.\n"
  },
  {
    "path": "docs/source/api/link/apollo-link-ws.mdx",
    "content": "---\ntitle: WebSocketLink\ndescription: Execute subscriptions (or other operations) over WebSocket with the subscriptions-transport-ws library\n---\n\n<Caution>\n\n**We no longer recommend using `WebSocketLink` or the `subscriptions-transport-ws` library**, because the library is not actively maintained. To execute subscriptions, We instead recommend using the newer `graphql-ws` library with the accompanying [`GraphQLWsLink`](./apollo-link-subscriptions).\n\nWhichever library you use, make sure you use the _same_ library in your server and any clients you support. For more information, see [Choosing a subscription library](../../data/subscriptions/#choosing-a-subscription-library).\n\n</Caution>\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link/ws!WebSocketLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  paramsOrClient: WebSocketLink.Configuration | SubscriptionClient\n): WebSocketLink\n```\n\n## Installation\n\n`WebSocketLink` requires the [`subscriptions-transport-ws`](https://github.com/apollographql/subscriptions-transport-ws) library. Install it in your project:\n\n```shell\nnpm install subscriptions-transport-ws\n```\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link/ws!WebSocketLink.Configuration:interface\"\n  headingLevel={3}\n  displayName=\"WebSocketLink.Configuration\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/apollo-link.mdx",
    "content": "---\ntitle: ApolloLink\ndescription: API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<DocBlock\n  canonicalReference=\"@apollo/client/link!ApolloLink:class\"\n  customOrder={[\"summary\", \"remarks\", \"example\"]}\n/>\n\n## Constructor signature\n\n```ts\nconstructor(\n  request?: ApolloLink.RequestHandler\n): ApolloLink\n```\n\n## Static methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.from:member(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.from\"\n  result={false}\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.split:member(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.split\"\n  result={false}\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.execute:member(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.execute\"\n  result={false}\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.empty:member(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.empty\"\n  result={false}\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.concat:member(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.concat\"\n  result={false}\n/>\n\n## Instance methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink#concat:member(1)\"\n  headingLevel={3}\n  result={false}\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink#split:member(1)\"\n  headingLevel={3}\n  result={false}\n/>\n\n## Types\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.ExecuteContext:interface\"\n  headingLevel={3}\n  displayName=\"ApolloLink.ExecuteContext\"\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.DocumentationTypes.ForwardFunction:function(1)\"\n  headingLevel={3}\n  displayName=\"ApolloLink.ForwardFunction\"\n  result={false}\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.Request:interface\"\n  headingLevel={3}\n  displayName=\"ApolloLink.Request\"\n/>\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.DocumentationTypes.RequestHandler:function(1)\"\n  headingLevel={3}\n  result={false}\n  displayName=\"ApolloLink.RequestHandler\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.Operation:interface\"\n  headingLevel={3}\n  displayName=\"ApolloLink.Operation\"\n/>\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client/link!ApolloLink.OperationContext:interface\"\n  headingLevel={3}\n  displayName=\"ApolloLink.OperationContext\"\n/>\n"
  },
  {
    "path": "docs/source/api/link/community-links.mdx",
    "content": "---\ntitle: Community links\n---\n\nThank you to all the Apollo community members who have contributed custom Apollo links! If you've built a link and would like it to be featured, please submit a pull request.\n\n> Links that do not appear to be actively maintained might be removed from this list at Apollo's discretion.\n\n| Link                                                                                                                        | Author                                                   | Description                                                                                                      |\n| --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |\n| [apollo-link-webworker](https://github.com/PCreations/apollo-link-webworker)                                                | [@PCreations](https://github.com/PCreations)             | Lets you use GraphQL client-side only, with a webworker as a \"server\" supporting normal query and subscriptions. |\n| [apollo-upload-client](https://github.com/jaydenseric/apollo-upload-client)                                                 | [@jaydenseric](https://github.com/jaydenseric)           | Enhances Apollo for intuitive file uploads via GraphQL mutations.                                                |\n| [apollo-angular-link-http](https://www.npmjs.com/package/apollo-angular-link-http)                                          | [@kamilkisiela](https://github.com/kamilkisiela)         | An HTTP link for use with [Apollo Angular](https://apollo-angular.com/).                                         |\n| [apollo-angular-link-headers](https://www.npmjs.com/package/apollo-angular-link-headers)                                    | [@kamilkisiela](https://github.com/kamilkisiela)         | Transform a key-value object into an instance of `HttpHeaders` (`@angular/common/http`).                         |\n| [react-apollo-network-status](https://github.com/molindo/react-apollo-network-status)                                       | [@amannn](https://github.com/amannn)                     | Brings information about the global network status from Apollo into React.                                       |\n| [apollo-link-watched-mutation](https://github.com/haytko/apollo-link-watched-mutation)                                      | [@haytko](https://github.com/haytko)                     | Organizes cache invalidations per query on a mutation.                                                           |\n| [apollo-link-token-refresh](https://github.com/newsiberian/apollo-link-token-refresh)                                       | [@newsiberian](https://github.com/newsiberian)           | Performs expired JWT renewal.                                                                                    |\n| [link-http-dataloader](https://github.com/graphcool/http-link-dataloader)                                                   | [@graphcool](https://github.com/graphcool)               | Batching and caching provided by dataloader.                                                                     |\n| [@absinthe/socket-apollo-link](https://github.com/absinthe-graphql/absinthe-socket/tree/master/packages/socket-apollo-link) | [@absinthe-graphql](https://github.com/absinthe-graphql) | Communicate over an Absinthe socket.                                                                             |\n| [apollo-absinthe-upload-link](https://github.com/bytewitchcraft/apollo-absinthe-upload-link)                                | [@bytewitchcraft](https://github.com/bytewitchcraft)     | Enables file uploading to Absinthe backends.                                                                     |\n| [apollo-link-logger](https://github.com/blackxored/apollo-link-logger)                                                      | [@blackxored](https://github.com/blackxored)             | Logger that uses similar format to redux-logger and includes performance information.                            |\n| [apollo-link-queue](https://github.com/helfer/apollo-link-queue)                                                            | [@helfer](https://github.com/helfer)                     | Buffers requests on a toggle, such as an on/offline event.                                                       |\n| [apollo-link-optimistic](https://github.com/helfer/apollo-link-optimistic)                                                  | [@helfer](https://github.com/helfer)                     | Returns an immediate optimistic response before returning server results.                                        |\n| [apollo-link-serialize](https://github.com/helfer/apollo-link-serialize)                                                    | [@helfer](https://github.com/helfer)                     | Serializes requests by key to ensure execution order.                                                            |\n| [apollo-link-debounce](https://github.com/helfer/apollo-link-debounce)                                                      | [@helfer](https://github.com/helfer)                     | Debounce requests made within an interval.                                                                       |\n| [apollo-link-segment](https://github.com/hobochild/apollo-link-segment)                                                     | [@hobochild](https://github.com/hobochild)               | Automatically track apollo operations with [segment](https://segment.com/).                                      |\n| [apollo-link-observable](https://github.com/dragozin/apollo-link-observable)                                                | [@dragozin](https://github.com/dragozin)                 | Link that allows you to make side effects of graphql queries using [RxJS](http://github.com/ReactiveX/RxJS).     |\n| [apollo-multi-endpoint-link](https://github.com/habx/apollo-multi-endpoint-link)                                            | [@habx](https://github.com/habx)                         | Add directive to redirect requests to right endpoint                                                             |\n| [@grafbase/apollo-link](https://github.com/grafbase/playground/tree/main/packages/grafbase-apollo-link)                     | [@grafbase](https://github.com/grafbase)                 | Use GraphQL `@live` queries with Server-Sent Events.                                                             |\n| [apollo-link-printer](https://github.com/egorlem/apollo-link-printer)                                                       | [@egorlem](https://github.com/egorlem)                   | Pretty logger of Apollo GraphQL network operations.                                                              |\n"
  },
  {
    "path": "docs/source/api/link/introduction.mdx",
    "content": "---\ntitle: Apollo Link overview\ndescription: Customize Apollo Client's data flow\n---\n\nThe **Apollo Link** library helps you customize the flow of data between Apollo Client and your GraphQL server. You can define your client's network behavior as a chain of **link** objects that execute in a sequence:\n\n```mermaid\nflowchart LR\n  subgraph Apollo Client\n  operation(GraphQL operation)\n  link1(Link)\n  link2(Link)\n  link3(Terminating Link)\n  operation--\"Initiated\"-->link1\n  link1--down-->link2\n  link2--down-->link3\n  link3--up-->link2\n  link2--up-->link1\n  link1--\"Completed\"-->operation\n  end\n  server(GraphQL server)\n  link3--Request-->server\n  server--Response-->link3\n  class server secondary;\n```\n\nEach link should represent either a self-contained modification to a GraphQL operation or a side effect (such as logging).\n\n**In the above diagram:**\n\n1.  The first link might log the details of the operation for debugging purposes.\n2.  The second link might add an HTTP header to the outgoing operation request for authentication purposes.\n3.  The final link (called the [terminating link](#the-terminating-link)) sends the operation to its destination (usually a GraphQL server over HTTP).\n4.  The server's response is passed back up each link in reverse order, enabling links to [modify the response](#handling-a-response) or take other actions before the data is cached.\n\n## Composing a link chain\n\nA link chain consists of one or more link objects. Each link represents either a self-contained modification to a GraphQL operation or a side effect (such as logging). By composing these links into a chain, you can create an arbitrarily complex model for your client's data flow.\n\nWhen you compose multiple links together, the result is a single link object that represents the entire chain. You provide the composed link to your Apollo Client instance using the `link` option:\n\n```ts {4}\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  link: /* your composed link */,\n  cache: new InMemoryCache(),\n});\n```\n\n### The terminating link\n\nThe last link in the link chain is called the _terminating link_. Instead of calling the [`forward` function](#the-forward-function), it is responsible for sending the GraphQL operation to the destination that executes it (typically a GraphQL server) and returning a result. If a link chain consists of a single link, the single link is the terminating link.\n\n[`HttpLink`](./apollo-link-http/) and [`BatchHttpLink`](./apollo-link-batch-http/) are examples of terminating links.\n\n### Link composition\n\nYou compose multiple links together to form a link chain using two forms of link composition: additive and directional.\n\n- [Additive composition](#additive-composition) involves combining a set of links into a serially executed chain:\n\n  ```mermaid\n  flowchart LR\n    link1(Link)\n    link2(Link)\n    link3(Terminating Link)\n    link1-->link2\n    link2-->link3\n  ```\n\n- [Directional composition](#directional-composition) involves branching to one of two links, depending on the details of an operation:\n\n  ```mermaid\n  flowchart LR\n    link1(Link)\n    link2(Link)\n    link3(Terminating Link)\n    link4(Terminating Link)\n    link1-->link2\n    link1-->link3\n    link2-->link4\n  ```\n\n<Note>\n\nNo matter how your chain branches, each branch always ends in a [terminating link](#the-terminating-link).\n\n</Note>\n\n#### Additive composition\n\nAdditive composition composes a link chain by executing links in serial order. You use the [`ApolloLink.from`](#apollolinkfrom) and [`ApolloLink.concat`](#apollolinkconcat) helpers to create a link chain using additive composition.\n\n##### `ApolloLink.from`\n\nThe most common way to compose multiple links together is to use the static `ApolloLink.from` helper. Pass an array of link objects to `ApolloLink.from` to create a composed link that executes each link in serial order:\n\n```ts\nimport { HttpLink, ApolloLink } from \"@apollo/client\";\nimport { RetryLink } from \"@apollo/client/link/retry\";\nimport MyAuthLink from \"../auth\";\n\nconst link = ApolloLink.from([\n  new RetryLink(),\n  new MyAuthLink(),\n  new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n]);\n```\n\n##### `ApolloLink.concat`\n\nEach link object includes a `concat` instance method to combine two links into a single composed link. This is useful to combine multiple links together using a chain of function calls:\n\n```ts\nimport { ApolloLink, HttpLink } from \"@apollo/client\";\nimport { RetryLink } from \"@apollo/client/link/retry\";\nimport MyAuthLink from \"../auth\";\n\nconst link = new RetryLink()\n  .concat(new MyAuthLink())\n  .concat(new HttpLink({ uri: \"http://localhost:4000/graphql\" }));\n```\n\n<Note>\n\nThe link chain created by the `from` and `concat` examples are functionally equivalent and differ only in style. Choose the style that best fits your application. You may choose to mix and match these styles as needed.\n\n</Note>\n\n#### Directional composition\n\nYou might want your link chain's execution to branch, depending on the details of the operation being performed. You use the `ApolloLink.split` method to create a link that conditionally routes to different sub-chains.\n\nThe `ApolloLink.split` function takes three arguments:\n\n| Name    | Description                                                                                                                                                                                        |\n| ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `test`  | A function that takes in the current `operation` and returns `true` or `false`. Returning `true` executes the `left` link. Returning `false` executes the `right` link.                            |\n| `left`  | The link passed as the second argument to `split`. This link executes when the `test` function returns `true`.                                                                                     |\n| `right` | An optional link passed as the third argument to `split`. This link executes when the `test` function returns `false`. If this is not provided, the request handler's `forward` parameter is used. |\n\nThe following example uses `ApolloLink.split` to create a link that routes to different `HttpLink` instances depending on the associated context's `version`:\n\n```ts\nimport { ApolloLink, HttpLink } from \"@apollo/client\";\n\nconst link = ApolloLink.split(\n  (operation) => operation.getContext().version === 1,\n  new HttpLink({ uri: \"http://localhost:4000/v1/graphql\" }),\n  new HttpLink({ uri: \"http://localhost:4000/v2/graphql\" })\n);\n```\n\n<Note>\n\nEach link instance also provides a `split` function. This is used to apply directional composition to an existing link.\n\n<ExpansionPanel title=\"Example\">\n\nThe following example adds directional composition to a `previousLink` to determine which `HttpLink` should be used as the terminating link.\n\n```ts\nconst link = previousLink.split(\n  (operation) => operation.getContext().version === 1,\n  new HttpLink({ uri: \"http://localhost:4000/v1/graphql\" }),\n  new HttpLink({ uri: \"http://localhost:4000/v2/graphql\" })\n);\n```\n\n</ExpansionPanel>\n\n</Note>\n\nOther uses for the `split` method include:\n\n- Using different transport methods depending on the operation type (such as HTTP for queries and WebSocket for subscriptions)\n- Customizing the number of allowed retry attempts depending on the operation type\n- Customizing logic depending on whether a user is logged in\n\nIn the following example, all subscription operations are sent to `GraphQLWsLink`, with all other operations sent to `HttpLink`:\n\n```ts\nimport { ApolloLink, HttpLink } from \"@apollo/client\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { OperationTypeNode } from \"graphql\";\nimport { createClient } from \"graphql-ws\";\n\nconst link = ApolloLink.split(\n  ({ operationType }) => {\n    return operationType === OperationTypeNode.SUBSCRIPTION;\n  },\n  new GraphQLWsLink(createClient({ url: \"ws://localhost:3000/subscriptions\" })),\n  new HttpLink({ uri: \"http://localhost:4000/graphql\" })\n);\n```\n\n## Creating a custom link\n\nA link object is an instance of the [`ApolloLink` class](https://github.com/apollographql/apollo-client/blob/main/src/link/core/ApolloLink.ts). Each link must define a [_request handler_](#the-request-handler) to handle the request.\n\n### The request handler\n\nEvery link must define a request handler. The request handler is a method responsible for performing some logic and executing the request, either by [forwarding](#the-forward-function) the operation to the next link in the chain, or sending the operation to the destination that executes it, such as a GraphQL server.\n\nThis request handler receives the following arguments:\n\n- `operation`: The [operation object](#the-operation-object) that provides information about the currently executed GraphQL request passed through the link.\n- `forward`: A [function](#the-forward-function) called to execute the next link in the chain.\n\nApollo Client executes a GraphQL operation by calling the request handler of the first link in the composed link chain. Each non-terminating link is then responsible for executing its logic and delegating execution down to the next link by calling the [`forward` function](#the-forward-function). After the operation reaches the [terminating link](#the-terminating-link), the request handler sends the operation to the destination and reports the result back up through the chain.\n\n#### Define a request handler using a callback function\n\nThe most common way to provide a request handler is by passing a callback function to the `ApolloLink` constructor:\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\n\nconst link = new ApolloLink((operation, forward) => {\n  // Handle the request\n});\n```\n\nThe callback function is called for each GraphQL operation sent through the link chain.\n\n#### Define a request handler for an Apollo Link subclass\n\nYou define a request handler for a subclass of `ApolloLink` by overriding the `request` method. Subclassing is typically used to create [stateful links](#stateful-links).\n\n```ts {7-9}\nclass MyCustomLink extends ApolloLink {\n  constructor() {\n    super();\n    // ...other setup logic\n  }\n\n  request(operation, forward) {\n    // Handle the request\n  }\n}\n```\n\nThe `request` method is called for each GraphQL operation sent through the link chain.\n\n### The `Operation` object\n\nThe `Operation` object includes the following fields:\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client!ApolloLink.Operation:interface\"\n  idPrefix=\"operation\"\n/>\n\n### The `forward` function\n\nAfter your custom link's request handler is finished performing its logic, return a call to the `forward` function and provide the `operation` as an argument. Calling the `forward` function executes the next link in the chain.\n\n```tsx {5}\nconst link = new ApolloLink((operation, forward) => {\n  // ...Handle the request\n\n  // Execute the next link in the chain\n  return forward(operation);\n});\n```\n\nThe `forward` function returns an [`Observable`](https://rxjs.dev/guide/observable) provided by the [RxJS](https://rxjs.dev/) library. Learn more about Observables in the [RxJS documentation](https://rxjs.dev/guide/observable).\n\n<Caution>\n\nA non-terminating custom link's request handler must call `forward(operation)`. If it doesn't, the link is treated as a [terminating link](#the-terminating-link). This might result in the associated GraphQL operation not executed and the request remains pending indefinitely.\n\n</Caution>\n\n## Handling a response\n\nWhen your GraphQL server responds with an operation result, that result is passed back up through each link in your chain:\n\n```mermaid\nflowchart LR\n  subgraph Apollo Client\n  operation(GraphQL operation)\n  link1(Link)\n  link2(Link)\n  link3(Terminating Link)\n  operation--\"Initiated\"-->link1\n  link1--down-->link2\n  link2--down-->link3\n  link3--up-->link2\n  link2--up-->link1\n  link1--\"Completed\"-->operation\n  end\n  server(GraphQL server)\n  link3--Request-->server\n  server--Response-->link3\n  class server secondary;\n```\n\nEach link can perform custom logic on the result using [operators](https://rxjs.dev/guide/operators). These are special functions passed to an Observable's [`pipe`](https://rxjs.dev/guide/operators#piping) function.\n\nThe following example uses the RxJS [`map` operator](https://rxjs.dev/api/index/function/map) to modify the result before returning it back up the chain:\n\n```ts\nimport { map } from \"rxjs\";\n\nconst link = new ApolloLink((operation, forward) => {\n  return forward(operation).pipe(\n    map((result) => {\n      // ...modify result as desired here...\n      return result;\n    })\n  );\n});\n```\n\nThis modification is seen by any previous link in the chain because the result travels back up the chain in reverse order.\n\n<Note>\n\nThe `map` function is the most common operator for performing modifications to the result. See the RxJS [operators](https://rxjs.dev/guide/operators) documentation for references to other operators that provide other functionality that you can use when building custom links.\n\n</Note>\n\n### Executing side-effects\n\nLinks commonly perform side-effects when receiving responses instead of modifying the result.\n\nThe following example uses the [`tap` operator](https://rxjs.dev/api/operators/tap) to estimate the round-trip time of an operation by defining a start time on the [request context](#managing-context) then logging the total time when the response is received.\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\nimport { tap } from \"rxjs\";\n\nconst roundTripLink = new ApolloLink((operation, forward) => {\n  // Called before operation is sent to server\n  operation.setContext({ start: new Date() });\n\n  return forward(operation).pipe(\n    tap((result) => {\n      // Called after server responds\n      const time = new Date() - operation.getContext().start;\n      console.log(\n        `Operation ${operation.operationName} took ${time} to complete`\n      );\n    })\n  );\n});\n```\n\n<Note>\n\nThe `tap` function is the most common operator for performing side-effects on the response. See the RxJS [operators](https://rxjs.dev/guide/operators) documentation for references to other operators that provide other functionality that you might need when building custom links.\n\n</Note>\n\n## Link types\n\n### Stateless links\n\nMost links perform the same logic for every operation they process and they don't need to know anything about operations that have been executed previously. These links are _stateless_.\n\nStateless links typically define request handlers by providing a callback function to the constructor of an `ApolloLink` object:\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\nimport { tap } from \"rxjs\";\n\nconst consoleLink = new ApolloLink((operation, forward) => {\n  console.log(`starting request for ${operation.operationName}`);\n  return forward(operation).pipe(\n    tap(() => {\n      console.log(`ending request for ${operation.operationName}`);\n    })\n  );\n});\n```\n\nStateless links are great for building middleware. The following link adds an `Authorization` header to every outgoing request:\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\n\nconst authLink = new ApolloLink((operation, forward) => {\n  operation.setContext(({ headers }) => ({\n    headers: {\n      authorization: Auth.userId(), // however you get your token\n      ...headers,\n    },\n  }));\n\n  return forward(operation);\n});\n```\n\nYou can customize stateless links by wrapping them in a function:\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\n\nfunction reportErrors(errorCallback) {\n  return new ApolloLink((operation, forward) => {\n    return new Observable((observer) => {\n      const observable = forward(operation);\n      const subscription = observable.subscribe({\n        next(value) {\n          observer.next(value);\n        },\n        error(networkError) {\n          errorCallback({ networkError, operation });\n          observer.error(networkError);\n        },\n        complete() {\n          observer.complete();\n        },\n      });\n\n      return () => subscription.unsubscribe();\n    });\n  });\n}\n\nconst link = reportErrors(console.error);\n```\n\n#### Extending `ApolloLink`\n\nYou can also create stateless links by subclassing the `ApolloLink` class and overriding the constructor and request handler.\n\nHere's the same `reportErrors` link written as a subclass of `ApolloLink`:\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\nimport { tap } from \"rxjs\";\n\nclass ReportErrorLink extends ApolloLink {\n  constructor(errorCallback) {\n    super();\n    this.errorCallback = errorCallback;\n  }\n  request(operation, forward) {\n    return forward(operation).pipe(\n      tap({\n        // errors will be sent to the errorCallback\n        error: this.errorCallback,\n      })\n    );\n  }\n}\n\nconst link = new ReportErrorLink(console.error);\n```\n\n<Note>\n\nThe `ReportErrorLink` link is still considered a stateless link despite being built as a subclass because it does not maintain state between requests.\n\n</Note>\n\n### Stateful links\n\nLinks that maintain state between operations are called _stateful links_. You create stateful links by defining subclasses of `ApolloLink` and overriding the `constructor` and `request` methods.\n\nThe following example maintains an operation counter using an instance variable. The counter is incremented for every request that passes through the link.\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\n\nclass OperationCountLink extends ApolloLink {\n  constructor() {\n    super();\n    this.operationCount = 0;\n  }\n  request(operation, forward) {\n    this.operationCount += 1;\n    return forward(operation);\n  }\n}\n\nconst link = new OperationCountLink();\n```\n\n## Managing context\n\nAs an operation moves along the link chain, it maintains a `context` that each link can read and modify. This enables both links and request-based APIs (such as [`useQuery`](../react/useQuery)) to pass metadata along the chain that other links use in their execution logic. Context is not included in the terminating link's request to the GraphQL server or other destination.\n\n<Note>\n\nIf your application is built using TypeScript, we recommend reading the [Defining context types](../../development-testing/static-typing#defining-context-types) guide to learn how to provide types for the context object.\n\n</Note>\n\n### Reading context\n\nYou get the current context object by calling `operation.getContext()` in a [request handler](#the-request-handler).\n\n```ts {2}\nconst link = new ApolloLink((operation, forward) => {\n  const context = operation.getContext();\n\n  // handle the request\n});\n```\n\n<Note>\n\nChanges to the `context` object returned from `operation.getContext()` are not persisted, and downstream links won't see them. Use `operation.setContext()` to make modifications to context.\n\n</Note>\n\n### Modifying context\n\nModify context by calling `operation.setContext()`. You provide the updated context as an object directly to `setContext`.\n\n```ts {2}\nconst timeStartLink = new ApolloLink((operation, forward) => {\n  operation.setContext({ start: new Date() });\n\n  return forward(operation);\n});\n```\n\nIt is common to read existing context to make modifications to it before writing it back. As a shortcut, you can provide a callback function to `operation.setContext()`. The callback function provides the previous context as an argument and expects the function to return the new context.\n\n```ts {2-4}\nconst counterLink = new ApolloLink((operation, forward) => {\n  operation.setContext((prevContext) => ({\n    count: prevContext.count + 1,\n  }));\n\n  return forward(operation);\n});\n```\n\n### Providing context for an operation\n\nContext is typically used to communicate between a request API (such as [`useQuery`](../react/useQuery)) and the links in the link chain. You provide context for a particular operation using the `context` option.\n\nThe following example provides the initial context with [`useQuery`](../react/useQuery) to define the initial `count` from the previous example.\n\n```ts\nfunction MyComponent() {\n  const { data } = useQuery(MY_QUERY, { context: { count: 10 } });\n\n  // render data\n}\n```\n"
  },
  {
    "path": "docs/source/api/react/ApolloProvider.mdx",
    "content": "---\ntitle: ApolloProvider\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n## The `ApolloProvider` component\n\nThe `ApolloProvider` component uses [React's Context API](https://react.dev/reference/react/useContext) to make a configured Apollo Client instance available throughout a React component tree. This component can be imported directly from the `@apollo/client/react` package.\n\n```js\nimport { ApolloProvider } from \"@apollo/client/react\";\n```\n\n### Props\n\n| Option   | Type           | Description                 |\n| -------- | -------------- | --------------------------- |\n| `client` | `ApolloClient` | An `ApolloClient` instance. |\n\n### Example\n\n```jsx {7-9}\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({\n    uri: \"http://localhost:4000/graphql\",\n  }),\n});\n\nReactDOM.render(\n  <ApolloProvider client={client}>\n    <MyRootComponent />\n  </ApolloProvider>,\n  document.getElementById(\"root\")\n);\n```\n"
  },
  {
    "path": "docs/source/api/react/hooks-experimental.mdx",
    "content": "---\ntitle: Hooks (experimental)\ndescription: Apollo Client experimental react hooks API reference\n---\n\nThe latest minor version of Apollo Client has no experimental hooks. Please see the [Hooks page](./hooks) for a list of available stable React hooks.\n"
  },
  {
    "path": "docs/source/api/react/hooks.mdx",
    "content": "---\ntitle: Hooks\ndescription: Apollo Client react hooks API reference\nminVersion: 3.0.0\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nThis page has been split into individual hook pages. Select a hook from the navigation sidebar to view its documentation.\n"
  },
  {
    "path": "docs/source/api/react/preloading.mdx",
    "content": "---\ntitle: createQueryPreloader\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!createQueryPreloader:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/skipToken.mdx",
    "content": "---\ntitle: skipToken\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n## `skipToken`\n\n`skipToken` provides a type-safe mechanism to skip query execution. It is currently supported with `useQuery`, `useSuspenseQuery` and `useBackgroundQuery`.\nWhen you pass a `skipToken` to one of the supported hooks instead of the `options` object, the hook will not cause any requests or suspenseful behavior and keeps the last `data` available. It is typically used conditionally to start query execution when the input data is available.\n\n```js title=\"Recommended usage of skipToken with useQuery\"\nimport { skipToken, useQuery } from \"@apollo/client/react\";\n\nconst { data } = useQuery(query, id ? { variables: { id } } : skipToken);\n```\n\n```js title=\"Recommended usage of skipToken with useSuspenseQuery\"\nimport { skipToken, useSuspenseQuery } from \"@apollo/client/react\";\nconst { data } = useSuspenseQuery(\n  query,\n  id ? { variables: { id } } : skipToken\n);\n```\n\n```js title=\"Recommended usage of skipToken with useBackgroundQuery\"\nimport { skipToken, useBackgroundQuery } from \"@apollo/client/react\";\nconst [queryRef] = useBackgroundQuery(\n  query,\n  id ? { variables: { id } } : skipToken\n);\n```\n\n### Why do we recommend `skipToken` over `{ skip: true }`?\n\nImagine this very common scenario for `skip`: You want to skip your query if a certain required variable is not set. You might be tempted to write something like this:\n\n```ts\nconst { data } = useSuspenseQuery(query, {\n  variables: { id },\n  skip: !id,\n});\n```\n\nBut in that case, TypeScript will complain:\n\n```\nType 'number | undefined' is not assignable to type 'number'.\n      Type 'undefined' is not assignable to type 'number'.ts(2769)\n```\n\nTo get around that, you have to tell TypeScript to ignore the fact that `id` could be `undefined`:\n\n```ts\nconst { data } = useSuspenseQuery(query, {\n  variables: { id: id! },\n  skip: !id,\n});\n```\n\nAlternatively, you could also use some obscure default value:\n\n```ts\nconst { data } = useSuspenseQuery(query, {\n  variables: { id: id || 0 },\n  skip: !id,\n});\n```\n\nBoth of these solutions hide a potential bug. If your `skip` logic becomes more complex, you might accidentally introduce a bug that causes your query to execute, even when `id` is still `undefined`. In that case, TypeScript cannot warn you about it.\n\nInstead we recommend using `skipToken`. It provides type safety without the need for an obscure default value:\n\n```ts\nconst { data } = useSuspenseQuery(\n  query,\n  id ? { variables: { id } } : skipToken\n);\n```\n\nHere it becomes apparent for TypeScript that there is a direct connection between skipping and the `variables` option - and it will work without unsafe workarounds.\n"
  },
  {
    "path": "docs/source/api/react/ssr.mdx",
    "content": "---\ntitle: SSR\ndescription: Apollo Client React server side rendering API\n---\n\n## Installation\n\nApollo Client >= 3 includes React hooks functionality out of the box. You don't need to install any additional packages.\n\n## `getDataFromTree`\n\nThe `getDataFromTree` function takes your React tree, determines which queries are needed to render them, and then fetches them all.\n\n```js\nimport { getDataFromTree } from \"@apollo/client/react/ssr\";\n```\n\n### Params\n\n| Param     | Type                     | description                                                                                              |\n| --------- | ------------------------ | -------------------------------------------------------------------------------------------------------- |\n| `tree`    | React.ReactNode          | The React tree you would like to render and fetch data for.                                              |\n| `context` | `{ [key: string]: any }` | Optional values you would like to make available in the React Context during rendering / data retrieval. |\n\n### Result\n\n`getDataFromTree` returns a promise (`Promise<string>`) which resolves when the data is ready in your Apollo Client store. The result is generated using [`ReactDOMServer.renderToStaticMarkup`](https://react.dev/reference/react-dom/server/renderToStaticMarkup) under the hood.\n\n### Example\n\nSee [Executing queries with `getDataFromTree`](../../performance/server-side-rendering/#executing-queries-with-getdatafromtree).\n\n## `renderToStringWithData`\n\nThe `renderToStringWithData` function is similar to `getDataFromTree`, but uses [`ReactDOMServer.renderToString`](https://react.dev/reference/react-dom/server/renderToString) to render its result instead of [`ReactDOMServer.renderToStaticMarkup`](https://react.dev/reference/react-dom/server/renderToStaticMarkup) (the React docs help explain the difference).\n\n```js\nimport { renderToStringWithData } from \"@apollo/client/react/ssr\";\n```\n\n### Params\n\n| Param       | Type                | description                                                           |\n| ----------- | ------------------- | --------------------------------------------------------------------- |\n| `component` | `ReactElement<any>` | The React component tree you would like to render and fetch data for. |\n\n### Result\n\n`renderToStringWithData` returns a promise (`Promise<string>`) which resolves when the data is ready in your Apollo Client store. The result is generated using [`ReactDOMServer.renderToString`](https://react.dev/reference/react-dom/server/renderToString) under the hood.\n"
  },
  {
    "path": "docs/source/api/react/testing.mdx",
    "content": "---\ntitle: MockProvider\ndescription: Apollo Client API reference\n---\n\n> For more guidance on running tests with `MockedProvider`, see [Testing React components](../../development-testing/testing/).\n\n## `MockedProvider`\n\n```js\nimport { MockedProvider } from \"@apollo/client/testing/react\";\n```\n\nThe `MockedProvider` component is a mocked version of [`ApolloProvider`](./hooks/#the-apolloprovider-component) that doesn't send network requests to your API. Instead, it allows you to specify the exact response payload for a given GraphQL operation. This enables you to test your application's operations without communicating with a server.\n\n#### Props\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n<tr>\n<td>\n\n###### `mocks`\n\n`ReadonlyArray<MockedResponse>`\n\n</td>\n<td>\n\nAn array containing GraphQL operation definitions and their corresponding mocked responses. See [Defining mocked responses](../../development-testing/testing/#defining-mocked-responses).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `defaultOptions`\n\n`DefaultOptions`\n\n</td>\n<td>\n\nAn object containing options to pass directly to the `MockedProvider`'s `ApolloClient` instance. See [Example `defaultOptions` object](../core/ApolloClient/#example-defaultoptions-object).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `cache`\n\n`ApolloCache<TSerializedCache>`\n\n</td>\n<td>\n\nA custom cache for the `MockedProvider`'s `ApolloClient` instance to use. Useful when you need to define a custom `dataIdFromObject` function for automatic cache updates.\n\nBy default, `MockedProvider` creates an `InMemoryCache` with default configuration.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `resolvers`\n\n`Resolvers`\n\n</td>\n<td>\n\n**Deprecated.** A collection of [local resolvers](../../local-state/local-resolvers/) for the `MockedProvider`'s `ApolloClient` instance to use.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `childProps`\n\n`object`\n\n</td>\n<td>\n\nProps to pass down to the `MockedProvider`'s child.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `showWarnings`\n\n`boolean`\n\n</td>\n<td>\n\nWhen a request fails to match a mock, a warning is logged to the console to indicate the mismatch. Set this to `false` to silence these warnings.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n</tbody>\n</table>\n\n#### Example `mocks` array\n\n```js\nconst mocks = [\n  {\n    request: {\n      query: GET_DOG,\n      variables: { index: 4 },\n    },\n    result: {\n      data: {\n        dog: {\n          name: \"Douglas\",\n        },\n      },\n    },\n  },\n  {\n    request: {\n      query: GET_DOG,\n      variables: { index: 8 },\n    },\n    error: new Error(\"Something went wrong\"),\n  },\n];\n```\n\nWith the `mocks` array above:\n\n- If the `GET_DOG` operation is executed with variables `{ index: 4 }`, it returns a dog named `Douglas`.\n- If `GET_DOG` is executed with variables `{ index: 8 }`, it returns an `error`.\n\n#### Usage\n\nSee [Testing React components](../../development-testing/testing/).\n"
  },
  {
    "path": "docs/source/api/react/useApolloClient.mdx",
    "content": "---\ntitle: useApolloClient\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useApolloClient:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useBackgroundQuery.mdx",
    "content": "---\ntitle: useBackgroundQuery\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useBackgroundQuery.DocumentationTypes.useBackgroundQuery:function(1)\"\n  headingLevel={2}\n\n>\n\n```ts\n[\n  QueryRef<TData, TVariables> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n```\n\nA tuple of two values:\n\n  <ManualTuple>\n\n    <ManualTupleItem\n      idPrefix=\"usebackgroundquery-result\"\n      name=\"queryRef\"\n      type=\"QueryRef<TData, TVariables> | undefined\"\n    >\n      A `QueryRef` that can be passed to `useReadQuery` to read the query result. The `queryRef` is `undefined` if the query is skipped.\n    </ManualTupleItem>\n    <ManualTupleItem\n      idPrefix=\"usebackgroundquery-result\"\n      name=\"result\"\n      type=\"useBackgroundQuery.Result<TData, TVariables>\"\n      canonicalReference={\"@apollo/client/react!useBackgroundQuery.Result:interface\"}\n    >\n      An object containing helper functions for the query:\n      - `refetch`: A function to re-execute the query\n      - `fetchMore`: A function to fetch more results for pagination\n      - `subscribeToMore`: A function to subscribe to updates\n    </ManualTupleItem>\n\n  </ManualTuple>\n</FunctionDetails>\n\nIf no query has been executed yet and you skip the query, the hook will return `undefined` instead of a `queryRef`.\n"
  },
  {
    "path": "docs/source/api/react/useFragment.mdx",
    "content": "---\ntitle: useFragment\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useFragment.DocumentationTypes.useFragment:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useLazyQuery.mdx",
    "content": "---\ntitle: useLazyQuery\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails canonicalReference=\"@apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery:function(1)\" headingLevel={2}>\n  ```ts\n  [execute: LazyQueryExecFunction<TData, TVariables>, result: QueryResult<TData, TVariables>]\n  ```\n\nA tuple of two values:\n\n  <ManualTuple>\n    <ManualTupleItem\n      name=\"execute\"\n      type=\"(options?: LazyQueryHookOptions<TVariables>) => Promise<LazyQueryResult<TData, TVariables>>\"\n    >\n      Function that can be triggered to execute the query. The `useLazyQuery` function returns a promise that fulfills with a query result when the query succeeds or fails.\n    </ManualTupleItem>\n    <ManualTupleItem\n      name=\"result\"\n      type=\"QueryResult<TData, TVariables>\"\n      canonicalReference=\"@apollo/client/react!useLazyQuery.DocumentationTypes.useLazyQuery.Result:interface\"\n    >\n      The result of the query. See the `useQuery` hook for more details.\n    </ManualTupleItem>\n  </ManualTuple>\n</FunctionDetails>\n"
  },
  {
    "path": "docs/source/api/react/useLoadableQuery.mdx",
    "content": "---\ntitle: useLoadableQuery\ndescription: Apollo Client API reference\n---\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useLoadableQuery.DocumentationTypes.useLoadableQuery:function(1)\"\n  headingLevel={2}\n>\n  ```ts\n  [\n    loadQuery: LoadQueryFunction<TVariables>,\n    queryRef: QueryRef<TData, TVariables> | null,\n    {\n      fetchMore: FetchMoreFunction<TData, TVariables>;\n      refetch: RefetchFunction<TData, TVariables>;\n      subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n      reset: ResetFunction;\n    }\n  ]\n  ```\n\nA tuple of three values:\n\n  <ManualTuple>\n    <ManualTupleItem\n      idPrefix=\"useloadablequery-result\"\n      name=\"loadQuery\"\n      type=\"LoadQueryFunction<TVariables>\"\n    >\n      A function used to imperatively load a query. Calling this function will create or update the `queryRef` returned by `useLoadableQuery`, which should be passed to `useReadQuery`.\n    </ManualTupleItem>\n    <ManualTupleItem\n      idPrefix=\"useloadablequery-result\"\n      name=\"queryRef\"\n      type=\"QueryRef<TData, TVariables> | null\"\n    >\n      The `queryRef` used by `useReadQuery` to read the query result.\n    </ManualTupleItem>\n    <ManualTupleItem\n      idPrefix=\"useloadablequery-result\"\n      name=\"handlers\"\n      type=\"{ fetchMore: FetchMoreFunction<TData, TVariables>; refetch: RefetchFunction<TData, TVariables>; subscribeToMore: SubscribeToMoreFunction<TData, TVariables>; reset: ResetFunction; }\"\n    >\n      Additional handlers used for the query, such as `refetch`.\n    </ManualTupleItem>\n  </ManualTuple>\n</FunctionDetails>\n"
  },
  {
    "path": "docs/source/api/react/useMutation.mdx",
    "content": "---\ntitle: useMutation\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useMutation:function(1)\"\n  headingLevel={2}\n>\n  ```ts\n  [\n    mutate: (options?: MutationFunctionOptions<TData, TVariables>) => Promise<FetchResult<TData>>,\n    result: MutationResult<TData>\n  ]\n  ```\n  A tuple of two values:\n  <ManualTuple>\n    <ManualTupleItem\n      name=\"mutate\"\n      type={`(\n        options?: MutationFunctionOptions<TData, TVariables>\n      ) => Promise<FetchResult<TData>>`}\n      idPrefix=\"usemutation-result\"\n    >\n      A function to trigger the mutation from your UI. You can optionally pass this function any of the following options:\n\n      - `awaitRefetchQueries`\n      - `context`\n      - `fetchPolicy`\n      - `onCompleted`\n      - `onError`\n      - `optimisticResponse`\n      - `refetchQueries`\n      - `onQueryUpdated`\n      - `update`\n      - `variables`\n      - `client`\n\n      Any option you pass here overrides any existing value for that option that you passed to `useMutation`.\n\n      The mutate function returns a promise that fulfills with your mutation result.\n    </ManualTupleItem>\n    <ManualTupleItem\n      name=\"result\"\n      type=\"MutationResult<TData>\"\n      canonicalReference=\"@apollo/client/react!useMutation.Result:interface\"\n      idPrefix=\"usemutation-result\"\n    >\n      The result of the mutation.\n    </ManualTupleItem>\n\n  </ManualTuple>\n</FunctionDetails>\n"
  },
  {
    "path": "docs/source/api/react/useQuery.mdx",
    "content": "---\ntitle: useQuery\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useQuery.DocumentationTypes.useQuery:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useQueryRefHandlers.mdx",
    "content": "---\ntitle: useQueryRefHandlers\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useQueryRefHandlers:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useReactiveVar.mdx",
    "content": "---\ntitle: useReactiveVar\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useReactiveVar:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useReadQuery.mdx",
    "content": "---\ntitle: useReadQuery\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useReadQuery.DocumentationTypes.useReadQuery:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useSubscription.mdx",
    "content": "---\ntitle: useSubscription\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useSubscription:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/api/react/useSuspenseQuery.mdx",
    "content": "---\ntitle: useSuspenseQuery\ndescription: Apollo Client API reference\n---\n\n{/* @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/react!useSuspenseQuery.DocumentationTypes.useSuspenseQuery:function(1)\"\n  headingLevel={2}\n/>\n"
  },
  {
    "path": "docs/source/caching/advanced-topics.mdx",
    "content": "---\ntitle: Advanced topics on caching in Apollo Client\n---\n\nThis article describes special cases and considerations when using the [Apollo Client cache](./overview).\n\n## Bypassing the cache\n\nSometimes you _shouldn't_ use the cache for a particular GraphQL operation. For example, a query's response might be a token that's only used once. In cases like this, use [the `no-cache` fetch policy](../data/queries/#setting-a-fetch-policy):\n\n```js\nconst { loading, error, data } = useQuery(GET_DOGS, {\n  fetchPolicy: \"no-cache\", // highlight-line\n});\n```\n\nOperations that use this fetch policy don't write their result to the cache, and they also don't check the cache for data before sending a request to your server. [See all available fetch policies.](../data/queries/#setting-a-fetch-policy)\n\n## Persisting the cache\n\nYou can persist and rehydrate the `InMemoryCache` from a storage provider like `AsyncStorage` or `localStorage`. To do so, use the [`apollo3-cache-persist`](https://github.com/apollographql/apollo-cache-persist) library. This library works with a variety of [storage providers](https://github.com/apollographql/apollo-cache-persist/blob/master/docs/storage-providers.md).\n\nTo get started, pass your cache and a storage provider to `persistCache`. By default, the contents of your cache are immediately restored asynchronously, and they're persisted on every write to the cache with a short configurable debounce interval.\n\n<Note>\n\nThe `persistCache` method is async and returns a `Promise`.\n\n</Note>\n\n```js\nimport AsyncStorage from \"@react-native-async-storage/async-storage\";\nimport { InMemoryCache } from \"@apollo/client\";\nimport { persistCache } from \"apollo3-cache-persist\";\n\nconst cache = new InMemoryCache();\n\npersistCache({\n  cache,\n  storage: AsyncStorage,\n}).then(() => {\n  // Continue setting up Apollo Client as usual.\n});\n```\n\nFor advanced usage and additional configuration options, see the [README of `apollo3-cache-persist`](https://github.com/apollographql/apollo-cache-persist).\n\n## Resetting the cache\n\nSometimes, you might want to reset the cache entirely, such as [when a user logs out](../networking/authentication/#reset-store-on-logout). To accomplish this, call `client.resetStore`. This method is asynchronous, because it also refetches any of your active queries.\n\n```js\nimport { useQuery } from \"@apollo/client\";\nfunction Profile() {\n  const { data, client } = useQuery(PROFILE_QUERY);\n  return (\n    <Fragment>\n      <p>Current user: {data?.currentUser}</p>\n      <button onClick={async () => client.resetStore()}>Log out</button>\n    </Fragment>\n  );\n}\n```\n\nTo reset the cache _without_ refetching active queries, use `client.clearStore()` instead of `client.resetStore()`.\n\n### Responding to cache resets\n\nYou can register callback functions that execute whenever `client.resetStore` is called. To do so, call `client.onResetStore` and pass in your callback. To register multiple callbacks, call `client.onResetStore` multiple times. All of your callbacks are added to an array and are executed concurrently whenever the cache is reset.\n\nIn this example, we use `client.onResetStore` to write default values to the cache. This is useful when using Apollo Client's [local state management](../local-state/local-state-management/) features and calling `client.resetStore` anywhere in your application.\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { withClientState } from \"apollo-link-state\";\n\nimport { resolvers, defaults } from \"./resolvers\";\n\nconst cache = new InMemoryCache();\nconst stateLink = withClientState({ cache, resolvers, defaults });\n\nconst client = new ApolloClient({\n  cache,\n  link: stateLink,\n});\n\nclient.onResetStore(stateLink.writeDefaults);\n```\n\nYou can also call `client.onResetStore` from your React components. This can be useful if you want to force your UI to rerender after the cache is reset.\n\nThe `client.onResetStore` method's return value is a function you can call to unregister your callback:\n\n```js {8-10,13}\nimport { useApolloClient } from \"@apollo/client/react\";\n\nfunction Foo() {\n  const [reset, setReset] = useState(0);\n  const client = useApolloClient();\n\n  useEffect(() => {\n    const unsubscribe = client.onResetStore(\n      () => new Promise(() => setReset(reset + 1))\n    );\n\n    return () => {\n      unsubscribe();\n    };\n  });\n\n  return reset ? <div /> : <span />;\n}\n\nexport default Foo;\n```\n\n## TypePolicy inheritance\n\nJavaScript developers will be familiar with the idea of [inheritance](<https://en.m.wikipedia.org/wiki/Inheritance_(object-oriented_programming)>) from the `extends` clause of `class` declarations, or possibly from dealing with prototype chains created by `Object.create`.\n\nInheritance is a powerful code-sharing tool, and it works well with Apollo Client for several reasons:\n\n- `InMemoryCache` already knows about the supertype-subtype relationships (_interfaces and unions_) in your schema, thanks to `possibleTypes`, so no additional configuration is necessary to provide that information.\n\n- Inheritance allows a supertype to provide default configuration values to all its subtypes, including `keyFields` and individual field policies, which can be selectively overridden by subtypes that want something different.\n\n- A single subtype can have multiple supertypes in a GraphQL schema, which is difficult to model using the single inheritance model of classes or prototypes. In other words, supporting multiple inheritance in JavaScript requires building a system something like this one, rather than just reusing built-in language features.\n\n- Developers can add their own client-only supertypes to the `possibleTypes` map, as a way of reusing behavior across types, even if their schema knows nothing about those supertypes.\n\n- The `possibleTypes` map is currently used only for fragment matching purposes, which is an important but fairly small part of what the client does. Inheritance adds another compelling use for `possibleTypes`, and should drastically reduce repetition of `typePolicies` when used effectively.\n\nHere's how type policy inheritance works for `InMemoryCache`, considering the example below:\n\n```ts\nconst cache = new InMemoryCache({\n  possibleTypes: {\n    Reptile: [\"Snake\", \"Turtle\"],\n    Snake: [\"Python\", \"Viper\", \"Cobra\"],\n    Viper: [\"Cottonmouth\", \"DeathAdder\"],\n  },\n\n  typePolicies: {\n    Reptile: {\n      // Suppose all our reptiles are captive, and have a tag with an ID.\n      keyFields: [\"tagId\"],\n      fields: {\n        // Scientific name-related logic can be shared among Reptile subtypes.\n        scientificName: {\n          merge(_, incoming) {\n            // Normalize all scientific names to lower case.\n            return incoming.toLowerCase();\n          },\n        },\n      },\n    },\n\n    Snake: {\n      fields: {\n        // Default to a truthy non-boolean value if we don't know\n        // whether this snake is venomous.\n        venomous(status = \"unknown\") {\n          return status;\n        },\n      },\n    },\n  },\n});\n```\n\n## Refetching queries after a mutation\n\nIn certain cases, writing an `update` function to [update the cache after a mutation](../data/mutations/#updating-local-data) can be complex, or even impossible if the mutation doesn't return modified fields.\n\nIn these cases, you can provide a `refetchQueries` option to the `useMutation` hook to automatically rerun certain queries after the mutation completes.\n\nFor details, see [Refetching queries](../data/mutations/#refetching-queries).\n\n<Note>\n\nAlthough `refetchQueries` can be faster to implement than an `update` function, it also requires additional network requests that are usually undesirable. For more information, see [this blog post](https://www.apollographql.com/blog/when-to-use-refetch-queries/).\n\n</Note>\n\n## Cache redirects\n\nIn some cases, a query requests data that already exists in the cache under a different reference. For example, your UI might have a list view and a detail view that both use the same data.\n\nThe list view might run the following query:\n\n```graphql\nquery Books {\n  books {\n    id\n    title\n    abstract\n  }\n}\n```\n\nWhen a specific book is selected, the detail view might display an individual item using this query:\n\n```graphql\nquery Book($id: ID!) {\n  book(id: $id) {\n    id\n    title\n    abstract\n  }\n}\n```\n\nIn a case like this, _we_ know that the second query's data might already be in the cache, but because that data was fetched by a different query, _Apollo Client_ doesn't know that. To tell Apollo Client where to look for the cached `Book` object, we can define a field policy `read` function for the `book` field:\n\n```js {9-14}\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            read(_, { args, toReference }) {\n              return toReference({\n                __typename: \"Book\",\n                id: args.id,\n              });\n            },\n          },\n        },\n      },\n    },\n  }),\n});\n```\n\nThis `read` function uses the `toReference` helper utility to generate and return a **cache reference** for a `Book` object, based on its `__typename` and `id`.\n\nNow whenever a query includes the `book` field, the `read` function above executes and returns a reference to a `Book` object. Apollo Client uses this reference to look up the object in its cache and return it if it's present. If it _isn't_ present, Apollo Client knows it needs to execute the query over the network.\n\n<Note>\n\nTo avoid a network request, _all_ of a query's requested fields must already be present in the cache. If the detail view's query fetches _any_ `Book` field that the list view's query _didn't_, Apollo Client considers the cache hit to be incomplete, and it executes the full query over the network.\n\n</Note>\n\n## Pagination utilities\n\nPagination is a best practice in GraphQL [for several reasons](../pagination/overview). Apollo Client enables fetching and caching paginated results using the [Core pagination API](../pagination/core-api). The API includes a few important utilities, including the [`fetchMore`](../pagination/core-api/#the-fetchmore-function) function and the `@connection` directive.\n\n### Incremental loading: `fetchMore`\n\nYou can use the `fetchMore` function to update a query's cached result with data returned by a _follow-up_ query. Most often, `fetchMore` is used to handle infinite-scroll pagination and other situations where you're loading more data when you already have some.\n\nFor details, see [The `fetchMore` function](../pagination/core-api/#the-fetchmore-function).\n\n### The `@connection` directive\n\nThe `@connection` directive solves the problem of multiple copies of the same field in the cache. This can happen with paginated queries because the `fetchMore` function sends follow-up queries to fetch additional pages of results using arguments like [`offset`](../pagination/offset-based/) and [`limit`](../pagination/offset-based/). These arguments inadvertently fragment data from different pagination requests across the cache.\n\nThe `@connection` directive lets you unify paginated results by specifying a custom, stable cache key for a field. It also lets you _intentionally_ separate paginated results in the cache by fields that you specify.\n\n<Tip>\n\nStarting in Apollo Client v3, setting the [`keyArgs` field policy](../pagination/key-args/#setting-keyargs) is the most straightforward way to resolve fragmented pagination results in the cache. For example, setting [`keyArgs` to `false`](../pagination/key-args/#supported-values-for-keyargs) indicates that no arguments should be included in cache keys, causing all pagination results to be cached together. Additionally, you only have to set your `keyArgs` configuration once, rather than using `@connection` in multiple queries. Refer to the [usage instructions](#connection-directive-usage) below to compare `@connection` and `keyArgs` usage.\n\nThe `@connection` directive is useful when you want to store distinct data in the cache on a query-by-query, field-by-field basis. See the [advanced usage instructions](#advanced-connection-directive-usage) for more details.\n\n</Tip>\n\n#### `@connection` directive usage\n\n<Tip>\n\nFor the standard `@connection` directive usage described in this section, it's best to configure a [`keyArgs` field policy](../pagination/key-args/#setting-keyargs). For example, you can use the following [`keyArgs`](../pagination/key-args/#setting-keyargs) configuration for the same effect as the `@connection` example below.\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"type\"],\n        },\n      },\n    },\n  },\n});\n```\n\nWith this centralized `keyArg`s configuration, you don't need to include the `@connection` directive in your queries because the `type` argument is adequate for keeping feeds of different types separate in the cache. For an example of storing distinct data on a query-by-query basis, see the [advanced usage instructions](#advanced-connection-directive-usage).\n\n</Tip>\n\nTo use the `@connection` directive, add it to the field you want a custom cache key for. The directive requires a `key` parameter to specify the custom cache key. You can optionally include the `filter` parameter, which takes an array of query argument names to include in the generated custom cache key.\n\n```js\nconst query = gql`\n  query Feed($type: FeedType!, $offset: Int, $limit: Int) {\n    feed(type: $type, offset: $offset, limit: $limit)\n      @connection(key: \"feed\", filter: [\"type\"]) {\n      ...FeedEntry\n    }\n  }\n`;\n```\n\nWith the above query, even when multiple `fetchMore`s queries are performed, each feed update always results in an update to the cache's `feed` key with the latest accumulated values. The example also uses the `@connection` directive's optional `filter` argument to include the `type` query argument in the cache key. This creates multiple cache values that accumulate queries from each type of feed.\n\nWith a stable cache key, you can use [`writeQuery`](./cache-interaction/#writequery) to perform a cache update that clears out the feed.\n\n```js\nclient.writeQuery({\n  query: gql`\n    query Feed($type: FeedType!) {\n      feed(type: $type) @connection(key: \"feed\", filter: [\"type\"]) {\n        id\n      }\n    }\n  `,\n  variables: {\n    type: \"top\",\n  },\n  data: {\n    feed: [],\n  },\n});\n```\n\n<Note>\n\nBecause this example uses the `type` argument in the cache key, it doesn't need to provide `offset` or `limit` arguments.\n\n</Note>\n\n#### Advanced `@connection` directive usage\n\nThe `@connection` directive is useful when using the same field in multiple queries, with no distinguishing arguments (for example, `type`) that `keyArgs` can use, and you want to keep that field's data separate in the cache.\n\nFor example, Apollo's [Spotify showcase](https://github.com/apollographql/spotify-showcase) uses `@connection` to independently cache lists of playlists. One list is in the left sidebar, where you navigate between playlists. The other appears when you right-click a song to add it to a playlist.\n\n<img\n  src=\"../img/spotify-playlists.jpg\"\n  class=\"screenshot\"\n  alt=\"Separately cached playlists in Apollo's Spotify Showcase\"\n></img>\n\nWithout caching the playlists separately, loading the next page of data from one list affects the other, negatively impacting the UX.\n\nFor code examples, see:\n\n- [The type policy](https://github.com/apollographql/spotify-showcase/blob/185f7b8a155209e9a099490dbc5d1e3bfba4c32f/client/src/apollo/client.ts#L105-L108)\n- [Playlist sidebar query](https://github.com/apollographql/spotify-showcase/blob/185f7b8a155209e9a099490dbc5d1e3bfba4c32f/client/src/components/LoggedInLayout.tsx#L75)\n- [Add to playlist menu](https://github.com/apollographql/spotify-showcase/blob/185f7b8a155209e9a099490dbc5d1e3bfba4c32f/client/src/components/ContextMenuAction/AddToPlaylist.tsx#L17)\n"
  },
  {
    "path": "docs/source/caching/cache-configuration.mdx",
    "content": "---\ntitle: Configuring the Apollo Client cache\n---\n\nThis article describes cache setup and configuration. To learn how to interact with cached data, see [Reading and writing data to the cache](./cache-interaction).\n\n## Initialization\n\nCreate an `InMemoryCache` object and provide it to the `ApolloClient` constructor, like so:\n\n```ts\nimport { InMemoryCache, ApolloClient } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  // ...other arguments...\n  cache: new InMemoryCache(options),\n});\n```\n\nThe `InMemoryCache` constructor accepts a variety of [configuration options](#configuration-options).\n\n## Configuration options\n\nYou can configure the cache's behavior to better suit your application. For example, you can:\n\n- Customize the format of a particular type's [cache ID](#customizing-cache-ids)\n- Customize the storage and retrieval of [individual fields](./cache-field-behavior/)\n- Define polymorphic type relationships for [fragment matching](#possibletypes)\n- Define patterns for [pagination](../pagination/overview/)\n- Manage client-side [local state](../local-state/local-state-management/)\n\nTo customize cache behavior, you provide a configuration object to the `InMemoryCache` constructor. This object supports the following fields:\n\n<table class=\"field-table api-ref\">\n  <thead>\n    <tr>\n      <th>Name /<br/>Type</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n\n<tbody>\n<tr>\n<td>\n\n###### `resultCaching`\n\n`Boolean`\n\n</td>\n<td>\n\nIf `true`, the cache returns an identical (`===`) response object for every execution of the same query, as long as the underlying data remains unchanged. This helps you detect changes to a query's result.\n\nThe default value is `true`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `resultCacheMaxSize`\n\n`number`\n\n</td>\n<td>\n\nThe limit of the number of result objects that will be retained in memory to speed up repeated reads to the cache.\n\nThe default value is `Math.pow(2, 16)`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `possibleTypes`\n\n`Object`\n\n</td>\n<td>\n\nInclude this object to define polymorphic relationships between your schema's types. Doing so enables you to look up cached data by interface or by union.\n\nEach key in the object is the `__typename` of an interface or union, and the corresponding value is an array of the `__typename`s of the types that belong to that union or implement that interface.\n\nFor an example, see [Defining `possibleTypes` manually](../data/fragments/#defining-possibletypes-manually).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `typePolicies`\n\n`Object`\n\n</td>\n<td>\n\nInclude this object to customize the cache's behavior on a type-by-type basis.\n\nEach key in the object is the `__typename` of a type to customize, and the corresponding value is a [`TypePolicy` object](#typepolicy-fields).\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `dataIdFromObject`\n\n`Function`\n\n</td>\n<td>\n\nA function that takes a response object and returns a unique identifier to be used when normalizing the data in the store.\n\nFor details, see [Customizing identifier generation globally](#customizing-identifier-generation-globally).\n\n</td>\n</tr>\n</tbody>\n</table>\n\n## Customizing cache IDs\n\nYou can customize how the `InMemoryCache` generates cache IDs for individual types in your schema ([see the default behavior](./overview/#2-generate-cache-ids)). This is helpful especially if a type uses a field (or fields!) _besides_ `id` or `_id` as its unique identifier.\n\nTo accomplish this, you define a `TypePolicy` for each type you want to customize. You specify all of your cache's `typePolicies` in [the `options` object you provide to the `InMemoryCache` constructor](#configuration-options).\n\nInclude a `keyFields` field in relevant `TypePolicy` objects, like so:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Product: {\n      // In an inventory management system, products might be identified\n      // by their UPC.\n      keyFields: [\"upc\"],\n    },\n    Person: {\n      // In a user account system, the combination of a person's name AND email\n      // address might uniquely identify them.\n      keyFields: [\"name\", \"email\"],\n    },\n    Book: {\n      // If one of the keyFields is an object with fields of its own, you can\n      // include those nested keyFields by using a nested array of strings:\n      keyFields: [\"title\", \"author\", [\"name\"]],\n    },\n    AllProducts: {\n      // Singleton types that have no identifying field can use an empty\n      // array for their keyFields.\n      keyFields: [],\n    },\n    Store: {\n      // If you need to disable normalization, set the keyFields to false\n      // and the object will be embedded in the parent\n      keyFields: false,\n    },\n    Location: {\n      // You can also use a function to determine any of the values above.\n      // The first argument is the reference to the record to be written, and the second is the runtime context\n      keyFields: (location, context) => {\n        if (context.readField(\"state\")) {\n          return [\"city\", \"state\", \"country\"];\n        } else {\n          return [\"city\", \"country\"];\n        }\n      },\n    },\n  },\n});\n```\n\nThis example shows a variety of `typePolicies` with different `keyFields`:\n\n- The `Product` type uses its `upc` field as its identifying field.\n- The `Person` type uses the combination of both its `name` _and_ `email` fields.\n- The `Book` type includes a _subfield_ as part of its cache ID.\n  - The `[\"name\"]` item indicates that the `name` field of the _previous_ field in the array (`author`) is part of the cache ID. The `Book`'s `author` field must be an object that includes a `name` field for this to be valid.\n  - A valid cache ID for the `Book` type has the following structure:\n    ```\n    Book:{\"title\":\"Fahrenheit 451\",\"author\":{\"name\":\"Ray Bradbury\"}}\n    ```\n- The `AllProducts` type illustrates a special strategy for a **singleton** type. If the cache will only ever contain one `AllProducts` object and that object has _no_ identifying fields, you can provide an empty array for its `keyFields`.\n- The `Store` type provides an example of how you can [disable normalization](https://www.apollographql.com/docs/react/caching/cache-configuration/#disabling-normalization) by setting the keyFields to `false`\n- The `Location` type provides an example of using custom function given object and runtime context to calculate what fields should be used for the key field selection.\n  - Keep in mind that the first argument here is a reference to the record that will be written. As such, it does NOT include subselected fields, only scalar fields, and it contains aliases from the operation. If you need to read the real type you can use `context.storeObject`. To read even more indepth about how this function can work the best source will be our own [test cases for the cache policies](https://github.com/apollographql/apollo-client/blob/8bc7d4d406402962bf5151cdd2c5c75c9398d10c/src/cache/inmemory/__tests__/policies.ts#L5543-L5622)\n\nIf an object has multiple `keyFields`, the cache ID always lists those fields in the same order to ensure uniqueness.\n\nNote that these `keyFields` strings always refer to the canonical field names defined in the schema. This means that ID computation is _not_ sensitive to field aliases.\n\n### Calculating an object's cache ID\n\nIf you define a custom cache ID that uses multiple fields, it can be challenging to calculate and provide that ID to methods that require it (such as `cache.readFragment`).\n\nTo help with this, you can use the `cache.identify` method to calculate the cache ID for any normalized object you fetch from your cache. See [Obtaining an object's custom ID](./cache-interaction/#obtaining-an-objects-cache-id).\n\n### Customizing identifier generation globally\n\nIf you need to define a single fallback `keyFields` function that isn't specific to any particular `__typename`, you can use the `dataIdFromObject` function that was introduced in Apollo Client 2.x:\n\n```ts\nimport { defaultDataIdFromObject } from \"@apollo/client\";\n\nconst cache = new InMemoryCache({\n  dataIdFromObject(responseObject) {\n    switch (responseObject.__typename) {\n      case \"Product\":\n        return `Product:${responseObject.upc}`;\n      case \"Person\":\n        return `Person:${responseObject.name}:${responseObject.email}`;\n      default:\n        return defaultDataIdFromObject(responseObject);\n    }\n  },\n});\n```\n\n> The `dataIdFromObject` API is included in Apollo Client 3 to ease the transition from Apollo Client 2.x.\n\nNotice that the above function still uses different logic to generate keys based on an object's `__typename`. In a case like this, you should almost always define `keyFields` arrays for the `Product` and `Person` types via `typePolicies`.\n\nThis code also has the following drawbacks:\n\n- It's sensitive to aliasing mistakes.\n- It does nothing to protect against undefined object properties.\n- Accidentally using different key fields at different times can cause inconsistencies in the cache.\n\n### Customizing Type Policies\n\nAfter creating an `InMemoryCache` instance, you can use the `addTypePolicies` method to add or modify type policies.\n\nHere is an example of how to use the `addTypePolicies` method:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        name: {\n          read(name = \"UNKNOWN NAME\") {\n            return name.toUpperCase();\n          },\n        },\n      },\n    },\n  },\n});\n\n// Add a type policy to the cache.\ncache.policies.addTypePolicies({\n  Person: {\n    fields: {\n      email: {\n        read(email = \"unknown@example.com\") {\n          return email;\n        },\n      },\n    },\n  },\n});\n```\n\nThe code creates an `InMemoryCache` with a custom type policy for the `Person` type. The type policy specifies that if the `name` field is not available in the cache, it should return a default value of \"UNKNOWN NAME\" and converts it to uppercase.\n\nThen, the code adds an additional type policy to the cache using `cache.policies.addTypePolicies`. This new type policy is related to the `Person` type and its `email` field. The custom read function specifies that if the email field is not available in the cache, it should return a default value of \"unknown@example.com\".\n\nOverall, the code sets up caching behaviors for the `Person` type, ensuring that default values are provided for the `name` and `email` fields if they are not present in the cache.\n\n### Disabling normalization\n\nYou can instruct the `InMemoryCache` _not_ to normalize objects of a particular type. This can be useful for metrics and other transient data that's identified by a timestamp and never receives updates.\n\nTo disable normalization for a type, define a `TypePolicy` for the type (as shown in [Customizing cache IDs](#customizing-cache-ids)) and set the policy's `keyFields` field to `false`.\n\nObjects that are not normalized are instead embedded within their _parent_ object in the cache. You can't access these objects directly, but you can access them via their parent.\n\n## `TypePolicy` fields\n\nTo customize how the cache interacts with specific types in your schema, you can pass the `InMemoryCache` constructor an object that maps `__typename` strings to `TypePolicy` objects.\n\nA `TypePolicy` object can include the following fields:\n\n```ts\ntype TypePolicy = {\n  // Allows defining the primary key fields for this type, either using an\n  // array of field names, a function that returns an arbitrary string, or\n  // false to disable normalization for objects of this type.\n  keyFields?: KeySpecifier | KeyFieldsFunction | false;\n\n  // If your schema uses a custom __typename for any of the root Query,\n  // Mutation, and/or Subscription types (rare), set the corresponding\n  // field below to true to indicate that this type serves as that type.\n  queryType?: true;\n  mutationType?: true;\n  subscriptionType?: true;\n\n  fields?: {\n    [fieldName: string]:\n      | FieldPolicy<StoreValue>\n      | FieldReadFunction<StoreValue>;\n  };\n};\n\n// Recursive type aliases are coming in TypeScript 3.7, so this isn't the\n// actual type we use, but it's what it should be:\ntype KeySpecifier = (string | KeySpecifier)[];\n\ntype KeyFieldsFunction = (\n  object: Readonly<StoreObject>,\n  context: {\n    typename: string;\n    selectionSet?: SelectionSetNode;\n    fragmentMap?: FragmentMap;\n  }\n) => string | null | void;\n```\n\n### Overriding root operation types (uncommon)\n\nIn addition to `keyFields`, a `TypePolicy` can indicate that its type represents the root query, mutation, or subscription type by setting `queryType`, `mutationType`, or `subscriptionType` to `true`:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    UnconventionalRootQuery: {\n      // The RootQueryFragment can only match if the cache knows the __typename\n      // of the root query object.\n      queryType: true,\n    },\n  },\n});\n\nconst result = cache.readQuery({\n  query: gql`\n    query MyQuery {\n      ...RootQueryFragment\n    }\n    fragment RootQueryFragment on UnconventionalRootQuery {\n      field1\n      field2 {\n        subfield\n      }\n    }\n  `,\n});\n\nconst equivalentResult = cache.readQuery({\n  query: gql`\n    query MyQuery {\n      field1\n      field2 {\n        subfield\n      }\n    }\n  `,\n});\n```\n\nThe cache usually obtains `__typename` information by adding the `__typename` field to every query selection set it sends to the server. It could technically use this same method for the outermost selection set of every operation, but the `__typename`s of the root query and mutation are almost always `\"Query\"` and `\"Mutation\"`, so the cache assumes those common defaults unless instructed otherwise in a `TypePolicy`.\n\nFor most objects in a graph, the `__typename` field is vital for proper identification and normalization. For the root query and mutation types, the `__typename` is not nearly as useful or important, because those types are singletons with only one instance per client.\n\n### The `fields` property\n\nThe final property within `TypePolicy` is the `fields` property, which enables you to [customize the behavior of individual cached fields](./cache-field-behavior).\n"
  },
  {
    "path": "docs/source/caching/cache-field-behavior.mdx",
    "content": "---\ntitle: Customizing the behavior of cached fields\n---\n\nYou can customize how a particular field in your Apollo Client cache is read and written. To do so, you define a **field policy** for the field. A field policy can include:\n\n- A [`read` function](#the-read-function) that specifies what happens when the field's cached value is read\n- A [`merge` function](#the-merge-function) that specifies what happens when field's cached value is written\n- An array of [key arguments](#specifying-key-arguments) that help the cache avoid storing unnecessary duplicate data.\n\nYou provide field policies to the constructor of `InMemoryCache`. Each field policy is defined inside whichever [`TypePolicy` object](./cache-configuration/#typepolicy-fields) corresponds to the field's parent type.\n\nThe following example defines a field policy for the `name` field of a `Person` type:\n\n```ts {5-10}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        name: {\n          read(name) {\n            // Return the cached name, transformed to upper case\n            return name.toUpperCase();\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThis field policy defines a [`read` function](#the-read-function) that specifies what the cache returns whenever `Person.name` is queried.\n\n## The `read` function\n\nIf you define a `read` function for a field, the cache calls that function whenever your client queries for the field. In the query response, the field is populated with the `read` function's return value, _instead of the field's cached value_.\n\nEvery `read` function is passed two parameters:\n\n- The first parameter is the field's currently cached value (if one exists). You can use this to help calculate the value to return.\n\n- The second parameter is an object that provides access to several properties and helper functions, including any arguments passed to the field.\n  - See the fields of the `FieldFunctionOptions` type in [`FieldPolicy` API reference](#fieldpolicy-api-reference).\n\nThe following `read` function returns a default value of `UNKNOWN NAME` for the `name` field of a `Person` type whenever a value isn't available in the cache. If a cached value _is_ available, it's returned unmodified.\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        name: {\n          // highlight-start\n          read(name = \"UNKNOWN NAME\") {\n            return name;\n          },\n          // highlight-end\n        },\n      },\n    },\n  },\n});\n```\n\n### Handling field arguments\n\nIf a field accepts arguments, the `read` function's second parameter includes an `args` object that contains the values provided for those arguments.\n\nFor example, the following `read` function checks whether the `maxLength` argument was provided for the `name` field. If it _was_ provided, the function returns only the first `maxLength` characters of the person's name. Otherwise, the person's full name is returned.\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        // If a field's TypePolicy would only include a read function,\n        // you can optionally define the function like so, instead of\n        // nesting it inside an object as shown in the previous example.\n        name(name: string, { args }) {\n          if (args && typeof args.maxLength === \"number\") {\n            return name.substring(0, args.maxLength);\n          }\n          return name;\n        },\n      },\n    },\n  },\n});\n```\n\nIf a field requires numerous parameters then each parameter must be wrapped in a variable that is then destructured and returned.\nEach parameter will be available as individual subfields.\n\nThe following `read` function assigns a default value of `UNKNOWN FIRST NAME` to the `firstName` subfield of a `fullName` field and a `UNKNOWN LAST NAME` to the `lastName` of a `fullName` field.\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        fullName: {\n          read(\n            fullName = {\n              firstName: \"UNKNOWN FIRST NAME\",\n              lastName: \"UNKNOWN LAST NAME\",\n            }\n          ) {\n            return { ...fullName };\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThe following `query` returns the `firstName` and `lastName` subfields from the `fullName` field:\n\n```graphql\nquery personWithFullName {\n  fullName {\n    firstName\n    lastName\n  }\n}\n```\n\nYou can define a `read` function for a field that isn't even defined in your schema. For example, the following `read` function enables you to query a `userId` field that is always populated with locally stored data:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        userId() {\n          return localStorage.getItem(\"loggedInUserId\");\n        },\n      },\n    },\n  },\n});\n```\n\n> Note that to query for a field that is only defined locally, your query should [include the `@client` directive](../local-state/managing-state-with-field-policies#querying) on that field so that Apollo Client doesn't include it in requests to your GraphQL server.\n\nOther use cases for a `read` function include:\n\n- Transforming cached data to suit your client's needs, such as rounding floating-point values to the nearest integer\n- Deriving [local-only fields](../local-state/managing-state-with-field-policies/) from one or more schema fields on the same object (such as deriving an `age` field from a `birthDate` field)\n- Deriving local-only fields from one or more schema fields across _multiple_ objects\n\nFor a full list of the options provided to the `read` function, see the [API reference](#fieldpolicy-api-reference). You will almost never need to use all of these options, but each one has an important role when reading fields from the cache.\n\n## The `merge` function\n\nIf you define a `merge` function for a field, the cache calls that function whenever the field is about to be written with an incoming value (such as from your GraphQL server). When the write occurs, the field's new value is set to the `merge` function's return value, _instead of the original incoming value_.\n\n### Merging arrays\n\nA common use case for a `merge` function is to define how to write to a field that holds an array. By default, the field's existing array is _completely replaced_ by the incoming array. In many cases, it's preferable to _concatenate_ the two arrays instead, like so:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Agenda: {\n      fields: {\n        tasks: {\n          merge(existing = [], incoming: any[]) {\n            return [...existing, ...incoming];\n          },\n        },\n      },\n    },\n  },\n});\n```\n\n> This pattern is especially common when working with [paginated lists](#handling-pagination).\n\nNote that `existing` is undefined the very first time this function is called for a given instance of the field, because the cache does not yet contain any data for the field. Providing the `existing = []` default parameter is a convenient way to handle this case.\n\n> Your `merge` function **cannot** push the `incoming` array directly onto the `existing` array. It must instead return a new array to prevent potential errors. In development mode, Apollo Client prevents unintended modification of the `existing` data with `Object.freeze`.\n\n### Merging non-normalized objects\n\nYou can use a `merge` function to intelligently combine nested objects that are _not_ normalized in your cache, assuming those objects are nested within the same normalized parent.\n\n<ExpansionPanel title=\"See the code\">\n\n```ts {6-8}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        author: {\n          // Non-normalized Author object within Book\n          merge(existing, incoming, { mergeObjects }) {\n            return mergeObjects(existing, incoming);\n          },\n        },\n      },\n    },\n  },\n});\n```\n\n</ExpansionPanel>\n\n#### Example\n\nLet's say our graph's schema includes the following types:\n\n```graphql\ntype Book {\n  id: ID!\n  title: String!\n  author: Author!\n}\n\ntype Author { # Has no key fields\n  name: String!\n  dateOfBirth: String!\n}\n\ntype Query {\n  favoriteBook: Book!\n}\n```\n\nWith this schema, our cache can normalize `Book` objects because they have an `id` field. However, `Author` objects have no `id` field, and they also have no _other_ fields that can uniquely identify a particular instance. Therefore, the cache _can't_ normalize `Author` objects, and it can't tell when two different `Author` objects actually represent the _same_ author.\n\nNow, let's say our client executes the following two queries, in order:\n\n```graphql {5,14}\nquery BookWithAuthorName {\n  favoriteBook {\n    id\n    author {\n      name\n    }\n  }\n}\n\nquery BookWithAuthorBirthdate {\n  favoriteBook {\n    id\n    author {\n      dateOfBirth\n    }\n  }\n}\n```\n\nWhen the _first_ query returns, Apollo Client writes a `Book` object like the following to the cache:\n\n```json\n{\n  \"__typename\": \"Book\",\n  \"id\": \"abc123\",\n  \"author\": {\n    \"__typename\": \"Author\",\n    \"name\": \"George Eliot\"\n  }\n}\n```\n\n> Remember that because `Author` objects can't be normalized, they're nested directly within their parent object.\n\nNow, when the _second_ query returns, the cached `Book` object is updated to the following:\n\n```json {6}\n{\n  \"__typename\": \"Book\",\n  \"id\": \"abc123\",\n  \"author\": {\n    \"__typename\": \"Author\",\n    \"dateOfBirth\": \"1819-11-22\"\n  }\n}\n```\n\nThe `Author`'s `name` field has been removed! This is because Apollo Client can't be sure that the `Author` objects returned by the two queries actually refer to the same author. So instead of merging fields of the two objects, Apollo Client completely _overwrites_ the object (and logs a warning).\n\nHowever, _we_ are confident that these two objects represent the same author, because a book's author virtually never changes. Therefore, we can tell the cache to treat `Book.author` objects as the _same_ object as long as they belong to the same `Book`. This enables the cache to merge the `name` and `dateOfBirth` fields returned by different queries above.\n\nTo achieve this, we can define a custom `merge` function for the `author` field within the type policy for `Book`:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        author: {\n          merge(existing, incoming, { mergeObjects }) {\n            return mergeObjects(existing, incoming);\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nHere, we use the `mergeObjects` helper function to merge values from the `existing` and `incoming` `Author` objects. It's important to use `mergeObjects` here instead of merging the objects with [object spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax), because `mergeObjects` makes sure to call any defined `merge` functions for _subfields_ of `Book.author`.\n\nNotice that this `merge` function has zero `Book`- or `Author`-specific logic in it! This means you can reuse it for any number of non-normalized object fields. And because this exact `merge` function definition is so common, you can also define it with the following shorthand:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        author: {\n          // Equivalent to options.mergeObjects(existing, incoming).\n          merge: true,\n        },\n      },\n    },\n  },\n});\n```\n\nIn summary, the `Book.author` policy above enables the cache to intelligently merge all of the `author` objects associated with any particular normalized `Book` object.\n\n> Remember that for `merge: true` to merge two non-normalized objects, all of the following must be true:\n>\n> - The two objects must occupy the exact same field of the exact same _normalized_ object in the cache.\n> - The two objects must have the same `__typename`.\n>   - This is important for fields with an interface or union return type, which might return one of multiple object types.\n>\n> If you require behavior that violates any of these rules, you need to write a custom `merge` function instead of using `merge: true`.\n\n### Merging arrays of non-normalized objects\n\n> Make sure you've read [Merging arrays](#merging-arrays) and [Merging non-normalized objects](#merging-non-normalized-objects) first.\n\nConsider what happens if a `Book` can have multiple `authors`:\n\n```graphql\nquery BookWithAuthorNames {\n  favoriteBook {\n    isbn\n    title\n    authors {\n      name\n    }\n  }\n}\n\nquery BookWithAuthorLanguages {\n  favoriteBook {\n    isbn\n    title\n    authors {\n      language\n    }\n  }\n}\n```\n\nThe `favoriteBook.authors` field contains a _list_ of non-normalized `Author` objects. In this case, we need to define a more sophisticated `merge` function to make sure the `name` and `language` fields returned by the two queries above are correctly associated with each other.\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        authors: {\n          merge(existing: any[], incoming: any[], { readField, mergeObjects }) {\n            const merged: any[] = existing ? existing.slice(0) : [];\n            const authorNameToIndex: Record<string, number> = {};\n            if (existing) {\n              existing.forEach((author, index) => {\n                authorNameToIndex[readField<string>(\"name\", author)] = index;\n              });\n            }\n            incoming.forEach((author) => {\n              const name = readField<string>(\"name\", author);\n              const index = authorNameToIndex[name];\n              if (typeof index === \"number\") {\n                // Merge the new author data with the existing author data.\n                merged[index] = mergeObjects(merged[index], author);\n              } else {\n                // First time we've seen this author in this array.\n                authorNameToIndex[name] = merged.length;\n                merged.push(author);\n              }\n            });\n            return merged;\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nInstead of replacing the existing `authors` array with the incoming array, this code concatenates the arrays together, while also checking for duplicate author names. Whenever a duplicate name is found, the fields of the repeated `Author` objects are merged.\n\nThe `readField` helper function is more robust than using `author.name` directly, because it tolerates the possibility that the `author` is a `Reference` object referring to data elsewhere in the cache. This is important if the `Author` type eventually defines `keyFields` and therefore becomes normalized.\n\nAs this example suggests, `merge` functions can become quite sophisticated. When this happens, you can often extract the generic logic into a reusable helper function:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        authors: {\n          merge: mergeArrayByField<AuthorType>(\"name\"),\n        },\n      },\n    },\n  },\n});\n```\n\nNow that you've hidden the details behind a reusable abstraction, it no longer matters how complicated the implementation gets. This is liberating, because it allows you to improve your client-side business logic over time, while keeping related logic consistent across your entire application.\n\n### Defining a `merge` function at the type level\n\nIn Apollo Client 3.3 and later, you can define a default `merge` function for a non-normalized object type. If you do, every field that _returns_ that type uses your default `merge` function unless it's overridden on a field-by-field basis.\n\nYou define this default `merge` function in the type policy for the non-normalized type. Here's what that looks like for the non-normalized `Author` type from [Merging non-normalized objects](#merging-non-normalized-objects):\n\n```ts {13}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Book: {\n      fields: {\n        // No longer required!\n        // author: {\n        //   merge: true,\n        // },\n      },\n    },\n\n    Author: {\n      merge: true,\n    },\n  },\n});\n```\n\nAs shown above, the field-level `merge` function for `Book.author` is no longer required. The net result in this basic example is identical, _but_ this strategy automatically applies the default `merge` function to any _other_ `Author`-returning fields you might add in the future (such as `Essay.author`).\n\n### Handling pagination\n\nWhen a field holds an array, it's often useful to [paginate](../pagination/overview/) that array's results, because the total result set can be arbitrarily large.\n\nTypically, a query includes pagination arguments that specify:\n\n- Where to start in the array, using either a numeric offset or a starting ID\n- The maximum number of elements to return in a single \"page\"\n\nIf you implement pagination for a field, it's important to keep pagination arguments in mind if you then implement `read` and `merge` functions for the field:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Agenda: {\n      fields: {\n        tasks: {\n          merge(existing: any[], incoming: any[], { args }) {\n            const merged = existing ? existing.slice(0) : [];\n            // Insert the incoming elements in the right places, according to args.\n            const end = args.offset + Math.min(args.limit, incoming.length);\n            for (let i = args.offset; i < end; ++i) {\n              merged[i] = incoming[i - args.offset];\n            }\n            return merged;\n          },\n\n          read(existing: any[], { args }) {\n            // If we read the field before any data has been written to the\n            // cache, this function will return undefined, which correctly\n            // indicates that the field is missing.\n            const page =\n              existing && existing.slice(args.offset, args.offset + args.limit);\n            // If we ask for a page outside the bounds of the existing array,\n            // page.length will be 0, and we should return undefined instead of\n            // the empty array.\n            if (page && page.length > 0) {\n              return page;\n            }\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nAs this example shows, your `read` function often needs to cooperate with your `merge` function, by handling the same arguments in the inverse direction.\n\nIf you want a given \"page\" to start after a specific entity ID instead of starting from `args.offset`, you can implement your `merge` and `read` functions as follows, using the `readField` helper function to examine existing task IDs:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Agenda: {\n      fields: {\n        tasks: {\n          merge(existing: any[], incoming: any[], { args, readField }) {\n            const merged = existing ? existing.slice(0) : [];\n            // Obtain a Set of all existing task IDs.\n            const existingIdSet = new Set(\n              merged.map((task) => readField(\"id\", task))\n            );\n            // Remove incoming tasks already present in the existing data.\n            incoming = incoming.filter(\n              (task) => !existingIdSet.has(readField(\"id\", task))\n            );\n            // Find the index of the task just before the incoming page of tasks.\n            const afterIndex = merged.findIndex(\n              (task) => args.afterId === readField(\"id\", task)\n            );\n            if (afterIndex >= 0) {\n              // If we found afterIndex, insert incoming after that index.\n              merged.splice(afterIndex + 1, 0, ...incoming);\n            } else {\n              // Otherwise insert incoming at the end of the existing data.\n              merged.push(...incoming);\n            }\n            return merged;\n          },\n\n          read(existing: any[], { args, readField }) {\n            if (existing) {\n              const afterIndex = existing.findIndex(\n                (task) => args.afterId === readField(\"id\", task)\n              );\n              if (afterIndex >= 0) {\n                const page = existing.slice(\n                  afterIndex + 1,\n                  afterIndex + 1 + args.limit\n                );\n                if (page && page.length > 0) {\n                  return page;\n                }\n              }\n            }\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nNote that if you call `readField(fieldName)`, it returns the value of the specified field from the current object. If you pass an object as a _second_ argument to `readField`, (e.g., `readField(\"id\", task)`), `readField` instead reads the specified field from the specified object. In the above example, reading the `id` field from existing `Task` objects allows us to deduplicate the `incoming` task data.\n\nThe pagination code above is complicated, but after you implement your preferred pagination strategy, you can reuse it for every field that uses that strategy, regardless of the field's type. For example:\n\n```ts\nfunction afterIdLimitPaginatedFieldPolicy<T>() {\n  return {\n    merge(existing: T[], incoming: T[], { args, readField }): T[] {\n      ...\n    },\n    read(existing: T[], { args, readField }): T[] {\n      ...\n    },\n  };\n}\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Agenda: {\n      fields: {\n        tasks: afterIdLimitPaginatedFieldPolicy<Reference>(),\n      },\n    },\n  },\n});\n```\n\n### Opting in to the default behavior for non-normalized fields\n\nApollo Client replaces existing data with incoming data for non-normalized fields by default. When this happens, you will encounter console warnings like \"Cache data may be lost when...\", even when the default behavior is desirable. You can tell Apollo Client you want this behavior by passing `merge: false` to a field's `FieldPolicy`. By opting into this behavior, the console warning is no longer emitted:\n\n```ts {6}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Author: {\n      fields: {\n        books: {\n          merge: false,\n        },\n      },\n    },\n  },\n});\n```\n\nIn some cases, you might want the same behavior for all occurrences of a particular type. To do so, pass `merge: false` to the type policy for that type like so:\n\n```ts {19}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    // No longer necessary!\n    // Article: {\n    //   fields: {\n    //     author: {\n    //       merge: false,\n    //     },\n    //   },\n    // },\n    // Book: {\n    //   fields: {\n    //     author: {\n    //       merge: false,\n    //     },\n    //   },\n    // },\n    Author: {\n      merge: false,\n    },\n  },\n});\n```\n\n## Specifying key arguments\n\nIf a field accepts arguments, you can specify an array of `keyArgs` in the field's `FieldPolicy`. This array indicates which arguments are **key arguments** that affect the field's return value. Specifying this array can help reduce the amount of duplicate data in your cache.\n\n#### Example\n\nLet's say your schema's `Query` type includes a `monthForNumber` field. This field returns the details of particular month, given a provided `number` argument (January for `1` and so on). The `number` argument is a key argument for this field, because its value affects the field's return value:\n\n```ts\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        monthForNumber: {\n          keyArgs: [\"number\"],\n        },\n      },\n    },\n  },\n});\n```\n\nAn example of a _non-key_ argument is an access token, which is used to authorize a query but _not_ to calculate its result. If `monthForNumber` also accepts an `accessToken` argument, the value of that argument does _not_ affect which month's details are returned.\n\n**By default, _all_ of a field's arguments are key arguments.** This means that the cache stores a separate value for _every unique combination of argument values you provide when querying a particular field_.\n\nIf you specify a field's key arguments, the cache understands that the _rest_ of that field's arguments _aren't_ key arguments. This means that the cache _doesn't_ need to store a completely separate value when a non-key argument changes.\n\nFor example, let's say you execute two different queries with the `monthForNumber` field, passing the _same_ `number` argument but _different_ `accessToken` arguments. In this case, the second query response will _overwrite_ the first, because both invocations use an identical value for the only key argument.\n\n### Providing a `keyArgs` function\n\nIf you need more control over a particular field's `keyArgs`, you can pass a function instead of an array of argument names. This `keyArgs` function takes two parameters:\n\n- An `args` object containing all argument values provided for the field\n- A `context` object providing other relevant details\n\nFor details, see `KeyArgsFunction` in the [API reference](#fieldpolicy-api-reference) below.\n\n## `FieldPolicy` API reference\n\nHere are the definitions for the `FieldPolicy` type and its related types:\n\n```ts\n// These generic type parameters will be inferred from the provided policy in\n// most cases, though you can use this type to constrain them more precisely.\ntype FieldPolicy<TExisting, TIncoming = TExisting, TReadResult = TExisting> = {\n  keyArgs?: KeySpecifier | KeyArgsFunction | false;\n  read?: FieldReadFunction<TExisting, TReadResult>;\n  merge?: FieldMergeFunction<TExisting, TIncoming> | boolean;\n};\n\ntype KeySpecifier = (string | KeySpecifier)[];\n\ntype KeyArgsFunction = (\n  args: Record<string, any> | null,\n  context: {\n    typename: string;\n    fieldName: string;\n    field: FieldNode | null;\n    variables?: Record<string, any>;\n  }\n) => string | KeySpecifier | null | void;\n\ntype FieldReadFunction<TExisting, TReadResult = TExisting> = (\n  existing: Readonly<TExisting> | undefined,\n  options: FieldFunctionOptions\n) => TReadResult;\n\ntype FieldMergeFunction<TExisting, TIncoming = TExisting> = (\n  existing: Readonly<TExisting> | undefined,\n  incoming: Readonly<TIncoming>,\n  options: FieldFunctionOptions\n) => TExisting;\n\n// These options are common to both read and merge functions:\ninterface FieldFunctionOptions {\n  cache: InMemoryCache;\n\n  // The final argument values passed to the field, after applying variables.\n  // If no arguments were provided, this property will be null.\n  args: Record<string, any> | null;\n\n  // The name of the field, equal to options.field.name.value when\n  // options.field is available. Useful if you reuse the same function for\n  // multiple fields, and you need to know which field you're currently\n  // processing. Always a string, even when options.field is null.\n  fieldName: string;\n\n  // The FieldNode object used to read this field. Useful if you need to\n  // know about other attributes of the field, such as its directives. This\n  // option will be null when a string was passed to options.readField.\n  field: FieldNode | null;\n\n  // The variables that were provided when reading the query that contained\n  // this field. Possibly undefined, if no variables were provided.\n  variables?: Record<string, any>;\n\n  // Easily detect { __ref: string } reference objects.\n  isReference(obj: any): obj is Reference;\n\n  // Returns a Reference object if obj can be identified, which requires,\n  // at minimum, a __typename and any necessary key fields. If true is\n  // passed for the optional mergeIntoStore argument, the object's fields\n  // will also be persisted into the cache, which can be useful to ensure\n  // the Reference actually refers to data stored in the cache. If you\n  // pass an ID string, toReference will make a Reference out of it. If\n  // you pass a Reference, toReference will return it as-is.\n  toReference(\n    objOrIdOrRef: StoreObject | string | Reference,\n    mergeIntoStore?: boolean\n  ): Reference | undefined;\n\n  // Helper function for reading other fields within the current object.\n  // If a foreign object or reference is provided, the field will be read\n  // from that object instead of the current object, so this function can\n  // be used (together with isReference) to examine the cache outside the\n  // current object. If a FieldNode is passed instead of a string, and\n  // that FieldNode has arguments, the same options.variables will be used\n  // to compute the argument values. Note that this function will invoke\n  // custom read functions for other fields, if defined. Always returns\n  // immutable data (enforced with Object.freeze in development).\n  readField<T = StoreValue>(\n    nameOrField: string | FieldNode,\n    foreignObjOrRef?: StoreObject | Reference\n  ): T;\n\n  // Returns true for non-normalized StoreObjects and non-dangling\n  // References, indicating that readField(name, objOrRef) has a chance of\n  // working. Useful for filtering out dangling references from lists.\n  canRead(value: StoreValue): boolean;\n\n  // A handy place to put field-specific data that you want to survive\n  // across multiple read function calls. Useful for field-level caching,\n  // if your read function does any expensive work.\n  storage: Record<string, any>;\n\n  // Instead of just merging objects with { ...existing, ...incoming }, this\n  // helper function can be used to merge objects in a way that respects any\n  // custom merge functions defined for their fields.\n  mergeObjects<T extends StoreObject | Reference>(\n    existing: T,\n    incoming: T\n  ): T | undefined;\n\n  // Extensions that were provided when writing to the cache.\n  extensions?: Record<string, unknown>;\n}\n```\n"
  },
  {
    "path": "docs/source/caching/cache-interaction.mdx",
    "content": "---\ntitle: Reading and writing data to the cache\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\nYou can read and write data directly to the Apollo Client cache, _without_ communicating with your GraphQL server. You can interact with data that you previously fetched from your server, _and_ with data that's only available [locally](../local-state/local-state-management/).\n\nApollo Client supports multiple strategies for interacting with cached data:\n\n| Strategy                                               | API                                                                 | Description                                                                                    |\n| ------------------------------------------------------ | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |\n| [Using GraphQL queries](#using-graphql-queries)        | `readQuery` / `writeQuery` / `updateQuery`                          | Use standard GraphQL queries for managing both remote and local data.                          |\n| [Using GraphQL fragments](#using-graphql-fragments)    | `readFragment` / `writeFragment` / `updateFragment` / `useFragment` | Access the fields of any cached object without composing an entire query to reach that object. |\n| [Directly modifying cached fields](#using-cachemodify) | `cache.modify`                                                      | Manipulate cached data without using GraphQL at all.                                           |\n| [Batching cache operations](#using-cachebatch)         | `cache.batch`                                                       | Group multiple cache operations into a single transaction for better performance.              |\n\nYou can use whichever combination of strategies and methods are most helpful for your use case.\n\nBear in mind the difference between fields that contain references to other objects in the cache and fields that contain literal values. References are objects that contain a `__ref` field—see the [example](./overview/#example) in the caching overview. Modifying a reference will not change the values contained in the object to which the reference points. So avoid updating an object from something like `{__ref: '5'}` to `{__ref: '5', completed: true}`.\n\n> All code samples below assume that you have initialized an instance of `ApolloClient` and that you have imported the `gql` function from `@apollo/client`. If you haven't, [get started](../get-started).\n>\n> In a React component, you can access your instance of `ApolloClient` using [`ApolloProvider`](../api/react/hooks/#the-apolloprovider-component) and the [`useApolloClient`](../api/react/hooks/#useapolloclient) hook.\n\n## Using GraphQL queries\n\nYou can read and write cache data using GraphQL queries that are similar (or even identical) to queries that you execute on your server:\n\n### `readQuery`\n\nThe `readQuery` method enables you to execute a GraphQL query directly on your cache, like so:\n\n```js {12-19}\nconst READ_TODO = gql`\n  query ReadTodo($id: ID!) {\n    todo(id: $id) {\n      id\n      text\n      completed\n    }\n  }\n`;\n\n// Fetch the cached to-do item with ID 5\nconst { todo } = client.readQuery({\n  query: READ_TODO,\n  // Provide any required variables in this object.\n  // Variables of mismatched types will return `null`.\n  variables: {\n    id: 5,\n  },\n});\n```\n\nIf your cache contains data for _all_ of the query's fields, `readQuery` returns an object that matches the shape of the query.\n\nTo successfully execute queries with variables, the field with the specified argument must already be in the cache. In the above example, to get the to-do item with the `id` of `5`, the `todo` field(s) for `id:5` must already be cached. For this example, the cache would need to look something like this:\n\n```js\n{\n  ROOT_QUERY: {\n    'todo({\"id\":5})': {\n      __ref: 'Todo:5'\n    }\n  },\n  'Todo:5': {\n    // ...\n  }\n}\n```\n\nOtherwise the client treats the data as missing and `readQuery` returns `null`. To learn more about how the caching works, checkout the [caching overview](./overview).\n\n```js\n{\n  todo: {\n    __typename: 'Todo', // __typename is automatically included\n    id: 5,\n    text: 'Buy oranges 🍊',\n    completed: true\n  }\n}\n```\n\n> Apollo Client automatically queries for every object's `__typename` by default, even if you don't include this field in your query string.\n\n**Do not modify the returned object directly.** The same object might be returned to multiple components. To update cached data safely, see [Combining reads and writes](#combining-reads-and-writes).\n\nIf the cache is missing data for _any_ of the query's fields, `readQuery` returns `null`. It does _not_ attempt to fetch data from your GraphQL server.\n\nThe query you provide `readQuery` can include fields that are _not_ defined in your GraphQL server's schema (i.e., [local-only fields](../local-state/managing-state-with-field-policies/)).\n\n> Prior to Apollo Client 3.3, `readQuery` threw a `MissingFieldError` exception to report missing fields. Beginning with Apollo Client 3.3, `readQuery` always returns `null` to indicate that fields are missing.\n\n### `writeQuery`\n\nThe `writeQuery` method enables you to write data to your cache in a shape that matches a GraphQL query. It resembles `readQuery`, except that it requires a `data` option:\n\n```js\nclient.writeQuery({\n  query: gql`\n    query WriteTodo($id: Int!) {\n      todo(id: $id) {\n        id\n        text\n        completed\n      }\n    }\n  `,\n  data: {\n    // Contains the data to write\n    todo: {\n      __typename: \"Todo\",\n      id: 5,\n      text: \"Buy grapes 🍇\",\n      completed: false,\n    },\n  },\n  variables: {\n    id: 5,\n  },\n});\n```\n\nThis example creates (or edits) a cached `Todo` object with ID `5`.\n\nNote the following about `writeQuery`:\n\n- Any changes you make to cached data with `writeQuery` are **not** pushed to your GraphQL server. If you reload your environment, these changes disappear.\n- The shape of your query is _not_ enforced by your GraphQL server's schema:\n  - The query can include fields that are _not_ present in your schema.\n  - You can (but usually **shouldn't**) provide values for schema fields that are _invalid_ according to your schema.\n\n#### Editing existing data\n\nIn the example above, if your cache _already_ contains a `Todo` object with ID `5`, `writeQuery` overwrites the fields that are included in `data` (other fields are preserved):\n\n```js {6-7,17-18}\n// BEFORE\n{\n  'Todo:5': {\n    __typename: 'Todo',\n    id: 5,\n    text: 'Buy oranges 🍊',\n    completed: true,\n    dueDate: '2022-07-02'\n  }\n}\n\n// AFTER\n{\n  'Todo:5': {\n    __typename: 'Todo',\n    id: 5,\n    text: 'Buy grapes 🍇',\n    completed: false,\n    dueDate: '2022-07-02'\n  }\n}\n```\n\n> If you include a field in `query` but don't include a _value_ for it in `data`, the field's current cached value is preserved.\n\n## Using GraphQL fragments\n\nYou can read and write cache data using GraphQL fragments on _any_ normalized cache object. This provides more \"random access\" to your cached data than `readQuery`/`writeQuery`, which require a complete valid query.\n\n### `readFragment`\n\nThis example fetches the same data as [the example for `readQuery`](#readquery) using `readFragment` instead:\n\n```js\nconst todo = client.readFragment({\n  id: \"Todo:5\", // The value of the to-do item's cache ID\n  fragment: gql`\n    fragment MyTodo on Todo {\n      id\n      text\n      completed\n    }\n  `,\n});\n```\n\nUnlike `readQuery`, `readFragment` requires an `id` option. This option specifies the cache ID for the object in your cache. [By default](./overview/#2-generate-cache-ids), cache IDs have the format `<__typename>:<id>` (which is why we provide `Todo:5` above). You can [customize this ID](./cache-configuration/#customizing-cache-ids).\n\nIn the example above, `readFragment` returns `null` in either of the following cases:\n\n- There is no cached `Todo` object with ID `5`.\n- There _is_ a cached `Todo` object with ID `5`, but it's missing a value for either `text` or `completed`.\n\n> Prior to Apollo Client 3.3, `readFragment` threw `MissingFieldError` exceptions to report missing fields, and returned `null` only when reading a fragment from a nonexistent ID. Beginning with Apollo Client 3.3, `readFragment` always returns `null` to indicate insufficient data (missing ID or missing fields), instead of throwing a `MissingFieldError`.\n\n### `writeFragment`\n\nIn addition to reading \"random-access\" data from the Apollo Client cache with `readFragment`, you can _write_ data to the cache with the `writeFragment` method.\n\n> **Any changes you make to cached data with `writeFragment` are not pushed to your GraphQL server.** If you reload your environment, these changes will disappear.\n\nThe `writeFragment` method resembles `readFragment`, except it requires an additional `data` variable. For example, the following call to `writeFragment` updates the `completed` flag for a `Todo` object with an `id` of `5`:\n\n```js\nclient.writeFragment({\n  id: \"Todo:5\",\n  fragment: gql`\n    fragment MyTodo on Todo {\n      completed\n    }\n  `,\n  data: {\n    completed: true,\n  },\n});\n```\n\nAll subscribers to the Apollo Client cache (including all active queries) see this change and update your application's UI accordingly.\n\n### `watchFragment`\n\n<DocBlock\n  canonicalReference={\"@apollo/client!ApolloClient#watchFragment:member(1)\"}\n/>\n\n### `useFragment`\n\nYou can read data for a given fragment directly from the cache using the `useFragment` hook. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. [See the API reference.](../api/react/hooks#usefragment)\n\n## Combining reads and writes\n\nYou can combine `readQuery` and `writeQuery` (or `readFragment` and `writeFragment`) to fetch currently cached data and make selective modifications to it. The following example creates a new `Todo` item and adds it to your cached to-do list. Remember, this addition is _not_ sent to your remote server.\n\n<ExpansionPanel title=\"Click to expand\">\n\n```js\n// Query that fetches all existing to-do items\nconst query = gql`\n  query MyTodoAppQuery {\n    todos {\n      id\n      text\n      completed\n    }\n  }\n`;\n\n// Get the current to-do list\nconst data = client.readQuery({ query });\n\n// Create a new to-do item\nconst myNewTodo = {\n  id: \"6\",\n  text: \"Start using Apollo Client.\",\n  completed: false,\n  __typename: \"Todo\",\n};\n\n// Write back to the to-do list, appending the new item\nclient.writeQuery({\n  query,\n  data: {\n    todos: [...data.todos, myNewTodo],\n  },\n});\n```\n\n</ExpansionPanel>\n\n### Using `updateQuery` and `updateFragment`\n\nAs a convenience, you can use `cache.updateQuery` or `cache.updateFragment` to combine reading and writing cached data with a single method call:\n\n```js {12-17}\n// Query to fetch all todo items\nconst query = gql`\n  query MyTodoAppQuery {\n    todos {\n      id\n      text\n      completed\n    }\n  }\n`;\n\n// Set all todos in the cache as completed\ncache.updateQuery({ query }, (data) => ({\n  todos: data.todos.map((todo) => ({ ...todo, completed: true })),\n}));\n```\n\nEach of these methods takes two parameters:\n\n- The same `options` parameter as its `read` method counterpart (which always includes a `query` or `fragment`)\n- An **update function**\n\nAfter either method fetches data from the cache, it calls its update function and passes it the cached `data`. The update function can then return a value to _replace_ that `data` in the cache. In the example above, every cached `Todo` object has its `completed` field set to `true` (and other fields remain unchanged).\n\nPlease note that the replacement value has to be calculated in an immutable way. You can read more about immutable updates in [the React documentation](https://beta.reactjs.org/learn/updating-objects-in-state).\n\nIf the update function shouldn't make _any_ changes to the cached data, it can return `undefined`.\n\nThe update function's return value is passed to either `writeQuery` or `writeFragment`, which modifies the cached data.\n\n> See the full API reference for [`cache.updateQuery`](../api/cache/InMemoryCache/#updatequery) and [`cache.updateFragment`](../api/cache/InMemoryCache/#updatefragment).\n\n### Using `cache.batch`\n\nUse `cache.batch` to group multiple cache operations into a single transaction. This provides two key benefits:\n\n- **Performance**: Watchers (and thereby React components) are notified only once after all operations complete, rather than after each individual operation.\n- **Control**: You gain fine-grained control over optimistic updates and can intercept watcher notifications.\n\nHere's an example that updates multiple cached items at once:\n\n```js\ncache.batch({\n  update(cache) {\n    // All these operations happen in a single batch\n    cache.writeQuery({\n      query: GET_TODOS,\n      data: { todos: updatedTodos },\n    });\n\n    cache.modify({\n      id: cache.identify(currentUser),\n      fields: {\n        todoCount(existing) {\n          return existing + 1;\n        },\n      },\n    });\n\n    // Cleanup after the updates\n    cache.evict({ id: \"Todo:old-item\" });\n  },\n});\n```\n\n#### Working with optimistic updates\n\nThe `optimistic` option controls how `batch` handles optimistic data:\n\n```js\n// Create a new optimistic layer with a specific ID\ncache.batch({\n  optimistic: \"add-todo-123\",\n  update(cache) {\n    cache.modify({\n      fields: {\n        todos(existing = []) {\n          const newTodoRef = cache.writeFragment({\n            data: optimisticTodo,\n            fragment: gql`\n              fragment NewTodo on Todo {\n                id\n                text\n                completed\n              }\n            `,\n          });\n          return [...existing, newTodoRef];\n        },\n      },\n    });\n  },\n});\n\n// Later, remove the optimistic layer when the server responds\ncache.batch({\n  update(cache) {\n    // Write the real server data\n    cache.writeQuery({\n      query: GET_TODOS,\n      data: serverResponse.data,\n    });\n  },\n  // Remove the optimistic layer in the same batch\n  removeOptimistic: \"add-todo-123\",\n});\n```\n\nThe `optimistic` option accepts three types of values:\n\n| Value            | Behavior                                                                                           |\n| ---------------- | -------------------------------------------------------------------------------------------------- |\n| `string`         | Creates a new optimistic layer with the given ID. Use this to remove these specific changes later. |\n| `true` (default) | Updates happen on the current top layer of the cache.                                              |\n| `false`          | Updates apply only to the root (non-optimistic) cache data, ignoring any optimistic layers.        |\n\n#### Intercepting watcher notifications\n\nUse the `onWatchUpdated` callback to inspect or prevent notifications to specific watchers:\n\n```js\ncache.batch({\n  update(cache) {\n    cache.writeQuery({\n      query: GET_USER,\n      data: { user: updatedUser },\n    });\n  },\n  onWatchUpdated(watch, diff, lastDiff) {\n    console.log(\"Query affected:\", watch.query);\n    console.log(\"New result:\", diff.result);\n\n    // Return false to prevent notifying this watcher\n    if (shouldSkipUpdate(watch)) {\n      return false;\n    }\n  },\n});\n```\n\n#### Return values\n\nThe `batch` method returns whatever value your `update` function returns:\n\n```js\nconst result = cache.batch({\n  update(cache) {\n    const before = cache.readQuery({ query: GET_COUNT });\n    cache.writeQuery({\n      query: GET_COUNT,\n      data: { count: before.count + 1 },\n    });\n    return before.count; // Return the previous count\n  },\n});\n\nconsole.log(\"Previous count was:\", result);\n```\n\n> See the full API reference for [`cache.batch`](../api/cache/InMemoryCache/#batch).\n\n## Using `cache.modify`\n\nThe `modify` method of `InMemoryCache` enables you to directly modify the values of individual cached fields, or even delete fields entirely.\n\n- Like `writeQuery` and `writeFragment`, `modify` triggers a refresh of all active queries that depend on modified fields (unless you override this behavior by passing `broadcast: false`).\n- _Unlike_ `writeQuery` and `writeFragment`:\n  - `modify` circumvents any [`merge` functions](cache-field-behavior/#the-merge-function) you've defined, which means that fields are always overwritten with exactly the values you specify.\n  - `modify` _cannot_ write fields that do not already exist in the cache.\n- Watched queries can control what happens when they're invalidated by updates to the cache, by passing options like `fetchPolicy` and `nextFetchPolicy` to [`client.watchQuery`](../api/core/ApolloClient/#ApolloClient.watchQuery) or the [`useQuery`](../api/react/hooks/#options) hook.\n\n### Parameters\n\nCanonically documented in the [API reference](../api/cache/InMemoryCache/#modify), the `modify` method takes the following parameters:\n\n- The ID of a cached object to modify (which we recommend obtaining with [`cache.identify`](#obtaining-an-objects-cache-id))\n- A map of **modifier functions** to execute (one for each field to modify)\n- Optional `broadcast` and `optimistic` boolean values to customize behavior\n\nA modifier function applies to a single field. It takes its associated field's current cached value as a parameter and returns whatever value should replace it.\n\nHere's an example call to `modify` that modifies a `name` field to convert its value to upper case:\n\n```js\ncache.modify({\n  id: cache.identify(myObject),\n  fields: {\n    name(cachedName) {\n      return cachedName.toUpperCase();\n    },\n  },\n  /* broadcast: false // Include this to prevent automatic query refresh */\n});\n```\n\n> If you don't provide a modifier function for a particular field, that field's cached value remains unchanged.\n\n#### Values vs. references\n\nWhen you define a modifier function for a field that contains a scalar, an enum, or a list of these base types, the modifier function is passed the exact existing value for the field. For example, if you define a modifier function for an object's `quantity` field that has current value `5`, your modifier function is passed the value `5`.\n\n**However**, when you define a modifier function for a field that contains an object type or a list of objects, those objects are represented as **references**. Each reference points to its corresponding object in the cache by its cache ID. If you return a _different_ reference in your modifier function, you change _which_ other cached object is contained in this field. You _don't_ modify the original cached object's data. Additionally, modifying a field (or adding a new one) in a reference will only take effect for the location you're modifying.\n\n### Modifier function utilities\n\nA modifier function can optionally take a second parameter, which is an object that contains several helpful utilities.\n\nSome of these utilities (namely, the `readField` function and the `DELETE` sentinel object) are used in the examples below. For descriptions of all available utilities, see the [API reference](../api/cache/InMemoryCache/#modifier-function-api).\n\n### Examples\n\n#### Example: Removing an item from a list\n\nLet's say we have a blog application where each `Post` has an array of `Comment`s. Here's how we might remove a specific `Comment` from a paginated `Post.comments` array:\n\n```js\nconst idToRemove = \"abc123\";\n\ncache.modify({\n  id: cache.identify(myPost),\n  fields: {\n    comments(existingCommentRefs, { readField }) {\n      return existingCommentRefs.filter(\n        (commentRef) => idToRemove !== readField(\"id\", commentRef)\n      );\n    },\n  },\n});\n```\n\nLet's break this down:\n\n- In the `id` field, we use [`cache.identify`](#obtaining-an-objects-cache-id) to obtain the cache ID of the cached `Post` object we want to remove a comment from.\n\n- In the `fields` field, we provide an object that lists our modifier functions. In this case, we define a single modifier function (for the `comments` field).\n\n- The `comments` modifier function takes our existing cached array of comments as a parameter (`existingCommentRefs`). It also uses the `readField` utility function, which helps you read the value of any cached field.\n\n- The modifier function returns an array that filters out all comments with an ID that matches `idToRemove`. The returned array replaces the existing array in the cache.\n\n#### Example: Adding an item to a list\n\nNow let's look at _adding_ a `Comment` to a `Post`:\n\n```js\nconst newComment = {\n  __typename: \"Comment\",\n  id: \"abc123\",\n  text: \"Great blog post!\",\n};\n\ncache.modify({\n  id: cache.identify(myPost),\n  fields: {\n    comments(existingCommentRefs = [], { readField }) {\n      const newCommentRef = cache.writeFragment({\n        data: newComment,\n        fragment: gql`\n          fragment NewComment on Comment {\n            id\n            text\n          }\n        `,\n      });\n\n      // Quick safety check - if the new comment is already\n      // present in the cache, we don't need to add it again.\n      if (\n        existingCommentRefs.some(\n          (ref) => readField(\"id\", ref) === newComment.id\n        )\n      ) {\n        return existingCommentRefs;\n      }\n\n      return [...existingCommentRefs, newCommentRef];\n    },\n  },\n});\n```\n\nWhen the `comments` field modifier function is called, it first calls `writeFragment` to store our `newComment` data in the cache. The `writeFragment` function returns a reference (`newCommentRef`) that points to the newly cached comment.\n\nAs a safety check, we then scan the array of existing comment references (`existingCommentRefs`) to make sure that our new isn't already in the list. If it isn't, we add the new comment reference to the list of references, returning the full list to be stored in the cache.\n\n#### Example: Updating the cache after a mutation\n\nIf you call `writeFragment` with an `options.data` object that the cache is able to identify ( based on its `__typename` and cache ID fields), you can avoid passing `options.id` to `writeFragment`.\n\nWhether you provide `options.id` explicitly or let `writeFragment` figure it out using `options.data`, `writeFragment` returns a `Reference` to the identified object.\n\nThis behavior makes `writeFragment` a good tool for obtaining a `Reference` to an existing object in the cache, which can come in handy when writing an `update` function for [`useMutation`](../data/mutations/):\n\nFor example:\n\n```js\nconst [addComment] = useMutation(ADD_COMMENT, {\n  update(cache, { data: { addComment } }) {\n    cache.modify({\n      id: cache.identify(myPost),\n      fields: {\n        comments(existingCommentRefs = [], { readField }) {\n          const newCommentRef = cache.writeFragment({\n            data: addComment,\n            fragment: gql`\n              fragment NewComment on Comment {\n                id\n                text\n              }\n            `,\n          });\n          return [...existingCommentRefs, newCommentRef];\n        },\n      },\n    });\n  },\n});\n```\n\nIn this example, `useMutation` automatically creates a `Comment` and adds it to the cache, but it _doesn't_ automatically know how to add that `Comment` to the corresponding `Post`'s list of `comments`. This means that any queries watching the `Post`'s list of `comments` _won't_ update.\n\nTo address this, we use the [`update` callback](../data/mutations/#updating-local-data) of `useMutation` to call `cache.modify`. Like the [previous example](#example-adding-an-item-to-a-list), we add the new comment to the list. _Unlike_ the previous example, the comment was already added to the cache by `useMutation`. Consequently, `cache.writeFragment` returns a reference to the existing object.\n\n#### Example: Deleting a field from a cached object\n\nA modifier function's optional second parameter is an object that includes [several helpful utilities](#modifier-function-utilities), such as the `canRead` and `isReference` functions. It also includes a sentinel object called `DELETE`.\n\nTo delete a field from a particular cached object, return the `DELETE` sentinel object from the field's modifier function, like so:\n\n```js\ncache.modify({\n  id: cache.identify(myPost),\n  fields: {\n    comments(existingCommentRefs, { DELETE }) {\n      return DELETE;\n    },\n  },\n});\n```\n\n#### Example: Invalidating fields within a cached object\n\nNormally, changing or deleting a field's value also _invalidates_ the field, causing watched queries to be reread if they previously consumed the field.\n\nUsing `cache.modify`, it's also possible to invalidate the field without changing or deleting its value, by returning the `INVALIDATE` sentinel:\n\n```js\ncache.modify({\n  id: cache.identify(myPost),\n  fields: {\n    comments(existingCommentRefs, { INVALIDATE }) {\n      return INVALIDATE;\n    },\n  },\n});\n```\n\nIf you need to invalidate _all_ fields within a given object, you can pass a modifier function as the value of the `fields` option:\n\n```js\ncache.modify({\n  id: cache.identify(myPost),\n  fields(fieldValue, details) {\n    return details.INVALIDATE;\n  },\n});\n```\n\nWhen using this form of `cache.modify`, you can determine individual field names using `details.fieldName`. This technique works for any modifier function, not just those that return `INVALIDATE`.\n\n## Obtaining an object's cache ID\n\nIf a type in your cache uses a [custom cache ID](./cache-configuration/#customizing-cache-ids) (or even if it doesn't), you can use the `cache.identify` method to obtain the cache ID for an object of that type. This method takes an object and computes its ID based on both its `__typename` and its identifier field(s). This means you don't have to keep track of which fields make up each type's cache ID.\n\n### Example\n\nLet's say we have a JavaScript representation of a cached GraphQL object, like this:\n\n```js {3}\nconst invisibleManBook = {\n  __typename: \"Book\",\n  isbn: \"9780679601395\", // The key field for this type's cache ID\n  title: \"Invisible Man\",\n  author: {\n    __typename: \"Author\",\n    name: \"Ralph Ellison\",\n  },\n};\n```\n\nIf we want to interact with this object in our cache with methods like [`writeFragment`](#writefragment) or [`cache.modify`](#using-cachemodify), we need the object's cache ID. Our `Book` type's cache ID appears to be custom, because the `id` field isn't present.\n\nInstead of needing to look up that our `Book` type uses the `isbn` field for its cache ID, we can use the `cache.identify` method, like so:\n\n```js {8}\nconst bookYearFragment = gql`\n  fragment BookYear on Book {\n    publicationYear\n  }\n`;\n\nconst fragmentResult = cache.writeFragment({\n  id: cache.identify(invisibleManBook),\n  fragment: bookYearFragment,\n  data: {\n    publicationYear: \"1952\",\n  },\n});\n```\n\nThe cache knows that the `Book` type uses the `isbn` field for its cache ID, so `cache.identify` can correctly populate the `id` field above.\n\nThis example is straightforward because our cache ID uses a single field (`isbn`). But custom cache IDs can consist of _multiple_ fields (such as both `isbn` _and_ `title`). This makes it much more challenging and repetitive to specify an object's cache ID _without_ using `cache.identify`.\n"
  },
  {
    "path": "docs/source/caching/garbage-collection.mdx",
    "content": "---\ntitle: Garbage collection and cache eviction\n---\n\nApollo Client 3 enables you to selectively remove cached data that is no longer useful. The default garbage collection strategy of the `gc` method is suitable for most applications, but the `evict` method provides more fine-grained control for applications that require it.\n\n> You call these methods directly on the `InMemoryCache` object, not on the `ApolloClient` object.\n\n## `cache.gc()`\n\nThe `gc` method removes all objects from the normalized cache that are not **reachable**:\n\n```js\ncache.gc();\n```\n\nTo determine whether an object is reachable, the cache starts from all known root objects (usually `Query` and/or `Mutation`) and uses a tracing strategy to recursively visit all available child references. Any normalized objects that are _not_ visited during this process are removed. The `cache.gc()` method returns a list of the IDs of the removed objects.\n\nIn addition to pruning your GraphQL data, `cache.gc` can also release memory that the cache uses to preserve unchanged parts of previous cache results:\n\n```js\ncache.gc({ resetResultCache: true });\n```\n\nFreeing this memory temporarily slows down cache reads, because those reads don't benefit from any previous reading work.\n\nThese additional `cache.gc` options can be useful for investigating memory usage patterns or leaks. Before taking heap snapshots or recording allocation timelines, it's a good idea to force _JavaScript_ garbage collection using your browser's devtools, to ensure memory released by the cache has been fully collected and returned to the heap.\n\n### Configuring garbage collection\n\nYou can use the `retain` method to prevent an object (and its children) from being garbage collected, even if the object isn't reachable:\n\n```js\ncache.retain(\"my-object-id\");\n```\n\nIf you later want a `retain`ed object to be garbage collected, use the `release` method:\n\n```js\ncache.release(\"my-object-id\");\n```\n\nIf the object is unreachable, it will be garbage collected during next call to `gc`.\n\n## `cache.evict()`\n\nYou can remove any normalized object from the cache using the `evict` method:\n\n```js\ncache.evict({ id: \"my-object-id\" });\n```\n\nYou can also remove a _single field_ from a cached object by providing the name of the field to remove:\n\n```js\ncache.evict({ id: \"my-object-id\", fieldName: \"yearOfFounding\" });\n```\n\nEvicting an object often makes _other_ cached objects unreachable. Because of this, you should call [`cache.gc`](#cachegc) after `evict`ing one or more objects from the cache.\n\n## Dangling references\n\nWhen an object is `evict`ed from the cache, references to that object might remain in _other_ cached objects. Apollo Client preserves these dangling references by default, because the referenced object might be written _back_ to the cache at a later time. This means the reference might still be useful.\n\nYou can customize behavior for dangling references by defining a custom [`read` function](./cache-field-behavior/#the-read-function) for any field that might contain one. This function can perform whatever cleanup is necessary when the field's referenced object is missing. For example, the `read` function might:\n\n- Filter the referenced object out of a list of available objects\n- Set the field's value to `null`\n- Return a particular default value\n\nEvery `read` function is passed a `canRead` function that helps it detect when its field currently contains a dangling reference.\n\nThe following code defines two `read` functions (one for `Query.ruler` and one for `Deity.offspring`) that both use `canRead`:\n\n```js\nnew InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        ruler(existingRuler, { canRead, toReference }) {\n          // If there is no existing ruler, Apollo becomes the ruling deity\n          return canRead(existingRuler) ? existingRuler : toReference({\n            __typename: \"Deity\",\n            name: \"Apollo\",\n          });\n        },\n      },\n    },\n\n    Deity: {\n      keyFields: [\"name\"],\n      fields: {\n        offspring(existingOffspring: Reference[], { canRead }) {\n          // Filter out any dangling references left over from removing\n          // offspring, supplying a default empty array if there are no\n          // offspring left.\n          return existingOffspring\n            ? existingOffspring.filter(canRead)\n            : [];\n        },\n      },\n    },\n  },\n})\n```\n\n- The `read` function for `Query.ruler` returns a default ruler (`Apollo`) if the `existingRuler` has been deposed.\n- The `read` function for `Deity.offspring` filters its array to return only offspring that are alive and well in the cache.\n\nFiltering dangling references out of a cached list field (like the `Deity.offspring` example above) is so common that the default `read` function for a list field performs this filtering _automatically_. You can define a custom `read` function to override this behavior.\n\nThere isn't a similarly common solution for a field that contains a _single_ dangling reference (like the `Query.ruler` example above), so this is where writing a custom `read` function comes in handy most often.\n"
  },
  {
    "path": "docs/source/caching/memory-management.mdx",
    "content": "---\ntitle: Memory management\nsubtitle: Learn how to choose and set custom cache sizes\ndescription: Learn how to choose and set custom cache sizes with Apollo Client.\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\n## Cache Sizes\n\nFor better performance, Apollo Client caches (or, in other words, memoizes) many\ninternally calculated values.\nIn most cases, these values are cached in [weak caches](https://en.wikipedia.org/wiki/Weak_reference), which means that if the\nsource object is garbage-collected, the cached value will be garbage-collected,\ntoo.\n\nThese caches are also Least Recently Used (LRU) caches, meaning that if the cache is full,\nthe least recently used value will be garbage-collected.\n\nDepending on your application, you might want to tweak the cache size to fit your\nneeds.\n\nYou can set your cache size [before (recommended)](#setting-cache-sizes-before-loading-the-apollo-client-library) or [after](#adjusting-cache-sizes-after-loading-the-apollo-client-library) loading the Apollo Client library.\n\n### Setting cache sizes before loading the Apollo Client library\n\nSetting cache sizes before loading the Apollo Client library is recommended because some caches are already initialized when the library is loaded. Changed cache sizes only\naffect caches created after the fact, so you'd have to write additional runtime code to recreate these caches after changing their size.\n\n```ts\nimport type { CacheSizes } from \"@apollo/client/utilities\";\n\nglobalThis[Symbol.for(\"apollo.cacheSize\")] = {\n  parser: 100,\n  \"fragmentRegistry.lookup\": 500,\n} satisfies Partial<CacheSizes>;\n```\n\n### Adjusting cache sizes after loading the Apollo Client library\n\nYou can also adjust cache sizes after loading the library.\n\n```js\nimport { cacheSizes } from \"@apollo/client/utilities\";\nimport { print } from \"@apollo/client\";\n\ncacheSizes.print = 100;\n// cache sizes changed this way will only take effect for caches\n// created after the cache size has been changed, so we need to\n// reset the cache for it to be effective\n\nprint.reset();\n```\n\n### Choosing appropriate cache sizes\n\n<Remarks canonicalReference=\"@apollo/client/utilities!CacheSizes:interface\" />\n\nTo choose good sizes for our memoization caches, you need to know what they\nuse as source values, and have a general understanding of the data flow inside of\nApollo Client.\n\nFor most memoized values, the source value is a parsed GraphQL document&mdash;\na `DocumentNode`. There are two types:\n\n- **User-supplied `DocumentNode`s** are created\n  by the user, for example by using the `gql` template literal tag.\n  This is the `QUERY`, `MUTATION`, or `SUBSCRIPTION` argument passed\n  into a [`useQuery` hook](../data/queries/#usequery-api) or as the `query` option to `client.query`.\n- **Transformed `DocumentNode`s** are derived from\n  user-supplied `DocumentNode`s, for example, by applying [`DocumentTransform`s](../data/document-transforms/) to them.\n\nAs a rule of thumb, you should set the cache sizes for caches using a transformed\n`DocumentNode` at least to the same size as for caches using a user-supplied\n`DocumentNode`. If your application uses a custom `DocumentTransform` that does\nnot always transform the same input to the same output, you should set the cache\nsize for caches using a Transformed `DocumentNode` to a higher value than for\ncaches using a user-supplied `DocumentNode`.\n\nBy default, Apollo Client uses a base value of 1000 cached objects for caches using\nuser-supplied `DocumentNode` instances, and scales other cache sizes relative\nto that. For example, the default base value of 1000 for user-provided `DocumentNode`s would scale to 2000, 4000, etc. for transformed `DocumentNode`s, depending on the transformation performed.\n\nThis base value should be plenty for most applications, but you can tweak them if you have different requirements.\n\n#### Measuring cache usage\n\nSince estimating appropriate cache sizes for your application can be hard, Apollo Client\nexposes an API for cache usage measurement.<br />\nThis way, you can click around in your application and then take a look at the\nactual usage of the memoizing caches.\n\nKeep in mind that this API is primarily meant for usage with the Apollo DevTools\n(an integration is coming soon), and the API may change at any\npoint in time.<br />\nIt is also only included in development builds, not in production builds.\n\n<Note>\n\nThe cache usage API is only meant for manual measurements. Don't rely on it in production code or tests.\n\n</Note>\n\n<Example\n  canonicalReference=\"@apollo/client!ApolloClient#getMemoryInternals:member\"\n  index={0}\n/>\n\n<Example\n  collapsible\n  canonicalReference=\"@apollo/client!ApolloClient#getMemoryInternals:member\"\n  index={1}\n/>\n\n### Cache options\n\n<PropertySignatureTable\n  idPrefix=\"cachesizes-interface\"\n  canonicalReference=\"@apollo/client/utilities!CacheSizes:interface\"\n  properties\n/>\n"
  },
  {
    "path": "docs/source/caching/overview.mdx",
    "content": "---\ntitle: Caching in Apollo Client\ndescription: Overview\n---\n\nApollo Client stores the results of your GraphQL queries in a local, [normalized](#data-normalization), in-memory cache. This enables Apollo Client to respond almost immediately to queries for already-cached data, without even sending a network request.\n\nFor example, the _first_ time your app executes a `GetBook` query for a `Book` object with id `5`, the flow looks like this:\n\n```mermaid\nsequenceDiagram\n  Apollo Client->>InMemoryCache: GetBook(bookId: \"5\")\n  Note over InMemoryCache: Book:5 not found<br/>in cache\n  InMemoryCache->>GraphQL Server: Query sent to server\n  GraphQL Server->>InMemoryCache: Server responds<br/>with Book\n  Note over InMemoryCache: Book:5 is cached\n  InMemoryCache->>Apollo Client: Returns Book\n```\n\nAnd each _later_ time your app executes `GetBook` for that same object, the flow looks like this instead:\n\n```mermaid\nsequenceDiagram\n  Apollo Client->>InMemoryCache: GetBook(bookId: \"5\")\n  Note over InMemoryCache: Book:5 found<br/>in cache!\n  InMemoryCache->>Apollo Client: Returns Book\n  Note over GraphQL Server: (Server is never queried)\n```\n\nThe Apollo Client cache is highly configurable. You can customize its behavior for individual types and fields in your schema, and you can even use it to store and interact with local data that _isn't_ fetched from your GraphQL server.\n\n## How is data stored?\n\nApollo Client's `InMemoryCache` stores data as a **flat lookup table** of objects that can reference each other. These objects correspond to the objects that are returned by your GraphQL queries. A single cached object might include fields returned by multiple queries, if those queries fetch _different_ fields of the _same_ object.\n\nThe cache is flat, but objects returned by a GraphQL query often _aren't_! In fact, their nesting can be arbitrarily deep. Take a look at this example query response:\n\n```json\n{\n  \"data\": {\n    \"person\": {\n      \"__typename\": \"Person\",\n      \"id\": \"cGVvcGxlOjE=\",\n      \"name\": \"Luke Skywalker\",\n      \"homeworld\": {\n        \"__typename\": \"Planet\",\n        \"id\": \"cGxhbmV0czox\",\n        \"name\": \"Tatooine\"\n      }\n    }\n  }\n}\n```\n\nThis response contains a `Person` object, which in turn contains a `Planet` object in its `homeworld` field.\n\nSo how does the `InMemoryCache` store _nested_ data in a _flat_ lookup table? Before storing this data, the cache needs to **normalize** it.\n\n### Data normalization\n\nWhenever the Apollo Client cache receives query response data, it does the following:\n\n#### 1. Identify objects\n\nFirst, the cache identifies all of the distinct objects included in a query response. In [the example above](#how-is-data-stored), there are two objects:\n\n- A `Person` with `id` `cGVvcGxlOjE=`\n- A `Planet` with `id` `cGxhbmV0czox`\n\n#### 2. Generate cache IDs\n\nAfter identifying all objects, the cache generates a **cache ID** for each one. A cache ID uniquely identifies a particular object while it's in the `InMemoryCache`.\n\nBy default, an object's cache ID is the concatenation of the object's `__typename` and `id` (or `_id`) fields, separated by a colon (`:`).\n\nSo, the default cache IDs for the objects in [the example above](#how-is-data-stored) are:\n\n- `Person:cGVvcGxlOjE=`\n- `Planet:cGxhbmV0czox`\n\n> You can customize the cache ID format for a particular object type. See [Customizing cache IDs](./cache-configuration/#customizing-cache-ids).\n\nIf the cache _can't_ generate a cache ID for a particular object (for example, if no `id` or `_id` field is present), that object is cached directly inside its _parent_ object, and it must be referenced via the parent (this means the cache isn't always _completely_ flat).\n\n#### 3. Replace object fields with references\n\nNext, the cache takes each field that contains an object and replaces its value with a **reference** to the appropriate object.\n\nFor example, here's the `Person` object from the example above _before_ reference replacement:\n\n```json {5-9}\n{\n  \"__typename\": \"Person\",\n  \"id\": \"cGVvcGxlOjE=\",\n  \"name\": \"Luke Skywalker\",\n  \"homeworld\": {\n    \"__typename\": \"Planet\",\n    \"id\": \"cGxhbmV0czox\",\n    \"name\": \"Tatooine\"\n  }\n}\n```\n\nAnd here's that same object _after_ replacement:\n\n```json {5-7}\n{\n  \"__typename\": \"Person\",\n  \"id\": \"cGVvcGxlOjE=\",\n  \"name\": \"Luke Skywalker\",\n  \"homeworld\": {\n    \"__ref\": \"Planet:cGxhbmV0czox\"\n  }\n}\n```\n\nThe `homeworld` field now contains a reference to the appropriate normalized `Planet` object.\n\n> This replacement does _not_ occur for a particular object if [the previous step](#2-generate-cache-ids) failed to generate a cache ID for that object. Instead, the original object remains.\n\nLater, if you query for _another_ `Person` who has the same `homeworld`, that normalized `Person` object will contain a reference to the _same_ cached object! Normalization can dramatically reduce data duplication, and it also helps your local data stay up to date with your server.\n\n#### 4. Store normalized objects\n\nFinally, the resulting objects are all stored in the cache's flat lookup table.\n\nWhenever an incoming object has the same cache ID as an _existing_ cached object, the fields of those objects are _merged:_\n\n- If the incoming object and the existing object share any fields, the incoming object _overwrites_ the cached values for those fields.\n- Fields that appear in _only_ the existing object or _only_ the incoming object are preserved.\n\nNormalization constructs a partial copy of your graph on your client, in a format that's optimized for reading and updating as your app's state changes.\n\n## Visualizing the cache\n\nTo help understand the structure of your cached data, we strongly recommend installing the [Apollo Client Devtools](../development-testing/developer-tooling/#apollo-client-devtools).\n\nThis browser extension includes an inspector that enables you to view all of the normalized objects contained in your cache:\n\n<img\n  src=\"../img/cache-inspector.jpg\"\n  class=\"screenshot\"\n  alt=\"The Cache tab of the Apollo Client Devtools\"\n></img>\n\n### Example\n\nLet's say we use Apollo Client to run the following query on the [SWAPI demo API](https://github.com/graphql/swapi-graphql):\n\n```graphql\nquery {\n  allPeople(first: 3) {\n    # Return the first 3 items\n    people {\n      id\n      name\n      homeworld {\n        id\n        name\n      }\n    }\n  }\n}\n```\n\nThis query returns the following result of three `Person` objects, each with a corresponding `homeworld` (a `Planet` object):\n\n<ExpansionPanel title=\"Click to expand\">\n\n```json\n{\n  \"data\": {\n    \"allPeople\": {\n      \"people\": [\n        {\n          \"__typename\": \"Person\",\n          \"id\": \"cGVvcGxlOjE=\",\n          \"name\": \"Luke Skywalker\",\n          \"homeworld\": {\n            \"__typename\": \"Planet\",\n            \"id\": \"cGxhbmV0czox\",\n            \"name\": \"Tatooine\"\n          }\n        },\n        {\n          \"__typename\": \"Person\",\n          \"id\": \"cGVvcGxlOjI=\",\n          \"name\": \"C-3PO\",\n          \"homeworld\": {\n            \"__typename\": \"Planet\",\n            \"id\": \"cGxhbmV0czox\",\n            \"name\": \"Tatooine\"\n          }\n        },\n        {\n          \"__typename\": \"Person\",\n          \"id\": \"cGVvcGxlOjM=\",\n          \"name\": \"R2-D2\",\n          \"homeworld\": {\n            \"__typename\": \"Planet\",\n            \"id\": \"cGxhbmV0czo4\",\n            \"name\": \"Naboo\"\n          }\n        }\n      ]\n    }\n  }\n}\n```\n\n</ExpansionPanel>\n\n> Notice that each object in the result includes a `__typename` field, even though our query string _didn't_ include this field. That's because Apollo Client _automatically_ queries for every object's `__typename`.\n\nAfter the result is cached, we can view the state of our cache in the Apollo Client Devtools:\n\n<img\n  src=\"../img/cache-inspector.jpg\"\n  class=\"screenshot\"\n  alt=\"The Cache tab of the Apollo Client Devtools\"\n></img>\n\nOur cache now contains five normalized objects (in addition to the `ROOT_QUERY` object): three `Person` objects and two `Planet` objects.\n\n**Why do we only have two `Planet` objects?** Because two of the three returned `Person` objects have the same `homeworld`. By [normalizing data](#data-normalization) like this, Apollo Client can cache a single copy of an object, and multiple _other_ objects can include _references_ to it (see the `__ref` field of the object in the screenshot above).\n\n## Next steps\n\nNow that you have a basic understanding of how Apollo Client's cache works, learn more about how to [configure it](./cache-configuration/).\n\nThen, you can learn how to [read and write data to your cache](./cache-interaction/) directly, without executing a query against your server. This is a powerful option for [local state management](../local-state/local-state-management/).\n"
  },
  {
    "path": "docs/source/data/defer.mdx",
    "content": "---\ntitle: \"Using the @defer directive in Apollo Client\"\ndescription: Receive query response data incrementally\n---\n\nThe [`@defer` directive](https://github.com/graphql/graphql-wg/blob/main/rfcs/DeferStream.md) enables your queries to receive data for specific fields _incrementally_, instead of receiving all field data at the same time. This is helpful whenever some fields in a query take much longer to resolve than others.\n\n## Prerequisites\n\nTo use `@defer` with Apollo Client, you need to configure an incremental delivery format handler using the format you want to use.\n\n<Note>\n\nThe incremental delivery format used by `@defer` has not yet been standardized. There have been multiple proposals and varying implementations in the `graphql` package. Apollo Client does not default to a specific format for this reason.\n\n</Note>\n\n### Available handlers\n\nApollo Client provides the following incremental delivery handlers that are all exported from `@apollo/client/incremental`:\n\n- `NotImplementedHandler` (default) - Throws when `@defer` or `@stream` is detected\n- `Defer20220824Handler` - Implements the `@defer` and `@stream` transport format that ships with [Apollo Router](https://www.apollographql.com/docs/graphos/routing/operations/defer)\n- `GraphQL17Alpha2Handler` - Implements the `@defer` and `@stream` transport format that ships with GraphQL 17.0.0-alpha.2\n- `GraphQL17Alpha9Handler` - Implements the `@defer` and `@stream` transport format that ships with GraphQL 17.0.0-alpha.9\n\n<Note>\n\n`Defer20220824Handler` and `GraphQL17Alpha2Handler` are aliases for the same delivery format and can be used interchangeably.\n\n</Note>\n\n### Configuration example\n\nTo enable `@defer` support, configure your Apollo Client instance with an incremental handler:\n\n```ts\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  incrementalHandler: new Defer20220824Handler(),\n});\n```\n\nWithout configuring an incremental handler, using the `@defer` directive results in an error.\n\n<Note>\n\nFor a query to defer fields successfully, the queried endpoint must _also_ support the `@defer` directive. Entity-based `@defer` support is also at the General Availability stage in [GraphOS Router](/router/executing-operations/defer-support/) and is compatible with all [federation-compatible subgraph libraries](/federation/building-supergraphs/supported-subgraphs/).\n\n</Note>\n\n## Example\n\nLet's say we're building a social media application that can quickly fetch a user's basic profile information, but retrieving that user's friends takes longer.\n\nGraphQL allows us to declare all the fields our UI requires in a single query, but this also means that _our query will be as slow as the field that takes the longest to resolve_. The `@defer` directive allows us to mark parts of the query that are not necessary for our app's initial render which will be resolved once it becomes available.\n\nTo achieve this, we apply the `@defer` directive to an in-line fragment that contains all slow-resolving fields related to friend data:\n\n```graphql\nquery PersonQuery($personId: ID!) {\n  person(id: $personId) {\n    # Basic fields (fast)\n    id\n    firstName\n    lastName\n\n    # highlight-start\n    # Friend fields (slower)\n    ... @defer {\n      friends {\n        id\n      }\n    }\n    # highlight-end\n  }\n}\n```\n\nUsing this syntax, _if the queried server supports `@defer`,_ our client can receive the \"Basic fields\" in an initial response payload, followed by a supplementary payload containing the \"Friend fields\".\n\nLet's look at an example in React. Here's we can assume `GET_PERSON` is the above query, `PersonQuery`, with a deferred list of friends' `id`s:\n\n```jsx title=\"app.jsx\"\nimport { gql, useQuery } from \"@apollo/client\";\n\nfunction App() {\n  const { dataState, error, data } = useQuery(GET_PERSON, {\n    variables: {\n      id: 1,\n    },\n  });\n\n  if (error) return `Error! ${error.message}`;\n  if (dataState === \"empty\") return \"Loading...\";\n\n  return (\n    <>\n      Welcome, {data.firstName} {data.lastName}!\n      <details>\n        <summary>Friends list</summary>\n        {data.friends ?\n          <ul>\n            {data.friends.map((id) => (\n              <li>{id}</li>\n            ))}\n          </ul>\n        : null}\n      </details>\n    </>\n  );\n}\n```\n\nWhen our call to the `useQuery` hook first resolves with an initial payload of data, `firstName` and `lastName` will be populated with the values from the server and `dataState` will change from `empty` to `streaming`. Our deferred fields will not exist as keys on `data` yet, so we must add conditional logic that checks for their presence.\n\n<Note>\n\nThis example does not use the `loading` boolean to render the loading state. While the response is streaming, the `loading` flag remains `true` to indicate that the query has not yet fully completed. The `networkStatus` field starts as `NetworkStatus.loading` and changes to `NetworkStatus.streaming` as the initial chunk arrives. After all deferred data is received, `loading` becomes `false` and `networkStatus` is `NetworkStatus.ready`.\n\n</Note>\n\nWhen subsequent chunks of deferred data arrive, `useQuery` re-renders and `data` includes the deferred data as it arrives.\n\nFor this reason, `@defer` can be thought of as a tool to improve initial rendering speeds when some slower data will be displayed below the fold or offscreen. In this case, we're rendering the friends list inside a `<details>` element which is closed by default, avoiding any layout shift as the `friends` data arrives.\n\n## `loading`, `networkStatus`, `dataState`, and `data` merging\n\nThese tables represent how `loading`, `networkStatus`, `dataState`, and `data` change as a query with the `@defer` directive is executed.\n\n### Starting a new query\n\n|                                         | `loading` | `networkStatus`           | `dataState`   | `data`                                                   |\n| --------------------------------------- | --------- | ------------------------- | ------------- | -------------------------------------------------------- |\n| query started                           | `true`    | `NetworkStatus.loading`   | `\"empty\"`     | `undefined`                                              |\n| initial response received               | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | partial `data`, contains all non-deferred fields         |\n| one or more deferred fragments received | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | partial `data` contains initial and some deferred fields |\n| final response received                 | `false`   | `NetworkStatus.ready`     | `\"complete\"`  | `data` contains all fields, including deferred ones      |\n\n### Refetching\n\n|                                         | `loading` | `networkStatus`           | `dataState`   | `data`                                                          |\n| --------------------------------------- | --------- | ------------------------- | ------------- | --------------------------------------------------------------- |\n| query started                           | `true`    | `NetworkStatus.refetch`   | `\"complete\"`  | previous `data` stays present                                   |\n| initial response received               | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | `data` contains previous data merged with incoming partial data |\n| one or more deferred fragments received | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | `data` gets more received data merged in                        |\n| final response received                 | `false`   | `NetworkStatus.ready`     | `\"complete\"`  | `data` is updated with all newly received data                  |\n\n<Note>\n\nAs chunks arrive and replace existing data, data that cannot be merged, such as arrays without a type policy might replace existing \"complete\" data with \"streaming\" incomplete data.\n\n</Note>\n\n### Refetching with different variables\n\n|                                         | `loading` | `networkStatus`           | `dataState`   | `data`                                              |\n| --------------------------------------- | --------- | ------------------------- | ------------- | --------------------------------------------------- |\n| query started                           | `true`    | `NetworkStatus.refetch`   | `\"empty\"`     | `undefined`                                         |\n| initial response received               | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | `data` contains initial fields                      |\n| one or more deferred fragments received | `true`    | `NetworkStatus.streaming` | `\"streaming\"` | `data` gets more received data merged in            |\n| final response received                 | `false`   | `NetworkStatus.ready`     | `\"complete\"`  | `data` contains all fields, including deferred ones |\n\n## Using with code generation\n\nIf you currently use [GraphQL Code Generator](https://www.the-guild.dev/graphql/codegen) for your codegen needs, you'll need to use the Codegen version v4.0.0 or higher.\n\n## Usage in React Native\n\nIn order to use `@defer` in a React Native application, additional configuration is required. See the [React Native docs](../integrations/react-native#consuming-multipart-http-via-text-streaming) for more information.\n"
  },
  {
    "path": "docs/source/data/directives.mdx",
    "content": "---\ntitle: \"Using GraphQL directives in Apollo Client\"\ndescription: Configure GraphQL fields and fragments\n---\n\nA directive decorates part of a GraphQL schema or operation with additional configuration. Tools like Apollo Client can read a GraphQL document's directives and perform custom logic as appropriate.\n\nDirectives are preceded by the `@` character, like so:\n\n```graphql\nquery myQuery($someTest: Boolean) {\n  experimentalField @skip(if: $someTest)\n}\n```\n\nThis example shows the `@skip` directive, which is a built-in directive (i.e., it's part of the [GraphQL specification](http://spec.graphql.org/June2018/#sec-Type-System.Directives)). It demonstrates the following about directives:\n\n- Directives can take arguments of their own (`if` in this case).\n- Directives appear after the declaration of what they decorate (the `experimentalField` field in this case).\n\n## `@client`\n\nThe `@client` directive allows you to resolve client-only data alongside your server data. These fields are not sent to the GraphQL server.\n\n```graphql\nquery LaunchDetails($launchId: ID!) {\n  launch(id: $launchId) {\n    site\n    rocket {\n      type\n      # resolved locally on the client,\n      # removed from the request to the server\n      description @client\n    }\n  }\n}\n```\n\nFor more information about the `@client` directive, see this section on [local-only fields](/react/local-state/managing-state-with-field-policies/). The `@client` directive is also useful for [client schema mocking](/react/development-testing/client-schema-mocking/#3-query-with-the-client-directive) before a given field is supported in the GraphQL API your application is consuming.\n\n## `@connection`\n\nThe `@connection` directive allows you to specify a custom cache key for paginated results. For more information, see this section on the [`@connection` directive](/react/caching/advanced-topics/#the-connection-directive).\n\n```graphql\nquery Feed($offset: Int, $limit: Int) {\n  feed(offset: $offset, limit: $limit) @connection(key: \"feed\") {\n    ...FeedFields\n  }\n}\n```\n\n## `@defer`\n\nThe [`@defer` directive](https://github.com/graphql/graphql-wg/blob/main/rfcs/DeferStream.md) enables your queries to receive data for specific fields _incrementally_, instead of receiving all field data at the same time. This is helpful whenever some fields in a query take much longer to resolve than others.\n\n<Note>\n\nTo use the `@defer` directive, you need to choose an incremental delivery format handler . See the [Defer](./defer#setting-up-defer-support-by-choosing-an-incrementalhandler) guide for more information.\n\n</Note>\n\nTo use the `@defer` directive, we apply it to an inline or named fragment that contains all slow-resolving fields:\n\n```graphql\nquery PersonQuery($personId: ID!) {\n  person(id: $personId) {\n    # Basic fields (fast)\n    id\n    firstName\n    lastName\n\n    # Friend fields (slower)\n    ... @defer {\n      friends {\n        id\n      }\n    }\n  }\n}\n```\n\n<Note>\n\nIn order to use `@defer` in a React Native application, additional configuration is required. See the [React Native docs](../integrations/react-native#consuming-multipart-http-via-text-streaming) for more information.\n\n</Note>\n\nFor more information on using the `@defer` directive, see the [Defer](./defer) guide.\n\n<MinVersion version=\"4.1\">\n\n## `@stream`\n\n</MinVersion>\n\nThe [`@stream` directive](https://github.com/graphql/graphql-wg/blob/main/rfcs/DeferStream.md) enables your queries to receive list items _incrementally_, instead of receiving the entire list at once. This is helpful when a field returns a large list that takes time to fully resolve.\n\n<Note>\n\nTo use the `@stream` directive, you need to configure an incremental delivery format handler. See the [Defer](./defer#setting-up-defer-support-by-choosing-an-incrementalhandler) guide for more information.\n\n</Note>\n\nApply the `@stream` directive to a list field. Use the `initialCount` argument to specify the number of items to include in the initial response:\n\n```graphql\nquery FeedQuery {\n  feed @stream(initialCount: 5) {\n    id\n    contents\n  }\n}\n```\n\nThe server returns the first five items immediately, then delivers remaining items as they become available. Your UI can render the initial items while waiting for the rest.\n\n<Note>\n\nIn order to use `@stream` in a React Native application, additional configuration is required. See the [React Native docs](../integrations/react-native#consuming-multipart-http-via-text-streaming) for more information.\n\n</Note>\n\nFor more information on using `@stream`, including details on how `loading`, `networkStatus`, and `dataState` change as list items arrive, see the [Defer](./defer#loading-networkstatus-datastate-and-data-merging) guide.\n\n## `@export`\n\nIf your GraphQL query uses variables, the local-only fields of that query can provide the values of those variables.\n\nTo do so, you apply the `@export(as: \"variableName\")` directive, like so:\n\n```js\nconst GET_CURRENT_AUTHOR_POST_COUNT = gql`\n  query CurrentAuthorPostCount($authorId: Int!) {\n    currentAuthorId @client @export(as: \"authorId\")\n    postCount(authorId: $authorId)\n  }\n`;\n```\n\nIn the query above, the result of the local-only field `currentAuthorId` is used as the value of the `$authorId` variable that's passed to `postCount`.\n\nYou can do this even if `postCount` is also a local-only field (i.e., if it's also marked as `@client`).\n\nFor more information and other considerations when using the `@export` directive, check out the [local-only fields docs](/react/local-state/managing-state-with-field-policies/#using-local-only-fields-as-graphql-variables).\n\n## `@nonreactive`\n\nThe `@nonreactive` directive can be used to mark query fields or fragment spreads and is used to indicate that changes to the data contained within the subtrees marked `@nonreactive` should _not_ trigger rerendering. This allows parent components to fetch data to be rendered by their children without rerendering themselves when the data corresponding with fields marked as `@nonreactive` change.\n\nConsider an `App` component that fetches and renders a list of ski trails:\n\n```jsx\nconst TrailFragment = gql`\n  fragment TrailFragment on Trail {\n    name\n    status\n  }\n`;\n\nconst ALL_TRAILS = gql`\n  query allTrails {\n    allTrails {\n      id\n      ...TrailFragment @nonreactive\n    }\n  }\n  ${TrailFragment}\n`;\n\nfunction App() {\n  const { data, loading } = useQuery(ALL_TRAILS);\n  return (\n    <main>\n      <h2>Ski Trails</h2>\n      <ul>\n        {data?.trails.map((trail) => (\n          <Trail key={trail.id} id={trail.id} />\n        ))}\n      </ul>\n    </main>\n  );\n}\n```\n\nThe `Trail` component renders a trail's name and status and allows the user to execute a mutation to toggle the status of the trail between `\"OPEN\"` and `\"CLOSED\"`:\n\n```jsx\nconst Trail = ({ id }) => {\n  const [updateTrail] = useMutation(UPDATE_TRAIL);\n  const { data } = useFragment({\n    fragment: TrailFragment,\n    from: {\n      __typename: \"Trail\",\n      id,\n    },\n  });\n  return (\n    <li key={id}>\n      {data.name} - {data.status}\n      <input\n        checked={data.status === \"OPEN\" ? true : false}\n        type=\"checkbox\"\n        onChange={(e) => {\n          updateTrail({\n            variables: {\n              trailId: id,\n              status: e.target.checked ? \"OPEN\" : \"CLOSED\",\n            },\n          });\n        }}\n      />\n    </li>\n  );\n};\n```\n\nNotice that the `Trail` component isn't receiving the entire `trail` object via props, only the `id` which is used along with the fragment document to create a live binding for each trail item in the cache. This allows each `Trail` component to react to the cache updates for a single trail independently. Updates to a trail's `status` will not cause the parent `App` component to rerender since the `@nonreactive` directive is applied to the `TrailFragment` spread, a fragment that includes the `status` field.\n\n## `@unmask`\n\nThe `@unmask` directive is used to make fragment data available when using [data masking](./fragments#data-masking). It is primarily used to [incrementally adopt data masking in an existing application](./fragments#incremental-adoption-in-an-existing-application). It is considered an escape hatch for all other cases where working with masked data would otherwise be difficult.\n\n```graphql\nquery GetPosts {\n  posts {\n    id\n    ...PostDetails @unmask\n  }\n}\n\nfragment PostDetails on Post {\n  title\n  publishedAt\n  topComment {\n    id\n    ...CommentFragment @unmask\n  }\n}\n\nfragment CommentFragment on Comment {\n  content\n}\n```\n\n<Note>\n  When the `dataMasking` option is omitted or set to `false`, this directive has\n  no effect.\n</Note>\n\n### Migrate mode\n\n`@unmask` is best used to [incrementally adopt data masking in existing applications](./fragments#incremental-adoption-in-an-existing-application) by providing development-only warnings when accessing would-be masked fields throughout your application. To use `@unmask` in migrate mode, set the `mode` argument to `migrate`.\n\n```graphql\nquery GetPost(id: $id) {\n  post(id: $id) {\n    id\n    ...PostDetails @unmask(mode: \"migrate\")\n  }\n}\n\nfragment PostDetails on Post {\n  title\n}\n```\n\nNow when you access fields that would otherwise be masked, you will see a warning in the console.\n\n```tsx\nconst { data } = useQuery(GET_POST);\n\nconst title = data.post.title;\n```\n\nIn this example, accessing `title` on the `post` from the query result will result in the following warning:\n\n```disableCopy=true showLineNumbers=false\nAccessing unmasked field on query 'GetPost' at path 'post.title'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\n```\n\nFor more information on data masking, see the [data masking docs](./fragments#data-masking).\n"
  },
  {
    "path": "docs/source/data/document-transforms.mdx",
    "content": "---\ntitle: Document transforms\ndescription: Make custom modifications to your GraphQL documents\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\n> This article assumes you're familiar with the [anatomy of a GraphQL query](https://www.apollographql.com/blog/graphql/basics/the-anatomy-of-a-graphql-query/) and the concept of an [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree). To explore a GraphQL AST, visit [AST Explorer](https://astexplorer.net/).\n\nHave you noticed that Apollo Client modifies your queries—such as adding the `__typename` field—before sending those queries to your GraphQL server? It does this through **document transforms**, functions that modify GraphQL documents before query execution.\n\nApollo Client provides an advanced capability that lets you define your own GraphQL document transforms to modify your GraphQL queries. This article explains how to make and use custom GraphQL document transforms.\n\n## Overview\n\nDocument transforms allow you to programmatically modify GraphQL documents used to query data in your application. A GraphQL document is an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree) that defines one or more operations and fragments, parsed from a raw GraphQL query string using the `gql` function. You can create your own document transforms using the `DocumentTransform` class. The created transform is then passed to the `ApolloClient` constructor.\n\n```ts\nimport { DocumentTransform } from \"@apollo/client\";\n\nconst documentTransform = new DocumentTransform((document) => {\n  // modify the document\n  return transformedDocument;\n});\n\nconst client = new ApolloClient({\n  documentTransform,\n});\n```\n\n### Lifecycle\n\nApollo Client runs document transforms before every GraphQL request for all operations. This extends to any API that performs a network request, such as the [`useQuery`](/react/api/react/hooks#usequery) hook or the [`refetch`](/react/api/core/ObservableQuery#refetch) function on [`ObservableQuery`](/react/api/core/ObservableQuery).\n\nDocument transforms are run early in the request's lifecycle. This makes it possible for the cache to see modifications to GraphQL documents—an essential distinction from document modifications made to GraphQL documents in an [Apollo Link](/react/api/link/introduction). Since document transforms are run early in the request lifecycle, this makes it possible to add [`@client`](/react/data/directives#client) directives to fields in your document transform to turn the field into a [local-only field](/react/local-state/managing-state-with-field-policies), or to add fragment selections for fragments defined in the [fragment registry](/react/data/fragments#registering-named-fragments-using-createfragmentregistry).\n\n### Interacting with built-in transforms\n\nApollo Client ships with built-in document transforms that are essential to the client's functionality.\n\n- The `__typename` field is added to every selection set in a query to identify the type of all objects returned by the GraphQL operation.\n- GraphQL documents that use fragments defined in the [fragment registry](/react/data/fragments#registering-named-fragments-using-createfragmentregistry) are added to the document before the request is sent over the network (requires Apollo Client 3.7 or later).\n\nIt's crucial for custom document transforms to interact with these built-in features. To make the most of your custom document transform, Apollo Client runs these built-in transforms twice: once before and once after your transform.\n\nRunning the built-in transforms before your custom transform allows your transform to both see the `__typename` fields added to each field's selection set and modify fragment definitions defined in the fragment registry. Apollo Client understands that your transform may add new selection sets or new fragment selections to the GraphQL document. Because of this, Apollo Client reruns the built-in transforms after your custom transforms.\n\nRunning built-in transforms twice is a convenient capability because it means that you don't have to remember to include the `__typename` field for any added selection sets. Nor do you need to look up fragment definitions in the fragment registry for fragment selections added to the GraphQL document.\n\n## Write your own document transform\n\nAs an example, let's write a document transform that ensures an `id` field is selected anytime `currentUser` is queried. We will use several helper functions and utilities provided by the [`graphql-js`](https://graphql.org/graphql-js/) library to help us traverse the AST and modify the GraphQL document.\n\nFirst, we must create a new document transform using the `DocumentTransform` class provided by Apollo Client. The `DocumentTransform` constructor takes a callback function that runs for each GraphQL document transformed. The GraphQL `document` is passed as the only argument to this callback function.\n\n```ts\nimport { DocumentTransform } from \"@apollo/client\";\n\nconst documentTransform = new DocumentTransform((document) => {\n  // Modify the document\n});\n```\n\nTo modify the document, we bring in the [`visit`](https://graphql.org/graphql-js/language/#visit) function from `graphql-js` that walks the AST and allows us to modify its nodes. The `visit` function takes a GraphQL AST as the first argument and a visitor as the second argument. The `visit` function returns our modified or unmodified GraphQL document, which we return from our document transform callback function.\n\n```ts {5-9}\nimport { DocumentTransform } from \"@apollo/client\";\nimport { visit } from \"graphql\";\n\nconst documentTransform = new DocumentTransform((document) => {\n  const transformedDocument = visit(document, {\n    // visitor\n  });\n\n  return transformedDocument;\n});\n```\n\nVisitors allow you to visit many types of nodes in the AST, such as directives, fragments, and fields. In our example, we only care about visiting fields since we want to modify the `currentUser` field in our queries. To visit a field, we need to define a `Field` callback function that will be called whenever the traversal encounters one.\n\n```ts {2-4}\nconst transformedDocument = visit(document, {\n  Field(field) {\n    // ...\n  },\n});\n```\n\n<Note>\n\nThis example uses the shorthand visitor syntax, which defines the `enter` function on this node for us. This is equivalent to the following:\n\n```ts\nvisit(document, {\n  Field: {\n    enter(field) {\n      // ...\n    },\n  },\n});\n```\n\n</Note>\n\nOur document transform only needs to modify a field named `currentUser`, so we need to check the field's `name` property to determine if we are working with the `currentUser` field. Let's add a conditional check and return early if we encounter any field not named `currentUser`.\n\n```ts\nconst transformedDocument = visit(document, {\n  Field(field) {\n    if (field.name.value !== \"currentUser\") {\n      return;\n    }\n  },\n});\n```\n\n<Note>\n\nReturning `undefined` from our `Field` visitor tells the `visit` function to leave the node unchanged.\n\n</Note>\n\nNow that we've determined we are working with the `currentUser` field, we need to figure out if our `id` field is already part of the `currentUser` field's selection set. This ensures we don't accidentally select the field twice in our query.\n\nTo do so, let's get the field's `selectionSet` property and loop over its `selections` property to determine if the `id` field is included.\n\nIt's important to note that a `selectionSet` may contain `selections` of both fields and fragments. Our implementation only needs to perform checks against fields, so we also check the selection's `kind` property. If we find a match on a field named `id`, we can stop traversal of the AST.\n\nWe will bring in both the [`Kind`](https://graphql.org/graphql-js/language/#kind) enum from `graphql-js`, which allows us to compare against the selection's `kind` property, and the [`BREAK`](https://graphql.org/graphql-js/language/#break) sentinel, which directs the `visit` function to stop traversal of the AST.\n\n```ts {1,6-15}\nimport { visit, Kind, BREAK } from \"graphql\";\n\nconst transformedDocument = visit(document, {\n  Field(field) {\n    // ...\n    const selections = field.selectionSet?.selections ?? [];\n\n    for (const selection of selections) {\n      if (selection.kind === Kind.FIELD && selection.name.value === \"id\") {\n        return BREAK;\n      }\n    }\n  },\n});\n```\n\n<Note>\n\nTo keep our document transform simple, it does not traverse fragments within the `currentUser` field to determine if those fragments contain an `id` field. A more complete version of this document transform might perform this check.\n\n</Note>\n\nNow that we know the `id` field is missing, we can add it to our `currentUser` field's selection set. To do so, let's create a new field and give it a name of `id`. This is represented as a plain object with the `kind` property set to `Kind.FIELD` and a `name` node that defines the field's name.\n\n```ts\nconst idField = {\n  kind: Kind.FIELD,\n  name: {\n    kind: Kind.NAME,\n    value: \"id\",\n  },\n};\n```\n\nWe now return a modified field from our visitor that adds the `id` field to the `currentUser` field's `selectionSet`. This updates our GraphQL document.\n\n```ts {8-14}\nconst transformedDocument = visit(document, {\n  Field(field) {\n    // ...\n    const idField = {\n      // ...\n    };\n\n    return {\n      ...field,\n      selectionSet: {\n        ...field.selectionSet,\n        selections: [...selections, idField],\n      },\n    };\n  },\n});\n```\n\n<Note>\n\nThis example adds the `id` field to the end of the selection set. Order doesn't matter—you may prefer to put the field elsewhere in the `selections` array.\n\n</Note>\n\nHooray! We now have a working document transform that ensures the `id` field is selected whenever a query containing the `currentUser` field is sent to our server. For completeness, here is the full definition of our custom document transform after completing this example.\n\n```ts\nimport { DocumentTransform } from \"@apollo/client\";\nimport { visit, Kind, BREAK } from \"graphql\";\n\nconst documentTransform = new DocumentTransform((document) => {\n  const transformedDocument = visit(document, {\n    Field(field) {\n      if (field.name.value !== \"currentUser\") {\n        return;\n      }\n\n      const selections = field.selectionSet?.selections ?? [];\n\n      for (const selection of selections) {\n        if (selection.kind === Kind.FIELD && selection.name.value === \"id\") {\n          return BREAK;\n        }\n      }\n\n      const idField = {\n        kind: Kind.FIELD,\n        name: {\n          kind: Kind.NAME,\n          value: \"id\",\n        },\n      };\n\n      return {\n        ...field,\n        selectionSet: {\n          ...field.selectionSet,\n          selections: [...selections, idField],\n        },\n      };\n    },\n  });\n\n  return transformedDocument;\n});\n```\n\n### Check our document transform\n\nWe can check our custom document transform by calling the `transformDocument` function and passing a GraphQL query to it.\n\n```ts\nimport { print } from \"graphql\";\n\nconst query = gql`\n  query TestQuery {\n    currentUser {\n      name\n    }\n  }\n`;\n\nconst documentTransform = new DocumentTransform((document) => {\n  // ...\n});\n\nconst modifiedQuery = documentTransform.transformDocument(query);\n\nconsole.log(print(modifiedQuery));\n// query TestQuery {\n//   currentUser {\n//     name\n//     id\n//   }\n// }\n```\n\n<Note>\n\nWe use the [`print`](https://graphql.org/graphql-js/language/#print) function exported by `graphql-js` to make the query human-readable.\n\n</Note>\n\nSimilarly, we can verify that passing a query that _doesn't_ query for `currentUser` is unaffected by our transform.\n\n```ts\nconst query = gql`\n  query TestQuery {\n    user {\n      name\n    }\n  }\n`;\n\nconst modifiedQuery = documentTransform.transformDocument(query);\n\nconsole.log(print(modifiedQuery));\n// query TestQuery {\n//   user {\n//     name\n//   }\n// }\n```\n\n### Query your server using the document transform\n\nThe `transformDocument` function is useful to spot check your document transform. In practice, however, this will be done for you by Apollo Client.\n\nLet's add our document transform to Apollo Client and send a query to the server. The network request will contain the updated GraphQL query and the data returned from the server will include the `id` field.\n\n```ts\nimport { ApolloClient, DocumentTransform } from \"@apollo/client\";\n\nconst query = gql`\n  query TestQuery {\n    currentUser {\n      name\n    }\n  }\n`;\n\nconst documentTransform = new DocumentTransform((document) => {\n  // ...\n});\n\nconst client = new ApolloClient({\n  // ...\n  documentTransform,\n});\n\nconst result = await client.query({ query });\n\nconsole.log(result.data);\n// {\n//   currentUser: {\n//     id: \"...\",\n//     name: \"...\"\n//   }\n// }\n```\n\n## Composing document transforms\n\nYou may have noticed that the `ApolloClient` constructor only takes a single `documentTransform` option. As you add new capabilities to your document transforms, it may grow unwieldy. The `DocumentTransform` class makes it easy to split and compose multiple transforms into a single one.\n\n### Combining multiple document transforms\n\nYou can combine multiple document transforms together using the `concat()` function. This forms a \"chain\" of document transforms that are run one right after the other.\n\n```ts\nconst documentTransform1 = new DocumentTransform(transform1);\nconst documentTransform2 = new DocumentTransform(transform2);\n\nconst documentTransform = documentTransform1.concat(documentTransform2);\n```\n\nHere `documentTransform1` is combined with `documentTransform2` into a single document transform. Calling the `transformDocument()` function on `documentTransform` runs the GraphQL document through `documentTransform1` and then through `documentTransform2`. Changes made to the GraphQL document in `documentTransform1` are seen by `documentTransform2`.\n\n#### A note about performance\n\nCombining multiple transforms is a powerful feature that makes it easy to split up transform logic, which can boost maintainability. Depending on the implementation of your visitor, this can result in the traversal of the GraphQL document AST multiple times. Most of the time, this shouldn't be an issue. We recommend using the [`BREAK`](https://graphql.org/graphql-js/language/#break) sentinel from `graphql-js` to prevent unnecessary traversal.\n\nSuppose you are sending very large queries that require several traversals and have already optimized your visitors with the `BREAK` sentinel. In that case, it's best to combine the transforms into a single visitor that traverses the AST once.\n\nSee the section on [document caching](#document-caching) to learn how Apollo Client applies optimizations to individual document transforms to mitigate the performance impact when transforming the same GraphQL document multiple times.\n\n### Conditionally running document transforms\n\nAt times, you may need to conditionally run a document transform depending on the GraphQL document. You can conditionally run a transform by calling the `split()` static function on the `DocumentTransform` constructor.\n\n```ts\nimport { isSubscriptionOperation } from \"@apollo/client/utilities\";\n\nconst subscriptionTransform = new DocumentTransform(transform);\n\nconst documentTransform = DocumentTransform.split(\n  (document) => isSubscriptionOperation(document),\n  subscriptionTransform\n);\n```\n\n<Note>\n\nThis example uses the `isSubscriptionOperation` utility function. Similarly, `isQueryOperation` and `isMutationOperation` utility functions are available for use.\n\n</Note>\n\nHere the `subscriptionTransform` is only run for subscription operations. For all other operations, no modifications are made to the GraphQL document. The resulting document transform will first check to see if the `document` is a subscription operation, and if so, proceed to run `subscriptionTransform`. If not, `subscriptionTransform` is bypassed, and the GraphQL document is returned as-is.\n\nThe `split` function also allows you to pass a second document transform to its function, allowing you to replicate an if/else condition.\n\n```ts\nconst subscriptionTransform = new DocumentTransform(transform1);\nconst defaultTransform = new DocumentTransform(transform2);\n\nconst documentTransform = DocumentTransform.split(\n  (document) => isSubscriptionOperation(document),\n  subscriptionTransform,\n  defaultTransform\n);\n```\n\nHere the `subscriptionTransform` is only run for subscription operations. For all other operations, the GraphQL document is run through the `defaultTransform`.\n\n#### Why should I use the `split()` function instead of a conditional check inside of the transform function?\n\nSometimes, using the `split()` function is more efficient than running a conditional check inside the transform function.\n\nFor example, you can run a transform by adding a conditional check inside the transform function itself:\n\n```ts\nconst documentTransform = new DocumentTransform((document) => {\n  if (shouldTransform(document)) {\n    // ...\n    return transformedDocument;\n  }\n\n  return document;\n});\n```\n\nConsider the case where you've combined multiple document transforms using the `concat()` function:\n\n```ts\nconst documentTransform1 = new DocumentTransform(transform1);\nconst documentTransform2 = new DocumentTransform(transform2);\nconst documentTransform3 = new DocumentTransform(transform3);\n\nconst documentTransform = documentTransform1\n  .concat(documentTransform2)\n  .concat(documentTransform3);\n```\n\nThe `split()` function makes skipping the _entire_ chain of document transforms easier.\n\n```ts\nconst documentTransform = DocumentTransform.split(\n  (document) => shouldTransform(document),\n  documentTransform1.concat(documentTransform2).concat(documentTransform3)\n);\n```\n\n## Document caching\n\nYou should strive to make your document transforms deterministic. This means the document transform should always output the same transformed GraphQL document when given the same input GraphQL document. The `DocumentTransform` class optimizes for this case by caching the transformed result for each input GraphQL document. This speeds up repeated calls to the document transform to avoid unnecessary work.\n\nThe `DocumentTransform` class takes this further and records all transformed documents. That means that passing an _already_ transformed document to the document transform will immediately return the GraphQL document.\n\n```ts\nconst transformed1 = documentTransform.transformDocument(document);\nconst transformed2 = documentTransform.transformDocument(transformed1);\n\ntransformed1 === transformed2; // => true\n```\n\n<Note>\n\nIn practice, this optimization is invisible to you. Apollo Client calls the `transformDocument` function on the document transform for you. This optimization primarily benefits the internals of Apollo Client where the transformed document is passed around several areas of the code base.\n\n</Note>\n\n### Non-deterministic document transforms\n\nIn rare circumstances, you may need to rely on a runtime condition from outside the transform function that changes the result of the document transform. Due to the automatic caching of the document transform, this becomes a problem when that runtime condition changes between calls to your document transform.\n\nInstead of completely disabling the document cache in these situations, you can provide a custom cache key that will be used to cache the result of the document transform. This ensures your transform is only called as often as necessary while maintaining the flexibility of the runtime condition.\n\nTo customize the cache key, pass the `getCacheKey` function as an option to the second argument of the `DocumentTransform` constructor. This function receives the `document` that will be passed to your transform function and is expected to return an array.\n\nAs an example, here is a document transform that depends on whether the user is connected to the network.\n\n```ts\nconst documentTransform = new DocumentTransform(\n  (document) => {\n    if (window.navigator.onLine) {\n      // Transform the document when the user is online\n    } else {\n      // Transform the document when the user is offline\n    }\n  },\n  {\n    getCacheKey: (document) => [document, window.navigator.onLine],\n  }\n);\n```\n\n<Caution>\n\n**It is highly recommended you use the `document` as part of your cache key.** In this example, if the `document` is omitted from the cache key, the document transform will only output two transformed documents: one for the `true` condition and one for the `false` condition. Using the `document` in the cache key ensures that each unique document in your application will be transformed accordingly.\n\n</Caution>\n\nYou may conditionally disable the cache for select GraphQL documents by returning `undefined` from the `getCacheKey` function. This will force the document transform to run, regardless of whether the input GraphQL document has been seen.\n\n```ts\nconst documentTransform = new DocumentTransform(\n  (document) => {\n    // ...\n  },\n  {\n    getCacheKey: (document) => {\n      // Always run the transform function when `shouldCache` is `false`\n      if (shouldCache(document)) {\n        return [document];\n      }\n    },\n  }\n);\n```\n\nAs a last resort, you may completely disable document caching to force your transform function to run each time your document transform is used. Set the `cache` option to `false` to disable the cache.\n\n```ts\nconst documentTransform = new DocumentTransform(\n  (document) => {\n    // ...\n  },\n  {\n    cache: false,\n  }\n);\n```\n\n### Caching within combined transforms\n\nWhen you combine multiple document transforms using the `concat()` function, each document transform's cache configuration is honored. This allows you to mix and match transforms that contain varying cache configurations and be confident the resulting GraphQL document is correctly transformed.\n\n```ts\nconst cachedTransform = new DocumentTransform(transform);\n\nconst varyingTransform = new DocumentTransform(transform, {\n  getCacheKey: (document) => [document, window.navigator.onLine],\n});\n\nconst conditionalCachedTransform = new DocumentTransform(transform, {\n  getCacheKey: (document) => {\n    if (shouldCache(document)) {\n      return [document];\n    }\n  },\n});\n\nconst nonCachedTransform = new DocumentTransform(transform, {\n  cache: false,\n});\n\nconst documentTransform = cachedTransform\n  .concat(varyingTransform)\n  .concat(conditionalCachedTransform)\n  .concat(nonCachedTransform);\n```\n\n<Note>\n\nWe recommend adding non-cached document transforms to the end of the `concat()` chain. Document caching relies on referential equality to determine if the GraphQL document has been seen. If a non-cached document transform is defined before a cached transform, the cached transform will store new GraphQL documents created by the non-cached document transform each run. This could result in a memory leak.\n\n</Note>\n\n## TypeScript and GraphQL Code Generator\n\n[GraphQL Code Generator](https://the-guild.dev/graphql/codegen) is a popular tool that generates TypeScript types for your GraphQL documents. It does this by statically analyzing your code to search for GraphQL query strings.\n\nDocument transforms present a challenge for this tool. Because document transforms are used at runtime, there's no way for static analysis to understand the changes applied to GraphQL documents from within document transforms.\n\nThankfully, GraphQL Code Generator provides a [document transform](https://the-guild.dev/graphql/codegen/docs/advanced/document-transform) feature that allows you to connect Apollo Client document transforms to GraphQL Code Generator. Use your document transform inside the `transform` function passed to the GraphQL Code Generator config:\n\n```ts title=\"codegen.ts\" {2,12-18}\nimport type { CodegenConfig } from \"@graphql-codegen/cli\";\nimport { documentTransform } from \"./path/to/your/transform\";\n\nconst config: CodegenConfig = {\n  schema: \"https://localhost:4000/graphql\",\n  documents: [\"src/**/*.tsx\"],\n  generates: {\n    \"./src/gql/\": {\n      preset: \"client\",\n      documentTransforms: [\n        {\n          transform: ({ documents }) => {\n            return documents.map((documentFile) => {\n              documentFile.document = documentTransform.transformDocument(\n                documentFile.document\n              );\n\n              return documentFile;\n            });\n          },\n        },\n      ],\n    },\n  },\n};\n```\n\n## You might not need document transforms\n\nDocument transforms are a powerful feature of Apollo Client. After reading this article, you may be rushing to find as many use cases for this feature as possible. While we encourage you to use this feature where it makes sense in your application, there can be a hidden cost to using it.\n\nConsider what happens when working in a large production application that spans many teams within your organization. Document transforms are typically defined in the code base far from where GraphQL queries are defined. Not all developers may be aware of their existence nor understand their impact on the final GraphQL document.\n\nDocument transforms can make endless modifications to GraphQL documents before they are sent to the network. You may find yourself in a position where the result returned from the GraphQL operation does not match the original GraphQL document. This can get especially confusing when document transforms remove fields or make other destructive changes.\n\nConsider leaning on existing techniques as a first resort, such as linting. For example, if you require that every selection set in your GraphQL document should include an `id` field, you may find it more useful to create a lint rule that complains when you forget to include it. This makes it more obvious exactly what to expect from your GraphQL queries since the lint rule is applied where your GraphQL queries are defined. Adding an `id` via a document transform makes this relationship an implicit one.\n\nWe encourage you to document your own document transforms to create a shared knowledge base to help avoid confusion. This doesn't mean we consider this feature dangerous. After all, Apollo Client has been performing document transformations for nearly its entire existence and they are necessary for its core functionality.\n\n### Can I use this to define my own custom directives?\n\nAt a glance, document transforms seem like a great place to create and define custom directives since they can detect their presence in the GraphQL document. Document transforms, however, don't have access to the cache, nor can they interact with the data returned from your GraphQL server. If your custom directive needs access to these features in Apollo Client, you will have difficulty finding ways to make this work.\n\n**Custom directives are limited to use cases that depend on modifications to the GraphQL document itself.**\n\nHere is an example that uses a DSL-like directive that depends on a feature flagging system to conditionally include fields in queries. The document transform modifies a custom `@feature` directive to a regular `@include` directive and adds a variable definition to the query.\n\n```ts\nconst query = gql`\n  query MyQuery {\n    myCustomField @feature(name: \"custom\", version: 2)\n  }\n`;\n\nconst documentTransform = new DocumentTransform((document) => {\n  // convert `@feature` directives to `@include` directives and update variable definitions\n});\n\ndocumentTransform.transformDocument(query);\n// query MyQuery($feature_custom_v2: Boolean!) {\n//   myCustomField @include(if: $feature_custom_v2)\n// }\n```\n\n## API Reference\n\n### Options\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!~DocumentTransformOptions:interface\"\n  headingLevel={3}\n/>\n"
  },
  {
    "path": "docs/source/data/error-handling.mdx",
    "content": "---\ntitle: Handling operation errors\ndescription: Learn how to manage errors in your application\n---\n\n{/* * @import {MDXProvidedComponents} from '../../../shared/MdxProvidedComponents.js' */}\n\nApollo Client can encounter a variety of errors when executing operations on your GraphQL server. Apollo Client helps you handle these errors according to their type, enabling you to show appropriate information to the user when an error occurs.\n\n## Understanding errors\n\nErrors in Apollo Client fall into two main categories: GraphQL errors and network errors. Each category has specific error classes that provide detailed information about what went wrong. Apollo Client adds any encountered errors to the `error` field returned by hooks like `useQuery`, wrapped in the appropriate error instance.\n\n### GraphQL errors\n\nThese are errors related to the server-side execution of a GraphQL operation. They include:\n\n- **Syntax errors** (e.g., a query was malformed)\n- **Validation errors** (e.g., a query included a schema field that doesn't exist)\n- **Resolver errors** (e.g., an error occurred while attempting to populate a query field)\n\nIf a syntax error or validation error occurs, your server doesn't execute the operation at all because it's invalid. If resolver errors occur, your server can still return [partial data](#partial-data-with-resolver-errors).\n\nWhen a GraphQL error occurs, your server includes it in the `errors` array of its response:\n\n<ExpansionPanel title=\"Example error response\">\n\n```json\n{\n  \"errors\": [\n    {\n      \"message\": \"Cannot query field \\\"nonexistentField\\\" on type \\\"Query\\\".\",\n      \"locations\": [\n        {\n          \"line\": 2,\n          \"column\": 3\n        }\n      ],\n      \"extensions\": {\n        \"code\": \"GRAPHQL_VALIDATION_FAILED\",\n        \"exception\": {\n          \"stacktrace\": [\n            \"GraphQLError: Cannot query field \\\"nonexistentField\\\" on type \\\"Query\\\".\",\n            \"...additional lines...\"\n          ]\n        }\n      }\n    }\n  ],\n  \"data\": null\n}\n```\n\n</ExpansionPanel>\n\nIn Apollo Client, GraphQL errors are represented by the [`CombinedGraphQLErrors`](../api/errors/CombinedGraphQLErrors) error type. This is the most common error type you'll encounter in your application.\n\n<Note>\n  If a GraphQL error prevents your server from executing your operation at all,\n  your server may respond with a non-`2xx` status code. Apollo Client handles\n  this according to the [GraphQL Over HTTP\n  specification](https://graphql.github.io/graphql-over-http/draft/).\n</Note>\n\n#### Partial data with resolver errors\n\nAn operation that produces resolver errors might _also_ return partial data. This means that some (but not all) of the data your operation requested is included in your server's response. Apollo Client _ignores_ partial data by default to avoid caching `null` values due to errors, but you can override this behavior by [setting a GraphQL error policy](#graphql-error-policies).\n\n### Network errors\n\nThese are errors encountered while attempting to communicate with your GraphQL server. The error may be a result of a `4xx` or `5xx` response status code, a failure to communicate with the server (such as when the network is unavailable), a failure to parse the response as valid JSON, or a custom error thrown in an [Apollo Link request handler](../api/link/introduction#the-request-handler).\n\nIn Apollo Client, network errors are represented by these error types:\n\n- [`CombinedProtocolErrors`](../api/errors/CombinedProtocolErrors) - Represents fatal transport-level errors that occur during multipart HTTP subscription execution.\n- [`ServerError`](../api/errors/ServerError) - Occurs when the server responds with a non-200 HTTP status code\n- [`ServerParseError`](../api/errors/ServerParseError) - Occurs when the server response cannot be parsed as valid JSON\n- [`LocalStateError`](../api/errors/LocalStateError) - Represents errors in [local state](../local-state/local-state-management) configuration or execution\n- [`UnconventionalError`](../api/errors/UnconventionalError) - Wraps non-standard errors (e.g., thrown symbols or objects) to ensure consistent error handling\n- Any other errors thrown inside the link chain (e.g. by browser APIs or other libraries) will be passed through as they are, as long as they are an object with at least a `message` property.\n\nWhen a network error occurs, Apollo Client adds it to the `error` field returned by the `useQuery` hook (or whichever operation hook you used) as the error that was returned by the link chain (typically an `Error` instance).\n\nYou can add retry logic and other advanced network error handling to your application with [Apollo Link](#advanced-error-handling-with-apollo-link).\n\n### Identifying error types\n\nEvery Apollo Client error class provides a static `is` method that reliably determines whether an error is of that specific type. This method provides a more robust alternative to `instanceof` because it avoids false positives and negatives, such as errors constructed in another realm (see [`Error.isError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError) for more information).\n\n```ts\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n  LocalStateError,\n  ServerError,\n  ServerParseError,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\n\n// Comprehensive error handling example.\nfunction handleError(error: unknown) {\n  if (CombinedGraphQLErrors.is(error)) {\n    // Handle GraphQL errors\n  } else if (CombinedProtocolErrors.is(error)) {\n    // Handle multipart subscription protocol errors\n  } else if (LocalStateError.is(error)) {\n    // Handle errors thrown by the `LocalState` class\n  } else if (ServerError.is(error)) {\n    // Handle server HTTP errors\n  } else if (ServerParseError.is(error)) {\n    // Handle JSON parse errors\n  } else if (UnconventionalError.is(error)) {\n    // Handle errors thrown by irregular types\n  } else {\n    // Handle other errors\n  }\n}\n```\n\nAll error classes extend the standard JavaScript `Error` class and provide additional properties specific to their error type. See the [individual error class references](#additional-resources) for detailed information about each error class.\n\n## GraphQL error policies\n\nIf a GraphQL operation produces one or more [GraphQL errors](#graphql-errors), your server's response might still include partial data in the `data` field:\n\n```json\n{\n  \"data\": {\n    \"getInt\": 12,\n    \"getString\": null\n  },\n  \"errors\": [\n    {\n      \"message\": \"Failed to get string!\"\n      // ...additional fields...\n    }\n  ]\n}\n```\n\nBy default, Apollo Client throws away partial data and populates the `error` field of the `useQuery` hook (or whichever hook you're using). You can instead _use_ these partial results by defining an **error policy** for your operation.\n\nApollo Client supports the following error policies:\n\n| Policy   | Description                                                                                                                                                                                                                                                                                 |\n| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `none`   | If the response includes errors, they are returned in the `error` field and the response `data` is set to `undefined` even if the server returns `data` in its response. This means network errors and GraphQL errors result in a similar response shape. This is the default error policy. |\n| `ignore` | Errors are ignored (`error` is _not_ populated), and any returned `data` is cached and rendered as if no errors occurred. Note: `data` may also be `undefined` in the event a network error occurs.                                                                                         |\n| `all`    | Both `data` and `error` are populated and any returned `data` is cached, enabling you to render both partial results and error information.                                                                                                                                                 |\n\n### Setting an error policy\n\nSpecify an error policy in the options object you provide your operation hook (such as `useQuery`), like so:\n\n```jsx {9}\nconst MY_QUERY = gql`\n  query WillFail {\n    badField # This field's resolver produces an error\n    goodField # This field is populated successfully\n  }\n`;\n\nfunction ShowingSomeErrors() {\n  const { loading, error, data } = useQuery(MY_QUERY, { errorPolicy: \"all\" });\n\n  if (loading) return <span>loading...</span>;\n\n  return (\n    <div>\n      <h2>Good: {data?.goodField}</h2>\n      <pre>Bad: {error && <span>{error.message}</span>}</pre>\n    </div>\n  );\n}\n```\n\nThis example uses the `all` error policy to render both partial data and error information whenever applicable.\n\n### Error handling across API types\n\nThe way Apollo Client exposes errors and how you handle them depends on both the API type you're using and the configured [error policy](#graphql-error-policies).\n\nApollo Client provides three types of APIs, each with different error handling characteristics:\n\n- **Promise-based APIs** (e.g. `client.query`, `client.mutate`) - Errors either reject the promise or are returned in the result as the `error` field.\n- **Observable-based APIs** (e.g. `client.watchQuery`) - Errors are emitted through the observer `next` callback.\n- **React hooks** (e.g. `useQuery`, `useMutation`) - Errors are provided as part of the hook's return value.\n\n#### Promise-based APIs\n\nPromise-based APIs, like `client.query` and `client.mutate`, return promises that resolve or reject based on your error policy:\n\n##### `errorPolicy: \"none\"`\n\nWith the default `none` error policy, an error causes the promise to reject. Use try-catch or the `.catch` method to prevent unhandled promise rejections.\n\n```ts\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n\ntry {\n  const result = await client.query({\n    query: MY_QUERY,\n    errorPolicy: \"none\", // default\n  });\n  console.log(result.data);\n} catch (error) {\n  if (CombinedGraphQLErrors.is(error)) {\n    console.log(\"GraphQL errors:\", error.errors);\n  }\n  // Network errors and other errors also reject the promise\n}\n```\n\n##### `errorPolicy: \"all\"`\n\nThe `all` error policy allows promises to resolve successfully even when errors occur. Access the error in the `error` field on the returned result.\n\n```ts\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n\n// With errorPolicy: \"all\" - returns both data and errors\nconst result = await client.query({\n  query: MY_QUERY,\n  errorPolicy: \"all\",\n});\n\nif (result.error && CombinedGraphQLErrors.is(result.error)) {\n  console.log(\"GraphQL errors:\", result.error.errors);\n  console.log(\"Partial data:\", result.data); // May contain partial data\n}\n```\n\n##### `errorPolicy: \"ignore\"`\n\nThe `ignore` error policy causes Apollo Client to discard errors entirely, treating operations as if they succeeded. The promise resolves with available data and no error information.\n\n```ts\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n\n// With errorPolicy: \"ignore\" - returns data but ignores errors\nconst result = await client.query({\n  query: MY_QUERY,\n  errorPolicy: \"ignore\",\n});\n\n// result.error will be undefined even if an error occurs\nconsole.log(\"Data (errors ignored):\", result.data);\n```\n\n#### Observable-based APIs\n\nObservable-based APIs like `client.watchQuery` and `client.subscribe` emit values and errors through the observer `next` callback. The error policy determines how the `data` and `error` properties are set:\n\n##### `errorPolicy: \"none\"`\n\nErrors are included as part of the result object emitted to the `next` callback through the `error` field, allowing the observable to continue receiving updates. `data` is always `undefined` when `error` is present.\n\n```ts\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n\nconst observable = client.watchQuery({\n  query: MY_QUERY,\n  errorPolicy: \"none\", // default\n});\n\nobservable.subscribe({\n  next(result) {\n    if (result.error) {\n      console.log(\"Got error:\", result.error.message);\n    } else {\n      console.log(\"Result:\", result.data);\n    }\n  },\n});\n```\n\n##### `errorPolicy: \"all\"`\n\nErrors are included as part of the result object emitted to the `next` callback through the `error` field, allowing the observable to continue running while providing access to both partial data and error information.\n\n```ts\nconst observable = client.watchQuery({\n  query: MY_QUERY,\n  errorPolicy: \"all\",\n});\n\nobservable.subscribe({\n  next(result) {\n    if (result.error) {\n      console.log(\"Got error:\", result.error.message);\n      console.log(\"Partial data\", result.data);\n    } else {\n      console.log(\"Result:\", result.data);\n    }\n  },\n});\n```\n\n##### `errorPolicy: \"ignore\"`\n\nResults are emitted to the `next` callback with GraphQL errors completely discarded. The observable continues running as if no errors occurred, which is useful for non-critical data that can be safely omitted when errors happen.\n\n```ts\nconst observable = client.watchQuery({\n  query: MY_QUERY,\n  errorPolicy: \"ignore\",\n});\n\nobservable.subscribe({\n  next(result) {\n    console.log(\"Result:\", result.data);\n  },\n});\n```\n\n<Note>\n\nThe same error handling behavior applies to subscriptions when using `client.subscribe()`. All errors are delivered through the `next` callback in `result.error`, never through the `error` callback. When an error causes the connection to terminate, the error is emitted through `next`, followed by a `complete` notification. See the [subscriptions documentation](./subscriptions/#handling-errors-in-subscriptions) for more details.\n\n</Note>\n\n#### React hooks\n\nReact hooks like `useQuery` and `useMutation` provide errors through the `error` property in their return value, regardless of error policy. The error policy affects whether `data` is populated alongside the error.\n\n```ts\nimport { useQuery, useMutation } from \"@apollo/client\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n\nfunction MyComponent() {\n  const { data, loading, error } = useQuery(MY_QUERY);\n\n  if (error) {\n    if (CombinedGraphQLErrors.is(error)) {\n      return <div>Query failed: {error.errors[0].message}</div>;\n    }\n\n    return <div>Network error: {error.message}</div>;\n  }\n\n  return <div>{/* render data */}</div>;\n}\n```\n\n<Note>\n  Suspense hooks, such as `useSuspenseQuery`, have different error handling\n  behavior - they might throw errors to React error boundaries based on the\n  configured `errorPolicy`, rather than returning them in the hook result. Learn\n  more about error handling with Suspense hooks in the [Suspense\n  documentation](./suspense#error-handling).\n</Note>\n\n## Advanced error handling with Apollo Link\n\nThe [Apollo Link](../api/link/introduction/) class enables you to configure advanced handling of errors that occur while executing GraphQL operations.\n\nAs a recommended first step, you can add an [`ErrorLink`](../api/link/apollo-link-error/) to your [link chain](../api/link/introduction/#handling-a-response) that receives error details and acts on them.\n\nThe following example provides a link chain to the `ApolloClient` constructor with two links:\n\n- An `ErrorLink` that receives error details through the error handler callback. It logs the details of errors it finds.\n- An `HttpLink` that sends each GraphQL operation to your server (this is the chain's [terminating link](../api/link/introduction/#the-terminating-link).)\n\n<ExpansionPanel title=\"Click to expand example\">\n\n```jsx\nimport {\n  ApolloClient,\n  HttpLink,\n  InMemoryCache,\n  CombinedGraphQLErrors,\n  from,\n} from \"@apollo/client\";\nimport { ErrorLink } from \"@apollo/client/link/error\";\n\nconst errorLink = new ErrorLink(({ error }) => {\n  if (CombinedGraphQLErrors.is(error)) {\n    error.errors.forEach(({ message, locations, path }) =>\n      console.log(\n        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n      )\n    );\n  } else {\n    console.error(\"[Network error]:\", error);\n  }\n});\n\nconst httpLink = new HttpLink({ uri: \"http://localhost:4000/graphql\" });\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: from([errorLink, httpLink]),\n});\n```\n\n</ExpansionPanel>\n\n### Retrying operations\n\nApollo Link helps you retry failed operations that might be resolved by a followup attempt. We recommend different links depending on the type of error that occurred:\n\n- The [`ErrorLink`](../api/link/apollo-link-error) for [GraphQL errors](#on-graphql-errors)\n- The [`RetryLink`](../api/link/apollo-link-retry) for [network errors](#on-network-errors)\n\n#### On GraphQL errors\n\nThe `ErrorLink` can retry a failed operation based on the type of GraphQL error that's returned. For example, when using token-based authentication, you might want to automatically handle re-authentication when the token expires.\n\nTo retry an operation, you `return forward(operation)` in your error handler function. Here's an example:\n\n```js {15}\nnew ErrorLink(({ error, operation, forward }) => {\n  if (CombinedGraphQLErrors.is(error)) {\n    for (let err of error.errors) {\n      switch (err.extensions.code) {\n        // Apollo Server, for example, sets `code` to `\"UNAUTHENTICATED\"`\n        // when an AuthenticationError is thrown in a resolver\n        case \"UNAUTHENTICATED\": {\n          // Modify the operation context with a new token\n          const oldHeaders = operation.getContext().headers;\n          operation.setContext({\n            headers: {\n              ...oldHeaders,\n              authorization: getNewToken(),\n            },\n          });\n          // Retry the request, returning the new observable\n          return forward(operation);\n        }\n      }\n    }\n  }\n\n  // Log the error for any unhandled GraphQL errors or network errors.\n  console.log(`[Error]: ${error.message}`);\n\n  // If nothing is returned from the error handler callback, the error will be\n  // emitted from the link chain as normal.\n});\n```\n\n<Note>\n  If your retried operation _also_ results in errors, those errors are _not_\n  passed to `ErrorLink` to prevent an infinite loop of operations. This means\n  that an `ErrorLink` can retry a particular operation only once.\n</Note>\n\nIf you don't want to retry an operation, your `ErrorLink`'s error handler function should return nothing.\n\nSee the [`ErrorLink` API reference](../api/link/apollo-link-error/) for more details.\n\n#### On network errors\n\nTo retry operations that encounter a network error, we recommend adding a `RetryLink` to your link chain. This link enables you to configure retry logic like exponential backoff and total number of attempts.\n\nSee the [`RetryLink` API reference](../api/link/apollo-link-retry/) for more details.\n\n## Additional resources\n\n- [`ErrorLink` documentation](../api/link/apollo-link-error/)\n- [`RetryLink` documentation](../api/link/apollo-link-retry/)\n- Individual error class references:\n  - [`CombinedGraphQLErrors`](../api/errors/CombinedGraphQLErrors/)\n  - [`CombinedProtocolErrors`](../api/errors/CombinedProtocolErrors/)\n  - [`LinkError`](../api/errors/LinkError/)\n  - [`ServerError`](../api/errors/ServerError/)\n  - [`ServerParseError`](../api/errors/ServerParseError/)\n  - [`LocalStateError`](../api/errors/LocalStateError/)\n  - [`UnconventionalError`](../api/errors/UnconventionalError/)\n"
  },
  {
    "path": "docs/source/data/file-uploads.mdx",
    "content": "---\ntitle: File uploads\ndescription: Enabling file uploads in Apollo Client\n---\n\nApollo Client doesn't support a file upload feature out of the box. If you'd like to enable file upload capabilities, you will have to set Apollo Client up manually with a 3rd party package.\n\nDetailed instructions on how to setup Apollo Client for file upload can be found here: [https://github.com/jaydenseric/apollo-upload-client](https://github.com/jaydenseric/apollo-upload-client).\n\nAn example configuration is show below using the [apollo-upload-client](https://github.com/jaydenseric/apollo-upload-client) package.\n\n```bash\nnpm install apollo-upload-client\n```\n\nBasic setup for the Apollo Client:\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport UploadHttpLink from \"apollo-upload-client/UploadHttpLink.mjs\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new UploadHttpLink(),\n});\n```\n"
  },
  {
    "path": "docs/source/data/fragments.mdx",
    "content": "---\ntitle: Fragments\ndescription: Share fields between operations\n---\n\nA [GraphQL fragment](http://graphql.org/learn/queries/#fragments) is a set of fields you can reuse across multiple queries and mutations. Fragments are especially useful when [colocated with components](#colocating-fragments) to define the component's data requirements.\n\nHere's the declaration of a `NameParts` fragment that can be used with any `Person` object:\n\n```graphql\nfragment NameParts on Person {\n  firstName\n  lastName\n}\n```\n\nEvery fragment includes a subset of the fields that belong to its associated type. In the above example, the `Person` type must declare `firstName` and `lastName` fields for the `NameParts` fragment to be valid.\n\nYou can include the `NameParts` fragment in any number of operations that refer to `Person` objects by using the spread operator (`...`), followed by the fragment name:\n\n```graphql\nquery GetPerson {\n  people(id: \"7\") {\n    ...NameParts\n    avatar(size: LARGE)\n  }\n}\n```\n\nBased on our `NameParts` definition, the above query is equivalent to:\n\n```graphql\nquery GetPerson {\n  people(id: \"7\") {\n    firstName\n    lastName\n    avatar(size: LARGE)\n  }\n}\n```\n\nChanges to the `NameParts` fragment automatically update the fields included in any operations that use it. This reduces the effort required to keep fields consistent across a set of operations.\n\n## Example usage\n\nLet's say we have a blog application that executes several GraphQL operations related to comments (submitting a comment, fetching a post's comments, etc.). Our application likely has a `Comment` component that is responsible for rendering comment data.\n\nWe can define a fragment on the `Comment` type to define the `Comment` component's data requirements, like so:\n\n```js title=\"Comment.js\"\nimport { gql } from \"@apollo/client\";\n\nexport const COMMENT_FRAGMENT = gql`\n  fragment CommentFragment on Comment {\n    id\n    postedBy {\n      username\n      displayName\n    }\n    createdAt\n    content\n  }\n`;\n```\n\n> The example above `export`s the fragment from the `Comment.js` component file. You can declare fragments in any file of your application, though we recommend this approach of [colocating fragments](#colocating-fragments) with your components.\n\nWe can then include the `CommentFragment` fragment in a GraphQL operation like so:\n\n```jsx {2,11,16} title=\"PostDetails.jsx\"\nimport { gql } from \"@apollo/client\";\nimport { COMMENT_FRAGMENT } from \"./Comment\";\n\nconst GET_POST_DETAILS = gql`\n  query GetPostDetails($postId: ID!) {\n    post(postId: $postId) {\n      title\n      body\n      author\n      comments {\n        ...CommentFragment\n      }\n    }\n  }\n\n  ${COMMENT_FRAGMENT}\n`;\n\n// ...PostDetails component definition...\n```\n\n- We first `import` `COMMENT_FRAGMENT` because it's declared in another file.\n- We add our fragment definition to the `GET_POST_DETAILS` `gql` template literal via a placeholder (`${COMMENT_FRAGMENT}`)\n- We include the `CommentFragment` fragment in our query with standard `...` notation.\n\n## Registering named fragments using `createFragmentRegistry`\n\nRegistering fragments with your `InMemoryCache` instance lets you refer to them by name in queries and cache operations (for example, `cache.readFragment`, `cache.readQuery`, and `cache.watch`) without needing to interpolate their declarations.\n\n<Note>\n  We do not recommend using the fragment registry when using the `graphql`\n  function generated by the GraphQL Codegen [client\n  preset](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client).\n  The client preset creates precompiled GraphQL documents that already include\n  fragment definitions.\n</Note>\n\nLet's look at an example in React.\n\n```js title=\"index.js\" {7-12}\nimport { ApolloClient, gql, InMemoryCache } from \"@apollo/client\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\n\nconst client = new ApolloClient({\n  uri: \"http://localhost:4000/graphql\",\n  cache: new InMemoryCache({\n    fragments: createFragmentRegistry(gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `),\n  }),\n});\n```\n\nSince `ItemFragment` was registered with `InMemoryCache`, it can be referenced by name, as seen below, with the fragment spread inside of the `GetItemList` query.\n\n```jsx title=\"ItemList.jsx\" {4,13}\nconst listQuery = gql`\n  query GetItemList {\n    list {\n      ...ItemFragment\n    }\n  }\n`;\nfunction ToDoList() {\n  const { data } = useQuery(listQuery);\n  return (\n    <ol>\n      {data?.list.map((item) => (\n        <Item key={item.id} text={item.text} />\n      ))}\n    </ol>\n  );\n}\n```\n\n### Overriding registered fragments with local versions\n\nQueries can declare their own local versions of named fragments which take precedence over ones registered via `createFragmentRegistry`, even if the local fragment is only indirectly referenced by other registered fragments. Take the following example:\n\n```js title=\"index.js\" {7-17}\nimport { ApolloClient, gql, InMemoryCache } from \"@apollo/client\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\n\nconst client = new ApolloClient({\n  uri: \"http://localhost:4000/graphql\",\n  cache: new InMemoryCache({\n    fragments: createFragmentRegistry(gql`\n      fragment ItemFragment on Item {\n        id\n        text\n        ...ExtraFields\n      }\n\n      fragment ExtraFields on Item {\n        isCompleted\n      }\n    `),\n  }),\n});\n```\n\nThe local version of the `ExtraFields` fragment declared in `ItemList.jsx` takes precedence over the `ExtraFields` fragment originally registered with the `InMemoryCache` instance. Thus, the local definition will _only be used when `GetItemList` query is executed_, because explicit definitions take precedence over registered fragments.\n\n```jsx title=\"ItemList.jsx\" {8-10,17}\nconst GET_ITEM_LIST = gql`\n  query GetItemList {\n    list {\n      ...ItemFragment\n    }\n  }\n\n  fragment ExtraFields on Item {\n    createdBy\n  }\n`;\nfunction ToDoList() {\n  const { data } = useQuery(GET_ITEM_LIST);\n  return (\n    <ol>\n      {data?.list.map((item) => (\n        {/* `createdBy` exists on the returned items, `isCompleted` does not */}\n        <Item key={item.id} text={item.text} author={item.createdBy} />\n      ))}\n    </ol>\n  );\n}\n```\n\n### Lazily registering named fragments\n\nFragments don't need to be defined upfront when the cache is created. Instead, you can register named fragments lazily with the fragment registry. This is especially useful when combined with [colocated fragments](#colocating-fragments) whose fragment definitions are defined in component files. Let's look at an example:\n\n```js title=\"fragmentRegistry.js\"\nexport const { fragmentRegistry } = createFragmentRegistry();\n```\n\n```js title=\"index.js\"\nimport { fragmentRegistry } from \"./fragmentRegistry\";\n\nconst client = new ApolloClient({\n  uri: \"http://localhost:4000/graphql\",\n  cache: new InMemoryCache({\n    fragments: fragmentRegistry,\n  }),\n});\n```\n\nWe create a separate file that creates and exports our fragment registry. This lets us access our shared fragment registry across our application. We use this shared fragment registry with our `InMemoryCache` instance.\n\n```jsx title=\"TodoItem.jsx\"\nimport { gql } from \"@apollo/client\";\nimport { fragmentRegistry } from \"./fragmentRegistry\";\n\n// Define the fragment outside the component to ensure it gets registered when this module is loaded.\nconst ITEM_FRAGMENT = gql`\n  fragment ItemFragment on Item {\n    # ...\n  }\n`;\n\nfragmentRegistry.register(ITEM_FRAGMENT);\n\nfunction TodoItem() {\n  // ...\n}\n```\n\nWe then import our shared fragment registry into our component file and register our fragment definition.\n\n<Caution>\n  You need to register fragment definitions with the fragment registry before\n  executing operations that use them. This can be problematic when lazy loading\n  component files because the application might not register the fragment\n  definition with the registry until after the query begins executing. Move the\n  fragment definition to a shared file that isn't lazy-loaded.\n</Caution>\n\n## Colocating fragments\n\nThe tree-like structure of a GraphQL response resembles the hierarchy of a frontend's rendered components. Because of this similarity, you can use fragments to split query logic _between_ components, so each component requests exactly the fields it needs. This helps make your component logic more succinct by combining multiple UI components into a single data fetch.\n\nConsider the following view hierarchy for an app:\n\n```mermaid\ngraph TD\n  subgraph FeedPageGroup[\" \"]\n    direction TB\n    FeedPage[&lt;FeedPage /&gt;]\n    FeedQuery[\"query FeedQuery { feed { ...FeedEntryFragment } }\"]\n    FeedPage ~~~ FeedQuery\n  end\n\n  subgraph FeedEntryGroup[\" \"]\n    direction TB\n    FeedEntry[\"&lt;FeedEntry /&gt;\"]\n    FeedEntryFragment[\"fragment FeedEntry { ...EntryInfoFragment ...VoteButtonsFragment }\"]\n    FeedEntry ~~~ FeedEntryFragment\n  end\n\n  subgraph EntryInfoGroup[\" \"]\n    direction TB\n    EntryInfo[\"&lt;EntryInfo /&gt;\"]\n    EntryInfoFragment[\"fragment EntryInfo { ... }\"]\n    EntryInfo ~~~ EntryInfoFragment\n  end\n\n  subgraph VoteButtonsGroup[\" \"]\n    direction TB\n    VoteButtons[\"&lt;VoteButtons /&gt;\"]\n    VoteButtonsFragment[\"fragment VoteButtons { ... }\"]\n    VoteButtons ~~~ VoteButtonsFragment\n  end\n\n  FeedPageGroup --> FeedEntryGroup\n  FeedEntryGroup --> EntryInfoGroup\n  FeedEntryGroup --> VoteButtonsGroup\n```\n\nIn this app, the `FeedPage` component executes a query to fetch a list of `FeedEntry` objects. The `EntryInfo` and `VoteButtons` subcomponents need specific fields from the enclosing `FeedEntry` object.\n\n### Creating colocated fragments\n\nA colocated fragment is just like any other fragment, except it's defined in the same file as a particular component that uses the fragment's fields. For example, the `VoteButtons` child component of `FeedPage` might use the fields `score` and `vote { choice }` from the `FeedEntry` object:\n\n```js title=\"VoteButtons.jsx\"\nexport const VOTE_BUTTONS_FRAGMENT = gql`\n  fragment VoteButtonsFragment on FeedEntry {\n    score\n    vote {\n      choice\n    }\n  }\n`;\n```\n\nAfter you define a fragment in a child component, the _parent_ component can refer to it in its _own_ colocated fragments, like so:\n\n```js title=\"FeedEntry.jsx\"\nexport const FEED_ENTRY_FRAGMENT = gql`\n  fragment FeedEntryFragment on FeedEntry {\n    commentCount\n    repository {\n      full_name\n      html_url\n      owner {\n        avatar_url\n      }\n    }\n    ...VoteButtonsFragment\n    ...EntryInfoFragment\n  }\n  ${VOTE_BUTTONS_FRAGMENT}\n  ${ENTRY_INFO_FRAGMENT}\n`;\n```\n\n<Tip>\n  To prevent coupling with deeply nested components, we recommend parent\n  components only add fragments defined by their directly-rendered children. In\n  this example, our `FeedPage` should not use the `EntryInfoFragment` or\n  `VoteButtonsFragment` directly. Instead the `FeedPage` uses the\n  `FeedEntryFragment` fragment colocated with the `FeedEntry` component to\n  combine the `VoteButtonsFragment` and `EntryInfoFragment` fragments into its\n  own fragment.\n</Tip>\n\nThere's nothing special about the naming of `VoteButtonsFragment` or `EntryInfoFragment`. We recommend prefixing the fragment name with the component name to make it easily identifiable when combined with other fragments. However any naming convention works as long as you can retrieve a component's fragments given the component.\n\n### Importing fragments when using Webpack\n\nWhen loading `.graphql` files with [graphql-tag/loader](https://github.com/apollographql/graphql-tag/blob/main/loader.js), include fragments using `import` statements. For example:\n\n```graphql\n#import \"./someFragment.graphql\"\n```\n\nThis makes the contents of `someFragment.graphql` available to the current file. See the [Webpack Fragments](../integrations/webpack/#fragments) section for additional details.\n\n## Using fragments with unions and interfaces\n\nYou can define fragments on [unions and interfaces](https://graphql.com/learn/interfaces-and-unions/).\n\nHere's an example of a query that includes a shared field and two in-line fragments:\n\n```graphql\nquery AllCharacters {\n  allCharacters {\n    name\n\n    ... on Jedi {\n      side\n    }\n\n    ... on Droid {\n      model\n    }\n  }\n}\n```\n\nThe `AllCharacters` query above returns a list of `Character` objects. The `Character` type is an interface type that both the `Jedi` and `Droid` types implement. Each item in the list includes a `side` field if it's an object of type `Jedi`, and it includes a `model` field if it's of type `Droid`. Both `Jedi` and `Droid` objects include a `name` field.\n\n**However**, for this query to work, the client needs to understand the polymorphic relationship between the `Character` interface and the types that implement it. To inform the client about these relationships, you must pass a `possibleTypes` option when you initialize your `InMemoryCache` instance.\n\n### Defining `possibleTypes` manually\n\nUse the `possibleTypes` option to the `InMemoryCache` constructor to specify supertype-subtype relationships in your schema. This object maps the name of an interface or union type (the supertype) to the types that implement or belong to it (the subtypes).\n\nHere's an example `possibleTypes` declaration:\n\n```js\nconst cache = new InMemoryCache({\n  possibleTypes: {\n    Character: [\"Jedi\", \"Droid\"],\n    Test: [\"PassingTest\", \"FailingTest\", \"SkippedTest\"],\n    Snake: [\"Viper\", \"Python\"],\n  },\n});\n```\n\nThis example lists three interfaces (`Character`, `Test`, and `Snake`) and the object types that implement them.\n\nIf your schema includes only a few unions and interfaces, you can probably specify your `possibleTypes` manually without issue. However, as your schema grows in size and complexity, you should instead [generate `possibleTypes` automatically from your schema](#generating-possibletypes-automatically).\n\n### Generating `possibleTypes` automatically\n\nThe following script translates a GraphQL introspection query into a `possibleTypes` configuration object:\n\n```js\nconst fetch = require(\"cross-fetch\");\nconst fs = require(\"fs\");\n\nfetch(`${YOUR_API_HOST}/graphql`, {\n  method: \"POST\",\n  headers: { \"Content-Type\": \"application/json\" },\n  body: JSON.stringify({\n    variables: {},\n    query: `\n      {\n        __schema {\n          types {\n            kind\n            name\n            possibleTypes {\n              name\n            }\n          }\n        }\n      }\n    `,\n  }),\n})\n  .then((result) => result.json())\n  .then((result) => {\n    const possibleTypes = {};\n\n    result.data.__schema.types.forEach((supertype) => {\n      if (supertype.possibleTypes) {\n        possibleTypes[supertype.name] = supertype.possibleTypes.map(\n          (subtype) => subtype.name\n        );\n      }\n    });\n\n    fs.writeFile(\n      \"./possibleTypes.json\",\n      JSON.stringify(possibleTypes),\n      (err) => {\n        if (err) {\n          console.error(\"Error writing possibleTypes.json\", err);\n        } else {\n          console.log(\"Fragment types successfully extracted!\");\n        }\n      }\n    );\n  });\n```\n\nYou can then `import` the generated `possibleTypes` JSON module into the file where you create your `InMemoryCache`:\n\n```ts\nimport possibleTypes from \"./path/to/possibleTypes.json\";\n\nconst cache = new InMemoryCache({\n  possibleTypes,\n});\n```\n\n### Generating `possibleTypes` with GraphQL Codegen\n\n[GraphQL Codegen](https://the-guild.dev/graphql/codegen) has the ability to generate `possibleTypes` for you using the [`fragment-matcher` plugin](https://the-guild.dev/graphql/codegen/plugins/other/fragment-matcher). Follow the guide in the [fragment matcher plugin docs](https://the-guild.dev/graphql/codegen/plugins/other/fragment-matcher) to configure GraphQL Codegen to write a JSON file that contains `possibleTypes`.\n\nYou can then `import` the generated `possibleTypes` JSON module into the file where you create your `InMemoryCache`:\n\n```ts\nimport possibleTypes from \"./path/to/possibleTypes.json\";\n\nconst cache = new InMemoryCache({\n  possibleTypes,\n});\n```\n\n## `useFragment`\n\nThe `useFragment` hook represents a lightweight live binding into the Apollo Client Cache. It enables Apollo Client to broadcast specific fragment results to individual components. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. `useFragment` never triggers network requests of its own.\n\n**The `useQuery` hook remains the primary hook responsible for querying and populating data in the cache** ([see the API reference](../api/react/hooks#usequery)). As a result, the component reading the fragment data via `useFragment` is still subscribed to all changes in the query data, but receives updates only when that fragment's specific data change.\n\n### Example\n\nGiven the following fragment definition:\n\n```js\nconst ITEM_FRAGMENT = gql`\n  fragment ItemFragment on Item {\n    text\n  }\n`;\n```\n\nWe can first use the `useQuery` hook to retrieve a list of items with `id`s as well as any fields selected on the named `ItemFragment` fragment by including `ItemFragment` in the `list` field in the `GetItemList` query.\n\n```jsx\nconst listQuery = gql`\n  query GetItemList {\n    list {\n      id\n      ...ItemFragment\n    }\n  }\n\n  ${ITEM_FRAGMENT}\n`;\n\nfunction List() {\n  const { loading, data } = useQuery(listQuery);\n\n  return (\n    <ol>\n      {data?.list.map((item) => (\n        <Item key={item.id} item={item} />\n      ))}\n    </ol>\n  );\n}\n```\n\n<Tip>\n  Instead of interpolating fragments within each query document, you can use\n  Apollo Client's `createFragmentRegistry` method to pre-register named\n  fragments with `InMemoryCache`. This allows Apollo Client to include the\n  definitions for registered fragments in the document sent over the network\n  before the request is sent. For more information, see [Registering named\n  fragments using\n  `createFragmentRegistry`](#registering-named-fragments-using-createfragmentregistry).\n</Tip>\n\nWe can then use `useFragment` from within the `<Item>` component to create a live binding for each item by providing the `fragment` document, `fragmentName` and object reference via `from`.\n\n<MultiCodeBlock>\n\n```tsx\nfunction Item(props: { id: number }) {\n  const { complete, data } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: {\n      __typename: \"Item\",\n      id: props.id,\n    },\n  });\n\n  return <li>{complete ? data.text : \"incomplete\"}</li>;\n}\n```\n\n```jsx\nfunction Item(props) {\n  const { complete, data } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: {\n      __typename: \"Item\",\n      id: props.id,\n    },\n  });\n\n  return <li>{complete ? data.text : \"incomplete\"}</li>;\n}\n```\n\n</MultiCodeBlock>\n\n<Tip>\n  You may omit the `fragmentName` option when your fragment definition only\n  includes a single fragment.\n</Tip>\n\nYou may instead prefer to pass the whole `item` as a prop to the `Item` component. This makes the `from` option more concise.\n\n<MultiCodeBlock>\n\n```tsx\nfunction Item(props: { item: { __typename: \"Item\"; id: number } }) {\n  const { complete, data } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: props.item,\n  });\n\n  return <li>{complete ? data.text : \"incomplete\"}</li>;\n}\n```\n\n```jsx\nfunction Item(props) {\n  const { complete, data } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: props.item,\n  });\n\n  return <li>{complete ? data.text : \"incomplete\"}</li>;\n}\n```\n\n</MultiCodeBlock>\n\n<Note>\n  `useFragment` can be used in combination with the `@nonreactive` directive in\n  cases where list items should react to individual cache updates without\n  rerendering the entire list. For more information, see the [`@nonreactive`\n  docs](/react/data/directives#nonreactive).\n</Note>\n\nSee the [API reference](../api/react/useFragment) for more details on the supported options.\n\n<MinVersion version=\"4.1\">\n\n### Working with arrays\n\n</MinVersion>\n\nSometimes your component might use a fragment to select fields for an array of items that are received from props. You can use the `useFragment` hook to watch for changes on each array item by providing the array to the `from` option.\n\nWhen you provide an array to the `from` option, the `data` property returned from `useFragment` is an array where each item corresponds to an item with the same index in the `from` option. If all of the items returned in `data` are complete, the `complete` property is set to `true` and the `dataState` property is set to `\"complete\"`. If at least one item in the array is incomplete, the `complete` property is set to `false` and the `dataState` property is set to `\"partial\"`.\n\n<MultiCodeBlock>\n\n```tsx\nfunction Items(props: { items: Array<{ __typename: \"Item\"; id: number }> }) {\n  const { data, complete } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: props.items,\n  });\n\n  if (!complete) {\n    return null;\n  }\n\n  return (\n    <ul>\n      {data.map((item) => (\n        <li key={item.id}>{item.text}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\n```js\nfunction Items(props) {\n  const { data, complete } = useFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: props.items,\n  });\n\n  if (!complete) {\n    return null;\n  }\n\n  return (\n    <ul>\n      {data.map((item) => (\n        <li key={item.id}>{item.text}</li>\n      ))}\n    </ul>\n  );\n}\n```\n\n</MultiCodeBlock>\n\n<Note>\n\nIf the array provided to the `from` option is an empty array, the returned `data` is an empty array with the `complete` property set to `true` and `dataState` property set to `\"complete\"`.\n\n</Note>\n\n#### Handling `null` values\n\nDepending on the GraphQL schema, it's possible the array might contain `null` values. When `useFragment` is provided an array that contains `null` values to the `from` property, `useFragment` returns those items as `null` in the `data` property and treats these items as complete. This means if all non-`null` items in the array are also complete, the whole result is complete.\n\n```ts\nconst { data, dataState, complete } = useFragment({\n  fragment: ITEM_FRAGMENT,\n  fragmentName: \"ItemFragment\",\n  from: [{ __typename: \"Item\", id: 1 }, { __typename: \"Item\", id: 2 }, null],\n});\n\nconsole.log({ data, dataState, complete });\n// {\n//   data: [\n//     { __typename: \"Item\", id: 1, text: \"...\" },\n//     { __typename: \"Item\", id: 2, text: \"...\" },\n//     null\n//   ],\n//   dataState: \"complete\",\n//   complete: true\n// }\n```\n\n<Note>\n\nIf the `from` array contains `null` values for every item, the result returned from `useFragment` contains all `null` values, the `complete` property is set to `true`, and the `dataState` property is set to `\"complete\"`.\n\n```ts\nconst { data, dataState, complete } = useFragment({\n  fragment: ITEM_FRAGMENT,\n  fragmentName: \"ItemFragment\",\n  from: [null, null, null],\n});\n\nconsole.log({ data, dataState, complete });\n// {\n//   data: [null, null, null],\n//   dataState: \"complete\",\n//   complete: true\n// }\n```\n\n</Note>\n\n## `useSuspenseFragment`\n\nFor those that have integrated with React [Suspense](https://react.dev/reference/react/Suspense), `useSuspenseFragment` is available as a drop-in replacement for `useFragment`. `useSuspenseFragment` works identically to `useFragment` but will suspend while `data` is incomplete.\n\nLet's update the example from the previous section to use `useSuspenseFragment`. First, we'll update our `Item` component and replace `useFragment` with `useSuspenseFragment`. Since we are using Suspense, we no longer have to check for a `complete` property to determine if the result is complete because the component will suspend otherwise.\n\n```tsx\nimport { useSuspenseFragment } from \"@apollo/client\";\n\nfunction Item(props) {\n  const { data } = useSuspenseFragment({\n    fragment: ITEM_FRAGMENT,\n    fragmentName: \"ItemFragment\",\n    from: props.item,\n  });\n\n  return <li>{data.text}</li>;\n}\n```\n\nNext, we'll will wrap our `Item` components in a `Suspense` boundary to show a loading indicator if the data from `ItemFragment` is not complete. Since we're using Suspense, we'll replace `useQuery` with `useSuspenseQuery` as well:\n\n```tsx\nfunction List() {\n  const { data } = useSuspenseQuery(listQuery);\n\n  return (\n    <ol>\n      {data.list.map((item) => (\n        <Suspense fallback={<Spinner />}>\n          <Item key={item.id} item={item} />\n        </Suspense>\n      ))}\n    </ol>\n  );\n}\n```\n\nAnd that's it! Suspense made our `Item` component a bit more succinct since we no longer need to check the `complete` property to determine if we can safely use `data`.\n\n<Note>\n  In most cases, `useSuspenseFragment` will not suspend when rendered as a child\n  of a query component. In this example `useSuspenseQuery` loads the full query\n  data before each `Item` is rendered so the `data` inside each fragment is\n  already complete. The `Suspense` boundary in this example ensures that a\n  loading spinner is shown if field data is removed for any given item in the\n  list in the cache, such as when a manual cache update is performed.\n</Note>\n\n### Using `useSuspenseFragment` with `@defer`\n\n`useSuspenseFragment` is helpful when combined with the [`@defer`](./defer) directive to show a loading state while the fragment data is streamed to the query. Let's update our `GetItemList` query to defer loading the `ItemFragment`'s fields.\n\n```graphql\nquery GetItemList {\n  list {\n    id\n    ...ItemFragment @defer\n  }\n}\n```\n\nOur list will now render as soon as our list returns but before the data for `ItemFragment` is loaded.\n\n<Caution>\n  You **must** ensure that any key fields used to identify the object passed to\n  the `from` option are not deferred. If they are, you risk suspending the\n  `useSuspenseFragment` hook forever. If you need to defer loading key fields,\n  conditionally render the component until the object passed to the `from`\n  option is identifiable by the cache.\n</Caution>\n\n## Data masking\n\nBy default, Apollo Client returns all data for all fields defined in a GraphQL operation. As your app grows, components that query your GraphQL data can become tightly coupled to their component subtrees. [Colocated fragments](#colocating-fragments) reduce the degree of coupling by moving components' data requirements into fragments. However, colocating fragments doesn't eliminate the issue.\n\nLet's take a look at an example. The following `Posts.jsx` defines a `Posts` component that fetches and displays a list of posts, optionally filtering out unpublished ones, using a GraphQL query that includes a fragment for post details.\n\n```jsx title=\"Posts.jsx\"\nimport { POST_DETAILS_FRAGMENT } from \"./PostDetails\";\n\nconst GET_POSTS = gql`\n  query GetPosts {\n    posts {\n      id\n      ...PostDetailsFragment\n    }\n  }\n\n  ${POST_DETAILS_FRAGMENT}\n`;\n\nexport default function Posts({ includeUnpublishedPosts }) {\n  const { data, loading } = useQuery(GET_POSTS);\n  const posts = data?.posts ?? [];\n\n  if (loading) {\n    return <Spinner />;\n  }\n\n  const allPosts =\n    includeUnpublishedPosts ? posts : posts.filter((post) => post.publishedAt);\n\n  if (allPosts.length === 0) {\n    return <div>No posts to display</div>;\n  }\n\n  return (\n    <div>\n      {allPosts.map((post) => (\n        <PostDetails key={post.id} post={post} />\n      ))}\n    </div>\n  );\n}\n```\n\nThe following `PostDetails.jsx` defines the fragment for post details and the associated UI elements.\n\n```jsx title=\"PostDetails.jsx\"\nexport const POST_DETAILS_FRAGMENT = gql`\n  fragment PostDetailsFragment on Post {\n    title\n    shortDescription\n    publishedAt\n  }\n`;\n\nexport default function PostDetails({ post }) {\n  return (\n    <section>\n      <h1>{post.title}</h1>\n      <p>{post.shortDescription}</p>\n      <p>\n        {post.publishedAt ?\n          `Published: ${formatDate(post.publishedAt)}`\n        : \"Private\"}\n      </p>\n    </section>\n  );\n}\n```\n\nThe `Posts` component is responsible for fetching and rendering a list of posts. We loop over each post and render a `PostDetails` component to display details about the post. `PostDetails` uses a colocated fragment to define its own data requirements necessary to render post details, which is included in the `GetPosts` query.\n\nWhen the `includeUnpublishedPosts` prop is false, the `Posts` component filters out unpublished posts from the list of all posts by checking the `publishedAt` property on the post object.\n\nThis strategy might work well for a while, but consider what happens when we start modifying the `PostDetails` component.\n\nSuppose we've decided we no longer want to show the publish date on the list of posts and prefer to display it on individual posts. Let's modify `PostDetails` accordingly.\n\n```jsx title=\"PostDetails.jsx\"\nexport const POST_DETAILS_FRAGMENT = gql`\n  fragment PostDetailsFragment on Post {\n    title\n    shortDescription\n  }\n`;\n\nexport default function PostDetails({ post }) {\n  return (\n    <section>\n      <h1>{post.title}</h1>\n      <p>{post.shortDescription}</p>\n    </section>\n  );\n}\n```\n\nWe've removed the check for `publishedAt` since we no longer show the publish date. We've also removed the `publishedAt` field from the `PostDetailsFragment` fragment since we no longer use this field in the `PostDetails` component.\n\nUh oh, we just broke our app—the `Posts` component no longer shows any posts! The `Posts` component still depends on `publishedAt`, but because the field was declared in the `PostDetailsFragment` fragment, changes to `PostDetails` resulted in a subtle breakage of the `Posts` component.\n\nThis coupling is an example of an **implicit dependency** between components. As the application grows in complexity, these implicit dependencies can become more and more difficult to track. Imagine if `PostDetails` was a component nested much deeper in the component tree or if multiple queries used it.\n\n**Data masking** helps eliminate these types of implicit dependencies by returning only the data declared by the component's query or fragment. As a result, data masking creates more loosely coupled components that are more resistant to change.\n\n### Enabling data masking\n\nTo enable data masking in Apollo Client, set the `dataMasking` flag in the `ApolloClient` constructor to `true`.\n\n```jsx {2}\nconst client = new ApolloClient({\n  dataMasking: true,\n  // ...\n});\n```\n\nWhen `dataMasking` is enabled, fields defined in fragments are hidden from components. This prevents the component from accessing data it didn't ask for.\n\nEnabling data masking applies it to all operation types and all request-based APIs, such as `useQuery`, `client.query`, `client.mutate`, etc. Cache APIs, such as `cache.readQuery` and `cache.readFragment` are never masked.\n\n<Tip>\n  We recommend enabling the `dataMasking` flag immediately when creating new\n  applications. See the section on [adoption in an existing\n  application](#adoption-in-an-existing-application) to learn how to enable data\n  masking in existing applications.\n</Tip>\n\nLet's revisit the example from the previous section.\n\n```jsx title=\"Posts.jsx\"\nconst GET_POSTS = gql`\n  query GetPosts {\n    posts {\n      id\n      ...PostDetailsFragment\n    }\n  }\n\n  ${POST_DETAILS_FRAGMENT}\n`;\n\nexport default function Posts({ includeUnpublishedPosts }) {\n  const { data, loading } = useQuery(GET_POSTS);\n\n  // ...\n}\n```\n\nOur `GetPosts` query asks for the `posts` field along with an `id` for each post. All other fields are defined in `PostDetailsFragment`. If we were to inspect `data`, we'd see that the only accessible fields are those defined in the query but not the fragment.\n\n```json\n{\n  \"posts\": [\n    {\n      \"__typename\": \"Post\",\n      \"id\": \"1\"\n    },\n    {\n      \"__typename\": \"Post\",\n      \"id\": \"2\"\n    }\n  ]\n}\n```\n\nWe can access more data by adding fields to the query. Let's fix the previous section's example by adding the `publishedAt` field to the `GetPosts` query so that the `Posts` component can use it.\n\n```jsx {5} title=\"Posts.jsx\"\nconst GET_POSTS = gql`\n  query GetPosts {\n    posts {\n      id\n      publishedAt\n      ...PostDetailsFragment\n    }\n  }\n\n  ${POST_DETAILS_FRAGMENT}\n`;\n```\n\nNow if we inspect `data`, we'll see that `publishedAt` is available to the `Posts` component.\n\n```json\n{\n  \"posts\": [\n    {\n      \"__typename\": \"Post\",\n      \"publishedAt\": \"2024-01-01\",\n      \"id\": \"1\"\n    },\n    {\n      \"__typename\": \"Post\",\n      \"publishedAt\": null,\n      \"id\": \"2\"\n    }\n  ]\n}\n```\n\n### Reading fragment data\n\nNow that the `GetPosts` query is masked, we've introduced a problem for the `PostDetails` component. The `post` prop no longer contains the fields from the `PostDetailsFragment` fragment, preventing us from rendering that data.\n\nWe read the fragment data with the [`useFragment` hook](#usefragment).\n\n```jsx title=\"PostDetails.jsx\"\nfunction PostDetails({ post }) {\n  const { data, complete } = useFragment({\n    fragment: POST_DETAILS_FRAGMENT,\n    from: post,\n  });\n\n  // ...\n}\n```\n\nNow we use the `data` property returned from `useFragment` to render the details from the `post`.\n\n```jsx {17-18} title=\"PostDetails.jsx\"\nfunction PostDetails({ post }) {\n  const { data, complete } = useFragment({\n    fragment: POST_DETAILS_FRAGMENT,\n    from: post,\n  });\n\n  // It's a good idea to check the `complete` flag to ensure all data was\n  // successfully queried from the cache. This can indicate a potential\n  // issue with the cache configuration or parent object when `complete`\n  // is `false`.\n  if (!complete) {\n    return null;\n  }\n\n  return (\n    <section>\n      <h1>{data.title}</h1>\n      <p>{data.shortDescription}</p>\n    </section>\n  );\n}\n```\n\n<Note>\n  It's important that the parent query or fragment selects any\n  [`keyFields`](../caching/cache-configuration#customizing-cache-ids) for\n  objects passed to the `from` option. Without this, we'd have no way to\n  identify the object with the cache and the `data` returned from `useFragment`\n  would be incomplete. If you forget to include key fields in the parent object,\n  you will see a warning in the console.\n</Note>\n\n### Nesting fragments in other fragments\n\nAs your UI grows in complexity, it is common to split up components into smaller, more reusable chunks. As a result you may end up with more deeply nested components that have their own data requirements. Much like queries, we can nest fragments within other fragments.\n\n<Note>\n  You can nest fragments with or without data masking (for an example, see the\n  section on [colocating fragments](#colocating-fragments).) This section\n  describes how you can use masking in components with `useFragment`.\n</Note>\n\nLet's add a `Comment` component that will be used by `PostDetails` to render the `topComment` for the post.\n\n```jsx title=\"Comment.jsx\"\nexport const COMMENT_FRAGMENT = gql`\n  fragment CommentFragment on Comment {\n    postedBy {\n      displayName\n    }\n    createdAt\n    content\n  }\n`;\n\nexport default function Comment({ comment }) {\n  const { data, complete } = useFragment({\n    fragment: COMMENT_FRAGMENT,\n    from: comment,\n  });\n\n  // ... render comment details\n}\n```\n\nMuch like `PostDetails`, we used `useFragment` to read the `CommentFragment` fragment data since it is masked and not available on the `comment` prop.\n\nWe can now use the `Comment` component and `CommentFragment` fragment in the `PostDetails` component to render the `topComment`.\n\n```jsx {1,7-10,13,29} title=\"PostDetails.jsx\"\nimport { COMMENT_FRAGMENT } from \"./Comment\";\n\nexport const POST_DETAILS_FRAGMENT = gql`\n  fragment PostDetailsFragment on Post {\n    title\n    shortDescription\n    topComment {\n      id\n      ...CommentFragment\n    }\n  }\n\n  ${COMMENT_FRAGMENT}\n`;\n\nexport default function PostDetails({ post }) {\n  const { data, complete } = useFragment({\n    fragment: POST_DETAILS_FRAGMENT,\n    from: post,\n    fragmentName: \"PostDetailsFragment\",\n  });\n\n  // complete check omitted for brevity\n\n  return (\n    <section>\n      <h1>{data.title}</h1>\n      <p>{data.shortDescription}</p>\n      <Comment comment={data.topComment} />\n    </section>\n  );\n}\n```\n\n<Note>\n  We added the `fragmentName` option to `useFragment` in `PostDetails`. This is\n  needed because we've added another fragment definition (`CommentFragment`) to\n  the `POST_DETAILS_FRAGMENT` document. `fragmentName` tells `useFragment` that\n  it should use the `PostDetailsFragment` fragment definition when querying for\n  data in the cache.\n</Note>\n\nIf we inspect the `data` property returned by `useFragment` in `PostDetails`, we'll see that only the fields included by the `PostDetailsFragment` fragment are a part of the object.\n\n```json\n{\n  \"__typename\": \"Post\",\n  \"title\": \"The Amazing Adventures of Data Masking\",\n  \"shortDescription\": \"In this article we dive into...\",\n  \"topComment\": {\n    \"__typename\": \"Comment\",\n    \"id\": \"1\"\n  }\n}\n```\n\nThroughout this example, You'll notice that we never touched the `GetPosts` query as a result of this change. Because we included `CommentFragment` with `PostDetailsFragment`, it was added to the query automatically. Colocating fragments like this is a powerful pattern that, when combined with data masking, provide very self-isolated components.\n\n<Tip>\n  We recommend that parent components only add fragments defined by their\n  directly-rendered children to prevent coupling with more deeply nested\n  components. In this example, the `GetPosts` query did not include the\n  `CommentFragment` fragment directly but rather it relied on the `PostDetails`\n  component to include it with the `PostDetailsFragment` fragment.\n</Tip>\n\n### Working with other operation types\n\nData masking is not limited to queries but also extends to other operation types. As a rule of thumb, any value that is used to _read_ data from a request-based API is masked. APIs that perform cache updates are never masked.\n\nRefer to the code samples below to see what data is masked in mutations and subscriptions.\n\n#### Mutations\n\nFor more information about mutations, visit the [mutations page](./mutations).\n\n```jsx\n// data is masked\nconst [mutate, { data }] = useMutation(MUTATION, {\n  onCompleted: (data) => {\n    // data is masked\n  },\n  update: (cache, { data }) => {\n    // data is unmasked\n  },\n  refetchQueries: ({ data }) => {\n    // data is unmasked\n  },\n  updateQueries: {\n    ExampleQuery: (previous, { mutationResult }) => {\n      // mutationResult is unmasked\n    },\n  },\n});\n\nasync function runMutation() {\n  const { data } = await mutate();\n\n  // data is masked\n}\n```\n\n```jsx\n// data is masked\nconst { data } = await client.mutate({\n  update: (cache, { data }) => {\n    // data is unmasked\n  },\n  refetchQueries: ({ data }) => {\n    // data is unmasked\n  },\n  updateQueries: {\n    ExampleQuery: (previous, { mutationResult }) => {\n      // mutationResult is unmasked\n    },\n  },\n});\n```\n\n#### Subscriptions\n\nFor more information about subscriptions, visit the [subscriptions page](./subscriptions).\n\n```jsx\nfunction MyComponent() {\n  // data is masked\n  const { data } = useSubscription(SUBSCRIPTION, {\n    onData: ({ data }) => {\n      // data is unmasked\n    },\n  });\n}\n```\n\n```jsx\nconst observable = client.subscribe({ query: SUBSCRIPTION });\n\nobservable.subscribe({\n  next: ({ data }) => {\n    // data is masked\n  },\n});\n```\n\n```jsx\nconst { subscribeToMore } = useQuery(QUERY);\n\nfunction startSubscription() {\n  subscribeToMore({\n    document: SUBSCRIPTION,\n    updateQuery: (queryData, { subscriptionData }) => {\n      // queryData is unmasked\n      // subscriptionData is unmasked\n    },\n  });\n}\n```\n\n### Selectively unmasking fragment data\n\nAs you work with data masking more extensively, you may need access to the full operation result. Apollo Client includes an `@unmask` directive you can apply to fragment spreads. Adding `@unmask` to a fragment spread makes the fragment data available.\n\n<Note>\n  The `@unmask` directive is an escape hatch. First try adding additional needed\n  fields to the operation before relying on `@unmask`. As an exception, you\n  might use `@unmask` frequently to [adopt data masking in an existing\n  application](#incremental-adoption-in-an-existing-application).\n</Note>\n\n```graphql\nquery GetPosts {\n  posts {\n    id\n    ...PostFragment @unmask\n  }\n}\n```\n\nOnly fragments marked with `@unmask` will unmask the results. Fragments not marked with `@unmask` will remain masked.\n\n```graphql\nquery GetPosts {\n  posts {\n    id\n    ...PostFragment @unmask\n    # This data remains masked\n    ...PostDetailsFragment\n  }\n}\n```\n\n### Using with TypeScript\n\nApollo Client provides robust TypeScript support for data masking. We've integrated data masking with [GraphQL Codegen](https://the-guild.dev/graphql/codegen) and the type format generated by its [Fragment Masking](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#fragment-masking) feature.\n\nMasked types don't include fields from fragment spreads. As an example, let's use the following query.\n\n```graphql\nquery GetCurrentUser {\n  currentUser {\n    id\n    ...ProfileFragment\n  }\n}\n\nfragment ProfileFragment on User {\n  name\n  age\n}\n```\n\nThe type definition for the query might resemble the following:\n\n```ts\ntype GetCurrentUserQuery = {\n  currentUser: {\n    __typename: \"User\";\n    id: string;\n    name: string;\n    age: number;\n  } | null;\n};\n```\n\n<Note>\n  This example does not use GraphQL Codegen's true type output since it includes\n  additional types that map scalar values differently.\n</Note>\n\nThis version of the `GetCurrentUserQuery` type is _unmasked_ since it includes fields from the `ProfileFragment`.\n\nOn the other hand, _masked_ types don't include fields defined in fragments.\n\n```ts\ntype GetCurrentUserQuery = {\n  currentUser: {\n    __typename: \"User\";\n    id: string;\n    // omitted: additional internal metadata\n  } | null;\n};\n```\n\n#### Generating masked types\n\nYou generate masked types with either the [`typescript-operations` plugin](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-operations) or the [client preset](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client). The following sections show how to configure GraphQL Codegen to output masked types.\n\n##### With the `typescript-operations` plugin\n\n<Note>\n  Support for the `@unmask` directive was introduced with\n  `@graphql-codegen/typescript-operations`\n  [v4.4.0](https://github.com/dotansimha/graphql-code-generator/releases/tag/release-1732308151614)\n</Note>\n\nAdd the following configuration to your GraphQL Codegen config.\n\n```ts title=\"codegen.ts\"\nconst config: CodegenConfig = {\n  // ...\n  generates: {\n    \"path/to/types.ts\": {\n      plugins: [\"typescript-operations\"],\n      config: {\n        // ...\n        inlineFragmentTypes: \"mask\",\n        customDirectives: {\n          apolloUnmask: true,\n        },\n      },\n    },\n  },\n};\n```\n\n##### With the `client-preset`\n\n<Note>\n  Support for the `@unmask` directive was introduced with\n  `@graphql-codegen/client-preset`\n  [v4.6.0](https://github.com/dotansimha/graphql-code-generator/releases/tag/release-1738065376043)\n</Note>\n\nYou can't use the `client-preset` [Fragment Masking](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#fragment-masking) and Apollo Client's data masking features simultaneously.\nThe incompatibility between the features is in runtime behavior only.\nApollo's data masking uses the same type output generated by CodeGen's Fragment Masking feature.\n\nTo migrate from CodeGen's fragment masking feature to Apollo Client's data masking, follow these steps:\n\n1. Replace the [generated `useFragment` function](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#the-usefragment-helper), with Apollo Client's [`useFragment`](#usefragment) hook.\n2. [Turn off Fragment Masking](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#how-to-disable-fragment-masking) in your GraphQL Codegen config, along with these additions:\n\n   ```ts title=\"codegen.ts\"\n   const config: CodegenConfig = {\n     // ...\n     generates: {\n       \"path/to/gql/\": {\n         preset: \"client\",\n         presetConfig: {\n           // ...\n           // disables the incompatible GraphQL Codegen fragment masking feature\n           fragmentMasking: false,\n         },\n         config: {\n           customDirectives: {\n             apolloUnmask: true\n           }\n           inlineFragmentTypes: \"mask\",\n         }\n       }\n     }\n   }\n   ```\n\n3. [Enable data masking](#enabling-data-masking) in Apollo Client.\n\n#### Setting data masking types\n\nBy default, Apollo Client makes no modification to the operation types provided to its APIs, regardless of whether the type definitions are masked or unmasked. This provides a simpler upgrade path when you're ready to [incrementally adopt](#incremental-adoption-in-an-existing-application) data masking.\n\nTo use GraphQL Codegen's masking format with your operation types, you need to tell Apollo Client to use the associated GraphQL Codegen masking types. You do this by defining a [type override](../development-testing/static-typing#overriding-type-implementations-of-built-in-types) that uses the GraphQL Codegen masking format.\n\nCreate a TypeScript file that will be used to modify the `TypeOverrides` interface. Extend `TypeOverrides` with the `GraphQLCodegenDataMasking.TypeOverrides` interface.\n\n```ts title=\"apollo-client.d.ts\"\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\nimport type { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\ndeclare module \"@apollo/client\" {\n  interface TypeOverrides extends GraphQLCodegenDataMasking.TypeOverrides {}\n}\n```\n\n<Note>\n\nThis example uses `apollo-client.d.ts` as the file name to make it easily identifiable. You can give this file any name.\n\n</Note>\n\n#### Using with fragments\n\nWhen using [colocated fragments](#colocating-fragments) with your components, it's best to ensure the object passed to your component is done in a type-safe way. This means:\n\n- TypeScript prevents you from accessing fields on the object that may be defined with the parent.\n- The object passed to the component is guaranteed to contain a fragment reference of the same type.\n\nApollo Client provides the `FragmentType` helper type for this purpose. As an example, let's use the `PostDetails` fragment from previous sections.\n\n```tsx {1,12} title=\"PostDetails.tsx\"\nimport type { FragmentType } from \"@apollo/client\";\nimport type { PostDetailsFragment } from \"./path/to/gql/types.ts\";\n\nexport const POST_DETAILS_FRAGMENT: TypedDocumentNode<PostDetailsFragment> = gql`\n  fragment PostDetailsFragment on Post {\n    title\n    shortDescription\n  }\n`;\n\ninterface PostDetailsProps {\n  post: FragmentType<PostDetailsFragment>;\n}\n\nfunction PostDetails({ post }: PostDetailsProps) {\n  const { data } = useFragment({\n    fragment: POST_DETAILS_FRAGMENT,\n    from: post,\n  });\n\n  // ...\n}\n```\n\nUsing properties from the `post` prop instead of the `data` from `useFragment` results in a TypeScript error similar to the following:\n\n```ts\nfunction PostDetails({ post }: PostDetailsProps) {\n  // ...\n\n  post.title;\n  // ❌ Property 'title' does not exist on type '{ \" $fragmentRefs\"?: { PostDetailsFragment: PostDetailsFragment; } | undefined; }'\n}\n```\n\n`FragmentType` also prevents parent components from accidentally omitting fragment spreads for child components, regardless of whether the field selection satisfies the fragment's data requirements.\n\n```tsx title=\"Posts.tsx\"\nconst GET_POSTS = gql`\n  query GetPosts {\n    posts {\n      id\n      title\n      shortDescription\n    }\n  }\n`;\n\nexport default function Posts() {\n  // ...\n\n  return (\n    <div>\n      {allPosts.map((post) => (\n        <PostDetails key={post.id} post={post} />\n        // ❌ Type '{ __typename: \"Post\"; id: string; title: string; shortDescription: string; }' has no properties in common with type '{ \" $fragmentRefs\"?: { PostDetailsFragment: PostDetailsFragment; } | undefined; }'.\n      ))}\n    </div>\n  );\n}\n```\n\nIn this example, the `GetPosts` query selects enough fields to satisfy the `PostDetails` data requirements, but TypeScript warns us because the `PostDetailsFragment` was not included in the `GetPosts` query.\n\n#### Unwrapping masked types\n\nOn rare occasions, you may need access to the unmasked type of a particular operation. Apollo Client provides the `Unmasked` helper type that unwraps masked types and removes meta information on the type.\n\n<Note>\n  This is the same helper type the client uses when unwrapping types while the\n  TypeScript data masking `mode` is set to `unmask` or for APIs that use the\n  full result.\n</Note>\n\n```ts\nimport { Unmasked } from \"@apollo/client\";\n\ntype QueryType = {\n  currentUser: {\n    __typename: \"User\";\n    id: string;\n    name: string;\n  } & { \" $fragmentRefs\"?: { UserFragment: UserFragment } };\n};\n\ntype UserFragment = {\n  __typename: \"User\";\n  age: number | null;\n} & { \" $fragmentName\"?: \"UserFragment\" };\n\ntype UnmaskedQueryType = Unmasked<QueryType>;\n//   ^? type UnmaskedQueryType = {\n//        currentUser: {\n//          __typename: \"User\";\n//          id: string;\n//          name: string;\n//          age: number | null;\n//        }\n//      }\n```\n\n<Note>\n  This example does not use GraphQL Codegen's true type output since it includes\n  additional types that map scalar values differently.\n</Note>\n\n### Incremental adoption in an existing application\n\nExisting applications can take advantage of the data masking features through an incremental adoption approach. This section will walk through the steps needed to adopt data masking in a larger codebase.\n\n#### 1. Apply the `@unmask` directive to all fragment spreads\n\nBefore enabling the `dataMasking` flag in the client, it is wise to ensure that your components continue to receive full results to avoid breakages. You can use the `@unmask` directive to handle this.\n\n<Tip>\n  We recommend using `@unmask` in migrate mode to enable development-only\n  warnings when accessing would-be masked fields. Learn more about migrate mode\n  in the [`@unmask` docs](./directives#unmask).\n</Tip>\n\n```graphql\nquery GetPost($id) {\n  post(id: $id) {\n    id\n    ...PostDetails @unmask(mode: \"migrate\")\n  }\n}\n```\n\nThis is rather tedious to do by hand for large applications. Apollo Client provides a codemod that applies `@unmask` to your GraphQL documents for you. To use the codemod:\n\n1. Clone the [`apollo-client` repository](https://github.com/apollographql/apollo-client)\n\n   ```sh\n   git clone https://github.com/apollographql/apollo-client.git\n   ```\n\n2. Install dependencies in `apollo-client`\n\n   ```sh\n   npm install\n   ```\n\n3. Run the codemod via [`jscodeshift`](https://github.com/facebook/jscodeshift) against your codebase.\n\n   ```sh\n   npx jscodeshift -t ../path/to/apollo-client/scripts/codemods/data-masking/unmask.ts --extensions ts --parser ts ./src/**/*.ts --mode migrate\n   ```\n\n   <Note>\n     This command uses the `--mode migrate` option to enable migrate mode on all\n     `@unmask` directives. Omit this option if you prefer to use `@unmask`\n     without the development-only warnings.\n   </Note>\n\nThe codemod supports `.js`, `.jsx`, `.ts`, `.tsx`, `.graphql`, and `.gql` files. For `.graphql` and `.gql` files, explicitly specify the file extensions.\n\n```sh\nnpx jscodeshift -t ../path/to/apollo-client/scripts/codemods/data-masking/unmask.ts --extensions graphql ./src/**/*.graphql --mode migrate\n```\n\nBy default, the codemod searches for `gql` and `graphql` tags in source files. If your application uses a custom name, use the `--tag` option to specify the name. Use `--tag` more than once to specify multiple names.\n\n```sh\nnpx jscodeshift ... --tag myGql\n```\n\n<Caution>\n  Comments in GraphQL documents may be lost after running the codemod because\n  the `graphql` library's `print` function used by the codemod doesn't retain\n  comments. Always check the output from changes made by the codemod before\n  committing them.\n</Caution>\n\n#### 2. Enable `dataMasking`\n\nWith fragments unmasked, it is safe to enable data masking in your application. Add the `dataMasking` option to your client instance to enable it.\n\n```js {2}\nnew ApolloClient({\n  dataMasking: true,\n  // ...\n});\n```\n\nEnabling data masking early in the adoption process makes it much easier to adopt for newly added queries and fragments since masking becomes the default behavior. Ideally data masking is enabled in the same pull request as the `@unmask` changes to ensure that no new queries and fragments are introduced to the codebase without the `@unmask` modifications applied.\n\n#### 3. Generate masked types\n\nIf you are using TypeScript in your application, you will need to update your GraphQL Codegen configuration to [generate masked types](#generating-masked-types).\n\nLearn more about using TypeScript with data masking in the [\"Using with TypeScript\"](#using-with-typescript) section.\n\n#### 4. Use `useFragment`\n\nWith data masking enabled, you can now begin the process of refactoring your components to use data masking. It is easiest to look for areas of the codebase where you see field access warnings in the console on would-be masked fields (requires migrate mode).\n\nRefactor components that consume query data from props to use `useFragment` instead. Use the `data` property returned from `useFragment` to get the field value instead of the prop.\n\n```jsx\nfunction PostDetails({ post }) {\n  const { data, complete } = useFragment({\n    fragment: POST_DETAILS_FRAGMENT,\n    from: post,\n  });\n\n  // ... use `data` instead of `post`\n}\n```\n\nAs you make these changes, you will begin to see warnings disappear. Repeat this process until you no longer see warnings in the console.\n\nWhen you no longer see field access warnings, it is safe to remove the `@unmask` directive from your query.\n\n```diff\nquery GetPosts {\n  posts {\n    id\n-   ...PostDetails @unmask(mode: \"migrate\")\n+   ...PostDetails\n  }\n}\n```\n\nRepeat this process until all `@unmask` directives have been removed from your codebase.\n\nCongratulations 🎉! Your application is now using data masking everywhere 😎.\n\n### Defining your own masking types using higher-kinded types\n\n<Note>\n\nIf you are using the [data masking types generated from GraphQL Codegen](#setting-data-masking-types), you can safely skip this section.\n\n</Note>\n\nApollo Client provides an [integration](#setting-data-masking-types) with GraphQL Codegen's [fragment masking](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#fragment-masking) output and orients its masking utility types around this format. If you aren't using GraphQL Codegen to generate your types, or your types are generated in a different format, the type implementations built into Apollo Client might be incompatible which results in inaccurate types.\n\nYou can use a technique called _higher-kinded types_ (HKT) to provide your own type implementations for Apollo Client's masking types. You can think of higher-kinded types as a way to define types and interfaces with generics that can be filled in by Apollo Client internals at a later time. Passing around un-evaluated types is otherwise not possible in TypeScript.\n\n#### Example\n\nLet's add our own type overrides for the `MaybeMasked` and `Unmasked` utility types.\n\nThe `MaybeMasked` type is used throughout Apollo Client to return the masked or unmasked type definition for a given type, assuming they have data masking types enabled and are maskable. Otherwise, it returns the unmasked type that is passed in.\n\nThe `Unmasked` type unwraps a masked type to its full result type and is used throughout Apollo Client where the full data type is needed for a given API (e.g. `client.writeQuery`).\n\nFor this example, we'll assume the data masking types are enabled and the operation types are generated using two variations:\n\n1. Data masked types are generated with a `__masked` virtual property. Its value is the operation type with any masked fields removed from the type.\n\n   ```ts\n   type MaskedQuery = {\n     // The masked variant of the operation type is provided under the\n     // `__masked` virtual property\n     __masked?: { user: { __typename: \"User\"; id: number } };\n\n     // The full result type includes all other fields in the type\n     user: { __typename: \"User\"; id: number; name: string };\n   };\n   ```\n\n2. Unmasked types are generated as their full result type with no `__masked` virtual property applied to them.\n\n   ```ts\n   type UnmaskedQuery = {\n     user: { __typename: \"User\"; id: number; name: string };\n   };\n   ```\n\n<Note>\n\nThis is a hypothetical format that doesn't exist in Apollo Client or any known code generation tool. This format is used specifically for this example to illustrate how to provide type overrides to Apollo Client.\n\n</Note>\n\nFirst, let's define our custom implementation of the `MaybeMasked` type. The implementation works by checking if the `__masking` virtual property exists on the type. If so, it returns the value on the `__masked` property as the type, otherwise it returns the input type unmodified.\n\n```ts title=\"masked-types.ts\"\ntype MaybeMasked<TData> =\n  TData extends { __masked?: infer TMaskedData } ? TMaskedData : TData;\n```\n\nNow let's provide an implementation for the `Unmasked` type that works in contrast to `MaybeMasked` by returning the unwrapped full result type. The implementation works by removing the `__masked` virtual property on the input type. This can be accomplished using the built-in [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) type.\n\n```ts {4} title=\"masked-types.ts\"\ntype MaybeMasked<TData> =\n  TData extends { __masked?: infer TMaskedData } ? TMaskedData : TData;\n\ntype Unmasked<TData> = Omit<TData, \"__masked\">;\n```\n\nNow that our custom type implementations are in place, we need to define higher-kinded types for each of these custom types. This provides the bridge needed by Apollo Client to use our custom type implementations. This is done by extending the `HKT` interface exported by `@apollo/client/utilities`.\n\nLet's provide HKTs for our `MaybeMasked` and `Unmasked` types. We'll put these in the same file as our type implementations.\n\n```ts {1,8-11,13-16} title=\"masked-types.ts\"\nimport { HKT } from \"@apollo/client/utilities\";\n\ntype MaybeMasked<TData> =\n  TData extends { __masked?: infer TMaskedData } ? TMaskedData : TData;\n\ntype Unmasked<TData> = Omit<TData, \"__masked\">;\n\nexport interface MaybeMaskedHKT extends HKT {\n  arg1: unknown; // TData\n  return: MaybeMasked<this[\"arg1\"]>;\n}\n\nexport interface UnmaskedHKT extends HKT {\n  arg1: unknown; // TData\n  return: Unmasked<this[\"arg1\"]>;\n}\n```\n\nWith our HKT types in place, we now need to tell Apollo Client about them.\n\nApollo Client uses [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to provide a hook point for overridable types. The `TypeOverrides` interface exported by the `@apollo/client` package is used for this purpose. Each property in the `TypeOverrides` interface corresponds to an overridable type in Apollo Client.\n\nLet's add type overrides for our custom type implementations. Create a TypeScript file and define a `TypeOverrides` interface for the `@apollo/client` module.\n\n```ts title=apollo-client.d.ts\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides {\n    // Type overrides will go here\n  }\n}\n```\n\nNow we'll import our HKT types and add them as keys in the `TypeOverrides` interface.\n\n```ts {4,8-9} title=apollo-client.d.ts\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\nimport { MaybeMaskedHKT, UnmaskedHKT } from \"./masked-types.ts\";\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides {\n    MaybeMasked: MaybeMaskedHKT;\n    Unmasked: UnmaskedHKT;\n  }\n}\n```\n\nAnd that's it! Now when Apollo Client uses the `MaybeMasked` or `Unmasked` types in its APIs, our custom implementation will be used instead 🎉.\n\n#### Available type overrides\n\nThe following masking utility types are available to override:\n\n- `FragmentType<TFragmentData>` - Type used with [fragments](#using-with-fragments) to ensure parent objects contain the fragment spread from the type.\n- `MaybeMasked<TData>` - Conditionally returns `TData` as either its masked type or unmasked type\n- `Unmasked<TData>` - Unwraps `TData` into the full result type\n\nFor more information about other overridable types in Apollo Client, see the [TypeScript guide](../development-testing/static-typing).\n"
  },
  {
    "path": "docs/source/data/mutations.mdx",
    "content": "---\ntitle: Mutations in Apollo Client\ndescription: Modify data with the useMutation hook\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\nNow that we've [learned how to query data](queries/) from our backend with Apollo Client, the natural next step is to learn how to _modify_ back-end data with **mutations**.\n\nThis article demonstrates how to send updates to your GraphQL server with the `useMutation` hook. You'll also learn how to update the Apollo Client cache after executing a mutation, and how to track loading and error states.\n\n> To follow along with the examples below, open up our [starter project](https://codesandbox.io/s/mutations-example-app-start-gm7i5) and [sample GraphQL server](https://codesandbox.io/s/mutations-example-app-server-sxewr) on CodeSandbox. You can view the completed version of the app [here](https://codesandbox.io/s/mutations-example-app-final-tjoje).\n\n## Prerequisites\n\n<Note>\n\nIf your application is built using TypeScript, we recommend reading the [TypeScript guide](../development-testing/static-typing) to learn how to use TypeScript with Apollo Client.\n\n</Note>\n\nThis article assumes you're familiar with building basic GraphQL mutations. If you need a refresher, we recommend that you\n[read this guide](https://graphql.org/learn/mutations/).\n\nThis article also assumes that you've already set up Apollo Client and have wrapped your React app in an `ApolloProvider` component. For help with those steps, [get started](../get-started/).\n\n## Executing a mutation\n\nThe `useMutation` [React hook](https://react.dev/reference/react) is the primary API for executing mutations in an Apollo application.\n\nTo execute a mutation, you first call `useMutation` within a React component and pass it the mutation you want to execute, like so:\n\n```jsx {15} title=\"my-component.jsx\"\nimport { gql } from \"@apollo/client\";\nimport { useMutation } from \"@apollo/client/react\";\n\n// Define mutation\nconst INCREMENT_COUNTER = gql`\n  # Increments a back-end counter and gets its resulting value\n  mutation IncrementCounter {\n    incrementCounter {\n      currentValue\n    }\n  }\n`;\n\nfunction MyComponent() {\n  const [mutate, { data, loading, error }] = useMutation(INCREMENT_COUNTER);\n}\n```\n\nAs shown above, you use the `gql` function to parse the mutation string into a GraphQL document that you then pass to `useMutation`.\n\nWhen your component renders, `useMutation` returns a tuple that includes:\n\n- A **mutate function** that you can call at any time to execute the mutation\n  - Unlike `useQuery`, `useMutation` _doesn't_ execute its operation automatically on render. Instead, call the `mutate` function to execute the mutation.\n- An object with fields that represent the current status of the mutation's execution (`data`, `loading`, etc.)\n  - This object is similar to the object returned by the `useQuery` hook. For details, see [Result](#result).\n\n### Example\n\nLet's say we're creating a to-do list application and we want the user to be able to add items to their list. First, we'll create a corresponding GraphQL mutation named `ADD_TODO`. Remember to wrap GraphQL strings in the `gql` function to parse them into query documents:\n\n```jsx title=\"add-todo.jsx\"\nimport { gql } from \"@apollo/client\";\nimport { useMutation } from \"@apollo/client/react\";\n\nconst ADD_TODO = gql`\n  mutation AddTodo($type: String!) {\n    addTodo(type: $type) {\n      id\n      type\n    }\n  }\n`;\n```\n\nNext, we'll create a component named `AddTodo` that represents the submission form for the to-do list. Inside it, we'll pass our\n`ADD_TODO` mutation to the `useMutation` hook:\n\n```jsx {3,13} title=\"add-todo.jsx\"\nfunction AddTodo() {\n  const [value, setValue] = useState(\"\");\n  const [addTodo, { data, loading, error }] = useMutation(ADD_TODO);\n\n  if (loading) return \"Submitting...\";\n  if (error) return `Submission error! ${error.message}`;\n\n  return (\n    <div>\n      <form\n        onSubmit={(e) => {\n          e.preventDefault();\n          addTodo({ variables: { type: value } });\n          setValue(\"\");\n        }}\n      >\n        <input\n          value={value}\n          onChange={(e) => {\n            setValue(e.target.value);\n          }}\n        />\n        <button type=\"submit\">Add Todo</button>\n      </form>\n    </div>\n  );\n}\n```\n\nIn this example, our form's `onSubmit` handler calls the **mutate function** (named `addTodo`) that's returned by the `useMutation` hook. This tells Apollo Client to execute the mutation by sending it to our GraphQL server.\n\n<Note>\n\n`useMutation` behaves differently than [`useQuery`](./queries/), which executes its operation as soon as its component renders. This is because mutations are more commonly executed in response to a user action (such as submitting a form in this case).\n\n</Note>\n\n### Providing options\n\nThe `useMutation` hook accepts an `options` object as its second parameter. Here's an example that provides some default values for GraphQL `variables`:\n\n```js\nconst [addTodo, { data, loading, error }] = useMutation(ADD_TODO, {\n  variables: {\n    type: \"placeholder\",\n    someOtherVariable: 1234,\n  },\n});\n```\n\nYou can _also_ provide options directly to your mutate function, as demonstrated in this snippet from [the example above](#example):\n\n```js\naddTodo({\n  variables: {\n    type: value,\n  },\n});\n```\n\nHere, we use the `variables` option to provide the values of any GraphQL variables that our mutation requires (specifically, the `type` of the created to-do item).\n\nLearn more about the available options in [Options](#options).\n\n#### Option precedence\n\nIf you provide the same option to both `useMutation` _and_ your mutate function, the mutate function's value takes precedence. In the specific case of the `variables` option, the two objects are merged _shallowly_, which means any variables provided only to `useMutation` are preserved in the resulting object. This helps you set default values for variables.\n\nIn [the example snippets above](#providing-options), `value` would override `\"placeholder\"` as the value of the `type` variable. The value of `someOtherVariable` (`1234`) would be preserved.\n\n<Note>\n\nWhen using TypeScript, you might see an error related to a missing variable when a required variable is not provided to either the hook or the `mutate` function. Providing required variables to the hook makes them optional in the `mutate` function. If a required variable is not provided to the hook, it is required in the `mutate` function.\n\n</Note>\n\n<MinVersion version=\"4.1\">\n\n##### Merging `context` from the hook and `mutate` function\n\n</MinVersion>\n\nDue to option precedence, `context` provided to the `mutate` function overrides `context` provided to the `useMutation` hook. In some cases, you might want to merge the `context` value provided to the hook with a value available at the time you execute the `mutate` function.\n\nYou accomplish this by using a callback function for the `context` option provided to the `mutate` function. The callback function is called with the `context` value provided to the hook, allowing you to merge them together.\n\n```ts\naddTodo({\n  context: (hookContext) => ({\n    ...hookContext,\n    myCustomValue: true,\n  }),\n});\n```\n\n<Note>\n\nYour callback function is not required to merge the context values together. The `context` value sent to the link chain is the value returned from the function which makes it possible to change the `context` value in any way you wish, such as omitting a property from the hook context.\n\n</Note>\n\n### Tracking mutation status\n\nIn addition to a mutate function, the `useMutation` hook returns an object that represents the current state of the mutation's execution. The fields of this object include booleans that indicate whether the mutate function has been `called` and whether the mutation's result is currently `loading`.\n\n[The example above](#example) destructures the `loading` and `error` fields from this object to render the `AddTodo` component differently depending on the mutation's current status:\n\n```jsx\nif (loading) return \"Submitting...\";\nif (error) return `Submission error! ${error.message}`;\n```\n\n<Note>\n\nThe `useMutation` hook supports `onCompleted` and `onError` options if you need to perform side effects when the mutation completes. See the [API reference](../api/react/useMutation) for more details.\n\n</Note>\n\nLearn more about result object in [Result](#result).\n\n### Resetting mutation status\n\nThe mutation result object returned by `useMutation` includes a [`reset` function](#mutationresult-interface-reset):\n\n```js\nconst [login, { reset }] = useMutation(LOGIN_MUTATION);\n```\n\nCall `reset` to reset the mutation's result to its initial state (i.e., _before_ the mutate function was called). You can use this to enable users to dismiss mutation result data or errors in the UI.\n\n<Note>\n\nCalling `reset` does _not_ remove any cached data returned by the mutation's execution. It only affects the state associated with the `useMutation` hook, causing the corresponding component to rerender.\n\n</Note>\n\n```js {2,14}\nfunction LoginPage() {\n  const [login, { error, reset }] = useMutation(LOGIN_MUTATION);\n\n  return (\n    <>\n      <form>\n        <input class=\"login\" />\n        <input class=\"password\" />\n        <button onclick={login}>Login</button>\n      </form>\n      {error && (\n        <LoginFailedMessageWindow\n          message={error.message}\n          onDismiss={() => reset()}\n        />\n      )}\n    </>\n  );\n}\n```\n\n## Updating local data\n\nWhen you execute a mutation, you modify back-end data. Usually, you then want to update your _locally cached_ data to reflect the back-end modification. For example, if you execute a mutation to add an item to your to-do list, you also want that item to appear in your cached copy of the list.\n\n### Supported methods\n\nThe most straightforward way to update your local data is to [refetch any queries](#refetching-queries) that might be affected by the mutation. However, this method requires additional network requests.\n\nIf your mutation returns all of the objects and fields that it modified, you can [update your cache directly](#updating-the-cache-directly) _without_ making any followup network requests.\n\nWe recommend reading the guide on [Caching in Apollo Client](../caching/overview) to understand how data is stored in the cache and how to perform updates to that data.\n\n## Refetching queries\n\nYou can refetch queries after a mutation by providing a `refetchQueries` option to `useMutation`:\n\n```js {3-6}\n// Refetches two queries after mutation completes\nconst [addTodo, { data, loading, error }] = useMutation(ADD_TODO, {\n  refetchQueries: [\n    GET_POST, // DocumentNode object parsed with gql\n    \"GetComments\", // Query name\n  ],\n});\n```\n\nYou can provide one of the following values to `refetchQueries`:\n\n- A `refetchQueries` array to refetch specific queries\n- The shorthand `\"active\"` string to refetch all active queries\n- The shorthand `\"all\"` string to refetch all active and inactive queries\n\nIt is most common to provide a `refetchQueries` array when performing mutations. Learn more about active and inactive queries in the [Refetching](./refetching) guide.\n\nWhen providing `refetchQueries` as an array, each element in the `refetchQueries` array is one of the following:\n\n- A `DocumentNode` object parsed with the `gql` function\n- The name of a query as a string (e.g., `GetComments`)\n  - To refer to queries by name, make sure each of your app's queries have a _unique_ name.\n\n<Note>\n\nEach query in the `refetchQueries` array must be an _active_ query. If an inactive or unknown query is provided, a warning will be logged to the console.\n\n</Note>\n\nEach included query is executed with its most recently provided set of variables.\n\nYou can provide the `refetchQueries` option either to `useMutation` or to the mutate function. For details, see [Option precedence](#option-precedence).\n\n## Updating the cache directly\n\n### Include modified objects in mutation responses\n\nAs a best practice, a mutation response should include any object(s) the mutation modified. This enables Apollo Client to normalize those objects and cache them according to their `__typename` and [`keyFields`](../caching/cache-configuration/#customizing-cache-ids).\n\n[In the example above](#example), our `ADD_TODO` mutation might return a `Todo` object with the following structure:\n\n```json\n{\n  \"__typename\": \"Todo\",\n  \"id\": \"5\",\n  \"type\": \"groceries\"\n}\n```\n\n<Note>\n\nApollo Client automatically adds the `__typename` field to every object in your queries and mutations by default.\n\n</Note>\n\nUpon receiving this response object, Apollo Client caches it with key `Todo:5`. If a cached object _already_ exists with this key, Apollo Client overwrites any existing fields that are also included in the mutation response (other existing fields are preserved).\n\nReturning modified objects like this is a helpful first step to keeping your cache in sync with your backend. However, it isn't always sufficient. For example, a newly cached object isn't automatically added to any _list fields_ that should now include that object. To accomplish this, you can define an [`update` function](#the-update-function).\n\n### The `update` function\n\nWhen a [mutation's response](#include-modified-objects-in-mutation-responses) is insufficient to update _all_ modified fields in your cache (such as certain list fields), you can define an `update` function to apply manual changes to your cached data after a mutation.\n\nYou provide an `update` function to `useMutation`, like so:\n\n```jsx {12-29}\nconst GET_TODOS = gql`\n  query GetTodos {\n    todos {\n      id\n    }\n  }\n`;\n\nfunction AddTodo() {\n  let input;\n  const [addTodo] = useMutation(ADD_TODO, {\n    update(cache, { data: { addTodo } }) {\n      cache.modify({\n        fields: {\n          todos(existingTodos = []) {\n            const newTodoRef = cache.writeFragment({\n              data: addTodo,\n              fragment: gql`\n                fragment NewTodo on Todo {\n                  id\n                  type\n                }\n              `,\n            });\n            return [...existingTodos, newTodoRef];\n          },\n        },\n      });\n    },\n  });\n\n  return (\n    <div>\n      <form\n        onSubmit={(e) => {\n          e.preventDefault();\n          addTodo({ variables: { type: input.value } });\n          input.value = \"\";\n        }}\n      >\n        <input\n          ref={(node) => {\n            input = node;\n          }}\n        />\n        <button type=\"submit\">Add Todo</button>\n      </form>\n    </div>\n  );\n}\n```\n\nAs shown, the `update` function is passed a `cache` object that represents the Apollo Client cache. This object provides access to cache API methods like `readQuery`/`writeQuery`, `readFragment`/`writeFragment`, `modify`, and `evict`. These methods enable you to execute GraphQL operations on the cache as though you're interacting with a GraphQL server.\n\n> Learn more about supported cache functions in [Interacting with cached data](../caching/cache-interaction/).\n\nThe `update` function is _also_ passed an object with a `data` property that contains the result of the mutation. You can use this value to update the cache with `cache.writeQuery`, `cache.writeFragment`, or `cache.modify`.\n\n<Note>\n\nIf your mutation specifies an [optimistic response](../performance/optimistic-ui/), your `update` function is called **twice**: once with the optimistic result, and again with the actual result of the mutation when it returns.\n\n</Note>\n\nWhen the `ADD_TODO` mutation executes in the above example, the newly added and returned `addTodo` object is automatically saved into the cache _before_ the `update` function runs. However, the cached list of `ROOT_QUERY.todos` (which is watched by the `GET_TODOS` query) is _not_ automatically updated. This means that the `GET_TODOS` query isn't notified of the new `Todo` object, which in turn means that the query doesn't update to show the new item.\n\nTo address this, we use `cache.modify` to surgically insert or delete items from the cache, by running \"modifier\" functions. In the example above, we know the results of the `GET_TODOS` query are stored in the `ROOT_QUERY.todos` array in the cache, so we use a `todos` modifier function to update the cached array to include a reference to the newly added `Todo`. With the help of `cache.writeFragment`, we get an internal reference to the added `Todo`, then append that reference to the `ROOT_QUERY.todos` array.\n\nAny changes you make to cached data inside of an `update` function are automatically broadcast to queries that are listening for changes to that data. Consequently, your application's UI will update to reflect these updated cached values.\n\n### Refetching after `update`\n\nAn `update` function attempts to replicate a mutation's back-end modifications in your client's local cache. These cache modifications are broadcast to all affected active queries, which updates your UI automatically. If the `update` function does this correctly, your users see the latest data immediately, without needing to await another network round trip.\n\nHowever, an `update` function might get this replication _wrong_ by setting a cached value incorrectly. You can \"double check\" your `update` function's modifications by refetching affected active queries. To do so, you first provide an `onQueryUpdated` callback function to your mutate function:\n\n```js {6-11}\naddTodo({\n  variables: { type: input.value },\n  update(cache, result) {\n    // Update the cache as an approximation of server-side mutation effects\n  },\n  onQueryUpdated(observableQuery) {\n    // Define any custom logic for determining whether to refetch\n    if (shouldRefetchQuery(observableQuery)) {\n      return observableQuery.refetch();\n    }\n  },\n});\n```\n\nAfter your `update` function completes, Apollo Client calls `onQueryUpdated` _once for each active query with cached fields that were updated_. Within `onQueryUpdated`, you can use any custom logic to determine whether you want to refetch the associated query.\n\nTo refetch a query from `onQueryUpdated`, call `return observableQuery.refetch()`, as shown above. Otherwise, no return value is required. If a refetched query's response differs from your `update` function's modifications, your cache and UI are both automatically updated again. Otherwise, your users see no change.\n\nOccasionally, it might be difficult to make your `update` function update all relevant queries. Not every mutation returns enough information for the `update` function to do its job effectively. To make absolutely sure a certain query is included, you can combine `onQueryUpdated` with `refetchQueries: [...]`:\n\n```js\naddTodo({\n  variables: { type: input.value },\n  update(cache, result) {\n    // Update the cache as an approximation of server-side mutation effects.\n  },\n  // Force ReallyImportantQuery to be passed to onQueryUpdated.\n  refetchQueries: [\"ReallyImportantQuery\"],\n  onQueryUpdated(observableQuery) {\n    // If ReallyImportantQuery is active, it will be passed to onQueryUpdated.\n    // If no query with that name is active, a warning will be logged.\n  },\n});\n```\n\nIf `ReallyImportantQuery` was already going to be passed to `onQueryUpdated` thanks to your `update` function, then it will only be passed once. Using `refetchQueries: [\"ReallyImportantQuery\"]` just guarantees the query will be included.\n\nIf you find you've included more queries than you expected, you can skip or ignore a query by returning `false` from `onQueryUpdated`, after examining the `ObservableQuery` to determine that it doesn't need refetching. Returning a `Promise` from `onQueryUpdated` causes the final `Promise<FetchResult<TData>>` for the mutation to await any promises returned from `onQueryUpdated`, eliminating the need for the legacy `awaitRefetchQueries: true` option.\n\nTo use the `onQueryUpdated` API without performing a mutation, try the [`client.refetchQueries`](./refetching/#clientrefetchqueries) method. In the standalone `client.refetchQueries` API, the `refetchQueries: [...]` mutation option is called `include: [...]`, and the `update` function is called `updateCache` for clarity. Otherwise, the same internal system powers both `client.refetchQueries` and refetching queries after a mutation.\n\n## `useMutation` API\n\nSupported options and result fields for the `useMutation` hook are listed below.\n\nMost calls to `useMutation` can omit the majority of these options, but it's\nuseful to know they exist. To learn about the `useMutation` hook API in more\ndetail with usage examples, see the [API reference](../api/react/hooks/).\n\n### Options\n\nThe `useMutation` hook accepts the following options:\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useMutation.Options:interface\"\n  idPrefix=\"mutationhookoptions-interface\"\n/>\n\n### Result\n\nThe `useMutation` result is a tuple with a mutate function in the first position and an object representing the mutation result in the second position.\n\nYou call the mutate function to trigger the mutation from your UI.\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useMutation.Result:interface\"\n  idPrefix=\"mutationresult-interface\"\n/>\n\n## Next steps\n\nThe `useQuery` and `useMutation` hooks together represent Apollo Client's core\nAPI for performing GraphQL operations. Now that you're familiar with both,\nyou can begin to take advantage of Apollo Client's full feature set, including:\n\n- [Optimistic UI](../performance/optimistic-ui/): Learn how to improve perceived performance by returning an optimistic response before your mutation result comes back from the server.\n- [Local state](../local-state/local-state-management/): Use Apollo Client to manage the entirety of your application's local state by executing client-side mutations.\n- [Caching in Apollo](../caching/cache-configuration/): Dive deep into the Apollo Client cache and how it's normalized. Understanding the cache is helpful when writing `update` functions for your mutations!\n"
  },
  {
    "path": "docs/source/data/operation-best-practices.mdx",
    "content": "---\ntitle: GraphQL query best practices\ndescription: Operation naming, GraphQL variables, and more\n---\n\nWhen creating queries and mutations, follow these best practices to get the most out of both GraphQL and Apollo tooling.\n\n## Name all operations\n\nThese two queries fetch the same data:\n\n```graphql\n# Recommended ✅\nquery GetBooks {\n  books {\n    title\n  }\n}\n\n# Not recommended ❌\nquery {\n  books {\n    title\n  }\n}\n```\n\nThe first query is named `GetBooks`. The second query is **anonymous**.\n\nYou should define a name for _every_ GraphQL operation in your application. Doing so provides the following benefits:\n\n- You clarify the purpose of each operation for both yourself and your teammates.\n- You avoid unexpected errors when combining multiple operations in a single query document (an anonymous operation can only appear alone).\n- You improve debugging output in both client _and_ server code, helping you identify exactly which operation is causing issues.\n- [Apollo GraphOS Studio](/graphos/graphs/studio-features) provides helpful operation-level metrics, which require named operations.\n\n## Use GraphQL variables to provide arguments\n\nThese two queries can both fetch a `Dog` object with ID `\"5\"`:\n\n```graphql {2-3,10-11}\n# Recommended ✅\nquery GetDog($dogId: ID!) {\n  dog(id: $dogId) {\n    name\n    breed\n  }\n}\n\n# Not recommended ❌\nquery GetDog {\n  dog(id: \"5\") {\n    name\n    breed\n  }\n}\n```\n\nThe first query uses a variable (`$dogId`) for the value of the `dog` field's required argument. This means you can use the query to fetch a `Dog` object with _any_ ID, making it much more reusable.\n\nYou pass variable values to `useQuery` (or `useMutation`) like so:\n\n```js {11-15} title=\"dog.tsx\"\nconst GET_DOG = gql`\n  query GetDog($dogId: ID!) {\n    dog(id: $dogId) {\n      name\n      breed\n    }\n  }\n`;\n\nfunction Dog({ id }) {\n  const { loading, error, data } = useQuery(GET_DOG, {\n    variables: {\n      dogId: id,\n    },\n  });\n  // ...render component...\n}\n```\n\n### Disadvantages of hardcoded GraphQL arguments\n\nBeyond reusability, hardcoded arguments have other disadvantages relative to variables:\n\n#### Reduced cache effectiveness\n\nIf two otherwise identical queries have different hardcoded argument values, they're considered _entirely different operations_ by your GraphQL server's cache. The cache enables your server to _skip_ parsing and validating operations that it's encountered before, improving performance.\n\nThe server-side cache also powers features like [automatic persisted queries](/apollo-server/performance/apq/) and query plans in a [federated gateway](/federation/building-supergraphs/router/). Hardcoded arguments reduce the performance gains of these features and take up useful space in the cache.\n\n#### Reduced information privacy\n\nThe value of a GraphQL argument might include sensitive information, such as an access token or a user's personal info. If this information is included in a query string, it's cached with the rest of that query string.\n\nVariable values are _not_ included in query strings. You can also specify _which_ variable values (if any) are [included in metrics reporting](/apollo-server/api/plugin/usage-reporting/#sendvariablevalues) to Studio.\n\n## Query only the data you need, where you need it\n\nOne of GraphQL's biggest advantages over a traditional REST API is its support for [declarative data fetching](/intro/benefits/#graphql-provides-declarative-efficient-data-fetching). Each component can (and should) query exactly the fields it requires to render, with no superfluous data sent over the network.\n\nIf instead your root component executes a single, enormous query to obtain data for all of its children, it might query on behalf of components that _aren't even rendered_ given the current state. This can result in a delayed response, and it drastically reduces the likelihood that the query's result can be reused by a [server-side response cache](/apollo-server/performance/caching/).\n\nIn the large majority of cases, a query such as the following should be divided into _multiple_ queries that are distributed among the appropriate components:\n\n<ExpansionPanel title=\"Click to expand\">\n\n```graphql\n# Not recommended ❌\nquery GetGlobalStatus {\n  stores {\n    id\n    name\n    address {\n      street\n      city\n    }\n    employees {\n      id\n    }\n    manager {\n      id\n    }\n  }\n  products {\n    id\n    name\n    price {\n      amount\n      currency\n    }\n  }\n  employees {\n    id\n    role\n    name {\n      firstName\n      lastName\n    }\n    store {\n      id\n    }\n  }\n  offers {\n    id\n    products {\n      id\n    }\n    discount {\n      discountType\n      amount\n    }\n  }\n}\n```\n\n</ExpansionPanel>\n\n- If you have collections of components that _are_ always rendered together, you can use fragments to distribute the structure of a single query between them. See [Colocating fragments](./fragments/#colocating-fragments).\n- If you're querying a list field that returns more items than your component needs to render, you should [paginate that field](../pagination/overview/).\n\n## Query global data and user-specific data separately\n\nSome fields return the exact same data regardless of which user queries them:\n\n```graphql\n# Returns all elements of the periodic table\nquery GetAllElements {\n  elements {\n    atomicNumber\n    name\n    symbol\n  }\n}\n```\n\nOther fields return _different_ data depending on which user queries them:\n\n```graphql\n# Returns the current user's documents\nquery GetMyDocuments {\n  myDocuments {\n    id\n    title\n    url\n    updatedAt\n  }\n}\n```\n\nTo improve the performance of your [server-side response cache](/apollo-server/performance/caching/), fetch these two types of fields in _separate queries_ whenever possible. By doing so, your server can cache just a _single_ response for a query like `GetAllElements` above, while caching separate responses for each user that executes `GetMyDocuments`.\n\n## Set your app's `name` and `version` for metrics reporting (paid)\n\n<Note>\n\nThis recommendation is _most_ pertinent to Studio organizations with a [paid plan](https://www.apollographql.com/pricing/), however it can be helpful for all apps.\n\n</Note>\n\nThe constructor of `ApolloClient` accepts the `clientAwareness` option with `name` and `version` properties:\n\n```js {4-7}\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache: new InMemoryCache(),\n  clientAwareness: {\n    name: \"MarketingSite\",\n    version: \"1.2\",\n  },\n});\n```\n\nIf you specify these values, Apollo Client automatically adds them to each operation request as HTTP headers (`apollographql-client-name` and `apollographql-client-version`).\n\nThen if you've configured metrics reporting in Studio, Apollo Server includes your app's `name` and `version` in the operation traces it reports to Studio. This enables you to [segment metrics by client](/graphos/metrics/client-awareness/).\n"
  },
  {
    "path": "docs/source/data/persisted-queries.mdx",
    "content": "---\ntitle: Persisted queries\ndescription: Secure your graph while minimizing request latency\nredirectFrom:\n  - /react/api/link/persisted-queries\n---\n\nUnlike REST APIs that use a fixed URL to load data, GraphQL provides a rich query language that can be used to express the shape of application data requirements. This is a marvelous advancement in technology, but it comes at a cost: GraphQL query strings are often much longer than REST URLS—in some cases by many kilobytes.\n\nIn practice we've seen GraphQL query sizes ranging well above 10 KB _just for the query text_. This is significant overhead when compared with a simple URL of 50-100 characters. When paired with the fact that the uplink speed from the client is typically the most bandwidth-constrained part of the chain, large queries can become bottlenecks for client performance.\n\nMalicious actors can exploit GraphQL APIs by sending large and complex requests that overwhelm servers and disrupt services. These attackers can abuse GraphQL's query flexibility to create deeply nested, resource-intensive queries that lead to excessive data fetching.\n\n## Solutions\n\n<ClientPQIntro />\n\n### Differences between persisted queries and APQ\n\n<ClientPQDifferences />\n\n## Implementation steps\n\nBecause persisted queries requires you to preregister operations, it has additional implementation steps.\n\n<ClientPQImplementation />\n\n## 0. Requirements\n\nUsing persisted queries for safelisting has the following requirements:\n\n- Apollo Client Web (v3.7.0+)\n- The [`@apollo/generate-persisted-query-manifest` package](https://www.npmjs.com/package/@apollo/generate-persisted-query-manifest)\n- The [`@apollo/persisted-query-lists` package](https://www.npmjs.com/package/@apollo/persisted-query-lists)\n- [GraphOS Router](/router) (v1.25.0+)\n- [GraphOS Enterprise plan](https://www.apollographql.com/pricing)\n\nYou can use APQ with the following versions of Apollo Client Web, Apollo Server, and Apollo Router Core:\n\n- Apollo Client Web (v3.2.0+)\n- [Apollo Server](/apollo-server/) (v1.0.0+)\n- [Apollo Router Core](/router) (v0.1.0+)\n\n<Note>\n\nYou can use _either_ Apollo Server _or_ Apollo Router Core for APQs. They don't need to be used together.\n\n</Note>\n\n## 1. Generate operation manifests\n\n<Note>\n\nThis step is only required for persisted queries, not APQ.\n\n</Note>\n\nAn operation manifest acts as a safelist the [GraphOS Router](/router/) can check incoming requests against.\nYou can generate the manifest using the [`@apollo/generate-persisted-query-manifest`](https://www.npmjs.com/package/@apollo/generate-persisted-query-manifest) package:\n\n1. Install the [`@apollo/generate-persisted-query-manifest`](https://www.npmjs.com/package/@apollo/generate-persisted-query-manifest) package as a dev dependency:\n\n```bash\nnpm install --save-dev @apollo/generate-persisted-query-manifest\n```\n\n2. Then use its CLI to extract queries from your app:\n\n```bash\nnpx generate-persisted-query-manifest\n```\n\nThe resulting operation manifest looks something like this:\n\n```json title=\"persisted-query-manifest.json\"\n{\n  \"format\": \"apollo-persisted-query-manifest\",\n  \"version\": 1,\n  \"operations\": [\n    {\n      \"id\": \"e0321f6b438bb42c022f633d38c19549dea9a2d55c908f64c5c6cb8403442fef\",\n      \"body\": \"query GetItem { thing { __typename } }\",\n      \"name\": \"GetItem\",\n      \"type\": \"query\"\n    }\n  ]\n}\n```\n\nYou can optionally create a configuration file in the root of your project to override the default options. Refer to the package's [README](https://www.npmjs.com/package/@apollo/generate-persisted-query-manifest) for details.\n\nTo automatically update the manifest for each new app release, include the `generate-persisted-query-manifest` command in your CI/CD pipeline.\n\n<Tip>\n\nIf you see a difference in the `id` generated in the manifest and the one your\nclient is sending at runtime, read the options available in the\n[`@apollo/generate-persisted-query-manifest`](https://www.npmjs.com/package/@apollo/generate-persisted-query-manifest)\npackage to ensure the configuration matches your usage of Apollo\nClient.<br/><br/>\n\nThis might also occur when you're not using the `@apollo/persisted-query-lists`\npackage with `PersistedQueryLink`. The most common source of mismatches occurs\nbecause the `@apollo/generate-persisted-query-manifest` package sorts top-level\ndefinitions before generating the hash. If you're using a different terminating\nlink, try using the `sortTopLevelDefinitions` function exported from\n`@apollo/persisted-query-lists` before generating the hash.\n\n<ExpansionPanel title=\"Example\">\n\nThe following example uses `sortTopLevelDefinitions` before generating the query\nhash to ensure the hash matches the manifest file.\n\n```ts {3,6} title=\"Your custom link\"\nimport { print } from \"graphql\";\nimport { sha256 } from \"crypto-hash\";\nimport { sortTopLevelDefinitions } from \"@apollo/persisted-query-lists\";\n\nconst link = new ApolloLink((operation, forward) => {\n  const hash = sha256(print(sortTopLevelDefinitions(operation.query)));\n  // ...\n});\n```\n\n</ExpansionPanel>\n\n</Tip>\n\n## 2. Publish manifests to a PQL\n\n<PublishPQMs />\n\n## 3. Enable persisted queries on `ApolloClient`\n\nYou use the **persisted queries** Apollo Link to send operations as IDs rather than full operation strings. The implementation details depend on whether you're using persisted queries or APQs.\n\n### Persisted queries implementation\n\nThe persisted queries link is included in the `@apollo/client` package:\n\n```bash\nnpm install @apollo/client\n```\n\nA persisted queries implementation also requires the [`@apollo/persisted-query-lists`](https://www.npmjs.com/package/@apollo/persisted-query-lists) package. This package contains helpers that work with the persisted queries link.\n\nInstall the [`@apollo/persisted-query-lists`](https://www.npmjs.com/package/@apollo/persisted-query-lists) package:\n\n```bash\nnpm install @apollo/persisted-query-lists\n```\n\nOne of the package's utilities, `generatePersistedQueryIdsFromManifest`, reads operation IDs from your [operation manifest](#1-generate-operation-manifests) so the client can use them to make requests. To do so, pass the `loadManifest` option a function that returns your manifest. We recommend using a dynamic import to avoid bundling the manifest configuration with your production build.\n\n```js\ngeneratePersistedQueryIdsFromManifest({\n  loadManifest: () => import(\"./path/to/persisted-query-manifest.json\"),\n});\n```\n\nFinally, combine the link that `generatePersistedQueryIdsFromManifest` returns with `ApolloClient`'s `HttpLink`. The easiest way to use them together is to `concat` them into a single link.\n\n```js\nimport { HttpLink, InMemoryCache, ApolloClient } from \"@apollo/client\";\nimport { generatePersistedQueryIdsFromManifest } from \"@apollo/persisted-query-lists\";\nimport { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\n\nconst persistedQueryLink = new PersistedQueryLink(\n  generatePersistedQueryIdsFromManifest({\n    loadManifest: () => import(\"./path/to/persisted-query-manifest.json\"),\n  })\n);\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: persistedQueriesLink.concat(httpLink),\n});\n```\n\nBy including the persisted queries link in your client instantiation, your client sends operation IDs from your manifest instead of the full operation string.\n\nThe [`@apollo/persisted-query-lists`](https://www.npmjs.com/package/@apollo/persisted-query-lists) package includes additional helpers you can use to [verify that you've properly configured your operation manifest](https://www.npmjs.com/package/@apollo/persisted-query-lists#createPersistedQueryManifestVerificationLink) and [generate operation IDs at runtime](https://www.npmjs.com/package/@apollo/persisted-query-lists#generatePersistedQueryIdsAtRuntime). Runtime generation is slower than fetching operation IDs from the manifest, but doesn't require making your manifest available to your client.\n\nRefer to the package [README](https://www.npmjs.com/package/@apollo/persisted-query-lists) for more information.\n\n### APQ implementation\n\nThe persisted queries Apollo Link used for APQs is included in the `@apollo/client` package:\n\n```bash\nnpm install @apollo/client\n```\n\nThis link requires but doesn't include a SHA-256 hash function. It does this to avoid forcing a particular hash function as a dependency. Developers should pick the most appropriate SHA-256 function (sync or async) for their needs and environment.\n\nIf you don't already have a SHA-256 based hashing function available in your application, install one separately. For example:\n\n```bash\nnpm install crypto-hash\n```\n\nThe link requires using `ApolloClient`'s `HttpLink`. The easiest way to use them together is to `concat` them into a single link.\n\n```js\nimport { HttpLink, InMemoryCache, ApolloClient } from \"@apollo/client\";\nimport { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\nimport { sha256 } from \"crypto-hash\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\nconst persistedQueriesLink = new PersistedQueryLink({ sha256 });\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: persistedQueriesLink.concat(httpLink),\n});\n```\n\nThat's it! By including the persisted queries link in your client instantiation, your client sends operation IDs instead of the full operation string. This results in improved network performance, but doesn't include the security benefits of operation safelisting that [persisted queries](#differences-between-persisted-queries-and-apq) provide.\n\nFor more details on the options available to `PersistedQueryLink`, see its [API reference documentation](../api/link/persisted-queries).\n\n## Apollo Studio\n\nApollo Studio supports receiving and fulfilling APQs. Simply adding this link into your client app will improve your network response times when using Apollo Studio.\n\n### Protocol\n\nAPQs are made up of three parts: the query signature, error responses, and the negotiation protocol.\n\n**Query Signature**\n\nThe query signature for APQs is sent through the `extensions` field of a request from the client. This is a transport independent way to send extra information along with the operation.\n\n```js\n{\n  operationName: 'MyQuery',\n  variables: null,\n  extensions: {\n    persistedQuery: {\n      version: 1,\n      sha256Hash: hashOfQuery\n    }\n  }\n}\n```\n\nWhen sending an Automatic Persisted Query, the client omits the `query` field normally present, and instead sends an extension field with a `persistedQuery` object as shown above. The hash algorithm defaults to a `sha256` hash of the query string.\n\nIf the client needs to register the hash, the query signature will be the same but include the full query text like so:\n\n```js\n{\n  operationName: 'MyQuery',\n  variables: null,\n  query: `query MyQuery { id }`,\n  extensions: {\n    persistedQuery: {\n      version: 1,\n      sha256Hash: hashOfQuery\n    }\n  }\n}\n```\n\nThis should only happen once across all clients when a new query is introduced into your application.\n\n**Error Responses**\n\nWhen the initial query signature is received by a backend, if it is unable to find the hash previously stored, it will send back the following response signature:\n\n```js\n{\n  errors: [{ message: \"PersistedQueryNotFound\" }];\n}\n```\n\nIf the backend doesn't support APQs, or does not want to support it for that particular client, it can send back the following which will tell the client to stop trying to send hashes:\n\n```\n{\n  errors: [\n    { message: 'PersistedQueryNotSupported' }\n  ]\n}\n```\n\n**Negotiation Protocol**\n\nIn order to support APQs, the client and server must follow the negotiation steps as outlined here:\n\n_Happy Path_\n\n1. Client sends query signature with no `query` field\n2. Server looks up query based on hash, if found, it resolves the data\n3. Client receives data and completes request\n\n_Missing hash path_\n\n1. Client sends query signature with no `query` field\n2. Server looks up query based on hash, none is found\n3. Server responds with NotFound error response\n4. Client sends both hash and query string to Server\n5. Server fulfills response and saves query string + hash for future lookup\n6. Client receives data and completes request\n\n### Build time generation\n\nIf you want to avoid hashing in the browser, you can use a build script to include the hash as part of the request, then pass a function to retrieve that hash when the operation is run. This works well with projects like [GraphQL Persisted Document Loader](https://github.com/leoasis/graphql-persisted-document-loader) which uses webpack to generate hashes at build time.\n\nIf you use the above loader, you can pass `{ generateHash: ({ documentId }) => documentId }` to the `PersistedQueryLink` class.\n"
  },
  {
    "path": "docs/source/data/queries.mdx",
    "content": "---\ntitle: Queries\ndescription: Fetch data with the useQuery hook\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\nThis article shows how to fetch GraphQL data in React with the `useQuery` hook and attach the result to your UI. You'll also learn how Apollo Client simplifies data management code by tracking error and loading states for you.\n\n<Note>\n  This article shows how to use Apollo Client in a React application that\n  doesn't make use of React's \"Suspense\" features. For modern React applications\n  built around Suspense, suspense-enabled data fetching hooks are described in\n  Apollo Client's [Suspense docs](./suspense/).\n</Note>\n\n## Prerequisites\n\n<Note>\n\nIf your application is built using TypeScript, we recommend reading the [TypeScript guide](../development-testing/static-typing) to learn how to use TypeScript with Apollo Client.\n\n</Note>\n\nThis article assumes you're familiar with building basic GraphQL queries. If you need a refresher, we recommend [this guide](http://graphql.org/learn/queries/). You can also build example queries against Apollo's [full-stack tutorial server](https://apollo-fullstack-tutorial.herokuapp.com/graphql).\n\nThis article also assumes that you've already set up Apollo Client and have wrapped your React app in an `ApolloProvider` component. For more information, see the [getting started guide](../get-started/).\n\n> To follow along with the examples below, open up our [starter project](https://codesandbox.io/s/queries-example-app-start-nvp9z) and [sample GraphQL server](https://codesandbox.io/s/queries-example-app-server-71z1g) on CodeSandbox. You can view the completed version of the app [here](https://codesandbox.io/s/queries-example-app-final-nrlnl).\n\n## Executing a query\n\nThe `useQuery` [React hook](https://react.dev/reference/react) is the primary API for executing queries in a non-suspenseful Apollo application (for information about using Apollo Client with suspenseful React, see [Suspense](./suspense)). To run a query within a React component, call `useQuery` and pass it a GraphQL document. When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, `dataState` and `data` properties you can use to render your UI.\n\nLet's look at an example. First, we'll create a GraphQL query named `GET_DOGS`. Remember to wrap query strings in the `gql` function to parse them into query documents:\n\n```js title=\"index.js\"\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nconst GET_DOGS = gql`\n  query GetDogs {\n    dogs {\n      id\n      breed\n    }\n  }\n`;\n```\n\nNext, we'll create a component named `Dogs`. Inside it, we'll pass our `GET_DOGS` query to the `useQuery` hook:\n\n```jsx title=\"index.js\"\nfunction Dogs({ onDogSelected }) {\n  const { loading, error, data } = useQuery(GET_DOGS);\n\n  if (loading) return \"Loading...\";\n  if (error) return `Error! ${error.message}`;\n\n  return (\n    <select name=\"dog\" onChange={onDogSelected}>\n      {data.dogs.map((dog) => (\n        <option key={dog.id} value={dog.breed}>\n          {dog.breed}\n        </option>\n      ))}\n    </select>\n  );\n}\n```\n\nAs our query executes and the values of `loading`, `error`, and `data` change, the `Dogs` component can intelligently render different UI elements according to the query's state:\n\n- As long as `loading` is `true` (indicating the query is still in flight), the component presents a `Loading...` notice.\n- When loading is `false` and there is no `error`, the query has completed. The component renders a dropdown menu that's populated with the list of dog breeds returned by the server.\n\nWhen the user selects a dog breed from the populated dropdown, the selection is sent to the parent component via the provided `onDogSelected` function.\n\n<Note>\n\nIf you are using TypeScript, `data` is typed as `unknown` when the query type is unknown. Accessing fields on `data` results in a TypeScript error. See the [TypeScript with Apollo Client](../development-testing/static-typing) guide to learn how to add types for your queries.\n\n</Note>\n\nIn the next step, we'll associate the dropdown with a more sophisticated query that uses GraphQL variables.\n\n## Caching query results\n\nWhenever Apollo Client fetches query results from your server, it automatically **caches** those results locally. This makes later executions of that same query extremely fast.\n\nTo see this caching in action, let's build a new component called `DogPhoto`. `DogPhoto` accepts a prop called `breed` that reflects the current value of the dropdown menu in our `Dogs` component:\n\n```jsx title=\"index.js\"\nconst GET_DOG_PHOTO = gql`\n  query Dog($breed: String!) {\n    dog(breed: $breed) {\n      id\n      displayImage\n    }\n  }\n`;\n\nfunction DogPhoto({ breed }) {\n  const { loading, error, data } = useQuery(GET_DOG_PHOTO, {\n    variables: { breed },\n  });\n\n  if (loading) return null;\n  if (error) return `Error! ${error}`;\n\n  return (\n    <img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />\n  );\n}\n```\n\nNotice that we're providing a configuration option (`variables`) to the `useQuery` hook this time. The `variables` option is an object that contains all of the variables we want to pass to our GraphQL query. In this case, we want to pass the currently selected `breed` from the dropdown.\n\nSelect `bulldog` from the dropdown to see its photo appear. Then switch to another breed, and then switch _back_ to `bulldog`. You'll notice that the bulldog photo loads instantly the second time around. This is the cache at work!\n\nNext, let's learn some techniques for ensuring that our cached data is fresh.\n\n## Updating cached query results\n\nSometimes, you want to make sure that your query's cached data is up to date with your _server's_ data. Apollo Client supports two strategies for this: **polling** and **refetching**.\n\n### Polling\n\nPolling provides near-real-time synchronization with your server by executing your query periodically at a specified interval. To enable polling for a query, pass a `pollInterval` configuration option to the `useQuery` hook with an interval in milliseconds:\n\n```jsx title=\"index.js\" {4}\nfunction DogPhoto({ breed }) {\n  const { loading, error, data } = useQuery(GET_DOG_PHOTO, {\n    variables: { breed },\n    pollInterval: 500,\n  });\n\n  if (loading) return null;\n  if (error) return `Error! ${error}`;\n\n  return (\n    <img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />\n  );\n}\n```\n\nBy setting `pollInterval` to 500, we fetch the current breed's image from the server every 0.5 seconds. Note that if you set `pollInterval` to `0`, the query does **not** poll.\n\n> You can also start and stop polling dynamically with the [`startPolling` and `stopPolling` functions](#startpolling) that are returned by the `useQuery` hook. When using these functions, set the `pollInterval` configuration option as a parameter of the `startPolling` function.\n\n### Refetching\n\nRefetching enables you to refresh query results in response to a particular user\naction, as opposed to using a fixed interval.\n\nLet's add a button to our `DogPhoto` component that calls our query's\n`refetch` function whenever it's clicked.\n\nYou can optionally provide a new `variables` object to the `refetch` function.\nIf you don't provide a `variables` object, the query uses the same `variables`\nobject that it used in its previous execution.\n\n```jsx {2,12} title=\"index.js\"\nfunction DogPhoto({ breed }) {\n  const { loading, error, data, refetch } = useQuery(GET_DOG_PHOTO, {\n    variables: { breed },\n  });\n\n  if (loading) return null;\n  if (error) return `Error! ${error}`;\n\n  return (\n    <div>\n      <img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />\n      <button onClick={() => refetch()}>Refetch new breed!</button>\n    </div>\n  );\n}\n```\n\nClick the button and notice that the UI updates with a new dog photo. Refetching is an excellent way to guarantee fresh data, but it introduces some complexity with loading state. In the next section, we'll cover strategies for handling complex loading and error state.\n\n#### Providing new variables to `refetch`\n\nYou call `refetch` with a new set of variables like so:\n\n```jsx\n<button\n  onClick={() =>\n    refetch({\n      breed: \"dalmatian\", // Always refetches a dalmatian instead of original breed\n    })\n  }\n>\n  Refetch!\n</button>;\n```\n\nIf you provide new values for _some_ of your original query's variables but not _all_ of them, `refetch` uses each omitted variable's original value.\n\n## Inspecting loading states\n\nWe've already seen that the `useQuery` hook exposes our query's current loading state. This is helpful when a query first loads, but what happens to our loading state when we're refetching or polling?\n\nLet's return to our refetching example from the previous section. If you click the refetch button, you'll see that the component re-renders while we're refetching the photo.\n\nThe `useQuery` hook's result object provides fine-grained information about the status of the query via the `networkStatus` property. This allows us to indicate to the user that we're refetching the photo:\n\n```jsx title=\"index.js\" {3,7}\nimport { NetworkStatus } from \"@apollo/client\";\n\nfunction DogPhoto({ breed }) {\n  const { loading, error, data, refetch, networkStatus } = useQuery(\n    GET_DOG_PHOTO,\n    {\n      variables: { breed },\n    }\n  );\n\n  if (networkStatus === NetworkStatus.refetch) return \"Refetching!\";\n  if (loading) return null;\n  if (error) return `Error! ${error}`;\n\n  return (\n    <div>\n      <img src={data.dog.displayImage} style={{ height: 100, width: 100 }} />\n      <button onClick={() => refetch()}>Refetch!</button>\n    </div>\n  );\n}\n```\n\nThe value of `loading` also updates accordingly. Even if you don't use the more fine-grained information provided by the `networkStatus` property, the `loading` property indicates that the refetch is in progress.\n\nThe `networkStatus` property is a `NetworkStatus` enum that represents different loading states. Refetch is represented by `NetworkStatus.refetch`. There are additional values for e.g. polling and pagination. For a full list of all the possible loading states, check out [this table](../api/core/ObservableQuery#networkstatus).\n\n<Note>\n\nIf you want to disable automatic re-rendering when the network status changes, set `notifyOnNetworkStatusChange` to `false` either in individual queries or globally via `defaultOptions`:\n\n```js\nconst client = new ApolloClient({\n  // ... other options\n  defaultOptions: {\n    watchQuery: {\n      notifyOnNetworkStatusChange: false,\n    },\n  },\n});\n```\n\n</Note>\n\n> To view a complete version of the app we just built, check out the CodeSandbox [here](https://codesandbox.io/s/queries-example-app-final-nrlnl).\n\n## Inspecting error states\n\nYou can customize your query error handling by providing the `errorPolicy`\nconfiguration option to the `useQuery` hook. The default value is `none`, which tells Apollo Client to treat all GraphQL errors as runtime errors. In this case, Apollo Client discards any query response data returned by the server and sets the `error` property in the `useQuery` result object.\n\nIf you set `errorPolicy` to `all`, `useQuery` does _not_ discard query response data, allowing you to render partial results.\n\nFor more information, see [Handling operation errors](./error-handling/).\n\n## Fetching in response to user interaction\n\nWhen React renders a component that calls `useQuery`, Apollo Client automatically executes the corresponding query. But what if you want to execute a query in response to a user interaction, such as a user clicking a button?\n\nThe [`useLazyQuery`](../api/react/useLazyQuery) hook is for manually executing queries. Unlike `useQuery`, when you use `useLazyQuery`, it doesn't immediately execute its associated query. Instead, it returns an execution function that you call whenever you need to execute the query.\n\nHere's an example:\n\n```jsx {2,5,15} title=\"index.js\"\nimport React from \"react\";\nimport { useLazyQuery } from \"@apollo/client/react\";\n\nfunction GetDogsOnClick() {\n  const [getDogs, { loading, error, data }] = useLazyQuery(GET_DOGS);\n\n  if (loading) return <p>Loading ...</p>;\n  if (error) return `Error! ${error.message}`;\n\n  return (\n    <div>\n      {data?.dogs.map((dog) => (\n        <Dog key={dog.id} dog={dog} />\n      ))}\n      <button onClick={() => getDogs()}>Load dogs</button>\n    </div>\n  );\n}\n```\n\nThe first item in `useLazyQuery`'s return tuple is the execution function, and the second item is an object that contains information about the executed query, such as the `loading`, `error`, `data`, and `dataState` properties.\n\n### Re-rendering with new options\n\nUnlike `useQuery`, options provided to `useLazyQuery` that change on re-renders do not automatically execute the query. Instead, `useLazyQuery` waits to execute the query with the updated options until you call the execution function again.\n\nThe following is an example that changes the fetch policy depending on whether the user is online or offline:\n\n```tsx\nfunction GetDogs({ isOnline }) {\n  const [getDogs, { loading, data }] = useLazyQuery(GET_DOGS, {\n    fetchPolicy: isOnline ? \"network-only\" : \"cache-only\",\n  });\n\n  if (loading) return <p>Loading ...</p>;\n\n  return (\n    <div>\n      {data && <Dogs data={data.dogs} />}\n      <button onClick={() => getDogs()}>Get dogs</button>\n    </div>\n  );\n}\n```\n\n<Note>\n\nThe changed options are immediately applied to the underlying `ObservableQuery` (accessible by the `observable` property) even though the query isn't executed. Inspecting the options on the `observable` returns the updated options. This means the updated options are used for other APIs (such as `refetch`), even before you call the execution function again.\n\n</Note>\n\n### Working with variables\n\nYou provide `variables` to the execution function when executing the query.\n\nThe following example gets a specific dog's photo when you click the **Get photo** button:\n\n```jsx\nfunction DogPhoto() {\n  const [getDogPhoto, { loading, error, data }] = useLazyQuery(GET_DOG_PHOTO);\n\n  if (loading) return <p>Loading ...</p>;\n  if (error) return `Error! ${error.message}`;\n\n  return (\n    <div>\n      {data?.dog && <img src={data.dog.displayImage} />}\n      <button onClick={() => getDogPhoto({ variables: { name: \"Lucky\" } })}>\n        Get photo\n      </button>\n    </div>\n  );\n}\n```\n\n<Note>\n\nWhen using TypeScript, the `variables` option is required if the query provided to `useLazyQuery` contains required variables. If the options argument isn't provided to the execution function, or the `variables` option is missing required variables, TypeScript raises an error.\n\n</Note>\n\n#### Changing variables\n\nYou change variables by calling the execution function with updated variables.\n\nThe following example gets the selected dog's photo when you click the **Get photo** button.\n\n```jsx\nfunction DogPhoto() {\n  const [selectedDog, setSelectedDog] = useState(null);\n  const [getDogPhoto, { loading, error, data }] = useLazyQuery(GET_DOG_PHOTO);\n\n  if (loading) return <p>Loading ...</p>;\n  if (error) return `Error! ${error.message}`;\n\n  return (\n    <div>\n      <DogSelect\n        onChange={(dogName) => setSelectedDog(dogName)}\n        value={selectedDog}\n      />\n      {data?.dog && <img src={data.dog.displayImage} />}\n      {selectedDog && (\n        <button\n          onClick={() => getDogPhoto({ variables: { name: selectedDog } })}\n        >\n          Get photo\n        </button>\n      )}\n    </div>\n  );\n}\n```\n\nIf you need to reference the currently executed query's variables, use the `variables` property returned by `useLazyQuery`. The `variables` property contains the value of the variables from the last execution of the query.\n\n<Tip>\n\nThe `variables` property is empty until you call the execution function for the first time. Use the `called` property returned by `useLazyQuery` to determine if you've called the execution function at least once.\n\n</Tip>\n\n```jsx\nfunction DogPhoto() {\n  const [getDogPhoto, { called, variables }] = useLazyQuery(GET_DOG_PHOTO);\n\n  return (\n    <div>\n      {/* ... */}\n      <button onClick={() => getDogPhoto({ variables: { name: selectedDog } })}>\n        Get photo\n      </button>\n\n      {called && <span>Last fetched: {variables.name}</span>}\n    </div>\n  );\n}\n```\n\n### Using the promise returned from the execution function\n\nThe execution function returns a promise that resolves with the query result:\n\n```jsx\nfunction GetDogs() {\n  const [getDogs, { data, loading, error }] = useLazyQuery(GET_DOGS);\n\n  const handleClick = async () => {\n    const { data } = await getDogs();\n\n    // Do something with `data`\n  };\n\n  return (\n    <div>\n      {/* ... */}\n      <button onClick={handleClick}>Get dogs</button>\n    </div>\n  );\n}\n```\n\nThe result returned from the promise is useful when you need to execute side-effects using the data returned by the query.\n\n<Tip>\n\nUse the `data`, `error`, and other properties returned by `useLazyQuery` to sync the query state with your component. Avoid using your own state setters from React's `useState` hook with data resolved from the promise. This ensures your component stays up-to-date with cache changes as they occur throughout your application.<br /><br />\n\nIn cases where you don't need to keep your component in sync with query state, use `client.query()` directly because it won't unnecessarily render your component for data that you don't use.\n\nUsing `useLazyQuery` in these situations is an antipattern.\n\n<ExpansionPanel title=\"Example\">\n\n```ts\nimport { useApolloClient } from \"@apollo/client/react\";\n\nfunction GetDogs() {\n  const client = useApolloClient();\n\n  const handleClick = async () => {\n    const { data } = await client.query({ query: GET_DOGS });\n\n    // Do something with `data`\n  };\n\n  return <button onClick={handleClick}>Get dogs</button>;\n}\n```\n\n</ExpansionPanel>\n\n</Tip>\n\n#### Handling errors\n\nThe promise resolves or rejects depending on the configured [`errorPolicy`](./error-handling#setting-an-error-policy). For a more comprehensive guide on working with errors, read the [Error handling documentation](./error-handling).\n\n##### `errorPolicy: \"none\"`\n\nThe promise rejects with the error that caused the query to fail.\n\n```ts\nconst handleClick = async () => {\n  try {\n    const { data } = await getDogs();\n  } catch (error) {\n    if (CombinedGraphQLErrors.is(error)) {\n      // handle GraphQL errors\n    }\n\n    // Handle other error types\n    console.log(error.message);\n  }\n};\n```\n\n<Note>\n\nErrors always cause the promise to reject. The `error` property is never set when the promise resolves.\n\n</Note>\n\n##### `errorPolicy: \"all\"`\n\nThe promise resolves with an object that includes the error and any partial data returned by the query. Read the partial data on the `data` property and the error that caused the query to fail on the `error` property.\n\n```ts\nconst handleClick = async () => {\n  const { data, error } = await getDogs();\n\n  if (CombinedGraphQLErrors.is(error)) {\n    // handle GraphQL errors returned by the query\n  }\n};\n```\n\n<Note>\n\nThe `data` property might be `undefined` instead of containing partial data. This typically occurs when a [network error](./error-handling#network-errors) causes the query to fail, because the error isn't associated with GraphQL execution.\n\n</Note>\n\n##### `errorPolicy: \"ignore\"`\n\nThe promise resolves with an object that includes any partial data returned by the query. Errors are discarded.\n\n```ts\nconst handleClick = async () => {\n  const { data } = await getDogs();\n\n  if (data !== undefined) {\n    // Do something with the returned data\n  }\n};\n```\n\n<Tip>\n\n`data` might be `undefined` if a [network error](./error-handling#network-errors) occurs. Check if `data` is `undefined` before you use it, in case an error occurs during query execution.\n\n</Tip>\n\n#### Retaining query results\n\nApollo Client aborts in-flight queries executed by `useLazyQuery` when the component unmounts or when you start another query by calling the execution function. This causes the promise to reject. In some cases, you might find this behavior undesirable and prefer to let the query run to completion.\n\n<Note>\n\nApollo Client ensures the rejected promise doesn't throw an unhandled rejection error when you don't add a rejection handler to the promise. However, this means that aborted errors are silent and might go unnoticed. If you want to be notified when the request is aborted, provide a rejection handler for the promise.\n\n</Note>\n\nThe promise returned by the execution function includes a `.retain()` method. When you call it, it ensures the query continues running even if the component unmounts or you start a new query before the previous one finishes.\n\n```jsx\nfunction GetDogs() {\n  const [getDogs] = useLazyQuery(GET_DOGS);\n\n  const handleClick = async () => {\n    const promise = getDogs();\n\n    // Retain the query even if component unmounts\n    promise.retain();\n\n    const { data } = await promise;\n\n    // Do something with data\n  };\n\n  return <button onClick={handleClick}>Get dogs</button>;\n}\n```\n\nThe `retain()` method returns the original promise, so you can shorten the previous example to a single line:\n\n```ts\nconst { data } = await getDogs().retain();\n```\n\nFor a complete list of supported options and result properties, see the [`useLazyQuery` API reference](../api/react/useLazyQuery).\n\n## Setting a fetch policy\n\nBy default, the `useQuery` hook checks the Apollo Client cache to see if all the data you requested is already available. If all of the data _is_ available in the cache, `useQuery` returns that data and _doesn't_ query your GraphQL server. This `cache-first` policy is Apollo Client's default **fetch policy**.\n\nYou specify a fetch policy using the `fetchPolicy` option. For example, we can instruct `useQuery` to bypass the cache and fetch from the network by setting the `fetchPolicy` option to `network-only`:\n\n```js {2}\nconst { loading, error, data } = useQuery(GET_DOGS, {\n  fetchPolicy: \"network-only\", // Doesn't check cache before making a network request\n});\n```\n\n### `nextFetchPolicy`\n\nYou can _also_ specify a query's `nextFetchPolicy`. When provided, `fetchPolicy` is used for the query's _first_ execution, and `nextFetchPolicy` is used to determine how the query responds to future cache updates:\n\n```js {3}\nconst { loading, error, data } = useQuery(GET_DOGS, {\n  fetchPolicy: \"network-only\", // Used for first execution\n  nextFetchPolicy: \"cache-first\", // Used for subsequent executions\n});\n```\n\nFor example, this is helpful if you want a query to always make an initial network request, but you're comfortable reading from the cache after that.\n\n#### `nextFetchPolicy` functions\n\nIf you want to apply a single `nextFetchPolicy` by default, because you find yourself manually providing `nextFetchPolicy` for most of your queries, you can configure `defaultOptions.watchQuery.nextFetchPolicy` when creating your `ApolloClient` instance:\n\n```js\nnew ApolloClient({\n  link,\n  client,\n  defaultOptions: {\n    watchQuery: {\n      nextFetchPolicy: \"cache-only\",\n    },\n  },\n});\n```\n\nThis configuration applies to all `client.watchQuery` calls and `useQuery` calls that do not otherwise configure `nextFetchPolicy`.\n\nIf you want more control over how `nextFetchPolicy` behaves, you can provide a function instead of a `WatchQueryFetchPolicy` string:\n\n```js\nnew ApolloClient({\n  link,\n  client,\n  defaultOptions: {\n    watchQuery: {\n      nextFetchPolicy(currentFetchPolicy) {\n        if (\n          currentFetchPolicy === \"network-only\" ||\n          currentFetchPolicy === \"cache-and-network\"\n        ) {\n          // Demote the network policies (except \"no-cache\") to \"cache-first\"\n          // after the first request.\n          return \"cache-first\";\n        }\n        // Leave all other fetch policies unchanged.\n        return currentFetchPolicy;\n      },\n    },\n  },\n});\n```\n\nThis `nextFetchPolicy` function will be called after each request, and uses the `currentFetchPolicy` parameter to decide how to modify the fetch policy.\n\nIn addition to being called after each request, your `nextFetchPolicy` function will also be called when variables change, which by default resets the `fetchPolicy` to its initial value, which is often important to trigger a fresh network request for queries that started out with `cache-and-network` or `network-only` fetch policies.\n\nTo intercept and handle the `variables-changed` case yourself, you can use the `NextFetchPolicyContext` object passed as the second argument to your `nextFetchPolicy` function:\n\n```js\nnew ApolloClient({\n  link,\n  client,\n  defaultOptions: {\n    watchQuery: {\n      nextFetchPolicy(\n        currentFetchPolicy,\n        {\n          // Either \"after-fetch\" or \"variables-changed\", indicating why the\n          // nextFetchPolicy function was invoked.\n          reason,\n          // The rest of the options (currentFetchPolicy === options.fetchPolicy).\n          options,\n          // The original value of options.fetchPolicy, before nextFetchPolicy was\n          // applied for the first time.\n          initialFetchPolicy,\n          // The ObservableQuery associated with this client.watchQuery call.\n          observable,\n        }\n      ) {\n        // When variables change, the default behavior is to reset\n        // options.fetchPolicy to context.initialFetchPolicy. If you omit this logic,\n        // your nextFetchPolicy function can override this default behavior to\n        // prevent options.fetchPolicy from changing in this case.\n        if (reason === \"variables-changed\") {\n          return initialFetchPolicy;\n        }\n\n        if (\n          currentFetchPolicy === \"network-only\" ||\n          currentFetchPolicy === \"cache-and-network\"\n        ) {\n          // Demote the network policies (except \"no-cache\") to \"cache-first\"\n          // after the first request.\n          return \"cache-first\";\n        }\n\n        // Leave all other fetch policies unchanged.\n        return currentFetchPolicy;\n      },\n    },\n  },\n});\n```\n\nIn order to debug these `nextFetchPolicy` transitions, it can be useful to add `console.log` or `debugger` statements to the function body, to see when and why the function is called.\n\n### Supported fetch policies\n\n<table class=\"field-table\">\n  <thead>\n    <tr>\n      <th>Name</th>\n      <th>Description</th>\n    </tr>\n  </thead>\n  <tbody>\n<tr>\n<td>\n\n###### `cache-first`\n\n(default)\n\n</td>\n<td>\n\nApollo Client first executes the query against the cache. If _all_ requested data is present in the cache, that data is returned. Otherwise, Apollo Client executes the query against your GraphQL server and returns that data after caching it.\n\nPrioritizes minimizing the number of network requests sent by your application.\n\nThis is the default fetch policy.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `cache-only`\n\n</td>\n<td>\n\nApollo Client executes the query _only_ against the cache. It never queries your server in this case.\n\nWhen the cache does not contain data for all requested fields, a `cache-only` query returns `data: undefined` with `dataState: \"empty\"` and a `networkStatus` of `NetworkStatus.ready`.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `cache-and-network`\n\n</td>\n<td>\n\nApollo Client executes the full query against both the cache _and_ your GraphQL server. The query automatically updates if the result of the server-side query modifies cached fields.\n\nProvides a fast response while also helping to keep cached data consistent with server data.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `network-only`\n\n</td>\n<td>\n\nApollo Client executes the full query against your GraphQL server, _without_ first checking the cache. The query's result _is_ stored in the cache. After the first result is received, external cache updates will be reflected by this query.\n\nPrioritizes consistency with server data, but can't provide a near-instantaneous response when cached data is available.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `no-cache`\n\n</td>\n<td>\n\nSimilar to `network-only`, except the query's result _is not_ stored in the cache and external cache updates are completely ignored.\n\n</td>\n</tr>\n\n<tr>\n<td>\n\n###### `standby`\n\n</td>\n<td>\n\nUses the same logic as `cache-first`, except this query does _not_ automatically update when underlying field values change. You can still _manually_ update this query with `refetch` and `updateQueries`.\n\n`standby` queries return `networkStatus: NetworkStatus.ready` even before subscription, providing immediate feedback to your UI.\n\n</td>\n</tr>\n</tbody>\n</table>\n\n<MinVersion version=\"4.0.4\">\n\n## Skipping queries with `skipToken`\n\n</MinVersion>\n\n`skipToken` provides a type-safe mechanism to skip query execution. When you pass `skipToken` to `useQuery` instead of the options object, the hook will not execute the query and keeps the last `data` available. It is typically used conditionally to start query execution when the input data is available.\n\n```js title=\"Recommended usage of skipToken with useQuery\"\nimport { skipToken, useQuery } from \"@apollo/client/react\";\n\nconst { data } = useQuery(query, id ? { variables: { id } } : skipToken);\n```\n\nImagine this common scenario: You want to skip your query if a certain required variable is not set. You might be tempted to write something like this:\n\n```ts\nconst { data } = useQuery(query, {\n  variables: { id },\n  skip: !id,\n});\n```\n\nBut in that case, TypeScript will complain:\n\n```\nType 'number | undefined' is not assignable to type 'number'.\n      Type 'undefined' is not assignable to type 'number'.ts(2769)\n```\n\nTo get around that, you have to tell TypeScript to ignore the fact that `id` could be `undefined`:\n\n```ts\nconst { data } = useQuery(query, {\n  variables: { id: id! },\n  skip: !id,\n});\n```\n\nAlternatively, you could also use some obscure default value:\n\n```ts\nconst { data } = useQuery(query, {\n  variables: { id: id || 0 },\n  skip: !id,\n});\n```\n\nBoth of these solutions hide a potential bug. If your `skip` logic becomes more complex, you might accidentally introduce a bug that causes your query to execute, even when `id` is still `undefined`. In that case, TypeScript cannot warn you about it.\n\nInstead we recommend using `skipToken`. It provides type safety without the need for an obscure default value:\n\n```ts\nconst { data } = useQuery(query, id ? { variables: { id } } : skipToken);\n```\n\nHere it becomes apparent for TypeScript that there is a direct connection between skipping and the `variables` option - and it will work without unsafe workarounds.\n\n## `useQuery` API\n\nSupported options and result fields for the `useQuery` hook are listed below.\n\nMost calls to `useQuery` can omit the majority of these options, but it's useful to know they exist. To learn about the `useQuery` hook API in more detail with usage examples, see the [API reference](../api/react/hooks/#usequery).\n\n### Options\n\nThe `useQuery` hook accepts the following options:\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useQuery.DocumentationTypes.useQuery.Options:interface\"\n  idPrefix=\"queryhookoptions-interface\"\n/>\n\n### Result\n\nAfter being called, the `useQuery` hook returns a result object with the following properties. This object contains your query result, plus some helpful functions for refetching, dynamic polling, and pagination.\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useQuery.DocumentationTypes.useQuery.Result:interface\"\n  idPrefix=\"queryresult-interface\"\n/>\n\n## Next steps\n\nNow that you understand how to fetch data with the `useQuery` hook, [learn how to _update_ your data with the `useMutation` hook!](mutations/)\n\nAfter that, learn about some other handy Apollo Client features:\n\n- [Local state management](../local-state/local-state-management/): Learn how to query local data.\n- [Pagination](../pagination/overview): Learn how to fetch data incrementally from list fields.\n"
  },
  {
    "path": "docs/source/data/refetching.mdx",
    "content": "---\ntitle: Refetching queries in Apollo Client\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\nApollo Client allows you to make local modifications to your GraphQL data by [updating the cache](./mutations/#updating-the-cache-directly), but sometimes it's more straightforward to update your client-side GraphQL data by refetching queries from the server.\n\nIn theory, you could refetch _every_ active query after a client-side update, but you can save time and network bandwidth by refetching queries more selectively. The `InMemoryCache` helps you determine _which_ active queries might have been invalidated by recent cache updates.\n\nLocal cache updates and refetching work especially well in combination: your application can display the results of local cache modifications immediately, while _also_ refetching in the background to obtain the very latest data from the server. The UI is then rerendered only if there are differences between local data and refetched data.\n\nRefetching is especially common after a mutation, so [mutate functions](./mutations/#executing-a-mutation) accept options like [`refetchQueries`](./mutations/#refetching-queries) and [`onQueryUpdated`](./mutations/#refetching-after-update) to specify which queries should be refetched, and how.\n\nTo selectively refetch queries _outside_ of a mutation, you instead use the `refetchQueries` method of `ApolloClient`, which is documented here.\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloClient#refetchQueries:member(1)\"\n  headingLevel={2}\n  displayName=\"client.refetchQueries\"\n>\n\nThe `client.refetchQueries` method collects the `TResult` results returned by `onQueryUpdated`, defaulting to `TResult = Promise<ApolloQueryResult<any>>` if `onQueryUpdated` is not provided. It combines those results into a single `Promise<TResolved[]>` using `Promise.all(results)`.\n\n<Note>\nThanks to the `Promise`-unwrapping behavior of `Promise.all`, this `TResolved` type is often the same type as `TResult`, except when `TResult` is a `PromiseLike<TResolved>` or a `boolean`.\n</Note>\n\nThe returned `Promise` object has two other useful properties:\n\n<InterfaceDetails\n  canonicalReference=\"@apollo/client!ApolloClient.RefetchQueriesResult.AdditionalProperties:interface\"\n  headingLevel={4}\n  displayName=\"ApolloClient.RefetchQueriesResult.AdditionalProperties\"\n/>\n\nThese two arrays parallel each other: they have the same length, and `results[i]` is the result produced by `onQueryUpdated` when called with the `ObservableQuery` found at `queries[i]`, for any index `i`.\n\n</FunctionDetails>\n\n### Refetch recipes\n\n#### Refetching a specific query\n\nTo refetch a specific query by name, use the `include` option by itself:\n\n```ts\nawait client.refetchQueries({\n  include: [\"SomeQueryName\"],\n});\n```\n\nThe `include` option can also refetch a specific query using its `DocumentNode`:\n\n```ts\nawait client.refetchQueries({\n  include: [SOME_QUERY],\n});\n```\n\n#### Refetching all queries\n\n<Note>\n\nThe distinction between \"active\" and \"inactive\" queries:\n\n- **Active queries**: Have at least one subscriber and are not skipped or in `standby`\n- **Inactive queries**: Have a subscriber but are either skipped from a React hook or have a `fetchPolicy` of `standby`\n\n</Note>\n\nTo refetch all _active_ queries, pass the `\"active\"` shorthand for `include`:\n\n```ts\nawait client.refetchQueries({\n  include: \"active\",\n});\n```\n\nOnly queries with active subscribers are registered with the client. This means `refetchQueries` will only affect queries that have at least one subscriber. Queries without subscribers are not tracked and cannot be refetched.\n\n`cache-only` queries are excluded from `refetchQueries` in all situations, including when affected by `updateCache` operations. A `cache-only` query _can_ be refetched however by providing an [`onQueryUpdated` function](#refetching-selectively).\n\nTo refetch _all_ queries managed by Apollo Client, including inactive queries, pass `\"all\"` for for `include`:\n\n```ts\nawait client.refetchQueries({\n  include: \"all\", // Consider using \"active\" instead!\n});\n```\n\n#### Refetching queries affected by cache updates\n\nYou can refetch queries affected by cache updates performed in the `updateCache` callback:\n\n```ts\nawait client.refetchQueries({\n  updateCache(cache) {\n    cache.evict({ fieldName: \"someRootField\" });\n  },\n});\n```\n\nThis refetches any queries that depend on `Query.someRootField`, without requiring you to know in advance which queries might be included. Any combination of cache operations (`writeQuery`, `writeFragment`, `modify`, `evict`, etc.) is allowed within `updateCache`.\n\nUpdates performed by `updateCache` persist in the cache by default. You can perform them in a temporary optimistic layer instead, if you want them to be discarded immediately after `client.refetchQueries` is done observing them, leaving the cache unchanged:\n\n```ts\nawait client.refetchQueries({\n  updateCache(cache) {\n    cache.evict({ fieldName: \"someRootField\" });\n  },\n\n  // Evict Query.someRootField only temporarily, in an optimistic layer.\n  optimistic: true,\n});\n```\n\nAnother way to \"update\" the cache without actually changing cache data is to use `cache.modify` and its `INVALIDATE` sentinel object:\n\n```ts\nawait client.refetchQueries({\n  updateCache(cache) {\n    cache.modify({\n      fields: {\n        someRootField(value, { INVALIDATE }) {\n          // Update queries that involve Query.someRootField, without actually\n          // changing its value in the cache.\n          return INVALIDATE;\n        },\n      },\n    });\n  },\n});\n```\n\n<Note>\n\nBefore `client.refetchQueries` was introduced, the `INVALIDATE` sentinel was [not very useful](https://github.com/apollographql/apollo-client/issues/7060#issuecomment-698026089), because invalidated queries with `fetchPolicy: \"cache-first\"` would typically re-read unchanged results, and therefore decide not to perform a network request. The `client.refetchQueries` method makes this invalidation system more accessible to application code, so you can control the refetching behavior of invalidated queries.\n\n</Note>\n\nIn all of the examples above, whether we use `include` or `updateCache`, `client.refetchQueries` refetches affected queries from the network and includes the resulting `Promise<ApolloQueryResult<any>>` results in the `Promise<TResolved[]>` returned by `client.refetchQueries`.\n\nIf a particular query is included both by `include` and by `updateCache`, that query is refetched only once. In other words, the `include` option is a good way to make sure certain queries are always included, no matter which queries are included by `updateCache`.\n\n#### Refetching selectively\n\nIn development, you probably want to make sure the appropriate queries are getting refetched, rather than blindly refetching them. To intercept each query before refetching, you can specify an `onQueryUpdated` callback:\n\n```ts\nconst results = await client.refetchQueries({\n  updateCache(cache) {\n    cache.evict({ fieldName: \"someRootField\" });\n  },\n\n  onQueryUpdated(observableQuery) {\n    // Logging and/or debugger breakpoints can be useful in development to\n    // understand what client.refetchQueries is doing.\n    console.log(`Examining ObservableQuery ${observableQuery.queryName}`);\n    debugger;\n\n    // Proceed with the default refetching behavior, as if onQueryUpdated\n    // was not provided.\n    return true;\n  },\n});\n\nresults.forEach((result) => {\n  // These results will be ApolloQueryResult<any> objects, after all\n  // results have been refetched from the network.\n});\n```\n\nNotice how adding `onQueryUpdated` in this example did not change the refetching behavior of `client.refetchQueries`, allowing us to use `onQueryUpdated` purely for diagnostic or debugging purposes.\n\nIf you want to skip certain queries that would otherwise be included, return `false` from `onQueryUpdated`:\n\n```ts\nawait client.refetchQueries({\n  updateCache(cache) {\n    cache.evict({ fieldName: \"someRootField\" });\n  },\n\n  onQueryUpdated(observableQuery, { complete, result, missing }) {\n    console.log(\n      `Examining ObservableQuery ${\n        observableQuery.queryName\n      } whose latest result is ${JSON.stringify(result)} which is ${\n        complete ? \"complete\" : \"incomplete\"\n      }`\n    );\n\n    if (shouldIgnoreQuery(observableQuery)) {\n      return false;\n    }\n\n    // Refetch the query unconditionally from the network.\n    return true;\n  },\n});\n```\n\nIn case the `ObservableQuery` does not provide enough information, you can also examine the latest `result` for the query, along with information about its `complete`ness and `missing` fields, using the `Cache.DiffResult` object passed as the second parameter to `onQueryUpdated`:\n\n```ts\nawait client.refetchQueries({\n  updateCache(cache) {\n    cache.evict({ fieldName: \"someRootField\" });\n  },\n\n  onQueryUpdated(observableQuery, { complete, result, missing }) {\n    if (shouldIgnoreQuery(observableQuery)) {\n      return false;\n    }\n\n    if (complete) {\n      // Update the query according to its chosen FetchPolicy, rather than\n      // refetching it unconditionally from the network.\n      return observableQuery.reobserve();\n    }\n\n    // Refetch the query unconditionally from the network.\n    return true;\n  },\n});\n```\n\nBecause `onQueryUpdated` has the ability to filter queries dynamically, it also pairs well with the bulk `include` options mentioned above:\n\n```ts\nawait client.refetchQueries({\n  // Include all active queries by default, which may be ill-advised unless\n  // you also use onQueryUpdated to filter those queries.\n  include: \"active\";\n\n  // Called once for every active query, allowing dynamic filtering:\n  onQueryUpdated(observableQuery) {\n    return !shouldIgnoreQuery(observableQuery);\n  },\n});\n```\n\n#### Handling refetch errors\n\nIn the examples above, we `await client.refetchQueries(...)` to find out the final `ApolloQueryResult<any>` results for all the refetched queries. This combined promise is created with `Promise.all`, so a single failure rejects the entire `Promise<TResolved[]>`, potentially hiding other successful results. If this is a problem, you can use the `queries` and `results` arrays returned by\n`client.refetchQueries` instead of (or in addition to) `await`ing the `Promise`:\n\n```ts\nconst { queries, results } = client.refetchQueries({\n  // Specific client.refetchQueries options are not relevant to this example.\n});\n\nconst finalResults = await Promise.all(\n  results.map((result, i) => {\n    return Promise.resolve(result).catch(error => {\n      console.error(`Error refetching query ${queries[i].queryName}: ${error}`);\n      return null; // Silence this Promise rejection.\n    });\n  })\n});\n```\n\nIn the future, just as additional input options may be added to the `client.refetchQueries` method, additional properties may be added to its result object, supplementing its `Promise`-related properties and the `queries` and `results` arrays.\n\nIf you discover that some specific additional `client.refetchQueries` input options or result properties would be useful, please feel free to [open an issue](https://github.com/apollographql/apollo-feature-requests/issues) explaining your use case(s).\n\n### Corresponding `client.mutate` options\n\nFor refetching after a mutation, `client.mutate` supports [options](./mutations/#options) similar to `client.refetchQueries`, which you should use instead of `client.refetchQueries`, because it's important for refetching logic to happen at specific times during the mutation process.\n\nFor historical reasons, `client.mutate` options have slightly different names from the new `client.refetchQueries` options, but their internal implementation is substantially the same, so you can translate between them using the following table:\n\n| `client.mutate(options)`                                         |     | `client.refetchQueries(options)`         |\n| ---------------------------------------------------------------- | --- | ---------------------------------------- |\n| [`options.refetchQueries`](./mutations/#refetching-queries)      | ⇔   | `options.include`                        |\n| [`options.update`](./mutations/#the-update-function)             | ⇔   | `options.updateCache`                    |\n| [`options.onQueryUpdated`](./mutations/#refetching-after-update) | ⇔   | `options.onQueryUpdated`                 |\n| [`options.awaitRefetchQueries`](./mutations/#options)            | ⇔   | Return a `Promise` from `onQueryUpdated` |\n"
  },
  {
    "path": "docs/source/data/subscriptions.mdx",
    "content": "---\ntitle: Subscriptions\ndescription: Get real-time updates from your GraphQL server\n---\n\n{/* @import {MDXProvidedComponents} from '../../shared/MdxProvidedComponents.js' */}\n\nIn addition to [queries](./queries/) and [mutations](./mutations/), GraphQL supports a third operation type: **subscriptions**.\n\nLike queries, subscriptions enable you to fetch data. _Unlike_ queries, subscriptions are long-lasting operations that can change their result over time. They can maintain an active connection to your GraphQL server (most commonly via WebSocket), enabling the server to push updates to the subscription's result.\n\nSubscriptions are useful for notifying your client in real time about changes to back-end data, such as the creation of a new object or updates to an important field.\n\n## When to use subscriptions\n\nIn the majority of cases, your client should _not_ use subscriptions to stay up to date with your backend. Instead, you should [poll intermittently](./queries/#polling) with queries, or [re-execute queries on demand](./queries/#refetching) when a user performs a relevant action (such as clicking a button).\n\nYou _should_ use subscriptions for the following:\n\n- **Small, incremental changes to large objects**. Repeatedly polling for a large object is expensive, especially when most of the object's fields rarely change. Instead, you can fetch the object's initial state with a query, and your server can proactively push updates to individual fields as they occur.\n\n- **Low-latency, real-time updates**. For example, a chat application's client wants to receive new messages as soon as they're available.\n\n<Note>\n\nSubscriptions cannot be used to listen to local client events, like subscribing to changes in the cache. Subscriptions are intended to be used to subscribe to external data changes, and have those received changes be stored in the cache. You can then leverage Apollo Client's observability model to watch for changes in the cache, using [`client.watchQuery`](../api/core/ApolloClient#ApolloClient.watchQuery), [`useQuery`](../api/react/hooks#usequery), or [`useFragment`](../api/react/useFragment).\n\n</Note>\n\n## Supported subscription protocols\n\nThe GraphQL spec does not define a specific protocol for sending subscription requests. Apollo Client supports the following protocols for subscriptions:\n\n- [**WebSocket**](#websocket-subprotocols), using one of the following subprotocols:\n  - [`graphql-ws`](https://github.com/enisdenjo/graphql-ws)\n  - [`subscriptions-transport-ws`](https://github.com/apollographql/subscriptions-transport-ws) (⚠️ unmaintained)\n- [**HTTP**](#http), using chunked multipart responses\n\n> **You must use the same protocol as the GraphQL endpoint you're communicating with.**\n\n### WebSocket subprotocols\n\nThe first popular JavaScript library to implement subscriptions over WebSocket is called `subscriptions-transport-ws`. **This library is no longer actively maintained.** Its successor is a library called `graphql-ws`. These two libraries _do not use the same WebSocket subprotocol_, so you need to use the same subprotocol that your GraphQL endpoint uses.\n\nThe [WebSocket setup](#websocket-setup) section below uses `graphql-ws`. If your endpoint uses `subscriptions-transport-ws`, see [this section](#the-older-subscriptions-transport-ws-library) for differences in configuration.\n\n> **Note**: Confusingly, the `subscriptions-transport-ws` library calls its _WebSocket subprotocol_ `graphql-ws`, and the `graphql-ws` _library_ calls its subprotocol `graphql-transport-ws`! In this article, we refer to the two _libraries_ (`subscriptions-transport-ws` and `graphql-ws`), _not_ the two subprotocols.\n\n### HTTP\n\nApollo Client provides out-of-the-box support for [multipart subscriptions over HTTP](https://github.com/graphql/graphql-over-http/blob/main/rfcs/IncrementalDelivery.md) when using [`HttpLink`](../api/link/apollo-link-http) as your [terminating link](../api/link/introduction#the-terminating-link). No additional configuration is required! Apollo Client automatically sends the required headers with the request if the terminating `HttpLink` is passed a subscription operation.\n\n#### Usage with Relay\n\nTo consume a multipart subscription over HTTP in an app using Relay, Apollo Client provides network layer adapters that handle the parsing of the multipart response format.\n\n##### Relay\n\n<MultiCodeBlock>\n\n```ts\nimport { createFetchMultipartSubscription } from \"@apollo/client/utilities/subscriptions/relay\";\nimport { Environment, Network, RecordSource, Store } from \"relay-runtime\";\n\nconst fetchMultipartSubs = createFetchMultipartSubscription(\n  \"https://api.example.com\"\n);\n\nconst network = Network.create(fetchQuery, fetchMultipartSubs);\n\nexport const RelayEnvironment = new Environment({\n  network,\n  store: new Store(new RecordSource()),\n});\n```\n\n</MultiCodeBlock>\n\n## Defining a subscription\n\nIn your application's client, you provide a GraphQL document with a `subscription` operation type:\n\n<MultiCodeBlock>\n\n```ts\nconst COMMENTS_SUBSCRIPTION: TypedDocumentNode<\n  OnCommentAddedSubscription,\n  OnCommentAddedSubscriptionVariables\n> = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n```\n\n```js\nconst COMMENTS_SUBSCRIPTION = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n```\n\n</MultiCodeBlock>\n\nWhen Apollo Client executes the `OnCommentAdded` subscription, it establishes a connection to your GraphQL server and listens for response data. Unlike a query, there is no expectation that the server will immediately process and return a response. Instead, your server only pushes data to your client when a particular event occurs on your backend.\n\nWhen your GraphQL server pushes data to the client, that object conforms to the [GraphQL response format](https://spec.graphql.org/October2021/#sec-Response-Format), just like it does for a query:\n\n```json\n{\n  \"data\": {\n    \"commentAdded\": {\n      \"id\": \"123\",\n      \"content\": \"What a thoughtful and well written post!\"\n    }\n  }\n}\n```\n\n## WebSocket setup\n\n### 1. Install required libraries\n\n[Apollo Link](../api/link/introduction/) is a library that helps you customize Apollo Client's network communication. You can use it to define a **link chain** that modifies your operations and routes them to the appropriate destination.\n\nTo execute subscriptions over WebSocket, you can add a `GraphQLWsLink` to your link chain. This link requires the `graphql-ws` library. Install it like so:\n\n```bash\nnpm install graphql-ws\n```\n\n### 2. Initialize a `GraphQLWsLink`\n\nImport and initialize a `GraphQLWsLink` object in the same project file where you initialize `ApolloClient`:\n\n<MultiCodeBlock>\n\n```ts title=\"index.ts\"\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\nconst wsLink = new GraphQLWsLink(\n  createClient({\n    url: \"ws://localhost:4000/subscriptions\",\n  })\n);\n```\n\n</MultiCodeBlock>\n\nReplace the value of the `url` option with your GraphQL server's subscription-specific WebSocket endpoint. If you're using Apollo Server, see [Setting a subscription endpoint](/apollo-server/data/subscriptions/#enabling-subscriptions).\n\n### 3. Split communication by operation (recommended)\n\nAlthough Apollo Client can use your `GraphQLWsLink` to execute all operation types, in most cases it should continue using HTTP for queries and mutations. This is because queries and mutations don't require a stateful or long-lasting connection, making HTTP more efficient and scalable if a WebSocket connection isn't already present.\n\nTo support this, the `@apollo/client` library provides a `split` function that lets you use one of two different `Link`s, according to the result of a boolean check.\n\nThe following example expands on the previous one by initializing both a `GraphQLWsLink` _and_ an `HttpLink`. It then uses the `split` function to combine those two `Link`s into a _single_ `Link` that uses one or the other according to the type of operation being executed.\n\n<MultiCodeBlock>\n\n```ts title=\"index.ts\"\nimport { OperationTypeNode } from \"graphql\";\nimport { ApolloLink, HttpLink } from \"@apollo/client\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\nconst httpLink = new HttpLink({\n  uri: \"http://localhost:4000/graphql\",\n});\n\nconst wsLink = new GraphQLWsLink(\n  createClient({\n    url: \"ws://localhost:4000/subscriptions\",\n  })\n);\n\n// The split function takes three parameters:\n//\n// * A function that's called for each operation to execute\n// * The Link to use for an operation if the function returns a \"truthy\" value\n// * The Link to use for an operation if the function returns a \"falsy\" value\nconst splitLink = ApolloLink.split(\n  ({ operationType }) => {\n    return operationType === OperationTypeNode.SUBSCRIPTION;\n  },\n  wsLink,\n  httpLink\n);\n```\n\n</MultiCodeBlock>\n\nUsing this logic, queries and mutations will use HTTP as normal, and subscriptions will use WebSocket.\n\n### 4. Provide the link chain to Apollo Client\n\nAfter you define your link chain, you provide it to Apollo Client via the `link` constructor option:\n\n<MultiCodeBlock>\n\n```ts {6} title=\"index.ts\"\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\n// ...code from the above example goes here...\n\nconst client = new ApolloClient({\n  link: splitLink,\n  cache: new InMemoryCache(),\n});\n```\n\n```js {6} title=\"index.js\"\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\n// ...code from the above example goes here...\n\nconst client = new ApolloClient({\n  link: splitLink,\n  cache: new InMemoryCache(),\n});\n```\n\n</MultiCodeBlock>\n\n### 5. Authenticate over WebSocket (optional)\n\nIt is often necessary to authenticate a client before allowing it to receive subscription results. To do this, you can provide a `connectionParams` option to the `GraphQLWsLink` constructor, like so:\n\n<MultiCodeBlock>\n\n```ts {6-8}\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\nconst wsLink = new GraphQLWsLink(\n  createClient({\n    url: \"ws://localhost:4000/subscriptions\",\n    connectionParams: {\n      authToken: user.authToken,\n    },\n  })\n);\n```\n\n```js {6-8}\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport { createClient } from \"graphql-ws\";\n\nconst wsLink = new GraphQLWsLink(\n  createClient({\n    url: \"ws://localhost:4000/subscriptions\",\n    connectionParams: {\n      authToken: user.authToken,\n    },\n  })\n);\n```\n\n</MultiCodeBlock>\n\nYour `GraphQLWsLink` passes the `connectionParams` object to your server whenever it connects. Your server receives the `connectionParams` object and can use it to perform authentication, along with any other connection-related tasks.\n\n## Subscriptions via multipart HTTP\n\nNo additional libraries or configuration are required. Apollo Client adds the required headers to your request when the default terminating `HTTPLink` receives a subscription operation at the `uri` specified when initializing the link or Apollo Client instance.\n\n<Note>\n\nIn order to use subscriptions over multipart HTTP in a React Native application, additional configuration is required. See the [React Native docs](../integrations/react-native#consuming-multipart-http-via-text-streaming) for more information.\n\n</Note>\n\n## Executing a subscription\n\nYou use the [`useSubscription`](../api/react/useSubscription) hook to execute a subscription. Like [`useQuery`](./queries/#executing-a-query), `useSubscription` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.\n\nThe following example component uses the subscription we defined earlier to render the most recent comment that's been added to a specified blog post. Whenever the GraphQL server pushes a new comment to the client, the component re-renders with the new comment.\n\n<MultiCodeBlock>\n\n```tsx\nconst COMMENTS_SUBSCRIPTION: TypedDocumentNode<\n  OnCommentAddedSubscription,\n  OnCommentAddedSubscriptionVariables\n> = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n\nfunction LatestComment({ postID }: LatestCommentProps) {\n  const { data, loading } = useSubscription(COMMENTS_SUBSCRIPTION, {\n    variables: { postID },\n  });\n\n  return <h4>New comment: {!loading && data.commentAdded.content}</h4>;\n}\n```\n\n```jsx\nconst COMMENTS_SUBSCRIPTION = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n\nfunction LatestComment({ postID }) {\n  const { data, loading } = useSubscription(COMMENTS_SUBSCRIPTION, {\n    variables: { postID },\n  });\n\n  return <h4>New comment: {!loading && data.commentAdded.content}</h4>;\n}\n```\n\n</MultiCodeBlock>\n\n## Handling errors in subscriptions\n\n### Error handling with `useSubscription`\n\nWhen using the `useSubscription` hook, errors are returned in the `error` property of the result object:\n\n<MultiCodeBlock>\n\n```tsx\nfunction LatestComment({ postID }: LatestCommentProps) {\n  const { data, loading, error } = useSubscription(COMMENTS_SUBSCRIPTION, {\n    variables: { postID },\n  });\n\n  if (error) {\n    return <div>Error: {error.message}</div>;\n  }\n\n  return <h4>New comment: {!loading && data?.commentAdded.content}</h4>;\n}\n```\n\n```jsx\nfunction LatestComment({ postID }) {\n  const { data, loading, error } = useSubscription(COMMENTS_SUBSCRIPTION, {\n    variables: { postID },\n  });\n\n  if (error) {\n    return <div>Error: {error.message}</div>;\n  }\n\n  return <h4>New comment: {!loading && data?.commentAdded.content}</h4>;\n}\n```\n\n</MultiCodeBlock>\n\n### Error handling with `client.subscribe()`\n\nWhen using `client.subscribe()` directly, all errors are delivered through the `next` callback in `result.error`. The `error` callback is never called:\n\n```ts\nclient.subscribe({ query: COMMENTS_SUBSCRIPTION }).subscribe({\n  next: (result) => {\n    if (result.error) {\n      // All errors are delivered here\n      console.log(\"Error:\", result.error.message);\n    }\n    // result.data may be undefined (with errorPolicy: 'none')\n    // or may contain partial data (with errorPolicy: 'all')\n  },\n  complete: () => {\n    // Called when the subscription terminates\n    console.log(\"Subscription completed\");\n  },\n});\n```\n\nThis behavior ensures that subscriptions can continue running even after encountering errors, allowing your server to send valid data after an error occurs. If an error causes the connection to terminate, the error is emitted through `next`, followed by a `complete` notification.\n\n### Error policies with subscriptions\n\nYou can control how Apollo Client handles partial data when GraphQL errors occur by setting an [`errorPolicy`](./error-handling/#graphql-error-policies):\n\n- **`errorPolicy: 'none'`** (default) - `result.data` is `undefined` when errors occur, and `result.error` contains the error.\n- **`errorPolicy: 'all'`** - Both `result.data` (with partial data) and `result.error` are populated.\n- **`errorPolicy: 'ignore'`** - Errors are ignored, and `result.error` is `undefined`.\n\n```ts\nuseSubscription(COMMENTS_SUBSCRIPTION, {\n  errorPolicy: \"all\", // Receive both partial data and errors\n});\n```\n\nLearn more about error handling in the [Error handling documentation](./error-handling/).\n\n## Subscribing to updates for a query\n\nWhenever a query returns a result in Apollo Client, that result includes a `subscribeToMore` function. You can use this function to execute a followup subscription that pushes updates to the query's original result.\n\n<Note>\n\nThe `subscribeToMore` function is similar in structure to the [`fetchMore`](../caching/advanced-topics/#incremental-loading-fetchmore) function that's commonly used for handling pagination. The primary difference is that `fetchMore` executes a followup _query_, whereas `subscribeToMore` executes a subscription.\n\n</Note>\n\nAs an example, let's start with a standard query that fetches all of the existing comments for a given blog post:\n\n<MultiCodeBlock>\n\n```tsx\nconst COMMENTS_QUERY: TypedDocumentNode<\n  CommentsForPostQuery,\n  CommentsForPostQueryVariables\n> = gql`\n  query CommentsForPost($postID: ID!) {\n    post(postID: $postID) {\n      comments {\n        id\n        content\n      }\n    }\n  }\n`;\n\nfunction CommentsPageWithData({ params }: CommentsPageWithDataProps) {\n  const result = useQuery(COMMENTS_QUERY, {\n    variables: { postID: params.postID },\n  });\n\n  return <CommentsPage {...result} />;\n}\n```\n\n```jsx\nconst COMMENTS_QUERY = gql`\n  query CommentsForPost($postID: ID!) {\n    post(postID: $postID) {\n      comments {\n        id\n        content\n      }\n    }\n  }\n`;\n\nfunction CommentsPageWithData({ params }) {\n  const result = useQuery(COMMENTS_QUERY, {\n    variables: { postID: params.postID },\n  });\n\n  return <CommentsPage {...result} />;\n}\n```\n\n</MultiCodeBlock>\n\nLet's say we want our GraphQL server to push an update to our client as soon as a _new_ comment is added to the post. First we need to define the subscription that Apollo Client will execute when the `COMMENTS_QUERY` returns:\n\n<MultiCodeBlock>\n\n```tsx\nconst COMMENTS_SUBSCRIPTION: TypedDocumentNode<\n  OnCommentAddedSubscription,\n  OnCommentAddedSubscriptionVariables\n> = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n```\n\n```jsx\nconst COMMENTS_SUBSCRIPTION = gql`\n  subscription OnCommentAdded($postID: ID!) {\n    commentAdded(postID: $postID) {\n      id\n      content\n    }\n  }\n`;\n```\n\n</MultiCodeBlock>\n\nNext, we modify our `CommentsPageWithData` component to call `subscribeToMore` after the comments query loads.\n\n<MultiCodeBlock>\n\n```tsx {10-23}\nfunction CommentsPageWithData({ params }: CommentsPageWithDataProps) {\n  const { subscribeToMore, ...result } = useQuery(COMMENTS_QUERY, {\n    variables: { postID: params.postID },\n  });\n\n  useEffect(() => {\n    // This assumes you want to wait to start the subscription\n    // after the query has loaded.\n    if (result.data) {\n      const unsubscribe = subscribeToMore({\n        document: COMMENTS_SUBSCRIPTION,\n        variables: { postID: params.postID },\n        updateQuery: (prev, { subscriptionData }) => {\n          if (!subscriptionData.data) return prev;\n          const newFeedItem = subscriptionData.data.commentAdded;\n\n          return Object.assign({}, prev, {\n            post: {\n              comments: [newFeedItem, ...prev.post.comments],\n            },\n          });\n        },\n      });\n\n      return () => {\n        unsubscribe();\n      };\n    }\n  }, [result.data, params.postID, subscribeToMore]);\n\n  return <CommentsPage {...result} />;\n}\n```\n\n```jsx {10-25}\nfunction CommentsPageWithData({ params }) {\n  const { subscribeToMore, ...result } = useQuery(COMMENTS_QUERY, {\n    variables: { postID: params.postID },\n  });\n\n  useEffect(() => {\n    if (result.data) {\n      const unsubscribe = subscribeToMore({\n        document: COMMENTS_SUBSCRIPTION,\n        variables: { postID: params.postID },\n        updateQuery: (prev, { subscriptionData }) => {\n          if (!subscriptionData.data) return prev;\n          const newFeedItem = subscriptionData.data.commentAdded;\n\n          return Object.assign({}, prev, {\n            post: {\n              comments: [newFeedItem, ...prev.post.comments],\n            },\n          });\n        },\n      });\n\n      return () => {\n        unsubscribe();\n      };\n    }\n  }, [result.data, params.postID]);\n\n  return <CommentsPage {...result} />;\n}\n```\n\n</MultiCodeBlock>\n\nIn the example above, we pass three options to `subscribeToMore`:\n\n- `document` indicates the subscription to execute.\n- `variables` indicates the variables to include when executing the subscription.\n- `updateQuery` is a function that tells Apollo Client how to combine the query's currently cached result (`prev`) with the `subscriptionData` that's pushed by our GraphQL server. The return value of this function **completely replaces** the current cached result for the query.\n\n## `useSubscription` API reference\n\n### Options\n\nThe `useSubscription` Hook accepts the following options:\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useSubscription.DocumentationTypes.useSubscription.Options:interface\"\n  idPrefix=\"subscriptionhookoptions-interface\"\n/>\n\n### Result\n\nAfter being called, the `useSubscription` Hook returns a result object with the following properties:\n\n<PropertySignatureTable\n  canonicalReference=\"@apollo/client/react!useSubscription.Result:interface\"\n  idPrefix=\"subscriptionresult-interface\"\n/>\n\n## The older `subscriptions-transport-ws` library\n\nIf your server uses `subscriptions-transport-ws` instead of the newer `graphql-ws` library, you need to make a few changes to how you set up your link:\n\n1. Instead of `npm install graphql-ws`:\n\n   ```bash\n   npm install subscriptions-transport-ws\n   ```\n\n2. Instead of `import { createClient } from 'graphql-ws'`:\n\n   ```js\n   import { SubscriptionClient } from \"subscriptions-transport-ws\";\n   ```\n\n3. Instead of `import { GraphQLWsLink } from '@apollo/client/link/subscriptions'`:\n\n   ```js\n   import { WebSocketLink } from \"@apollo/client/link/ws\";\n   ```\n\n4. The options you pass to `new SubscriptionClient` differ slightly from those passed to `createClient`:\n\n   - The first argument passed to the `SubscriptionClient` constructor is the URL for your subscription server.\n   - The `connectionParams` option is nested under an options object called `options` instead of being at the top level. (You can also pass the `new SubscriptionClient` constructor arguments directly to `new WebSocketLink`.)\n   - See [the `subscriptions-transport-ws` README](https://www.npmjs.com/package/subscriptions-transport-ws) for complete `SubscriptionClient` API docs.\n\nAfter you create your `wsLink`, everything else in this article still applies: `useSubscription`, `subscribeToMore`, and split links work exactly the same way for both implementations.\n\nThe following is an example of a typical `WebSocketLink` initialization:\n\n<MultiCodeBlock>\n\n```ts\nimport { WebSocketLink } from \"@apollo/client/link/ws\";\nimport { SubscriptionClient } from \"subscriptions-transport-ws\";\n\nconst wsLink = new WebSocketLink(\n  new SubscriptionClient(\"ws://localhost:4000/subscriptions\", {\n    connectionParams: {\n      authToken: user.authToken,\n    },\n  })\n);\n```\n\n</MultiCodeBlock>\n\nMore details on `WebSocketLink`'s API can be found in [its API docs](../api/link/apollo-link-ws).\n"
  },
  {
    "path": "docs/source/data/suspense.mdx",
    "content": "---\ntitle: Suspense\ndescription: Use React 18 Suspense features with Apollo Client\n---\n\n\"Suspense\" is generally used to refer to a new way of building React apps using the [**concurrent rendering engine**](https://react.dev/blog/2022/03/29/react-v18#what-is-concurrent-react) introduced in React 18. It's also a specific React API, [`<Suspense />`](https://react.dev/reference/react/Suspense), a component that lets you display a fallback until its children have finished loading.\n\nThis guide explores Apollo Client's data fetching hooks, which leverage React's powerful Suspense features.\n\n> To follow along with the examples below, open up our [Suspense demo](https://codesandbox.io/s/github/apollographql/docs-examples/tree/main/apollo-client/v3/suspense-hooks?file=/src/App.tsx) on CodeSandbox.\n\n## Fetching with Suspense\n\nThe `useSuspenseQuery` hook initiates a network request and causes the component calling it to suspend while the request is made. You can think of it as a Suspense-ready replacement for `useQuery` that lets you take advantage of React's Suspense features while fetching during render.\n\nLet's take a look at an example:\n\n```tsx {3,36,38,43-45}\nimport { Suspense } from \"react\";\nimport { gql, TypedDocumentNode } from \"@apollo/client\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\n\ninterface Data {\n  dog: {\n    id: string;\n    name: string;\n  };\n}\n\ninterface Variables {\n  id: string;\n}\n\ninterface DogProps {\n  id: string;\n}\n\nconst GET_DOG_QUERY: TypedDocumentNode<Data, Variables> = gql`\n  query GetDog($id: String) {\n    dog(id: $id) {\n      # By default, an object's cache key is a combination of\n      # its __typename and id fields, so we should always make\n      # sure the id is in the response so our data can be\n      # properly cached.\n      id\n      name\n      breed\n    }\n  }\n`;\n\nfunction App() {\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog id=\"3\" />\n    </Suspense>\n  );\n}\n\nfunction Dog({ id }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n  });\n\n  return <>Name: {data.dog.name}</>;\n}\n```\n\n<Note>\n\nThis example manually defines TypeScript interfaces for `Data` and `Variables` as well as the type for `GET_DOG_QUERY` using `TypedDocumentNode`. [GraphQL Code Generator](https://www.the-guild.dev/graphql/codegen) is a popular tool that creates these type definitions automatically for you. See the reference on [Using TypeScript](../development-testing/static-typing) for more information on integrating GraphQL Code Generator with Apollo Client.\n\n</Note>\n\nIn this example, our `App` component renders a `Dog` component which fetches the record for a single dog via `useSuspenseQuery`. When React attempts to render `Dog` for the first time, the cache is unable to fulfill the request for the `GetDog` query, so `useSuspenseQuery` initiates a network request. `Dog` suspends while the network request is pending, triggering the nearest `Suspense` boundary _above_ the suspended component in `App` which renders our \"Loading...\" fallback. Once the network request is complete, `Dog` renders with the newly cached `name` for Mozzarella the Corgi.\n\nYou may have noticed that `useSuspenseQuery` does not return a `loading` boolean. That's because the component calling `useSuspenseQuery` always suspends when fetching data. A corollary is that when it _does_ render, `data` is always defined! In the Suspense paradigm, fallbacks that exist **outside of suspended components** replace the loading states components were previously responsible for rendering themselves.\n\n<Note>\n\n**For TypeScript users**: Since `GET_DOG_QUERY` is a `TypedDocumentNode` in which we have specified the result type via `Data` generic type argument, the TypeScript type for `data` returned by `useSuspenseQuery` reflects that! This means that `data` is guaranteed to be defined when `Dog` renders, and that `data.dog` has the shape `{ id: string; name: string; breed: string; }`.\n\n</Note>\n\n### Changing variables\n\nIn the previous example, we fetched the record for a single dog by passing a hard-coded `id` variable to `useSuspenseQuery`. Now, let's say we want to fetch the record for a different dog using a dynamic value. We'll fetch the `name` and `id` for our list of dogs, and once the user selects an individual dog, we fetch more details, including their `breed`.\n\nLet's update our example:\n\n```tsx {22,26,34,41-43}\nexport const GET_DOG_QUERY: TypedDocumentNode<DogData, Variables> = gql`\n  query GetDog($id: String) {\n    dog(id: $id) {\n      id\n      name\n      breed\n    }\n  }\n`;\n\nexport const GET_DOGS_QUERY: TypedDocumentNode<DogsData, Variables> = gql`\n  query GetDogs {\n    dogs {\n      id\n      name\n    }\n  }\n`;\n\nfunction App() {\n  const { data } = useSuspenseQuery(GET_DOGS_QUERY);\n  const [selectedDog, setSelectedDog] = useState(data.dogs[0].id);\n\n  return (\n    <>\n      <select onChange={(e) => setSelectedDog(e.target.value)}>\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog id={selectedDog} />\n      </Suspense>\n    </>\n  );\n}\n\nfunction Dog({ id }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n  });\n\n  return (\n    <>\n      <div>Name: {data.dog.name}</div>\n      <div>Breed: {data.dog.breed}</div>\n    </>\n  );\n}\n```\n\nChanging the dog via the `select` causes the component to suspend each time we select a dog whose record **does not yet exist in the cache**. Once we've loaded a given dog's record in the cache, selecting that dog again from our dropdown does not cause the component to re-suspend, since under our default `cache-first` fetch policy Apollo Client does not make a network request after a cache hit.\n\n### Updating state without suspending\n\nSometimes we may want to avoid showing a loading UI in response to a pending network request and instead prefer to continue displaying the previous render. To do this, we can use a [_transition_](https://react.dev/blog/2022/03/29/react-v18#new-feature-transitions) to mark our update as non-urgent. This tells React to keep the existing UI in place until the new data has finished loading.\n\nTo mark a state update as a transition, we use the [`startTransition`](https://react.dev/reference/react/startTransition) function from React.\n\nLet's modify our example so that the previously displayed dog remains on the screen while the next one is fetched in a transition:\n\n```tsx {1,11-13}\nimport { useState, Suspense, startTransition } from \"react\";\n\nfunction App() {\n  const { data } = useSuspenseQuery(GET_DOGS_QUERY);\n  const [selectedDog, setSelectedDog] = useState(data.dogs[0].id);\n\n  return (\n    <>\n      <select\n        onChange={(e) => {\n          startTransition(() => {\n            setSelectedDog(e.target.value);\n          });\n        }}\n      >\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog id={selectedDog} />\n      </Suspense>\n    </>\n  );\n}\n```\n\nBy wrapping our `setSelectedDog` state update in React's `startTransition` function, we no longer see the Suspense fallback when selecting a new dog! Instead, the previous dog remains on the screen until the next dog's record has finished loading.\n\n### Showing pending UI during a transition\n\nIn the previous example, there is no visual indication that a fetch is happening when a new dog is selected. To provide nice visual feedback, let's update our example to use React's [`useTransition`](https://react.dev/reference/react/useTransition) hook which gives you an `isPending` boolean value to determine when a transition is happening.\n\nLet's dim the select dropdown while the transition is happening:\n\n```tsx {1,4,11}\nimport { useState, Suspense, useTransition } from \"react\";\n\nfunction App() {\n  const [isPending, startTransition] = useTransition();\n  const { data } = useSuspenseQuery(GET_DOGS_QUERY);\n  const [selectedDog, setSelectedDog] = useState(data.dogs[0].id);\n\n  return (\n    <>\n      <select\n        style={{ opacity: isPending ? 0.5 : 1 }}\n        onChange={(e) => {\n          startTransition(() => {\n            setSelectedDog(e.target.value);\n          });\n        }}\n      >\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog id={selectedDog} />\n      </Suspense>\n    </>\n  );\n}\n```\n\n### Rendering partial data\n\nWhen the cache contains partial data, you may prefer to render that data immediately without suspending. To do this, use the `returnPartialData` option.\n\n<Note>\n\nThis option only works when combined with either the `cache-first` (default) or `cache-and-network` fetch policy. `cache-only` isn't currently supported by `useSuspenseQuery`. For details on these fetch policies, see [Setting a fetch policy](/react/data/queries/#setting-a-fetch-policy).\n\n</Note>\n\nLet's update our example to use the partial cache data and render immediately:\n\n```tsx {38}\ninterface PartialData {\n  dog: {\n    id: string;\n    name: string;\n  };\n}\n\nconst PARTIAL_GET_DOG_QUERY: TypedDocumentNode<PartialData, Variables> = gql`\n  query GetDog($id: String) {\n    dog(id: $id) {\n      id\n      name\n    }\n  }\n`;\n\n// Write partial data for Buck to the cache\n// so it is available when Dog renders\nclient.writeQuery({\n  query: PARTIAL_GET_DOG_QUERY,\n  variables: { id: \"1\" },\n  data: { dog: { id: \"1\", name: \"Buck\" } },\n});\n\nfunction App() {\n  const client = useApolloClient();\n\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog id=\"1\" />\n    </Suspense>\n  );\n}\n\nfunction Dog({ id }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n    returnPartialData: true,\n  });\n\n  return (\n    <>\n      <div>Name: {data?.dog?.name}</div>\n      <div>Breed: {data?.dog?.breed}</div>\n    </>\n  );\n}\n```\n\nIn this example, we write partial data to the cache for Buck in order to show the behavior when a query cannot be entirely fulfilled from the cache. We tell `useSuspenseQuery` that we are ok rendering partial data by setting the `returnPartialData` option to `true`. When `Dog` renders for the first time, it does not suspend and uses the partial data immediately. Apollo Client then fetches the missing query data from the network in the background.\n\nOn first render, Buck's name is displayed after the `Name` label, followed by the `Breed` label with no value. Once the missing fields have loaded, `useSuspenseQuery` triggers a re-render and Buck's breed is displayed.\n\n<Note>\n\n**For TypeScript users**: With `returnPartialData` set to `true`, the returned type for the `data` property marks all fields in the query type as [optional](https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties). Apollo Client cannot accurately determine which fields are present in the cache at any given time when returning partial data.\n\n</Note>\n\n### Error handling\n\nBy default, both network errors and GraphQL errors are thrown by `useSuspenseQuery`. These errors are caught and displayed by the closest [error boundary](https://react.dev/reference/react/Component#static-getderivedstatefromerror).\n\n<Note>\n\nAn error boundary is a **class component** that implements `static getDerivedStateFromError`. For more information, see the React docs for [catching rendering errors with an error boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary).\n\n</Note>\n\nLet's create a basic error boundary that renders an error UI when errors are thrown by our query:\n\n```tsx\nclass ErrorBoundary extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = { hasError: false };\n  }\n\n  static getDerivedStateFromError(error) {\n    return { hasError: true };\n  }\n\n  render() {\n    if (this.state.hasError) {\n      return this.props.fallback;\n    }\n\n    return this.props.children;\n  }\n}\n```\n\n<Note>\n\nIn a real application, your error boundary might need a more robust implementation. Consider using a library like [`react-error-boundary`](https://github.com/bvaughn/react-error-boundary) when you need a high degree of flexibility and reusability.\n\n</Note>\n\nWhen the `GET_DOG_QUERY` inside of the `Dog` component returns a GraphQL error or a network error, `useSuspenseQuery` throws the error and the nearest error boundary renders its fallback component.\n\nOur example doesn't have an error boundary yet—let's add one!\n\n```tsx {14,18}\nfunction App() {\n  const { data } = useSuspenseQuery(GET_DOGS_QUERY);\n  const [selectedDog, setSelectedDog] = useState(data.dogs[0].id);\n\n  return (\n    <>\n      <select onChange={(e) => setSelectedDog(e.target.value)}>\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <ErrorBoundary fallback={<div>Something went wrong</div>}>\n        <Suspense fallback={<div>Loading...</div>}>\n          <Dog id={selectedDog} />\n        </Suspense>\n      </ErrorBoundary>\n    </>\n  );\n}\n```\n\nHere, we're using our `ErrorBoundary` component and placing it **outside** of our `Dog` component. Now, when the `useSuspenseQuery` hook inside the `Dog` component throws an error, the `ErrorBoundary` catches it and displays the `fallback` element we've provided.\n\n<Note>\n\nWhen working with some React frameworks, you may see an error dialog overlay in development mode when errors are thrown, even _with_ an error boundary. This is done to avoid the error being missed by developers.\n\n</Note>\n\n#### Rendering partial data alongside errors\n\nIn some cases, you may want to render partial data alongside an error. To do this, set the `errorPolicy` option to `all`. By setting this option, `useSuspenseQuery` avoids throwing the error and instead sets an `error` property returned by the hook. To ignore errors altogether, set the `errorPolicy` to `ignore`. See the [`errorPolicy` documentation](/react/data/error-handling#graphql-error-policies) for more information.\n\n### Avoiding request waterfalls\n\nSince `useSuspenseQuery` suspends while data is being fetched, a tree of components that all use `useSuspenseQuery` can cause a \"waterfall\", where each call to `useSuspenseQuery` depends on the previous to complete before it can start fetching. This can be avoided by fetching with `useBackgroundQuery` and reading the data with `useReadQuery`.\n\n`useBackgroundQuery` initiates a request for data in a parent component and returns a `queryRef` which is passed to `useReadQuery` to read the data in a child component. When the child component renders before the data has finished loading, the child component suspends.\n\nLet's update our example to utilize `useBackgroundQuery`:\n\n```tsx {2-3,10,35,39}\nimport {\n  useBackgroundQuery,\n  useReadQuery,\n  useSuspenseQuery,\n} from \"@apollo/client/react\";\n\nfunction App() {\n  // We can start the request here, even though `Dog`\n  // suspends and the data is read by a grandchild component.\n  const [queryRef] = useBackgroundQuery(GET_BREEDS_QUERY);\n\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog id=\"3\" queryRef={queryRef} />\n    </Suspense>\n  );\n}\n\nfunction Dog({ id, queryRef }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n  });\n\n  return (\n    <>\n      Name: {data.dog.name}\n      <Suspense fallback={<div>Loading breeds...</div>}>\n        <Breeds queryRef={queryRef} />\n      </Suspense>\n    </>\n  );\n}\n\ninterface BreedsProps {\n  queryRef: QueryRef<BreedData>;\n}\n\nfunction Breeds({ queryRef }: BreedsProps) {\n  const { data } = useReadQuery(queryRef);\n\n  return data.breeds.map(({ characteristics }) =>\n    characteristics.map((characteristic) => (\n      <div key={characteristic}>{characteristic}</div>\n    ))\n  );\n}\n```\n\nWe begin fetching our `GET_BREEDS_QUERY` when the `App` component renders. The network request is made in the background while React renders the rest of our component tree. When the `Dog` component renders, it fetches our `GET_DOG_QUERY` and suspends.\n\nWhen the network request for `GET_DOG_QUERY` completes, the `Dog` component unsuspends and continues rendering, reaching the `Breeds` component. Since our `GET_BREEDS_QUERY` request was initiated higher up in our component tree using `useBackgroundQuery`, the network request for `GET_BREEDS_QUERY` **has already completed**! When the `Breeds` component reads the data from the `queryRef` provided by `useBackgroundQuery`, it avoids suspending and renders immediately with the fetched data.\n\n<Note>\n\nWhen the `GET_BREEDS_QUERY` takes _longer_ to fetch than our `GET_DOG_QUERY`, `useReadQuery` suspends and the Suspense fallback inside of the `Dog` component is rendered instead.\n\n</Note>\n\n#### A note about performance\n\nThe `useBackgroundQuery` hook used in a parent component is responsible for kicking off fetches, but doesn't deal with reading or rendering data. This is delegated to the `useReadQuery` hook used in a child component. This separation of concerns provides a nice performance benefit because cache updates are observed by `useReadQuery` and re-render only the child component. You may find this as a useful tool to optimize your component structure to avoid unnecessarily re-rendering parent components when cache data changes.\n\n### Fetching in response to user interaction\n\nThe `useSuspenseQuery` and `useBackgroundQuery` hooks let us load data as soon as the component calling the hook mounts. But what about loading a query in response to user interaction? For example, we may want to start loading some data when a user hovers on a link.\n\nThe `useLoadableQuery` hook initiates a network request in response to user interaction. `useLoadableQuery` returns both an execution function and a `queryRef`. The execution function initiates a network request when called with the provided variables. Like `useBackgroundQuery`, passing the `queryRef` to `useReadQuery` in a child component suspends the child component until the query finishes loading.\n\n<Note>\n\nThe `queryRef` is `null` until the execution function is called for the first time. For this reason, any child components attempting to read data using the `queryRef` should be conditionally rendered.\n\n</Note>\n\nLet's update our example to start loading the dog's details as a result of selecting from a dropdown.\n\n```tsx {3,8,12,20,27}\nimport {\n  // ...\n  useLoadableQuery,\n} from \"@apollo/client/react\";\n\nfunction App() {\n  const { data } = useSuspenseQuery(GET_DOGS_QUERY);\n  const [loadDog, queryRef] = useLoadableQuery(GET_DOG_QUERY);\n\n  return (\n    <>\n      <select onChange={(e) => loadDog({ id: e.target.value })}>\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <Suspense fallback={<div>Loading...</div>}>\n        {queryRef && <Dog queryRef={queryRef} />}\n      </Suspense>\n    </>\n  );\n}\n\nfunction Dog({ queryRef }: DogProps) {\n  const { data } = useReadQuery(queryRef);\n\n  return (\n    <>\n      <div>Name: {data.dog.name}</div>\n      <div>Breed: {data.dog.breed}</div>\n    </>\n  );\n}\n```\n\nWe begin fetching our `GET_DOG_QUERY` by calling the `loadDog` function inside of the `onChange` handler function when a dog is selected. Once the network request is initiated, the `queryRef` is no longer `null`, rendering the `Dog` component.\n\n`useReadQuery` suspends the `Dog` component while the network request finishes, then returns `data` to the component. As a result of this change, we've also eliminated the need to track the selected dog `id` in component state.\n\n### Initiating queries outside React\n\nQueries can be initiated outside of React. This allows your app to begin fetching data before React renders your components, and can provide additional performance benefits.\n\nTo preload queries, you first need to create a preload function with `createQueryPreloader`. `createQueryPreloader` takes an `ApolloClient` instance as an argument and returns a function that, when called, initiates a network request.\n\n<Tip>\n\nConsider exporting your preload function along with your `ApolloClient` instance. This allows you to import that function directly without having to pass around your `ApolloClient` instance each time you preload a query.\n\n</Tip>\n\nThe preload function returns a `queryRef` that is passed to `useReadQuery` to read the query data and suspend the component while loading. `useReadQuery` ensures that your component is kept up-to-date with cache updates for the preloaded query.\n\nLet's update our example to start loading the `GET_DOGS_QUERY` before our app is rendered.\n\n```tsx {3,9-10,13,36,38}\nimport {\n  // ...\n  createQueryPreloader,\n} from \"@apollo/client/react\";\n\n// This `preloadQuery` function does not have to be created each time you\n// need to preload a new query. You may prefer to export this function\n// alongside your client instead.\nconst preloadQuery = createQueryPreloader(client);\nconst preloadedQueryRef = preloadQuery(GET_DOGS_QUERY);\n\nfunction App() {\n  const { data } = useReadQuery(preloadedQueryRef);\n  const [loadDog, queryRef] = useLoadableQuery(GET_DOG_QUERY);\n\n  return (\n    <>\n      <select onChange={(e) => loadDog({ id: e.target.value })}>\n        {data.dogs.map(({ id, name }) => (\n          <option key={id} value={id}>\n            {name}\n          </option>\n        ))}\n      </select>\n      <Suspense fallback={<div>Loading...</div>}>\n        <Dog queryRef={queryRef} />\n      </Suspense>\n    </>\n  );\n}\n\nconst root = createRoot(document.getElementById(\"app\"));\n\nroot.render(\n  <ApolloProvider client={client}>\n    <Suspense fallback={<div>Loading...</div>}>\n      <App />\n    </Suspense>\n  </ApolloProvider>\n);\n```\n\nWe begin loading data as soon as our `preloadQuery` function is called rather than waiting for React to render our `<App />` component. Because the `preloadedQueryRef` is passed to `useReadQuery` in our `App` component, we still get the benefit of suspense and cache updates.\n\n<Note>\n\nUnmounting components that contain preloaded queries is safe and disposes of the `queryRef`. When the component re-mounts, `useReadQuery` automatically resubscribes to the `queryRef` and any cache updates that occurred in the interim are read immediately as if the preloaded query had never been unmounted.\n\n</Note>\n\n#### Usage with data loading routers\n\nPopular routers such as [React Router](https://reactrouter.com/en/main) and [TanStack Router](https://tanstack.com/router) provide APIs to load data before route components are rendered. One example is the [`loader` function](https://reactrouter.com/en/main/route/route#loader) from React Router.\n\nLoading data before rendering route components is especially useful for nested routes where data loading is parallelized. It prevents situations where parent route components might otherwise suspend and create request waterfalls for child route components.\n\n`preloadQuery` pairs nicely with these router APIs as it lets you take advantage of those optimizations without sacrificing the ability to rerender cache updates in your route components.\n\nLet's update our example using React Router's `loader` function to begin loading data when we transition to our route.\n\n```ts {4,8-9}\nimport { useLoaderData } from 'react-router-dom';\n\nexport function loader() {\n  return preloadQuery(GET_DOGS_QUERY);\n}\n\nexport function RouteComponent() {\n  const queryRef = useLoaderData();\n  const { data } = useReadQuery(queryRef);\n\n  return (\n    // ...\n  );\n}\n```\n\n> The `loader` function is available in React Router versions 6.4 and above.\n\nReact Router calls the `loader` function which we use to begin loading the `GET_DOG_QUERY` query by calling the `preloadQuery` function. The `queryRef` created by `preloadQuery` is returned from the `loader` function making it accessible in the route component.\n\nWhen the route component renders, we access the `queryRef` from the `useLoaderData` hook, which is then passed to `useReadQuery`. We get the benefit of loading our data early in the routing lifecycle, and the route component maintains the ability to rerender with cache updates.\n\n<Note>\n\nThe `preloadQuery` function only works with client-side routing. The `queryRef` returned from `preloadQuery` isn't serializable across the wire and as such, won't work with routers that fetch on the server such as [Remix](https://remix.run/).\n\n</Note>\n\n#### Preventing route transitions until the query is loaded\n\nBy default, `preloadQuery` works similarly to a [deferred loader](https://reactrouter.com/en/main/guides/deferred): the route transitions immediately and the incoming page that's attempting to read the data via `useReadQuery` suspends until the network request finishes.\n\nBut what if we want to prevent the route from transitioning until the data is fully loaded? `preloadQuery`'s `toPromise` method provides access to a promise that resolves when the network request has completed. This promise resolves with the `queryRef` itself, making it easy to use with hooks such as `useLoaderData`.\n\nHere's an example:\n\n```ts\nexport async function loader() {\n  const queryRef = preloadQuery(GET_DOGS_QUERY);\n\n  return preloadQuery.toPromise(queryRef);\n}\n\nexport function RouteComponent() {\n  const queryRef = useLoaderData();\n  const { data } = useReadQuery(queryRef);\n\n  // ...\n}\n```\n\nThis instructs React Router to wait for the query to finish loading before the route transitions. When the route transitions after the promise resolves, the data is rendered immediately without the need to show a loading fallback in the route component.\n\n#### Why prevent access to `data` in `toPromise`?\n\nYou may be wondering why we resolve `toPromise` with the `queryRef` itself, rather than the data loaded from the query. We want to encourage you to leverage `useReadQuery` to avoid missing out on cache updates for your query. If `data` were available, it would be tempting to consume it in your `loader` functions and expose it to your route components. Doing so means missing out on cache updates.\n\nIf you need access to raw query data in your `loader` functions, use [`client.query()`](../api/core/ApolloClient#query) directly.\n\n### Refetching and pagination\n\nApollo's Suspense data fetching hooks return functions for refetching query data via the `refetch` function, and fetching additional pages of data via the `fetchMore` function.\n\nLet's update our example by adding the ability to refetch breeds. We destructure the `refetch` function from the second item in the tuple returned from `useBackgroundQuery`. We'll be sure to show a pending state to let the user know that data is being refetched by utilizing React's `useTransition` hook:\n\n```tsx {1,11-12,15-17,41,49,53}\nimport { Suspense, useTransition } from \"react\";\nimport { gql, TypedDocumentNode } from \"@apollo/client\";\nimport {\n  useSuspenseQuery,\n  useBackgroundQuery,\n  useReadQuery,\n  QueryRef,\n} from \"@apollo/client/react\";\n\nfunction App() {\n  const [isPending, startTransition] = useTransition();\n  const [queryRef, { refetch }] = useBackgroundQuery(GET_BREEDS_QUERY);\n\n  function handleRefetch() {\n    startTransition(() => {\n      refetch();\n    });\n  }\n\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog\n        id=\"3\"\n        queryRef={queryRef}\n        isPending={isPending}\n        onRefetch={handleRefetch}\n      />\n    </Suspense>\n  );\n}\n\nfunction Dog({ id, queryRef, isPending, onRefetch }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n  });\n\n  return (\n    <>\n      Name: {data.dog.name}\n      <Suspense fallback={<div>Loading breeds...</div>}>\n        <Breeds isPending={isPending} queryRef={queryRef} />\n      </Suspense>\n      <button onClick={onRefetch}>Refetch!</button>\n    </>\n  );\n}\n\nfunction Breeds({ queryRef, isPending }: BreedsProps) {\n  const { data } = useReadQuery(queryRef);\n\n  return data.breeds.map(({ characteristics }) =>\n    characteristics.map((characteristic) => (\n      <div style={{ opacity: isPending ? 0.5 : 1 }} key={characteristic}>\n        {characteristic}\n      </div>\n    ))\n  );\n}\n```\n\nIn this example, our `App` component renders a `Dog` component that fetches a single dog's record via `useSuspenseQuery`. When React attempts to render `Dog` for the first time, the cache can't fulfill the request for the `GetDog` query, so `useSuspenseQuery` initiates a network request. `Dog` suspends while the network request is pending, triggering the nearest `Suspense` boundary _above_ the suspended component in `App` which renders our \"Loading...\" fallback. Once the network request is complete, `Dog` renders with the newly cached `name` for the dog whose `id=\"3\"`: Mozzarella the Corgi.\n\n#### Usage with query preloading\n\nWhen loading queries [outside React](#initiating-queries-outside-react), the `preloadQuery` function returns a `queryRef` with no access to `refetch` or `fetchMore` functions. This presents a challenge when you need to refetch or paginate the preloaded query.\n\nYou can gain access to `refetch` and `fetchMore` functions by using the `useQueryRefHandlers` hook. This hook integrates with React transitions, giving you the ability to refetch or paginate without showing the loading fallback.\n\nLet's update our example to preload our `GET_BREEDS_QUERY` outside React and use the `useQueryRefHandlers` hook to refetch our query.\n\n```tsx {4,7,11}\n// ...\nimport {\n  // ...\n  useQueryRefHandlers,\n} from \"@apollo/client/react\";\n\nconst queryRef = preloadQuery(GET_BREEDS_QUERY);\n\nfunction App() {\n  const [isPending, startTransition] = useTransition();\n  const { refetch } = useQueryRefHandlers(queryRef);\n\n  function handleRefetch() {\n    startTransition(() => {\n      refetch();\n    });\n  }\n\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog id=\"3\" isPending={isPending} onRefetch={handleRefetch} />\n    </Suspense>\n  );\n}\n\n// ...\n```\n\nWe begin loading our `GET_BREEDS_QUERY` outside of React with the `preloadQuery` function. We pass the `queryRef` returned from `preloadQuery` to the `useQueryRefHandlers` hook which provides us with a `refetch` function we can use to refetch the query when the button is clicked.\n\n#### Using `useQueryRefHandlers` with query refs produced from other Suspense hooks\n\n`useQueryRefHandlers` can also be used in combination with any hook that returns a `queryRef`, such as `useBackgroundQuery` or `useLoadableQuery`. This is useful when you need access to the `refetch` and `fetchMore` functions in components where the `queryRef` is passed through deeply.\n\nLet's update our example to use `useBackgroundQuery` again and see how we can access a `refetch` function in our `Dog` component using `useQueryRefHandlers`:\n\n```tsx {15,16,18-22,30}\nfunction App() {\n  const [queryRef] = useBackgroundQuery(GET_BREEDS_QUERY);\n\n  return (\n    <Suspense fallback={<div>Loading...</div>}>\n      <Dog id=\"3\" queryRef={queryRef} />\n    </Suspense>\n  );\n}\n\nfunction Dog({ id, queryRef }: DogProps) {\n  const { data } = useSuspenseQuery(GET_DOG_QUERY, {\n    variables: { id },\n  });\n  const [isPending, startTransition] = useTransition();\n  const { refetch } = useQueryRefHandlers(queryRef);\n\n  function handleRefetch() {\n    startTransition(() => {\n      refetch();\n    });\n  }\n\n  return (\n    <>\n      Name: {data.dog.name}\n      <Suspense fallback={<div>Loading breeds...</div>}>\n        <Breeds queryRef={queryRef} isPending={isPending} />\n      </Suspense>\n      <button onClick={handleRefetch}>Refetch!</button>\n    </>\n  );\n}\n\n// ...\n```\n\n<Note>\n\nUsing the handlers returned from `useQueryRefHandlers` does not prevent you from using the handlers produced by query ref hooks. You can use the handlers in both locations, with or without React transitions to produce the desired result.\n\n</Note>\n\n## Distinguishing between queries with `queryKey`\n\nApollo Client uses the combination of `query` and `variables` to uniquely identify each query when using Apollo's Suspense data fetching hooks.\n\nIf your application renders multiple components that use the same `query` and `variables`, this may present a problem: the queries made by multiple hooks share the same identity causing them to **suspend at the same time**, regardless of which component initiates or re-initiates a network request.\n\nYou can prevent this with `queryKey` option to ensure each hook has a unique identity. When `queryKey` is provided, Apollo Client uses it as part of the hook's identity in addition to its `query` and `variables`.\n\nFor more information, see the [`useSuspenseQuery`](../api/react/useSuspenseQuery) or [`useBackgroundQuery`](../api/react/useBackgroundQuery) API docs.\n\n## Skipping suspense hooks\n\nWhile `useSuspenseQuery` and `useBackgroundQuery` both have a `skip` option, that option is only present to ease migration from `useQuery` with as few code changes as possible.\nIt should not be used in the long term.\n\nInstead, you should use [`skipToken`](../api/react/skipToken):\n\n```js title=\"Recommended usage of skipToken with useSuspenseQuery\"\nimport { skipToken, useSuspenseQuery } from \"@apollo/client/react\";\nconst { data } = useSuspenseQuery(\n  query,\n  id ? { variables: { id } } : skipToken\n);\n```\n\n```js title=\"Recommended usage of skipToken with useBackgroundQuery\"\nimport { skipToken, useBackgroundQuery } from \"@apollo/client/react\";\nconst [queryRef] = useBackgroundQuery(\n  query,\n  id ? { variables: { id } } : skipToken\n);\n```\n\n## React Server Components (RSC)\n\n### Usage with Next.js 13 App Router\n\nIn Next.js v13, Next.js's new [App Router](https://nextjs.org/docs/app) brought the React community the first framework with full support for [React Server Components (RSC)](https://react.dev/blog/2023/03/22/react-labs-what-we-have-been-working-on-march-2023#react-server-components) and Streaming SSR, integrating Suspense as a first-class concept from your application's routing layer all the way down.\n\nIn order to integrate with these features, the Apollo Client team released an integration package, [`@apollo/client-integration-nextjs`](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/nextjs), which allows for seamless use of Apollo Client with both RSC and Streaming SSR, one of the first of its kind for data fetching libraries. See its [README](https://github.com/apollographql/apollo-client-integrations/blob/main/packages/nextjs/README.md) and our [introductory blog post](https://www.apollographql.com/blog/apollo-client/next-js/how-to-use-apollo-client-with-next-js-13/) for more details.\n\n#### Streaming while fetching with `useBackgroundQuery` during streaming SSR\n\nIn a client-rendered application, `useBackgroundQuery` can be used to avoid request waterfalls, but its impact can be even more noticeable in an application using streaming SSR as the App Router does. This is because the server can begin streaming content to the client, bringing even greater performance benefits.\n\n### Error handling\n\nIn a purely client-rendered app, errors thrown in components are always caught and displayed by the closest [error boundary](https://react.dev/reference/react/Component#static-getderivedstatefromerror).\n\nErrors thrown on the server when using one of the [streaming server rendering APIs](https://react.dev/reference/react-dom/server) are treated differently. See the [React documentation](https://react.dev/reference/react/Suspense#providing-a-fallback-for-server-errors-and-client-only-content) for more information.\n\n## Further reading\n\nTo view a larger codebase that makes use of Apollo Client's Suspense hooks (and many other new features introduced in Apollo Client 3.8), check out Apollo's [Spotify Showcase](https://github.com/apollographql/spotify-showcase) on GitHub. It's a full-stack web application that pays homage to Spotify's iconic UI by building a clone using Apollo Client, Apollo Server and GraphOS.\n\n## useSuspenseQuery API\n\nMore details on `useSuspenseQuery`'s API can be found in [its API docs](../api/react/useSuspenseQuery).\n\n## useBackgroundQuery API\n\nMore details on `useBackgroundQuery`'s API can be found in [its API docs](../api/react/useBackgroundQuery).\n\n## useLoadableQuery API\n\nMore details on `useLoadableQuery`'s API can be found in [its API docs](../api/react/useLoadableQuery).\n\n## useQueryRefHandlers API\n\nMore details on `useQueryRefHandlers`'s API can be found in [its API docs](../api/react/useQueryRefHandlers).\n\n## useReadQuery API\n\nMore details on `useReadQuery`'s API can be found in [its API docs](../api/react/useReadQuery).\n"
  },
  {
    "path": "docs/source/data/typescript.mdx",
    "content": "---\ntitle: TypeScript with Apollo Client\ndescription: How to use TypeScript in your application\nredirectFrom:\n  - /react/development-testing/static-typing\n---\n\nAs your application grows, a type system becomes an essential tool for catching bugs early and improving your overall developer experience.\n\nGraphQL uses a type system to clearly define the available data for each type and field in a GraphQL schema. You can add type safety for your GraphQL operations using TypeScript.\n\nThis guide provides detail on how Apollo Client integrates TypeScript to provide you with type safety throughout your application.\n\n<Note>\n\nThis article covers general usage with TypeScript in Apollo Client. If you'd like to generate your GraphQL types automatically, read the [GraphQL Codegen](../development-testing/graphql-codegen) guide to learn how to use GraphQL Codegen with Apollo Client.\n\n</Note>\n\n## Using operation types\n\nBy default, Apollo Client sets the type of the `data` property to `unknown` type when the data type cannot be determined. This provides a layer of safety to avoid accessing properties on `data` that TypeScript doesn't know about.\n\nThe following example uses `gql` to create a GraphQL document for a query. The query is typed as a `DocumentNode` which doesn't provide type information about its data or variables.\n\n```tsx\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\n// This is of type `DocumentNode`\nconst GET_ROCKET_INVENTORY = gql`\n  query GetRocketInventory {\n    rocketInventory {\n      id\n      model\n      year\n      stock\n    }\n  }\n`;\n\nfunction RocketInventory() {\n  const { data } = useQuery(GET_ROCKET_INVENTORY);\n  //      ^? unknown\n\n  return (\n    <div>\n      {/* ❌ TypeScript Error: 'data' is of type 'unknown'. */}\n      {data.rocketInventory.map((rocket) => (\n        <Rocket key={rocket.id} rocket={rocket} />\n      ))}\n    </div>\n  );\n}\n```\n\nThis however makes it difficult to work with the `data` property. You either need to type cast each property on `data` to suppress the error, or cast `data` as an `any` type (not recommended) which removes type safety entirely.\n\nInstead, we can leverage the `TypedDocumentNode` type to provide types for GraphQL documents. `TypedDocumentNode` includes generic arguments for data and variables:\n\n```ts\nimport { TypedDocumentNode } from \"@apollo/client\";\n\ntype QueryType = TypedDocumentNode<DataType, VariablesType>;\n```\n\nApollo Client allows for the use of `TypedDocumentNode` everywhere a `DocumentNode` is accepted. This enables Apollo Client APIs to infer the data and variable types using the GraphQL document.\n\nThe following adds types to the query from the previous example using `TypedDocumentNode`.\n\n```tsx {5-13,15,17-20}\nimport { useQuery, TypedDocumentNode } from \"@apollo/client\";\n\n// In a real application, consider generating types from your schema\n// instead of writing them by hand\ntype GetRocketInventoryQuery = {\n  rocketInventory: {\n    __typename: \"Rocket\";\n    id: string;\n    model: string;\n    year: number;\n    stock: number;\n  };\n};\n\ntype GetRocketInventoryQueryVariables = Record<string, never>;\n\nconst GET_ROCKET_INVENTORY: TypedDocumentNode<\n  GetRocketInventoryQuery,\n  GetRocketInventoryQueryVariables\n> = gql`\n  query GetRocketInventory {\n    rocketInventory {\n      id\n      model\n      year\n      stock\n    }\n  }\n`;\n\nfunction RocketInventory() {\n  const { data } = useQuery(GET_ROCKET_INVENTORY);\n  //      ^? GetRocketInventoryQuery | undefined\n\n  // checks for loading and error states are omitted for brevity\n\n  return (\n    <div>\n      {/* No more 'unknown' type error */}\n      {data.rocketInventory.map((rocket) => (\n        <Rocket key={rocket.id} rocket={rocket} />\n      ))}\n    </div>\n  );\n}\n```\n\n<Tip>\n\nWe recommend using `TypedDocumentNode` and relying on type inference throughout your application for your GraphQL operations instead of specifying the generic type arguments on Apollo Client APIs, such as `useQuery`. This makes GraphQL documents more portable and provides better type safety wherever the document is used.\n\n<ExpansionPanel title=\"Example\">\n\n```ts\n// ❌ Don't leave GraphQL documents as plain `DocumentNode`s\nconst query = gql`\n  # ...\n`;\n// ❌ Don't provide generic arguments to Apollo Client APIs\nconst { data } = useQuery<QueryType, VariablesType>(query);\n\n// ✅ Add the type for the GraphQL document with `TypedDocumentNode`\nconst query: TypedDocumentNode<QueryType, VariablesType> = gql`\n  # ...\n`;\nconst { data } = useQuery(query);\n```\n\n</ExpansionPanel>\n\n</Tip>\n\n<Tip>\n\nWe recommend that you always provide the variables type to `TypedDocumentNode`, even when the GraphQL operation doesn't define any variables. This ensures you don't provide variable values to your query which results in runtime errors from your GraphQL server. Additionally, this ensures that TypeScript catches errors when you update your query over time and include required variables.<br/><br/>\n\nIf you use GraphQL Codegen, an empty variables type is generated for you using the type `Record<string, never>`.\n\n</Tip>\n\n### Type narrowing `data` with `dataState`\n\nThroughout the lifecycle of your component, the value of `data` changes. `data` is influenced by several factors that affect its value such as different options or the query's current state.\n\nSome examples of options that influence the value of `data` include:\n\n- `returnPartialData` which might return partial data from the cache\n- `errorPolicy` which affects the value of `data` when an error is returned\n- `variables` which affects when the query is re-executed as variables change\n- `fetchPolicy` which might provide a result from the cache\n- `skip` which waits to execute the query\n\nSome examples of the query state that influence the value of `data` include:\n\n- The query is currently loading\n- The query successfully loads its result\n- The query returns partial data from the cache when `returnPartialData` is `true`\n- The query returns an error\n- The query is currently streaming additional data while using [`@defer`](../data/defer)\n\nThe combination of these states and options make it difficult to provide robust types for `data` based solely on the `loading` and `error` properties.\n\nApollo Client provides a `dataState` property for this purpose. `dataState` provides information about the completeness of the `data` property and includes type narrowing to give you better type safety without the need to add additional completeness checks.\n\nThe `dataState` property has the following values:\n\n- `\"empty\"` - No data is available. `data` is `undefined`\n- `\"partial\"` - Partial data is returned from the cache. `data` is `DeepPartial<TData>`\n- `\"streaming\"` - Data from a deferred query is incomplete and still streaming. `data` is `TData`\n- `\"complete\"` - Data fully satisfies the query. `data` is `TData`\n\nThe following demonstrates how `dataState` affects the type of `data`.\n\n<Note>\n\nThis example uses `returnPartialData: true` to demonstrate the type of `data` when `dataState` is `partial`. When `returnPartialData` is `false` or omitted, `dataState` does not include the `partial` value and the type of `data` does not include `DeepPartial<TData>`.\n\n</Note>\n\n```tsx\nconst { data, dataState } = useQuery(GET_ROCKET_INVENTORY, {\n  returnPartialData: true,\n});\n\ndata;\n// ^? GetRocketInventoryQuery | DeepPartial<GetRocketInventoryQuery> | undefined\n\nif (dataState === \"empty\") {\n  data;\n  // ^? undefined\n}\n\nif (dataState === \"partial\") {\n  data;\n  // ^? DeepPartial<GetRocketInventoryQuery>\n}\n\nif (dataState === \"streaming\") {\n  data;\n  // ^? GetRocketInventoryQuery\n}\n\nif (dataState === \"complete\") {\n  data;\n  // ^? GetRocketInventoryQuery\n}\n```\n\n<Note>\n\nThe type of `data` is the same when `dataState` is either `streaming` or `complete`. Additionally, `dataState` always includes `streaming` as a value, even when `@defer` is not used and isn't seen at runtime. This is because it is difficult to determine whether a query uses `@defer` based solely on the output format of the query type.<br/><br/>\n\nIf you use a type format that makes this possible, you can provide your own type implementations for the `complete` and `streaming` states to provide a corrected type. See the guide on [overriding types](#overriding-types) to learn how to provide your own type implementations.\n\n</Note>\n\n### Working with variables\n\nWhen your GraphQL operations include variables, TypeScript ensures you provide all required variables with the correct types. Additionally, TypeScript ensures you omit variables that aren't included in the operation.\n\nThe following adds a non-null variable to the `GetRocketInventory` query used in previous examples.\n\n```tsx {5-6}\nconst GET_ROCKET_INVENTORY: TypedDocumentNode<\n  GetRocketInventoryQuery,\n  GetRocketInventoryQueryVariables\n> = gql`\n  query GetRocketInventory($year: Int!) {\n    rocketInventory(year: $year) {\n      id\n      model\n      year\n      stock\n    }\n  }\n`;\n\nfunction RocketInventory() {\n  // ❌ TypeScript Error: Expected 2 arguments, but got 1.\n  const { data } = useQuery(GET_ROCKET_INVENTORY);\n\n  // ❌ TypeScript Error: Property 'variables' is missing in type '{}'\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {});\n\n  // ❌ TypeScript Error: Property 'year' is missing in type '{}'\n  const { data } = useQuery(GET_ROCKET_INVENTORY, { variables: {} });\n\n  // ✅ Correct: Required variable provided\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { year: 2024 },\n  });\n\n  // ❌ TypeScript Error: Type 'string' is not assignable to type 'number'\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { year: \"2024\" },\n  });\n\n  // ❌ TypeScript Error: 'notAVariable' does not exist in type '{ id: string }'\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { year: \"2024\", notAVariable: true },\n  });\n}\n```\n\nFor operations with optional variables, TypeScript allows you to omit them:\n\n```tsx\nconst GET_ROCKET_INVENTORY: TypedDocumentNode<\n  GetRocketInventoryQuery,\n  GetRocketInventoryQueryVariables\n> = gql`\n  query GetRocketInventory($model: String, $year: Int) {\n    rocketInventory(model: $model, year: $year) {\n      id\n      model\n    }\n  }\n`;\n\nfunction RocketInventory() {\n  // ✅ All valid - all variables are optional\n  const { data } = useQuery(GET_ROCKET_INVENTORY);\n\n  // ✅ All valid - All variables satisfy the variables type\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { model: \"Falcon\" },\n  });\n\n  // ✅ All valid - All variables satisfy the variables type\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { year: 2024 },\n  });\n\n  // ✅ All valid - All variables satisfy the variables type\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { model: \"Falcon\", year: 2024 },\n  });\n\n  // ❌ TypeScript Error: 'notAVariable' does not exist in type '{ id: string }'\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    variables: { model: \"Falcon\", year: 2024, notAVariable: true },\n  });\n}\n```\n\n### Mutations\n\n> For a more comprehensive guide on using mutations, see the [Mutations guide](../data/mutations).\n\nLike `useQuery`, you provide `useMutation` a `TypedDocumentNode`. This adds the query type for the `data` property and ensures that `variables` are validated by TypeScript.\n\n```tsx\nimport { gql, TypedDocumentNode } from \"@apollo/client\";\nimport { useMutation } from \"@apollo/client/react\";\n\n// In a real application, consider generating types from your schema\n// instead of writing them by hand\ntype SaveRocketMutation = {\n  saveRocket: {\n    model: string;\n  } | null;\n};\n\ntype SaveRocketMutationVariables = {\n  rocket: {\n    model: string;\n    year: number;\n    stock: number;\n  };\n};\n\nconst SAVE_ROCKET: TypedDocumentNode<\n  SaveRocketMutation,\n  SaveRocketMutationVariables\n> = gql`\n  mutation SaveRocket($rocket: RocketInput!) {\n    saveRocket(rocket: $rocket) {\n      model\n    }\n  }\n`;\n\nexport function NewRocketForm() {\n  const [model, setModel] = useState(\"\");\n  const [year, setYear] = useState(0);\n  const [stock, setStock] = useState(0);\n\n  const [addRocket, { data }] = useMutation(SAVE_ROCKET, {\n    //                ^? SaveRocketMutation | null | undefined\n    variables: { rocket: { model, year, stock } },\n  });\n\n  return (\n    <form>\n      <p>\n        <label>Model</label>\n        <input name=\"model\" onChange={(e) => setModel(e.target.value)} />\n      </p>\n      <p>\n        <label>Year</label>\n        <input\n          type=\"number\"\n          name=\"year\"\n          onChange={(e) => setYear(+e.target.value)}\n        />\n      </p>\n      <p>\n        <label>Stock</label>\n        <input\n          type=\"number\"\n          name=\"stock\"\n          onChange={(e) => setStock(e.target.value)}\n        />\n      </p>\n      <button onClick={() => addRocket()}>Add rocket</button>\n    </form>\n  );\n}\n```\n\n<Note>\n\nUnlike `useQuery`, `useMutation` doesn't provide a `dataState` property. `data` isn't tracked the same way as `useQuery` because its value is not read from the cache. The value of `data` is a set result of the last execution of the mutation.\n\n</Note>\n\n#### Using variables with `useMutation`\n\n`useMutation` allows you to provide variables to either the hook or the mutate function returned in the result tuple. When variables are provided to both the hook and mutate function, they are shallowly merged (see the [Mutations guide](../data/mutations#option-precedence) for more information).\n\nThis behavior affects how TypeScript checks required variables with `useMutation`. Required variables must be provided to either the hook or the mutate function. If a required variable is not provided to the hook, the mutate function must include it. Required variables provided to the hook make them optional in the mutate function.\n\nThe following uses the previous example but flattens the variable declarations to demonstrate how required variables affect TypeScript validation.\n\n```tsx\nconst SAVE_ROCKET: TypedDocumentNode<\n  SaveRocketMutation,\n  SaveRocketMutationVariables\n> = gql`\n  mutation SaveRocket($model: String!, $year: Int!, $stock: Int) {\n    saveRocket(rocket: { model: $model, year: $year, stock: $stock }) {\n      model\n    }\n  }\n`;\n\nexport function NewRocketForm() {\n  // No required variables provided to the hook\n  const [addRocket] = useMutation(SAVE_ROCKET);\n\n  // ❌ TypeScript Error: Expected 1 argument, but got 0.\n  addRocket();\n  // ❌ TypeScript Error: Property 'variables' is missing in type '{}'\n  addRocket({});\n  // ❌ TypeScript Error: Type '{}' is missing the following properties from '{ year: number; model: string;, stock?: number }': model, year\n  addRocket({ variables: {} });\n  // ❌ TypeScript Error: Property 'year' is missing in type '{ model: string }'\n  addRocket({ variables: { model: \"Falcon\" } });\n  // ✅ Correct: All required variables provided\n  addRocket({ variables: { model: \"Falcon\", year: 2025 } });\n  // ❌ TypeScript Error: 'notAVariable' does not exist in type '{ year: number; model: string;, stock?: number }'\n  addRocket({ variables: { model: \"Falcon\", year: 2025, notAVariable: true } });\n\n  // Some required variables provided to the hook\n  const [addRocket] = useMutation(SAVE_ROCKET, {\n    variables: { model: \"Falcon\" },\n  });\n\n  // ❌ TypeScript Error: Expected 1 argument, but got 0.\n  addRocket();\n  // ❌ TypeScript Error: Property 'variables' is missing in type '{}'\n  addRocket({});\n  // ❌ TypeScript Error: Property 'year' is missing in type '{}'\n  addRocket({ variables: {} });\n  // ✅ Correct: All remaining required variables provided\n  addRocket({ variables: { year: 2025 } });\n  // ❌ TypeScript Error: 'notAVariable' does not exist in type '{ year: number; model?: string;, stock?: number }'\n  addRocket({ variables: { year: 2025, notAVariable: true } });\n\n  // All required variables provided to the hook\n  const [addRocket] = useMutation(SAVE_ROCKET, {\n    variables: { model: \"Falcon\", year: 2025 },\n  });\n\n  // ✅ Correct: All required variables are provided to the hook\n  addRocket();\n  // ✅ Correct: All required variables are provided to the hook\n  addRocket({ variables: { stock: 10 } });\n  // ❌ TypeScript Error: 'notAVariable' does not exist in type '{ year?: number; model?: string;, stock?: number }'\n  addRocket({ variables: { notAVariable: true } });\n}\n```\n\n### Subscriptions\n\n> For a more comprehensive guide on using subscriptions, see the [Subscriptions guide](../data/subscriptions).\n\nLike `useQuery`, you provide `useSubscription` a `TypedDocumentNode`. This adds the query type for the `data` property and ensures that `variables` are validated by TypeScript.\n\n```tsx\nimport { gql, TypedDocumentNode } from \"@apollo/client\";\nimport { useSubscription } from \"@apollo/client/react\";\n\n// In a real application, consider generating types from your schema\n// instead of writing them by hand\ntype GetLatestNewsSubscription = {\n  latestNews: {\n    content: string;\n  };\n};\n\ntype GetLatestNewsSubscriptionVariables = Record<string, never>;\n\nconst LATEST_NEWS: TypedDocumentNode<\n  GetLatestNewsSubscription,\n  GetLatestNewsSubscriptionVariables\n> = gql`\n  subscription GetLatestNews {\n    latestNews {\n      content\n    }\n  }\n`;\n\nexport function LatestNews() {\n  const { data } = useSubscription(LATEST_NEWS);\n  //      ^? GetLatestNewsSubscription | undefined\n\n  return (\n    <div>\n      <h5>Latest News</h5>\n      <p>{data?.latestNews.content}</p>\n    </div>\n  );\n}\n```\n\nVariables are validated the same as `useQuery`. See [working with variables](#working-with-variables) to learn more about how required variables are validated.\n\n## Defining context types\n\nApollo Client enables you to pass [custom context](../api/link/introduction#managing-context) through to the link chain. By default, context is typed as `Record<string, any>` to allow for any arbitrary value as context. However, this default has a few downsides. You don't get proper type safety and you don't get autocomplete suggestions in your editor to understand what context options are available to you.\n\nYou can define your own context types for better type safety in Apollo Client using TypeScript's [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html).\n\n### Adding custom context properties\n\nTo define types for your custom context properties, create a TypeScript file and define the `DefaultContext` interface.\n\n```ts title=\"apollo-client.d.ts\"\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  interface DefaultContext {\n    myProperty?: string;\n    requestId?: number;\n  }\n}\n```\n\nNow when you pass context for operations, TypeScript will validate the types:\n\n```tsx\nconst { data } = useQuery(MY_QUERY, {\n  context: {\n    myProperty: \"value\", // ✅ Valid value\n    requestId: \"123\", // ❌ Type 'string' is not assignable to type 'number | undefined'\n  },\n});\n```\n\n<Tip>\n\nWe recommend all custom context properties are optional by default. If a context value is necessary for the operation of your application (such as an authentication token used in request headers), we recommend that you try to provide the value with [`SetContextLink`](../api/link/apollo-link-context) or a [custom link](../api/link/introduction#creating-a-custom-link) first. Reserve required properties for options that are truly meant to be provided to every hook or request to your server and cannot be provided by a link in your link chain.\n\n</Tip>\n\n<Note>\n\nApollo Client doesn't validate that the `context` option is provided when it contains required properties like it does with the [`variables` option](#working-with-variables). However, adding the `context` option might result in a TypeScript error when any required properties are not provided.\n\n</Note>\n\n### Using context from built-in links\n\nSome links provided by Apollo Client have built-in context option types. You can extend `DefaultContext` with these types to get proper type checking for link-specific options.\n\nThe following example adds `HttpLink`'s context types to `DefaultContext`:\n\n```ts title=\"apollo-client.d.ts\"\nimport \"@apollo/client\";\nimport { HttpLink } from \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  interface DefaultContext extends HttpLink.ContextOptions {}\n}\n```\n\nNow when you pass context for operations, TypeScript will validate the types:\n\n```tsx\nconst { data } = useQuery(MY_QUERY, {\n  context: {\n    headers: {\n      \"X-Custom-Header\": \"value\", // ✅ Valid header value\n    },\n    credentials: \"include\", // ✅ Valid RequestCredentials value\n    fetchOptions: {\n      mode: \"none\", // ❌ Type \"none\" is not assignable to type 'RequestMode | undefined'\n    },\n  },\n});\n```\n\nIf you are using more than one link that has context options, you can extend from each link's context options:\n\n```ts title=\"apollo-client.d.ts\"\nimport \"@apollo/client\";\nimport type { BaseHttpLink } from \"@apollo/client/link/http\";\nimport type { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\n\ndeclare module \"@apollo/client\" {\n  interface DefaultContext\n    extends BaseHttpLink.ContextOptions,\n      ClientAwarenessLink.ContextOptions {}\n}\n```\n\nThe following built-in links provide context option types:\n\n- [`HttpLink.ContextOptions`](../api/link/apollo-link-http#httplinkcontextoptions)\n- [`BaseHttpLink.ContextOptions`](../api/link/apollo-link-base-http#basehttplinkcontextoptions)\n- [`BatchHttpLink.ContextOptions`](../api/link/apollo-link-batch-http#batchhttplinkcontextoptions)\n- [`BaseBatchHttpLink.ContextOptions`](../api/link/apollo-link-base-batch-http#basebatchhttplinkcontextoptions)\n- [`ClientAwarenessLink.ContextOptions`](../api/link/apollo-link-client-awareness#clientawarenesslinkcontextoptions)\n\n### Using context in custom links\n\nWith context types defined, context properties accessed in custom links are properly type checked when reading or writing context.\n\n```ts\nimport { ApolloLink } from \"@apollo/client\";\n\nconst customLink = new ApolloLink((operation, forward) => {\n  const context = operation.getContext();\n\n  // TypeScript knows about your custom properties\n  console.log(context.myProperty); // string | undefined\n  console.log(context.requestId); // number | undefined\n\n  operation.setContext({\n    requestId: \"123\", // ❌ Type 'string' is not assignable to type 'number | undefined'\n  });\n\n  return forward(operation);\n});\n```\n\n## Data masking\n\nLearn more about integrating TypeScript with data masking in the [data masking docs](../data/fragments#using-with-typescript).\n\n## `@defer`\n\nLearn more about integrating TypeScript with incremental responses the [`@defer` docs](../data/defer).\n\n## Overriding type implementations for built-in types\n\nApollo Client makes it possible to use custom implementations of certain built-in utility types. This enables you to work with custom type outputs that might otherwise be incompatible with the default type implementations in Apollo Client.\n\nYou use a technique called _higher-kinded types_ (HKT) to provide your own type implementations for Apollo Client's utility types. You can think of higher-kinded types as a way to define types and interfaces with generics that can be filled in by Apollo Client internals at a later time. Passing around un-evaluated types is otherwise not possible in TypeScript.\n\n### Anatomy of HKTs\n\nHKTs in Apollo Client consist of two parts:\n\n- The HKT type definition - This provides the plumbing necessary to use your custom type implementation with Apollo Client\n- The `TypeOverrides` interface - An interface used with [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) to provide the mapping for the overridden types to your HKT types\n\n#### Creating an HKT type\n\nYou create HKT types by extending the `HKT` interface exported by `@apollo/client/utilities`.\n\n```ts\nimport { HKT } from \"@apollo/client/utilities\";\n\n// The implementation of the type\ntype MyCustomImplementation<GenericArg1, GenericArg2> = SomeOtherUtility<\n  GenericArg1,\n  GenericArg2\n>;\n\ninterface MyTypeOverride extends HKT {\n  arg1: unknown; // GenericArg1\n  arg2: unknown; // GenericArg2\n  return: MyCustomImplementation<this[\"arg1\"], this[\"arg2\"]>;\n}\n```\n\nYou can think of each property on the `HKT` type as a placeholder. Each `arg*` property corresponds to a generic argument used for the implementation. The `return` property provides the mapping to the actual implementation of the type, using the `arg*` values as generic arguments.\n\n#### Mapping HKT types to its type override\n\nOnce your HKT type is created, you tell Apollo Client about it by using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) using the `TypeOverrides` interface. This interface is included in Apollo Client to enable you to provide mappings to your custom type implementations.\n\nCreate a TypeScript file that defines the `TypeOverrides` interface for the `@apollo/client` module.\n\n```ts title=apollo-client.d.ts\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides {\n    TypeOverride1: MyTypeOverride;\n  }\n}\n```\n\nEach key in the `TypeOverrides` interface corresponds to an overridable type in Apollo Client and its value maps to an HKT type that provides the definition for that type.\n\n<Note>\n\n`TypeOverride1` is used as an example in the previous code block but is not a valid overridable type so it is ignored. See the [available type overrides](#available-type-overrides) for more information on which types can be overridden.\n\n</Note>\n\n### Example: Custom `dataState` types\n\nLet's add our own type overrides for the `Complete` and `Streaming` utility types. These types are used to provide types for the `data` property when [`dataState`](#type-narrowing-data-with-datastate) is set to specific values. The `Complete` type is used when `dataState` is `\"complete\"`, and `Streaming` is used when `dataState` is `\"streaming\"`.\n\nFor this example, we'll assume a custom type generation format where:\n\n- Streamed types (i.e. operation types that use the `@defer` directive) include a `__streaming` virtual property. Its value is the operation type that should be used when the result is still streaming from the server.\n\n  ```ts\n  type StreamedQuery = {\n    // The streamed variant of the operation type is provided under the\n    // `__streaming` virtual property\n    __streaming?: {\n      user: { __typename: \"User\"; id: number } & (\n        | { name: string }\n        | { name?: never }\n      );\n    };\n\n    // The full result type includes all other fields in the type\n    user: { __typename: \"User\"; id: number; name: string };\n  };\n  ```\n\n- Complete types which provide the full type of a query\n\n  ```ts\n  type CompleteQuery = {\n    user: { __typename: \"User\"; id: number; name: string };\n  };\n  ```\n\n<Note>\n\nThis is a hypothetical format that doesn't exist in Apollo Client or any known code generation tool. This format is used specifically for this example to illustrate how to provide type overrides to Apollo Client.\n\n</Note>\n\nFirst, let's define our custom implementation of the `Streaming` type. The implementation works by checking if the `__streaming` virtual property exists on the type. If so, it returns the value on the `__streaming` property as the type, otherwise it returns the input type unmodified.\n\n```ts title=\"custom-types.ts\"\ntype Streaming<TData> =\n  TData extends { __streaming?: infer TStreamingData } ? TStreamingData : TData;\n```\n\nNow let's define our custom implementation of the `Complete` type. The implementation works by removing the `__streaming` virtual property on the input type. This can be accomplished using the built-in [`Omit`](https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys) type.\n\n```ts {4} title=\"custom-types.ts\"\ntype Streaming<TData> =\n  TData extends { __streaming?: infer TStreamingData } ? TStreamingData : TData;\n\ntype Complete<TData> = Omit<TData, \"__streaming\">;\n```\n\nNow we need to define higher-kinded types for each of these implementations. This provides the bridge needed by Apollo Client to use our custom type implementations. This is done by extending the `HKT` interface exported by `@apollo/client/utilities`.\n\nLet's provide HKTs for our `Complete` and `Streaming` types. We'll put these in the same file as our type implementations.\n\n```ts {8-11,13-16} title=\"custom-types.ts\"\nimport { HKT } from \"@apollo/client/utilities\";\n\ntype Streaming<TData> =\n  TData extends { __streaming?: infer TStreamingData } ? TStreamingData : TData;\n\ntype Complete<TData> = Omit<TData, \"__streaming\">;\n\nexport interface StreamingHKT extends HKT {\n  arg1: unknown; // TData\n  return: Streaming<this[\"arg1\"]>;\n}\n\nexport interface CompleteHKT extends HKT {\n  arg1: unknown; // TData\n  return: Complete<this[\"arg1\"]>;\n}\n```\n\nWith our HKT types in place, we now need to tell Apollo Client about them. We'll need to provide our type overrides on the `TypeOverrides` interface.\n\nCreate a TypeScript file and define a `TypeOverrides` interface for the `@apollo/client` module.\n\n```ts title=\"apollo-client.d.ts\"\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\nimport { CompleteHKT, StreamingHKT } from \"./custom-types\";\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides {\n    Complete: CompleteHKT;\n    Streaming: StreamingHKT;\n  }\n}\n```\n\nAnd that's it! Now when `dataState` is `\"complete\"` or `\"streaming\"`, Apollo Client will use our custom type implementations 🎉.\n\n### Available type overrides\n\nThe following utility types are available to override:\n\n- `FragmentType<TFragmentData>` - Type used with fragments to ensure parent objects contain the fragment spread\n- `Unmasked<TData>` - Unwraps masked types into the full result type\n- `MaybeMasked<TData>` - Conditionally returns either masked or unmasked type\n- `Complete<TData>` - Type returned when `dataState` is `\"complete\"`\n- `Streaming<TData>` - Type returned when `dataState` is `\"streaming\"` (for `@defer` queries)\n- `Partial<TData>` - Type returned when `dataState` is `\"partial\"`\n- `AdditionalApolloLinkResultTypes<TData, TExtensions>` - Additional types that can be returned from Apollo Link operations\n\nFor more information about data masking types specifically, see the [data masking guide](../data/fragments#defining-your-own-masking-types-using-higher-kinded-types).\n"
  },
  {
    "path": "docs/source/development-testing/client-schema-mocking.mdx",
    "content": "---\ntitle: Mocking schema capabilities\ndescription: Start on client-side features before your server supports them\n---\n\nIf your GraphQL server doesn't yet support a field that your client will use, you can still start building against that field by mocking its behavior within the client.\n\nFor example, let's say we want to add a feature to the Space Explorer app from [the full-stack quickstart course](https://www.apollographql.com/tutorials/fullstack-quickstart/introduction). Specifically, we want to display a description of the rocket used for each launch. To support this functionality on the server side, we'll add a `description` field to our schema's `Rocket` type:\n\n```graphql {5}\ntype Rocket {\n  id: ID!\n  name: String\n  type: String\n  description: String # field not yet supported\n}\n```\n\nBut what if our back-end team isn't finished adding support for the `description` field? By mocking the field's behavior, we can still start developing the feature in our client. To do so, we'll follow the steps below.\n\n## 1. Define a `read` function\n\nOur client app doesn't yet know how to populate the `Rocket.description` field. To fix this, we can define a [`read` function](../caching/cache-field-behavior/#the-read-function) for the field. The Apollo Client cache calls this function whenever the field is queried, and the function's return value is used as the field's value.\n\nLet's define our `read` function in the configuration object we provide to the `InMemoryCache` constructor:\n\n```js {5-9} title=\"index.js\"\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Rocket: {\n      fields: {\n        description: {\n          read() {\n            // Read function for Rocket.description\n            return \"Placeholder rocket description\";\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThis enables us to query the field, but we might not want to show the same boilerplate description for every rocket. To add variety to our mocked output, we can use a library like [faker.js](https://github.com/faker-js/faker):\n\n```js title=\"index.js\"\nimport { faker } from \"@faker-js/faker\";\n\n// Returns 1 or 2 sentences of Lorem Ipsum\nconst oneOrTwoSentences = () =>\n  faker.lorem.sentences(Math.random() < 0.5 ? 1 : 2);\n```\n\nWe can then update our `read` function like so:\n\n```js\n// (within InMemoryCache constructor)\nread() {\n  return oneOrTwoSentences();\n}\n```\n\n> Make sure to include libraries like faker.js only in your development build, because they can needlessly increase your production bundle size.\n\n## 2. Query with the `@client` directive\n\nWe're ready to execute a query that includes our new field. Here's an abridged `GET_LAUNCH_DETAILS` query from the [full-stack quickstart](https://www.apollographql.com/tutorials/fullstack-quickstart/fetching-data-with-queries) with our `description` field added:\n\n```jsx {7}\nexport const GET_LAUNCH_DETAILS = gql`\n  query LaunchDetails($launchId: ID!) {\n    launch(id: $launchId) {\n      site\n      rocket {\n        type\n        description @client\n      }\n    }\n  }\n`;\n```\n\nNotice that this field includes the `@client` directive. This directive tells Apollo Client _not_ to include `description` in the query it sends to our server. This is important for two related reasons:\n\n- The `description` field is populated entirely locally, so including it in network requests isn't helpful.\n- The `description` field _isn't_ in our server-side schema yet, so including it will produce a GraphQL error.\n\nWe can now execute this query in a component with the `useQuery` hook as usual:\n\n```jsx\nexport default function LaunchDetails({ launchId }) {\n  const { data } = useQuery(GET_LAUNCH_DETAILS, { variables: { rocketId } });\n  return (\n    <div>\n      <p>Rocket Type: {data.launch.rocket.type}</p>\n      <p>Description: {data.launch.rocket.description}</p>\n    </div>\n  );\n}\n```\n\n## 3. Use live data when ready\n\nWhen your server's support for the `Rocket.description` field is ready, you can begin using it by doing the following:\n\n1. Remove the `@client` directive from `description` in every query that includes it.\n2. Remove the field's `read` function (or modify the function so that it uses the current cached value instead of a random string).\n\n---\n\nFor more information on the Apollo Client features used here, see the following:\n\n- [Local-only fields](../local-state/managing-state-with-field-policies/)\n- [The `read` function](../caching/cache-field-behavior/#the-read-function)\n"
  },
  {
    "path": "docs/source/development-testing/developer-tooling.mdx",
    "content": "---\ntitle: Developer tools\ndescription: Improve your developer experience with these services and extensions\n---\n\n## Apollo Client skill\n\n[Skills](https://agentskills.io/what-are-skills) are a lightweight, open format for extending AI agents with specialized knowledge and workflows. The Apollo Client skill teaches your AI assistant expert patterns for working with Apollo Client 4.x.\n\nInstall it with:\n\n```bash\nnpx skills add apollographql/skills --skill apollo-client\n```\n\nOnce installed, your AI assistant gains expert knowledge about setup, configuration, troubleshooting, hooks, caching strategies, and React integration patterns.\n\n## GraphOS and Apollo Studio\n\n[GraphOS](/graphos/) is Apollo's all-purpose platform for growing and collaborating on your graph. **Apollo Studio** is the web interface for GraphOS, which provides helpful views into your graph's usage and performance.\n\nAmong others, these GraphOS features are available to all Apollo users for free:\n\n- The Explorer, a powerful GraphQL IDE that connects to all your environments and provides ergonomic ways to author and manage queries.\n- A GraphQL schema registry that tracks the evolution of your graph across your environments.\n- Key insights into which parts of your schema are being actively used, and by whom.\n- Team collaboration via organizations\n\nTo learn more about GraphOS, check out the [overview](/graphos/).\n\n## Apollo Client Devtools\n\nThe Apollo Client Devtools are available as an extension for [Chrome](https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm) and [Firefox](https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/).\n\n### Features\n\nThe Apollo Client Devtools appear as an \"Apollo\" tab in your web browser's Inspector panel, alongside default tabs like \"Console\" and \"Network\". The devtools currently have four main features:\n\n- **GraphiQL:** Send queries to your server through your web application's configured Apollo Client instance, or query the Apollo Client cache to see what data is loaded.\n- **Watched query inspector:** View active queries, variables, and cached results, and re-run individual queries.\n- **Mutation inspector:** View active mutations and their variables, and re-run individual mutations.\n- **Cache inspector:** Visualize the Apollo Client cache and search it by field name and/or value.\n\n<img\n  class=\"screenshot\"\n  alt=\"Apollo Client Devtools\"\n  src=\"../assets/devtools/apollo-client-devtools/ac-browser-devtools-3.png\"\n/>\n\n### Installation\n\nYou can install the extension via the webstores for [Chrome](https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm) and [Firefox](https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/).\n\n### Configuration\n\nWhile your app is in dev mode, the Apollo Client Devtools will appear as an \"Apollo\" tab in your web browser inspector. To enable the devtools in your app in production, pass `connectToDevTools: true` to the `ApolloClient` constructor in your app. Pass `connectToDevTools: false` if want to manually disable this functionality.\n\nFind more information about contributing and debugging on the [Apollo Client Devtools GitHub page](https://github.com/apollographql/apollo-client-devtools).\n\n## Apollo Client Devtools in VS Code\n\nThe Apollo VSCode extension ships with an instance of the Apollo Client Devtools.\nYou can use it to remotely debug your client, which makes it possible to also debug React Native and node applications.\n\nThe following sections walk through how to install and integrate with the extension.\n\n<Note>\n  This feature is currently released as \"experimental\" - please try it out and\n  give us feedback in our [GitHub\n  issues](https://github.com/apollographql/vscode-graphql/issues)!\n</Note>\n\n- Install the Apollo VS Code extension: [start installation](vscode:extension/apollographql.vscode-apollo) | [marketplace page](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo)\n- Set the \"Apollographql > Dev Tools: Show Panel\" setting to \"detect\" or \"always\" in the VS code settings dialog.\n  <img\n    class=\"screenshot\"\n    alt=\"A screenshot of the VS Code settings dialog focusing on the 'Show Panel' option\"\n    src=\"../assets/devtools/vscode-setting.png\"\n  />\n- In your code base, install the `@apollo/client-devtools-vscode` package:\n\n```sh\nnpm install @apollo/client-devtools-vscode\n```\n\n- After initializing your `ApolloClient` instance, call `connectApolloClientToVSCodeDevTools` with your client instance.\n\n```js\nimport { connectApolloClientToVSCodeDevTools } from \"@apollo/client-devtools-vscode\";\n\nconst client = new ApolloClient({\n  /* ... */\n});\n\n// we recommend wrapping this statement in a check for e.g. process.env.NODE_ENV === \"development\"\nconst devtoolsRegistration = connectApolloClientToVSCodeDevTools(\n  client,\n  // the default port of the VSCode DevTools is 7095\n  \"ws://localhost:7095\"\n);\n```\n\n- Open the \"Apollo Client DevTools\" panel in VS Code.\n- Start your application. It should automatically connect to the DevTools.\n  <img\n    class=\"screenshot\"\n    alt=\"Apollo Client Devtools in a VS Code panel\"\n    src=\"../assets/devtools/vscode-panel.png\"\n  />\n"
  },
  {
    "path": "docs/source/development-testing/graphql-codegen.mdx",
    "content": "---\ntitle: GraphQL Codegen\ndescription: How to generate TypeScript types for your application\n---\n\nManually creating types for your GraphQL operations is error prone. As you introduce change, it becomes cumbersome to maintain correct types across your entire application. Additionally, changes to your schema might cause changes to your existing operations. This becomes difficult to track and maintain.\n\nInstead, you can generate your TypeScript definitions automatically with [GraphQL Code Generator](https://www.the-guild.dev/graphql/codegen) using your application's schema to ensure type accuracy.\n\nThis guide provides detail on how to set up GraphQL Codegen in your application to provide types for your GraphQL operations.\n\n<Note>\n\nThis article covers GraphQL Codegen installation and configuration. If you'd like to learn how Apollo Client integrates with TypeScript more generally, read the [TypeScript with Apollo Client](../data/typescript) guide.\n\n</Note>\n\n## Setting up your project\n\nInstall the following packages. This installation assumes you already have [installed `@apollo/client` and its dependencies](../get-started#step-2-install-dependencies).\n\n```bash\nnpm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations\n```\n\n### Recommended starter configuration\n\nNext, we'll create a configuration file for GraphQL Code Generator, named [`codegen.ts`](https://www.the-guild.dev/graphql/codegen/docs/config-reference/codegen-config), at the root of our project. The following is a recommended minimal configuration for Apollo Client apps.\n\n```ts title=\"codegen.ts\"\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n  overwrite: true,\n  schema: \"<URL_OF_YOUR_GRAPHQL_API>\",\n  // This assumes that all your source files are in a top-level `src/` directory - you might need to adjust this to your file structure\n  documents: [\"src/**/*.{ts,tsx}\"],\n  // Don't exit with non-zero status when there are no documents\n  ignoreNoDocuments: true,\n  generates: {\n    // Use a path that works the best for the structure of your application\n    \"./src/types/__generated__/graphql.ts\": {\n      plugins: [\"typescript\", \"typescript-operations\"],\n      config: {\n        avoidOptionals: {\n          // Use `null` for nullable fields instead of optionals\n          field: true,\n          // Allow nullable input fields to remain unspecified\n          inputValue: false,\n        },\n        // Use `unknown` instead of `any` for unconfigured scalars\n        defaultScalarType: \"unknown\",\n        // Apollo Client always includes `__typename` fields\n        nonOptionalTypename: true,\n        // Apollo Client doesn't add the `__typename` field to root types so\n        // don't generate a type for the `__typename` for root operation types.\n        skipTypeNameForRoot: true,\n      },\n    },\n  },\n};\n\nexport default config;\n```\n\n<Note>\n\nThere are multiple ways to [specify a schema](https://www.the-guild.dev/graphql/codegen/docs/config-reference/schema-field#root-level) in your `codegen.ts`. Use the method that best fits your project's needs.\n\n</Note>\n\nFinally, we'll add the script to our `package.json` file:\n\n```json title=\"package.json\"\n{\n  \"scripts\": {\n    \"codegen\": \"graphql-codegen --config codegen.ts\"\n  }\n}\n```\n\nRunning the script generates types based on the schema file or GraphQL API you provided in `codegen.ts`:\n\n```bash showLineNumbers=false\n$ npm run codegen\n✔ Parse Configuration\n✔ Generate outputs\n```\n\n### A note about the `client` preset\n\nIf you follow GraphQL Codegen's [quickstart guide](https://the-guild.dev/graphql/codegen/docs/getting-started/installation), it recommends generating your config file using the GraphQL Code Generator CLI. This wizard installs and configures the [`@graphql-codegen/client-preset`](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client).\n\nWe do not recommend using the client preset with Apollo Client apps because it generates additional runtime code that adds bundle size to your application and includes features that are incompatible with Apollo Client. Instead, we recommend using the [`typescript`](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript) and [`typescript-operations`](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-operations) plugins directly (at minimum), which focus on only generating types and don't include additional runtime code. Follow the steps in the preceding section to use a setup that includes these plugins.\n\nIf you're already using the client preset, or you choose to use it instead of working directly with the plugins, we recommend the following minimal configuration for Apollo Client apps.\n\n```ts\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n  overwrite: true,\n  schema: \"<URL_OF_YOUR_GRAPHQL_API>\",\n  // This assumes that all your source files are in a top-level `src/` directory - you might need to adjust this to your file structure\n  documents: [\"src/**/*.{ts,tsx}\", \"!src/gql/**/*\"],\n  // Don't exit with non-zero status when there are no documents\n  ignoreNoDocuments: true,\n  generates: {\n    // Use a path that works the best for the structure of your application\n    \"./src/gql/\": {\n      preset: \"client\",\n      presetConfig: {\n        // Disable fragment masking\n        fragmentMasking: false,\n      },\n      config: {\n        avoidOptionals: {\n          // Use `null` for nullable fields instead of optionals\n          field: true,\n          // Allow nullable input fields to remain unspecified\n          inputValue: false,\n        },\n        // Use `unknown` instead of `any` for unconfigured scalars\n        defaultScalarType: \"unknown\",\n        // Apollo Client always includes `__typename` fields\n        nonOptionalTypename: true,\n        // Apollo Client doesn't add the `__typename` field to root types so\n        // don't generate a type for the `__typename` for root operation types.\n        skipTypeNameForRoot: true,\n      },\n    },\n  },\n};\n\nexport default config;\n```\n\n<Caution>\n\nThis configuration [disables fragment masking](https://the-guild.dev/graphql/codegen/plugins/presets/preset-client#how-to-disable-fragment-masking) in the client preset because it's incompatible with Apollo Client's data masking functionality. If you are using the generated `useFragment` function or anything generated from the fragment masking feature, you need to migrate away from it to use data masking in Apollo Client. See the guide on [data masking](../data/fragments#data-masking) for more information on using TypeScript with Apollo Client's data masking feature, including instructions on how to migrate away from GraphQL Codegen's fragment masking feature.\n\n</Caution>\n\n## Advanced GraphQL Codegen configuration\n\n### Generating relative types files\n\nAs your application scales, a single types file that contains all operation types might become unwieldy. The [`near-operation-file-preset`](https://the-guild.dev/graphql/codegen/plugins/presets/near-operation-file-preset) makes it possible to generate an operation types file relative to the file where the operation is defined.\n\n```bash\nnpm install -D @graphql-codegen/near-operation-file-preset\n```\n\nThe following is a recommended minimal configuration. See the [`near-operation-file-preset` documentation](https://the-guild.dev/graphql/codegen/plugins/presets/near-operation-file-preset) for additional configuration options, such as customizing the file name or extension.\n\n```ts title=\"codegen.ts\"\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n  overwrite: true,\n  schema: \"<URL_OF_YOUR_GRAPHQL_API>\",\n  // This assumes that all your source files are in a top-level `src/` directory - you might need to adjust this to your file structure\n  documents: [\"src/**/*.{ts,tsx}\"],\n  // Don't exit with non-zero status when there are no documents\n  ignoreNoDocuments: true,\n  generates: {\n    \"./src/types/__generated__/graphql.ts\": {\n      plugins: [\"typescript\"],\n    },\n    \"./src/\": {\n      preset: \"near-operation-file\",\n      presetConfig: {\n        // This should be the file generated by the \"typescript\" plugin above,\n        // relative to the directory specified for this configuration\n        baseTypesPath: \"./types/__generated__/graphql.ts\",\n      },\n      plugins: [\"typescript-operations\"],\n      // Note: these config options moved from the other generated file config\n      config: {\n        avoidOptionals: {\n          // Use `null` for nullable fields instead of optionals\n          field: true,\n          // Allow nullable input fields to remain unspecified\n          inputValue: false,\n        },\n        // Use `unknown` instead of `any` for unconfigured scalars\n        defaultScalarType: \"unknown\",\n        // Apollo Client always includes `__typename` fields\n        nonOptionalTypename: true,\n        // Apollo Client doesn't add the `__typename` field to root types so\n        // don't generate a type for the `__typename` for root operation types.\n        skipTypeNameForRoot: true,\n      },\n    },\n  },\n};\n\nexport default config;\n```\n\n#### Usage\n\nThe following example imports the generated types relative to the current file.\n\n```ts title=\"my-component.ts\"\nimport { useQuery, TypedDocumentNode } from \"@apollo/client/react\";\n// The query name and path might differ depending on your codegen config\nimport {\n  GetRocketInventoryQuery,\n  GetRocketInventoryQueryVariables,\n} from \"./my-component.generated\";\n\nconst GET_ROCKET_INVENTORY: TypedDocumentNode<\n  GetRocketInventoryQuery,\n  GetRocketInventoryQueryVariables\n> = gql`\n  query GetRocketInventory($year: Int!) {\n    rocketInventory(year: $year) {\n      id\n      model\n      year\n      stock\n    }\n  }\n`;\n\nfunction MyComponent() {\n  const { data } = useQuery(GET_ROCKET_INVENTORY, {\n    //    ^? GetRocketInventoryQuery | undefined;\n    variables: { year: 2025 },\n  });\n\n  // ...\n}\n```\n\n### Generating precompiled GraphQL documents with their type definitions\n\nThe `gql` template literal tag is used in Apollo Client apps to define GraphQL documents for use with Apollo Client APIs. Its purpose is to parse the GraphQL string into a standard GraphQL AST. Parsing occurs when the module is executed which adds startup time to your application. Additionally, the GraphQL document returned by `gql` is typed as a `DocumentNode` which doesn't include type information about its data or variables.\n\nThe [`typed-document-node`](https://the-guild.dev/graphql/codegen/plugins/typescript/typed-document-node) plugin makes it possible to generate precompiled GraphQL documents preconfigured with the `TypedDocumentNode` type.\n\n```bash\nnpm install -D @graphql-codegen/typed-document-node\n```\n\nThe following is a recommended minimal configuration which uses the `near-operation-file-preset` configuration from the previous section. If you don't use `near-operation-file-preset`, add the plugin to the file config that uses the `typescript-operations` plugin.\n\n```ts {21} title=\"codegen.ts\"\nimport { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n  overwrite: true,\n  schema: \"<URL_OF_YOUR_GRAPHQL_API>\",\n  // This assumes that all your source files are in a top-level `src/` directory - you might need to adjust this to your file structure\n  documents: [\"src/**/*.{ts,tsx}\"],\n  // Don't exit with non-zero status when there are no documents\n  ignoreNoDocuments: true,\n  generates: {\n    \"./src/types/__generated__/graphql.ts\": {\n      plugins: [\"typescript\"],\n    },\n    \"./src/\": {\n      preset: \"near-operation-file\",\n      presetConfig: {\n        // This should be the file generated by the \"typescript\" plugin above,\n        // relative to the directory specified for this configuration\n        baseTypesPath: \"./types/__generated__/graphql.ts\",\n      },\n      plugins: [\"typescript-operations\", \"typed-document-node\"],\n      // Note: these config options moved from the other generated file config\n      config: {\n        avoidOptionals: {\n          // Use `null` for nullable fields instead of optionals\n          field: true,\n          // Allow nullable input fields to remain unspecified\n          inputValue: false,\n        },\n        // Use `unknown` instead of `any` for unconfigured scalars\n        defaultScalarType: \"unknown\",\n        // Apollo Client always includes `__typename` fields\n        nonOptionalTypename: true,\n        // Apollo Client doesn't add the `__typename` field to root types so\n        // don't generate a type for the `__typename` for root operation types.\n        skipTypeNameForRoot: true,\n      },\n    },\n  },\n};\n\nexport default config;\n```\n\n<Note>\n\nYou might need to change the structure of your application to avoid bundling the query more than once in your application. If you author GraphQL documents using the `gql` template tag, you won't consume the returned GraphQL document since you'll import and use the precompiled document generated by this plugin instead.<br/><br/>\n\nYou may need to tweak your bundler settings to strip out unused variables from your bundle. Alternatively you can author GraphQL operations in `.graphql` files.\n\n</Note>\n\n#### Usage\n\nThe following example imports the query definition from the generated file.\n\n```ts title=\"my-component.ts\"\nimport { useQuery } from \"@apollo/client/react\";\n// The query name and path might differ depending on your codegen config\nimport { getRocketInventoryQuery } from \"./my-component.generated\";\n\nfunction MyComponent() {\n  const { data } = useQuery(getRocketInventoryQuery, {\n    //    ^? GetRocketInventoryQuery | undefined;\n    variables: { year: 2025 },\n  });\n\n  // ...\n}\n```\n"
  },
  {
    "path": "docs/source/development-testing/reducing-bundle-size.mdx",
    "content": "---\ntitle: Reducing bundle size\ndescription: Squeeze those last few bytes out of your production build\n---\n\nEvery byte counts in optimizing your app's performance. This page covers some configuration changes that can help reduce Apollo Client's bundle size:\n\n- Turn off Apollo Client's development mode\n- Pick a consistent style for your imports\n\n## Turning off development mode\n\nBy default, Apollo Client is in \"development mode\". That means Apollo Client performs additional checks and the browser console displays warnings.\nYou can disable development mode by setting `globalThis.__DEV__` to `false`.\nDoing so turns off those checks, but they will still end up in your production bundle—you have to tell your bundler to eliminate those checks at build time!\n\nYou can expect eliminating checks to result in a reduction of 1-3 KB in your production bundle.\n\n### Bundler-specific configuration\n\nHere are some bundler-specific suggestions for configuring your bundler to remove `globalThis.__DEV__` on build time.\n\n#### Vite\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```js title=\"vite.config.js\"\nexport default defineConfig({\n  // ...\n  define: {\n    \"globalThis.__DEV__\": JSON.stringify(false),\n  },\n});\n```\n\n</ExpansionPanel>\n\n#### Next.js\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```js title=\"next.config.js\"\n// ...\n/** @type {import('next').NextConfig} */\nconst nextConfig = {\n  webpack(config, { webpack }) {\n    config.plugins.push(\n      new webpack.DefinePlugin({\n        \"globalThis.__DEV__\": false,\n      })\n    );\n    return config;\n  },\n};\n\nmodule.exports = nextConfig;\n```\n\n</ExpansionPanel>\n\n#### create-react-app\n\nWith `create-react-app`, you need to use a third-party package like [`craco`](https://craco.js.org/) to modify the bundler configuration.\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```js title=\"craco.config.js\"\nconst webpack = require(\"webpack\");\nmodule.exports = {\n  webpack: {\n    plugins: [\n      new webpack.DefinePlugin({\n        \"globalThis.__DEV__\": false,\n      }),\n    ],\n  },\n};\n```\n\n</ExpansionPanel>\n\n#### esbuild\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```json\n{\n  \"define\": {\n    \"globalThis.__DEV__\": \"false\"\n  }\n}\n```\n\n</ExpansionPanel>\n\n#### Webpack\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```js\nconfig.plugins.push(\n  new webpack.DefinePlugin({\n    \"globalThis.__DEV__\": false,\n  })\n);\n```\n\n</ExpansionPanel>\n\n#### Rollup\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```js\nexport default [\n  {\n    // ... input, output, etc.\n    plugins: [\n      minify({\n        mangle: {\n          toplevel: true,\n        },\n        compress: {\n          toplevel: true,\n          global_defs: {\n            \"@globalThis.__DEV__\": \"false\",\n          },\n        },\n      }),\n    ],\n  },\n];\n```\n\n</ExpansionPanel>\n\n#### SWC\n\n<ExpansionPanel title=\"Click to expand suggested configuration\">\n\n```json title=\".swcrc\"\n{\n  \"jsc\": {\n    \"transform\": {\n      \"optimizer\": {\n        \"globals\": {\n          \"vars\": {\n            \"globalThis.__DEV__\": \"false\"\n          }\n        }\n      }\n    }\n  }\n}\n```\n\n</ExpansionPanel>\n\n### Why use `globalThis.__DEV__` instead of `process.env.NODE_ENV`?\n\nApollo Client uses the `__DEV__` variable instead of `process.env.NODE_ENV` because the latter is not available in non-Node.js environments. Apollo Client can be used from a CDN with an ESM import. Usage of the `process` variable within the library in this scenario would cause a crash in your application.\n\nIt's impossible for Apollo Client to use a guard statement like `typeof process !== \"undefined\" && process.env.NODE_ENV !== 'production'` because some bundlers, such as `esbuild`, cannot replace a statement like `typeof process` at build time. The development-only code would remain after the build, resulting in no bundle size reduction.\n\nIn contrast, checking for `globalThis.__DEV__` does not crash the browser and can be eliminated by every bundler.\n\n## Importing Apollo Client\n\nDepending on your bundler's capabilities and settings, you can use multiple styles of importing from Apollo Client.\n\n### Picking an import style\n\nApollo Client offers these two styles of imports:\n\n```js\n// \"main entrypoint import\" style\nimport { ApolloClient, InMemoryCache, useQuery } from \"@apollo/client\";\n\n// \"deep entrypoint import\" style\nimport { ApolloClient, InMemoryCache } from \"@apollo/client/core\";\nimport { useQuery } from \"@apollo/client/react/hooks\";\n```\n\nWith many modern bundlers, it should not matter which of these styles you choose.<br />\nIt is important to keep in mind though that bundlers are complex and it might make a difference - especially when your bundler picks up the CommonJS artifacts instead of the ESM artifacts.<br />\nEvery bundling setup is different and we cannot guarantee which style results in the smallest bundle size. We recommend trying out these styles in a small setup to determine which results in the best outcome in your environment.\n\n<Note>\n\nSome entry points are not part of the \"main\" entry point `'@apollo/client'` and can only be imported directly, for example, from `'@apollo/client/link/batch'`. It's fine to use these, even when using the \"main\" entry point.\n\n</Note>\n\n## Why have a larger library in the first place?\n\nApollo Client is more than a data fetcher. It's a normalized request and response cache, state manager, and React component integration, including React testing utilities.\n\nTo build a similar experience with other libraries, you need to write custom logic, libraries, and component wrappers. Scaling this custom code to all your app components often creates a bundle larger than Apollo Client's.\n\nA custom implementation also means extra maintenance work for your team. By using Apollo Client, you hand off that ownership to a team specializing in GraphQL clients.\n"
  },
  {
    "path": "docs/source/development-testing/schema-driven-testing.mdx",
    "content": "---\ntitle: Schema-driven testing\ndescription: Using createTestSchema and associated APIs\n---\n\n<Caution>\n  The testing utilities described in this document are deprecated and will be\n  removed in [Apollo Client\n  v4](https://community.apollographql.com/t/apollo-client-v4-alpha-releases-are-here/8719)\n  in June 2025. Please use [GraphQL Testing\n  Library](https://github.com/apollographql/graphql-testing-library) instead.\n</Caution>\n\nThis article describes best practices for writing integration tests using testing utilities released as experimental in v3.10. These testing tools allow developers to execute queries against a schema configured with mock resolvers and default scalar values in order to test an entire Apollo Client application, including the [link chain](/react/api/link/introduction).\n\n## Guiding principles\n\nKent C. Dodds [said it best](https://twitter.com/kentcdodds/status/977018512689455106):\n\n> The more your tests resemble the way your software is used, the more confidence they can give you.\n\nWhen it comes to testing applications built with Apollo Client, this means validating the code path your users' requests will travel from the UI to the network layer and back.\n\nUnit-style testing with [`MockedProvider`](/react/development-testing/testing) can be useful for testing individual components—or even entire pages or React subtrees—in isolation by mocking the expected response data for individual operations. However, it's important to also test the integration of your components with the network layer. That's where schema-driven testing comes in.\n\n> This page is heavily inspired by the excellent [Redux documentation](https://redux.js.org/usage/writing-tests#guiding-principles); the same principles apply to Apollo Client.\n\n## `createTestSchema` and `createSchemaFetch`\n\n### Installation\n\nFirst, ensure you have installed Apollo Client v3.10 or greater. Then, install the following peer dependencies:\n\n```bash\nnpm i @graphql-tools/merge @graphql-tools/schema @graphql-tools/utils undici --save-dev\n```\n\nConsider a React application that fetches a list of products from a GraphQL server:\n\n<ExpansionPanel title=\"Click to expand\">\n\n```tsx title=\"products.tsx\"\nimport { gql, TypedDocumentNode, useSuspenseQuery } from \"@apollo/client\";\n\ntype ProductsQuery = {\n  products: Array<{\n    __typename: \"Product\";\n    id: string;\n    title: string;\n    mediaUrl: string;\n  }>;\n};\n\nconst PRODUCTS_QUERY: TypedDocumentNode<ProductsQuery> = gql`\n  query ProductsQuery {\n    products {\n      id\n      title\n      mediaUrl\n    }\n  }\n`;\n\nexport function Products() {\n  const { data } = useSuspenseQuery(PRODUCTS_QUERY);\n\n  return (\n    <div>\n      {data.products.map((product) => (\n        <p key={product.id}>\n          <a href={product.mediaUrl}>\n            {product.title} - {product.id}\n          </a>\n        </p>\n      ))}\n    </div>\n  );\n}\n```\n\n</ExpansionPanel>\n\nNow let's write some tests using a test schema created with the `createTestSchema` utility that can then be used to create a mock fetch implementation with `createSchemaFetch`.\n\n### Configuring your test environment\n\nFirst, some Node.js globals will need to be polyfilled in order for JSDOM tests to run correctly. Create a file called e.g. `jest.polyfills.js`:\n\n```js title=\"jest.polyfills.js\"\n/**\n * @note The block below contains polyfills for Node.js globals\n * required for Jest to function when running JSDOM tests.\n * These have to be require's and have to be in this exact\n * order, since \"undici\" depends on the \"TextEncoder\" global API.\n */\n\nconst { TextDecoder, TextEncoder } = require(\"node:util\");\nconst { ReadableStream } = require(\"node:stream/web\");\nconst { clearImmediate } = require(\"node:timers\");\nconst { performance } = require(\"node:perf_hooks\");\n\nObject.defineProperties(globalThis, {\n  TextDecoder: { value: TextDecoder },\n  TextEncoder: { value: TextEncoder },\n  ReadableStream: { value: ReadableStream },\n  performance: { value: performance },\n  clearImmediate: { value: clearImmediate },\n});\n\nconst { Blob, File } = require(\"node:buffer\");\nconst { fetch, Headers, FormData, Request, Response } = require(\"undici\");\n\nObject.defineProperties(globalThis, {\n  fetch: { value: fetch, writable: true },\n  Response: { value: Response },\n  Blob: { value: Blob },\n  File: { value: File },\n  Headers: { value: Headers },\n  FormData: { value: FormData },\n  Request: { value: Request },\n});\n\n// Note: if your environment supports it, you can use the `using` keyword\n// but must polyfill Symbol.dispose here with Jest versions <= 29\n// where Symbol.dispose is not defined\n//\n// Jest bug: https://github.com/jestjs/jest/issues/14874\n// Fix is available in https://github.com/jestjs/jest/releases/tag/v30.0.0-alpha.3\nif (!Symbol.dispose) {\n  Object.defineProperty(Symbol, \"dispose\", {\n    value: Symbol(\"dispose\"),\n  });\n}\nif (!Symbol.asyncDispose) {\n  Object.defineProperty(Symbol, \"asyncDispose\", {\n    value: Symbol(\"asyncDispose\"),\n  });\n}\n```\n\nNow, in a `jest.config.ts` or `jest.config.js` file, add the following configuration:\n\n```ts title=\"jest.config.ts\"\nimport type { Config } from \"jest\";\n\nconst config: Config = {\n  globals: {\n    \"globalThis.__DEV__\": JSON.stringify(true),\n  },\n  testEnvironment: \"jsdom\",\n  setupFiles: [\"./jest.polyfills.js\"],\n  // You may also have an e.g. setupTests.ts file here\n  setupFilesAfterEnv: [\"<rootDir>/setupTests.ts\"],\n  // If you're using MSW, opt out of the browser export condition for MSW tests\n  // For more information, see: https://github.com/mswjs/msw/issues/1786#issuecomment-1782559851\n  testEnvironmentOptions: {\n    customExportConditions: [\"\"],\n  },\n  // If you plan on importing .gql/.graphql files in your tests, transform them with @graphql-tools/jest-transform\n  transform: {\n    \"\\\\.(gql|graphql)$\": \"@graphql-tools/jest-transform\",\n  },\n};\n\nexport default config;\n```\n\nIn the example `setupTests.ts` file below, `@testing-library/jest-dom` is imported to allow the use of custom `jest-dom` matchers (see the [`@testing-library/jest-dom` documentation](https://github.com/testing-library/jest-dom?tab=readme-ov-file#usage) for more information) and fragment warnings are disabled which can pollute the test output:\n\n```ts title=\"setupTests.ts\"\nimport \"@testing-library/jest-dom\";\nimport { gql } from \"@apollo/client\";\n\ngql.disableFragmentWarnings();\n```\n\n### Testing with MSW\n\nNow, let's write a test for the `Products` component using [MSW](https://mswjs.io/).\n\nMSW is a powerful tool for intercepting network traffic and mocking responses. Read more about its design and philosophy [here](https://mswjs.io/blog/why-mock-service-worker/).\n\nMSW has the concept of [handlers](https://mswjs.io/docs/best-practices/structuring-handlers/) that allow network requests to be intercepted. Let's create a handler that will intercept all GraphQL operations:\n\n```ts title=\"src/__tests__/handlers.ts\"\nimport { graphql, HttpResponse } from \"msw\";\nimport { execute } from \"graphql\";\nimport type { ExecutionResult } from \"graphql\";\nimport type { ObjMap } from \"graphql/jsutils/ObjMap\";\nimport { gql } from \"@apollo/client\";\nimport { createTestSchema } from \"@apollo/client/testing/experimental\";\nimport { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport graphqlSchema from \"../../../schema.graphql\";\n\n// First, create a static schema...\nconst staticSchema = makeExecutableSchema({ typeDefs: graphqlSchema });\n\n// ...which is then passed as the first argument to `createTestSchema`\n// along with mock resolvers and default scalar values.\nexport let testSchema = createTestSchema(staticSchema, {\n  resolvers: {\n    Query: {\n      products: () => [\n        {\n          id: \"1\",\n          title: \"Blue Jays Hat\",\n        },\n      ],\n    },\n  },\n  scalars: {\n    Int: () => 6,\n    Float: () => 22.1,\n    String: () => \"string\",\n  },\n});\n\nexport const handlers = [\n  // Intercept all GraphQL operations and return a response generated by the\n  // test schema. Add additional handlers as needed.\n  graphql.operation<ExecutionResult<ObjMap<unknown>, ObjMap<unknown>>>(\n    async ({ query, variables, operationName }) => {\n      const document = gql(query);\n\n      const result = await execute({\n        document,\n        operationName,\n        schema: testSchema,\n        variableValues: variables,\n      });\n\n      return HttpResponse.json(result);\n    }\n  ),\n];\n```\n\nMSW can be used in [the browser](https://mswjs.io/docs/integrations/browser), in [Node.js](https://mswjs.io/docs/integrations/node) and in [React Native](https://mswjs.io/docs/integrations/react-native). Since this example is using Jest and JSDOM to run tests in a Node.js environment, let's configure the server per the [Node.js integration guide](https://mswjs.io/docs/integrations/node):\n\n```ts title=\"src/__tests__/server.ts\"\nimport { setupServer } from \"msw/node\";\nimport { handlers } from \"./handlers\";\n\n// This configures a request mocking server with the given request handlers.\nexport const server = setupServer(...handlers);\n```\n\nFinally, let's do server set up and teardown in the `setupTests.ts` file created in the previous step:\n\n```ts title=\"setupTests.ts\" {6-8}\nimport \"@testing-library/jest-dom\";\nimport { gql } from \"@apollo/client\";\n\ngql.disableFragmentWarnings();\n\nbeforeAll(() => server.listen({ onUnhandledRequest: \"error\" }));\nafterAll(() => server.close());\nafterEach(() => server.resetHandlers());\n```\n\nFinally, let's write some tests 🎉\n\n```tsx title=\"src/__tests__/products.test.tsx\"\nimport { Suspense } from \"react\";\nimport { render as rtlRender, screen } from \"@testing-library/react\";\nimport {\n  ApolloClient,\n  ApolloProvider,\n  NormalizedCacheObject,\n} from \"@apollo/client\";\nimport { testSchema } from \"./handlers\";\nimport { Products } from \"../products\";\n// This should be a function that returns a new ApolloClient instance\n// configured just like your production Apollo Client instance - see the FAQ.\nimport { makeClient } from \"../client\";\n\nconst render = (renderedClient: ApolloClient) =>\n  rtlRender(\n    <ApolloProvider client={renderedClient}>\n      <Suspense fallback=\"Loading...\">\n        <Products />\n      </Suspense>\n    </ApolloProvider>\n  );\n\ndescribe(\"Products\", () => {\n  test(\"renders\", async () => {\n    render(makeClient());\n\n    await screen.findByText(\"Loading...\");\n\n    // This is the data from our initial mock resolver in the test schema\n    // defined in the handlers file 🎉\n    expect(await screen.findByText(/blue jays hat/i)).toBeInTheDocument();\n  });\n\n  test(\"allows resolvers to be updated via .add\", async () => {\n    // Calling .add on the test schema will update the resolvers\n    // with new data\n    testSchema.add({\n      resolvers: {\n        Query: {\n          products: () => {\n            return [\n              {\n                id: \"2\",\n                title: \"Mets Hat\",\n              },\n            ];\n          },\n        },\n      },\n    });\n\n    render(makeClient());\n\n    await screen.findByText(\"Loading...\");\n\n    // Our component now renders the new data from the updated resolver\n    await screen.findByText(/mets hat/i);\n  });\n\n  test(\"handles test schema resetting via .reset\", async () => {\n    // Calling .reset on the test schema will reset the resolvers\n    testSchema.reset();\n\n    render(makeClient());\n\n    await screen.findByText(\"Loading...\");\n\n    // The component now renders the initial data configured on the test schema\n    await screen.findByText(/blue jays hat/i);\n  });\n});\n```\n\n### Testing by mocking fetch with `createSchemaFetch`\n\nFirst, import `createSchemaFetch` and `createTestSchema` from the new `@apollo/client/testing` entrypoint. Next, import a local copy of your graph's schema: jest should be configured to transform `.gql` or `.graphql` files using `@graphql-tools/jest-transform` (see the `jest.config.ts` example configuration above.)\n\nHere's how an initial set up of the test file might look:\n\n```tsx title=\"products.test.tsx\"\nimport {\n  createSchemaFetch,\n  createTestSchema,\n} from \"@apollo/client/testing/experimental\";\nimport { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport { render as rtlRender, screen } from \"@testing-library/react\";\nimport graphqlSchema from \"../../../schema.graphql\";\n// This should be a function that returns a new ApolloClient instance\n// configured just like your production Apollo Client instance - see the FAQ.\nimport { makeClient } from \"../../client\";\nimport { ApolloProvider, NormalizedCacheObject } from \"@apollo/client\";\nimport { Products } from \"../../products\";\nimport { Suspense } from \"react\";\n\n// First, let's create an executable schema...\nconst staticSchema = makeExecutableSchema({ typeDefs: graphqlSchema });\n\n// which is then passed as the first argument to `createTestSchema`.\nconst schema = createTestSchema(staticSchema, {\n  // Next, let's define mock resolvers\n  resolvers: {\n    Query: {\n      products: () =>\n        Array.from({ length: 5 }, (_element, id) => ({\n          id,\n          mediaUrl: `https://example.com/image${id}.jpg`,\n        })),\n    },\n  },\n  // ...and default scalar values\n  scalars: {\n    Int: () => 6,\n    Float: () => 22.1,\n    String: () => \"default string\",\n  },\n});\n\n// This `render` helper function would typically be extracted and shared between\n// test files.\nconst render = (renderedClient: ApolloClient) =>\n  rtlRender(\n    <ApolloProvider client={renderedClient}>\n      <Suspense fallback=\"Loading...\">\n        <Products />\n      </Suspense>\n    </ApolloProvider>\n  );\n```\n\nNow let's write some tests 🎉\n\nFirst, `createSchemaFetch` can be used to mock the global `fetch` implementation with one that resolves network requests with payloads generated from the test schema.\n\n```tsx title=\"products.test.tsx\"\ndescribe(\"Products\", () => {\n  it(\"renders\", async () => {\n    using _fetch = createSchemaFetch(schema).mockGlobal();\n\n    render(makeClient());\n\n    await screen.findByText(\"Loading...\");\n\n    // title is rendering the default string scalar\n    const findAllByText = await screen.findAllByText(/default string/);\n    expect(findAllByText).toHaveLength(5);\n\n    // the products resolver is returning 5 products\n    await screen.findByText(/0/);\n    await screen.findByText(/1/);\n    await screen.findByText(/2/);\n    await screen.findByText(/3/);\n    await screen.findByText(/4/);\n  });\n});\n```\n\n#### A note on `using` and explicit resource management\n\nYou may have noticed a new keyword in the first line of the test above: `using`.\n\n`using` is part of a [proposed new language feature](https://github.com/tc39/proposal-explicit-resource-management) which is currently at Stage 3 of the TC39 proposal process.\n\nIf you are using TypeScript 5.2 or greater, or using Babel's [`@babel/plugin-proposal-explicit-resource-management` plugin](https://babeljs.io/docs/babel-plugin-proposal-explicit-resource-management), you can use the `using` keyword to automatically perform some cleanup when `_fetch` goes out of scope. In our case, this is when the test is complete; this means restoring the global fetch function to its original state automatically after each test.\n\nIf your environment does not support explicit resource management, you'll find that calling `mockGlobal()` returns a restore function that you can manually call at the end of each test:\n\n```tsx title=\"products.test.tsx\"\ndescribe(\"Products\", () => {\n  it(\"renders\", async () => {\n    const { restore } = createSchemaFetch(schema).mockGlobal();\n\n    render(makeClient());\n\n    // make assertions against the rendered DOM output\n\n    restore();\n  });\n});\n```\n\n## Modifying a test schema using `testSchema.add` and `testSchema.fork`\n\nIf you need to make changes to the behavior of a schema after it has been created, you can use the `testSchema.add` method to add new resolvers to the schema or overwrite existing ones.\nThis can be useful for testing scenarios where the behavior of the schema needs to change inside a test.\n\n````tsx title=\"products.test.tsx\"\ndescribe(\"Products\", () => {\n  it(\"renders\", async () => {\n    const { restore } = createSchemaFetch(schema).mockGlobal();\n\n    render(makeClient());\n\n    // make assertions against the rendered DOM output\n\n    // Here we want to change the return value of the `products` resolver\n    // for the next outgoing query.\n    testSchema.add({\n      resolvers: {\n        Query: {\n          products: () =>\n            Array.from({ length: 5 }, (_element, id) => ({\n              // we want to return ids starting from 5 for the second request\n              id: id + 5,\n              mediaUrl: `https://example.com/image${id + 5}.jpg`,\n            })),\n        },\n      },\n    });\n\n    // trigger a new query with a user interaction\n    userEvent.click(screen.getByText(\"Fetch more\"));\n\n    // make assertions against the rendered DOM output\n\n    restore();\n    testSchema.reset();\n  });\n});\n```\n\nAlternatively, you can use `testSchema.fork` to create a new schema with the same configuration as the original schema,\nbut with the ability to make changes to the new isolated schema without affecting the original schema.\nThis can be useful if you just want to mock the global fetch function with a different schema for each test without\nhaving to care about resetting your original testSchema.\nYou could also write incremental tests where each test builds on the previous one.\n\nIf you use MSW, you will probably end up using `testSchema.add`, as MSW needs to be set up with a single schema for all tests.\nIf you are going the `createSchemaFetch` route, you can use `testSchema.fork` to create a new schema for each test,\nand then use `forkedSchema.add` to make changes to the schema for that test.\n\n```tsx\nconst baseSchema = createTestSchema(staticSchema, {\n  resolvers: {\n    // ...\n  },\n  scalars: {\n    // ...\n  },\n});\n\ntest(\"a test\", () => {\n  const forkedSchema = baseSchema.fork();\n\n  const { restore } = createSchemaFetch(forkedSchema).mockGlobal();\n\n  // make assertions against the rendered DOM output\n\n  forkedSchema.add({\n    // ...\n  });\n\n  restore();\n  // forkedSchema will just be discarded, and there is no need to reset it\n});\n````\n\n### FAQ\n\n#### When should I use `createSchemaFetch` vs [MSW](https://mswjs.io/)?\n\nThere are many benefits to using [MSW](https://mswjs.io/): it's a powerful tool with a great set of APIs. Read more about its philosophy and benefits [here](https://mswjs.io/blog/why-mock-service-worker/).\n\nWherever possible, use MSW: it enables more realistic tests that can catch more bugs by intercepting requests _after_ they've been dispatched by an application. MSW also supports both REST and GraphQL handlers, so if your application uses a combination (e.g. to fetch data from a third party endpoint), MSW will provide more flexibility than `createSchemaFetch`, which is a more lightweight solution.\n\n#### Should I share a single `ApolloClient` instance between tests?\n\nNo; please create a new instance of `ApolloClient` for each test. Even if the cache is reset in between tests, the client maintains some internal state that is not reset. This could have some unintended consequences. For example, the `ApolloClient` instance could have pending queries that could cause the following test's queries to be deduplicated by default.\n\nInstead, create a `makeClient` function or equivalent so that every test uses the same client configuration as your production client, but no two tests share the same client instance. Here's an example:\n\n<ExpansionPanel title=\"Click to expand\">\n\n```ts title=\"src/client.ts\"\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\n\nconst httpLink = new HttpLink({\n  uri: \"https://example.com/graphql\",\n});\n\nexport const makeClient = () => {\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n  });\n};\n\nexport const client = makeClient();\n```\n\n</ExpansionPanel>\n\nThis way, every test can use `makeClient` to create a new client instance, and you can still use `client` in your production code.\n\n#### Can I use these testing tools with Vitest?\n\nUnfortunately not at the moment. This is caused by a known limitation with the `graphql` package and tools that bundle ESM by default known as the [dual package hazard](https://nodejs.org/api/packages.html#dual-package-hazard).\n\nPlease see [this issue](https://github.com/graphql/graphql-js/issues/4062) to track the related discussion on the `graphql/graphql-js` repository.\n\n## Sandbox example\n\nFor a working example that demonstrates how to use both Testing Library and Mock Service Worker to write integration tests with `createTestSchema`, check out this project on CodeSandbox:\n\n<a href=\"https://codesandbox.io/p/sandbox/github/apollographql/docs-examples/tree/main/apollo-client/v3/schema-driven-testing\">\n  <img\n    src=\"https://codesandbox.io/static/img/play-codesandbox.svg\"\n    width=\"12em\"\n    alt=\"Edit Testing React Components\"\n    style=\"display: inline;\"\n    noZoom\n  />\n</a>\n"
  },
  {
    "path": "docs/source/development-testing/testing.mdx",
    "content": "---\ntitle: Testing React components\ndescription: Using MockedProvider and associated APIs\n---\n\nThis article describes best practices for testing React components that use Apollo Client.\n\nThe examples below use [Jest](https://facebook.github.io/jest/docs/en/tutorial-react.html) and [React Testing Library](https://github.com/testing-library/react-testing-library), but the concepts apply to any testing framework.\n\n## The `MockedProvider` component\n\nEvery test for a React component that uses Apollo Client must make Apollo Client available on [React's context](https://react.dev/reference/react/useContext). In application code, you achieve this by wrapping your component tree with the `ApolloProvider` component. In your tests, you use the `MockedProvider` component instead.\n\nThe `MockedProvider` component enables you to define mock responses for individual queries that are executed in your test. This means your test _doesn't_ need to communicate with a GraphQL server, which removes an external dependency and therefore improves the test's reliability.\n\n### Example\n\nLet's say we want to test the following `Dog` component, which executes a basic query and displays its result:\n\n<ExpansionPanel title=\"Click to expand 🐶\">\n\n```jsx title=\"dog.jsx\"\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\n// Make sure that both the query and the component are exported\nexport const GET_DOG_QUERY = gql`\n  query GetDog($name: String) {\n    dog(name: $name) {\n      id\n      name\n      breed\n    }\n  }\n`;\n\nexport function Dog({ name }) {\n  const { loading, error, data } = useQuery(GET_DOG_QUERY, {\n    variables: { name },\n  });\n  if (loading) return <p>Loading...</p>;\n  if (error) return <p>{error.message}</p>;\n  return (\n    <p>\n      {data.dog.name} is a {data.dog.breed}\n    </p>\n  );\n}\n```\n\n</ExpansionPanel>\n\nA basic rendering test for the component looks like this (minus mocked responses):\n\n```jsx title=\"dog.test.js\"\nimport \"@testing-library/jest-dom\";\nimport { render, screen } from \"@testing-library/react\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport { GET_DOG_QUERY, Dog } from \"./dog\";\n\nconst mocks = []; // We'll fill this in next\n\nit(\"renders without error\", async () => {\n  render(\n    <MockedProvider mocks={mocks}>\n      <Dog name=\"Buck\" />\n    </MockedProvider>\n  );\n  expect(await screen.findByText(\"Loading...\")).toBeInTheDocument();\n});\n```\n\n> **Note:** Usually, you import `@testing-library/jest-dom` in your [test setup file](https://jestjs.io/docs/configuration), which provides certain [custom jest matchers](https://github.com/testing-library/jest-dom#custom-matchers) (such as `toBeInTheDocument`). The import is included in these examples for completeness.\n\n#### Defining mocked responses\n\nThe `mocks` prop of `MockedProvider` is an array of objects, each of which defines the mock response for a single operation. Let's define a mocked response for `GET_DOG_QUERY` when it's passed the `name` `Buck`:\n\n```jsx title=\"dog.test.js\"\nconst mocks = [\n  {\n    request: {\n      query: GET_DOG_QUERY,\n      variables: {\n        name: \"Buck\",\n      },\n    },\n    result: {\n      data: {\n        dog: { __typename: \"Dog\", id: \"1\", name: \"Buck\", breed: \"bulldog\" },\n      },\n    },\n  },\n];\n```\n\nEach mock object defines a `request` field (indicating the shape and variables of the operation to match against) and a `result` field (indicating the shape of the response to return for that operation).\n\n> **Your test must execute an operation that _exactly_ matches a mock's shape _and_ variables to receive the associated mocked response.**\n\nAlternatively, the `result` field can be a function that returns a mocked response after performing arbitrary logic:\n\n```jsx\nresult: (variables) => { // `variables` is optional\n  // ...arbitrary logic...\n\n  return {\n    data: {\n      dog: { __typename: 'Dog', id: '1', name: 'Buck', breed: 'bulldog' },\n    },\n  }\n},\n```\n\nCombining our code above, we get the following complete test:\n\n<ExpansionPanel title=\"Click to expand 🐶\">\n\n```jsx title=\"dog.test.js\"\nimport \"@testing-library/jest-dom\";\nimport { render, screen } from \"@testing-library/react\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport { GET_DOG_QUERY, Dog } from \"./dog\";\n\nconst mocks = [\n  {\n    request: {\n      query: GET_DOG_QUERY,\n      variables: {\n        name: \"Buck\",\n      },\n    },\n    result: {\n      data: {\n        dog: { __typename: \"Dog\", id: \"1\", name: \"Buck\", breed: \"bulldog\" },\n      },\n    },\n  },\n];\n\nit(\"renders without error\", async () => {\n  render(\n    <MockedProvider mocks={mocks}>\n      <Dog name=\"Buck\" />\n    </MockedProvider>\n  );\n  expect(await screen.findByText(\"Loading...\")).toBeInTheDocument();\n});\n```\n\n</ExpansionPanel>\n\n#### Reusing mocks\n\nBy default, a mock is only used once. If you want to reuse a mock for multiple operations, you can set the `maxUsageCount` field to a number indicating how many times the mock should be used:\n\n<ExpansionPanel title=\"Click to expand 🐶\">\n\n```jsx title=\"dog.test.js\"\nimport { GET_DOG_QUERY } from \"./dog\";\n\nconst mocks = [\n  {\n    request: {\n      query: GET_DOG_QUERY,\n      variables: {\n        name: \"Buck\",\n      },\n    },\n    result: {\n      data: {\n        dog: { __typename: \"Dog\", id: \"1\", name: \"Buck\", breed: \"bulldog\" },\n      },\n    },\n    maxUsageCount: 2, // The mock can be used twice before it's removed, default is 1\n  },\n];\n```\n\n</ExpansionPanel>\n\nPassing `Number.POSITIVE_INFINITY` will cause the mock to be reused indefinitely.\n\n### Dynamic variables\n\nSometimes, you don't know the exact value of the variables for a query. The `variables` property of the `MockedResponse` object accepts a callback function that takes the variables and returns a boolean indicating whether this mock should match the invocation for the provided query.\n\nFor example, this mock will match all dog queries:\n\n```ts\nimport { MockedResponse } from \"@apollo/client/testing\";\n\nconst dogMock: MockedResponse<Data, Variables> = {\n  request: {\n    query: GET_DOG_QUERY,\n    variables: (variables) => true,\n  },\n  result: {\n    data: { dog: { __typename: \"Dog\", id: 1, name: \"Buck\", breed: \"poodle\" } },\n  },\n};\n```\n\nThis can also be useful for asserting specific variables individually:\n\n```ts\nimport { MockedResponse } from \"@apollo/client/testing\";\n\nconst dogMock: MockedResponse<Data, Variables> = {\n  request: {\n    query: GET_DOG_QUERY,\n    variables: jest.fn().mockReturnValue(true),\n  },\n  result: {\n    data: { dog: { __typename: \"Dog\", id: 1, name: \"Buck\", breed: \"poodle\" } },\n  },\n};\n\nexpect(dogMock.request.variables).toHaveBeenCalledWith(\n  expect.objectContaining({\n    name: \"Buck\",\n  })\n);\n```\n\n## Testing the \"loading\" and \"success\" states\n\nTo test how your component is rendered after its query completes, Testing Library provides several `findBy` methods. From the [Testing Library docs](https://testing-library.com/docs/dom-testing-library/api-async/#findby-queries):\n\n> `findBy` queries work when you expect an element to appear but the change to the DOM might not happen immediately.\n\nWe can use the asynchronous `screen.findByText` method to query the DOM elements containing the loading message first, followed by the success message `\"Buck is a poodle\"` (which appears after our query completes):\n\n```jsx\nit(\"should render dog\", async () => {\n  const dogMock = {\n    delay: 30 // to prevent React from batching the loading state away\n    // delay: Infinity // if you only want to test the loading state\n\n    request: {\n      query: GET_DOG_QUERY,\n      variables: { name: \"Buck\" }\n    },\n    result: {\n      data: { dog: { __typename: \"Dog\", id: 1, name: \"Buck\", breed: \"poodle\" } }\n    }\n  };\n  render(\n    <MockedProvider mocks={[dogMock]}>\n      <Dog name=\"Buck\" />\n    </MockedProvider>\n  );\n  expect(await screen.findByText(\"Loading...\")).toBeInTheDocument();\n  expect(await screen.findByText(\"Buck is a poodle\")).toBeInTheDocument();\n});\n```\n\n## Testing error states\n\nYour component's error states are just as important to test as its success state, if not more so. You can use the `MockedProvider` component to simulate both network errors and GraphQL errors.\n\n- Network errors are errors that occur while your client attempts to communicate with your GraphQL server.\n- GraphQL errors are errors that occur while your GraphQL server attempts to resolve your client's operation.\n\n### Network errors\n\nTo simulate a network error, you can include an `error` field in your test's mock object, instead of the `result` field:\n\n```jsx\nit(\"should show error UI\", async () => {\n  const dogMock = {\n    request: {\n      query: GET_DOG_QUERY,\n      variables: { name: \"Buck\" },\n    },\n    error: new Error(\"An error occurred\"),\n  };\n  render(\n    <MockedProvider mocks={[dogMock]}>\n      <Dog name=\"Buck\" />\n    </MockedProvider>\n  );\n  expect(await screen.findByText(\"An error occurred\")).toBeInTheDocument();\n});\n```\n\nIn this case, when the `Dog` component executes its query, the `MockedProvider` returns the corresponding error. This applies the error state to our `Dog` component, enabling us to verify that the error is handled gracefully.\n\n### GraphQL errors\n\nTo simulate GraphQL errors, you define an `errors` field _inside_ a mock's `result` field. The value of this field is an array of instantiated `GraphQLError` objects:\n\n```js\nconst dogMock = {\n  // ...\n  result: {\n    errors: [new GraphQLError(\"Error!\")],\n  },\n};\n```\n\nBecause GraphQL supports returning partial results when an error occurs, a mock object's `result` can include both `errors` _and_ `data`.\n\n## Testing mutations\n\nYou test components that use `useMutation` similarly to how you test components that use `useQuery`. Just like in your application code, the primary _difference_ is that you need to call the mutation's **mutate function** to actually execute the operation.\n\n### Example\n\nThe following `DeleteButton` component executes the `DELETE_DOG_MUTATION` to delete a dog named `Buck` from our graph (don't worry, Buck will be fine 🐶):\n\n```jsx title=\"delete-dog.jsx\"\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useMutation } from \"@apollo/client/react\";\n\nexport const DELETE_DOG_MUTATION = gql`\n  mutation deleteDog($name: String!) {\n    deleteDog(name: $name) {\n      id\n      name\n      breed\n    }\n  }\n`;\n\nexport function DeleteButton() {\n  const [mutate, { loading, error, data }] = useMutation(DELETE_DOG_MUTATION);\n\n  if (loading) return <p>Loading...</p>;\n  if (error) return <p>Error!</p>;\n  if (data) return <p>Deleted!</p>;\n\n  return (\n    <button onClick={() => mutate({ variables: { name: \"Buck\" } })}>\n      Click to Delete Buck\n    </button>\n  );\n}\n```\n\nWe can test the initial rendering of this component just like we [tested our `Dog` component](#example):\n\n```jsx title=\"delete-dog.test.js\"\nimport \"@testing-library/jest-dom\";\nimport userEvent from \"@testing-library/user-event\";\nimport { render, screen } from \"@testing-library/react\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport { DeleteButton, DELETE_DOG_MUTATION } from \"./delete-dog\";\n\nit(\"should render without error\", () => {\n  render(\n    <MockedProvider mocks={[]}>\n      <DeleteButton />\n    </MockedProvider>\n  );\n});\n```\n\nIn the test above, `DELETE_DOG_MUTATION` is _not_ executed, because the mutate function is not called.\n\nThe following test _does_ execute the mutation by clicking the button:\n\n```jsx title=\"delete-dog.test.js\"\nit(\"should render loading and success states on delete\", async () => {\n  const deleteDog = { __typename: \"Dog\", name: \"Buck\", breed: \"Poodle\", id: 1 };\n  const mocks = [\n    {\n      request: {\n        query: DELETE_DOG_MUTATION,\n        variables: { name: \"Buck\" },\n      },\n      result: { data: deleteDog },\n    },\n  ];\n\n  render(\n    <MockedProvider mocks={mocks}>\n      <DeleteButton />\n    </MockedProvider>\n  );\n\n  // Find the button element...\n  const button = await screen.findByText(\"Click to Delete Buck\");\n  userEvent.click(button); // Simulate a click and fire the mutation\n\n  expect(await screen.findByText(\"Loading...\")).toBeInTheDocument();\n  expect(await screen.findByText(\"Deleted!\")).toBeInTheDocument();\n});\n```\n\nAgain, this example is similar to [the `useQuery`-based component above](#example), but it differs after the rendering is completed. Because this component relies on a button click to fire a mutation, we use Testing Library's [user-event](https://github.com/testing-library/user-event) library to simulate a click with its `click` method. This fires off the mutation, and the rest of the test runs as expected.\n\nRemember that the mock's value for `result` can also be a function, so you can perform arbitrary logic (like setting a boolean to indicate that the mutation completed) before returning its result.\n\n[Testing error states](#testing-error-states) for mutations is identical to testing them for queries.\n\n## Testing with the cache\n\nIf your application sets any [cache configuration options](../caching/cache-configuration/#configuration-options) (such as `possibleTypes` or `typePolicies`), you should provide `MockedProvider` with an instance of `InMemoryCache` that sets the exact same options:\n\n```jsx\nconst cache = new InMemoryCache({\n  // ...configuration options...\n})\n\n<MockedProvider mocks={mocks} cache={cache}>\n  <DeleteButton />\n</MockedProvider>,\n```\n\nThe following sample specifies `possibleTypes` and `typePolicies` in its cache configuration, both of which must also be specified in relevant tests to prevent unexpected behavior.\n\n<ExpansionPanel title=\"Click to expand 🐶\">\n\n```jsx\n// \"Dog\" supertype can be of type \"ShibaInu\"\nconst ShibaFragment = gql`\n  fragment ShibaInuFields on Dog {\n    ... on ShibaInu {\n      tail {\n        isCurly\n      }\n    }\n  }\n`;\n\nexport const GET_DOG_QUERY = gql`\n  query GetDog($name: String) {\n    dog(name: $name) {\n      id\n      name\n      breed\n\n      ...ShibaInuFields\n    }\n  }\n\n  ${ShibaFragment}\n`;\n\nexport const cache = new ApolloClient({\n  cache: new InMemoryCache({\n    possibleTypes: {\n      Dog: [\"ShibaInu\"],\n    },\n    // suppose you want you key fields for \"Dog\" to not be simply \"id\"\n    typePolicies: {\n      keyFields: {\n        Dog: [\"name\", \"breed\"],\n      },\n    },\n  }),\n});\n```\n\n</ExpansionPanel>\n\n## Testing local state\n\nIn order to properly test local state using `MockedProvider`, you'll need to pass a configured cache into `MockedProvider` itself.\n\n`MockedProvider` creates its own ApolloClient instance behind the scenes like this:\n\n```jsx\nconst { mocks, defaultOptions, cache, resolvers, link, showWarnings } =\n  this.props;\nconst client = new ApolloClient({\n  cache: cache || new Cache(),\n  defaultOptions,\n  link: link || new MockLink(mocks || [], { showWarnings }),\n  resolvers,\n});\n```\n\nTherefore if you're using Apollo Client 2.x local resolvers, or Apollo Client 3.x type/field policies, you have to tell the `MockedProvider` component what you're going to do with `@client` fields. Otherwise the `ApolloClient` instance created behind the scenes doesn't know how to handle your tests.\n\nIf using Apollo Client 2.x local resolvers, make sure your resolvers object is passed into `MockedProvider`:\n\n```jsx\n<MockedProvider mocks={mocks} resolvers={resolvers} ...\n```\n\nIf using Apollo Client 3.x type/field policies, make sure your configured cache instance (with your typePolicies) is passed into `MockedProvider`:\n\n```jsx\n<MockedProvider mocks={mocks} cache={cache} ...\n```\n\nIf you're using Apollo Client 2.x [local resolvers](../local-state/local-resolvers/), you _also_ need to pass your resolver map:\n\n```jsx\n<MockedProvider mocks={mocks} cache={cache} resolvers={resolvers} ...\n```\n\nThis is necessary because otherwise, the `MockedProvider` component doesn't know how resolve [local-only fields](../local-state/managing-state-with-field-policies/) in your queries.\n\n## Sandbox example\n\nFor a working example that demonstrates how to test components, check out this project on CodeSandbox:\n\n<a href=\"https://codesandbox.io/s/github/apollographql/docs-examples/tree/main/apollo-client/v3/testing-react-components?file=/src/dog.test.js\">\n  <img\n    src=\"https://codesandbox.io/static/img/play-codesandbox.svg\"\n    width=\"12em\"\n    alt=\"Edit Testing React Components\"\n    style=\"display: inline;\"\n    noZoom\n  />\n</a>\n"
  },
  {
    "path": "docs/source/get-started.mdx",
    "content": "---\ntitle: Get started with Apollo Client\nsubtitle: Set up Apollo Client and fetch GraphQL data with React\ndescription: Learn how to set up your React app, fetch GraphQL data, and integrate Apollo Client seamlessly into your UI with this step-by-step tutorial.\n---\n\nHello! 👋 This short tutorial gets you up and running with Apollo Client.\n\n> For an introduction to the entire Apollo platform, [check out **Odyssey**, Apollo's interactive learning platform](https://www.apollographql.com/tutorials/?utm_source=apollo_docs&utm_medium=referral).\n\n> **Using a modern React framework?** If you're using Next.js App Router, React Router Framework Mode, or TanStack Start, check out our [framework integration guides](./integrations/integrations#framework-integrations) for setup instructions optimized for your framework.\n\n<Note>\n\nNeed help as you work through this tutorial? [Skills](https://agentskills.io/what-are-skills) extend AI agents with specialized knowledge. Install the Apollo Client skill to teach your AI assistant Apollo Client best practices:\n\n```bash\nnpx skills add apollographql/skills --skill apollo-client\n```\n\n</Note>\n\n## Step 1: Setup\n\nTo start this tutorial, do one of the following:\n\n- Create a new React project locally with [Vite](https://vitejs.dev/), or\n- Create a new React sandbox on [CodeSandbox](https://codesandbox.io/).\n\n## Step 2: Install dependencies\n\nApplications that use Apollo Client require the following top-level dependencies:\n\n- `@apollo/client`: This single package contains virtually everything you need to set up Apollo Client. It includes the in-memory cache, local state management, error handling, and a React-based view layer.\n- `graphql`: This package provides logic for parsing GraphQL queries.\n- `rxjs`: This package provides the `Observable` primitive used throughout Apollo Client.\n\nRun the following command to install both of these packages:\n\n```bash\nnpm install @apollo/client graphql rxjs\n```\n\nOur example application will use the [FlyBy GraphQL API](https://flyby-router-demo.herokuapp.com/) from Apollo Odyssey's [Voyage tutorial series](https://www.apollographql.com/tutorials/voyage-part1/). This API provides a list of intergalactic travel locations and details about those locations 👽\n\n## Step 3: Initialize `ApolloClient`\n\nWith our dependencies set up, we can now initialize an `ApolloClient` instance.\n\nIn `main.jsx`, let's first import the symbols we need from `@apollo/client` and `@apollo/client/react`:\n\n```jsx title=\"main.jsx\"\nimport { ApolloClient, HttpLink, InMemoryCache, gql } from \"@apollo/client\";\nimport { ApolloProvider } from \"@apollo/client/react\";\n```\n\nNext we'll initialize `ApolloClient`, passing its constructor a configuration object with the `link` and `cache` fields:\n\n```jsx title=\"main.jsx\"\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"https://flyby-router-demo.herokuapp.com/\" }),\n  cache: new InMemoryCache(),\n});\n```\n\n- `link` specifies the [Apollo Link](./api/link/introduction/) that will be used to execute GraphQL operations against the network. We give it an instance of [`HttpLink`](./api/link/apollo-link-http) - a customized Apollo Link that knows how to execute network requests against a GraphQL server.\n- `cache` is an instance of `InMemoryCache`, which Apollo Client uses to cache query results after fetching them.\n\nThat's it! Our `client` is ready to start fetching data. Now before we start using Apollo Client with React, let's first try sending a query with plain JavaScript.\n\nIn the same `main.jsx` file, call `client.query()` with the query string (wrapped in the `gql` template literal) shown below:\n\n```jsx title=\"main.jsx\"\n// const client = ...\n\nclient\n  .query({\n    query: gql`\n      query GetLocations {\n        locations {\n          id\n          name\n          description\n          photo\n        }\n      }\n    `,\n  })\n  .then((result) => console.log(result));\n```\n\nRun this code, open your console, and inspect the result object. You should see a `data` property with `locations` attached. Nice!\n\nAlthough executing GraphQL operations directly like this can be useful, Apollo Client really shines when it's integrated with a view layer like React. You can bind queries to your UI and update it automatically as new data is fetched.\n\nLet's look at how that works!\n\n## Step 4: Connect your client to React\n\nYou connect Apollo Client to React with the [`ApolloProvider`](./api/react/ApolloProvider/) component. Similar to React's [`Context.Provider`](https://react.dev/reference/react/useContext), `ApolloProvider` wraps your React app and places Apollo Client on the context, enabling you to access it from anywhere in your component tree.\n\nIn `main.jsx`, let's wrap our React app with an `ApolloProvider`. We suggest putting the `ApolloProvider` near the root of your application, above any component that might need to access GraphQL data.\n\n```jsx title=\"main.jsx\" {16-18}\nimport React from \"react\";\nimport * as ReactDOM from \"react-dom/client\";\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloProvider } from \"@apollo/client/react\";\nimport App from \"./App\";\n\nconst client = new ApolloClient({\n  uri: \"https://flyby-router-demo.herokuapp.com/\",\n  cache: new InMemoryCache(),\n});\n\n// Supported in React 18+\nconst root = ReactDOM.createRoot(document.getElementById(\"root\"));\n\nroot.render(\n  <ApolloProvider client={client}>\n    <App />\n  </ApolloProvider>\n);\n```\n\n## Step 5: Fetch data with `useQuery`\n\nAfter your `ApolloProvider` is hooked up, you can start requesting data with [`useQuery`](./api/react/useQuery/). The `useQuery` hook is a [React hook](https://react.dev/reference/react) that shares GraphQL data with your UI.\n\nSwitching over to our `App.jsx` file, we'll start by replacing our existing file contents with the code snippet below:\n\n```jsx title=\"App.jsx\"\n// Import everything needed to use the `useQuery` hook\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nexport default function App() {\n  return (\n    <div>\n      <h2>My first Apollo app 🚀</h2>\n    </div>\n  );\n}\n```\n\nWe can define the query we want to execute by wrapping it in the `gql` template literal:\n\n```jsx title=\"App.jsx\"\nconst GET_LOCATIONS = gql`\n  query GetLocations {\n    locations {\n      id\n      name\n      description\n      photo\n    }\n  }\n`;\n```\n\nNext, let's define a component named `DisplayLocations` that executes our `GET_LOCATIONS` query with the `useQuery` hook:\n\n```jsx title=\"App.jsx\" {2}\nfunction DisplayLocations() {\n  const { loading, error, data } = useQuery(GET_LOCATIONS);\n\n  if (loading) return <p>Loading...</p>;\n  if (error) return <p>Error : {error.message}</p>;\n\n  return data.locations.map(({ id, name, description, photo }) => (\n    <div key={id}>\n      <h3>{name}</h3>\n      <img width=\"400\" height=\"250\" alt=\"location-reference\" src={`${photo}`} />\n      <br />\n      <b>About this location:</b>\n      <p>{description}</p>\n      <br />\n    </div>\n  ));\n}\n```\n\nWhenever this component renders, the `useQuery` hook automatically executes our query and returns a result object containing `loading`, `error`, `data`, and `dataState` properties:\n\n- Apollo Client automatically tracks a query's loading and error states, which are reflected in the `loading` and `error` properties.\n- When the result of your query comes back, it's attached to the `data` property.\n\nFinally, we'll add `DisplayLocations` to our existing component tree:\n\n```jsx title=\"App.jsx\" {6}\nexport default function App() {\n  return (\n    <div>\n      <h2>My first Apollo app 🚀</h2>\n      <br />\n      <DisplayLocations />\n    </div>\n  );\n}\n```\n\nWhen your app reloads, you should briefly see a loading indicator, followed by a list of locations and details about those locations! If you don't, you can compare your code against the [completed app on CodeSandbox](https://codesandbox.io/s/github/apollographql/docs-examples/tree/main/apollo-client/v3/getting-started).\n\nCongrats, you just made your first component that renders with GraphQL data from Apollo Client! 🎉 Now you can try building more components that use `useQuery` and experiment with the concepts you just learned.\n\n## Next steps\n\nNow that you've learned how to fetch data with Apollo Client, you're ready to dive deeper into creating more complex queries and mutations. After this section, we recommend moving on to:\n\n- [Queries](data/queries/): Learn how to fetch queries with arguments and dive deeper into configuration options. For a full list of options, check out the API reference for `useQuery`.\n- [Fragments](data/fragments/): Learn how to use fragments and data masking to build robust, data-driven components.\n- [Mutations](data/mutations/): Learn how to update data with mutations and when you'll need to update the Apollo cache. For a full list of options, check out the API reference for `useMutation`.\n- [TypeScript with Apollo Client](./development-testing/static-typing): Learn how to add type safety to your application using TypeScript with Apollo Client.\n- [Apollo Client API](api/core/ApolloClient/): Sometimes, you'll need to access the client directly like we did in our plain JavaScript example above. Visit the API reference for a full list of options.\n"
  },
  {
    "path": "docs/source/index.mdx",
    "content": "---\ntitle: Introduction to Apollo Client\nsubtitle: Learn how Apollo Client simplifies GraphQL data management to help build web apps\ndescription: Discover Apollo Client, a powerful state management library for JavaScript. Learn how it simplifies fetching, caching, and more with GraphQL.\n---\n\n**Apollo Client** is a comprehensive GraphQL state management library for JavaScript. It enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI.\n\nApollo Client helps you structure code in an economical, predictable, and declarative way that's consistent with modern development practices. The core `@apollo/client` library provides built-in integration with React, and the larger Apollo community maintains [integrations for other popular view layers](#community-integrations).\n\n<ButtonLink size=\"lg\" href=\"/react/get-started/\" colorScheme=\"navy\">\n  Get started!\n</ButtonLink>\n\n## Core features\n\nSome of Apollo Client's core capabilities include:\n\n- **Declarative data fetching:** Write a query and receive data without manually tracking loading states.\n- **Normalized request and response caching:** Boost performance by responding almost immediately to queries with cached data.\n- **Excellent developer experience:** Enjoy helpful tooling for TypeScript, Chrome / Firefox devtools, and VS Code.\n- **Designed for modern React:** Take advantage of the latest React features, such as hooks and Suspense.\n- **Incrementally adoptable:** Drop Apollo Client into any JavaScript or TypeScript app and incorporate it feature by feature.\n- **Universally compatible:** Use any build setup and any GraphQL API.\n- **Community driven:** Share knowledge with thousands of developers in the GraphQL community.\n\n## AI-powered assistance\n\nNeed help while coding? [Skills](https://agentskills.io/what-are-skills) are a lightweight format for extending AI agents with specialized knowledge. The Apollo Client skill teaches your AI assistant expert patterns for Apollo Client 4.x.\n\nInstall it with:\n\n```bash\nnpx skills add apollographql/skills --skill apollo-client\n```\n\nOnce installed, your AI assistant gains expert knowledge about setup, configuration, troubleshooting, hooks, caching strategies, and React integration patterns.\n\n## GraphOS supported features\n\nApollo Client works seamlessly with these GraphOS router supported features:\n\n- Receiving data for specific fields incrementally with the [`@defer` directive](/graphos/operations/defer)\n- Real-time updates via [GraphQL subscriptions](/graphos/operations/subscriptions)\n- Safelisting with [persisted queries](/graphos/operations/persisted-queries)\n\n<Note>\n\nApollo Client also supports `@defer` and GraphQL subscription implementations outside of GraphOS. See the [Defer](./react/data/defer) guide and [Subscriptions](./react/data/subscriptions) guide for more information.\n\n</Note>\n\n## Recommended docs\n\nAfter you [get started](/react/get-started/), check out the full Apollo Client documentation in the navigation.\n\nWe recommend the following articles in particular:\n\n- [**Queries**](/react/data/queries/). Learn how to fetch and render data using GraphQL queries.\n- [**Fragments**](/react/data/fragments/). Learn how to use fragments and data masking to build robust, data-driven components.\n- [**Mutations**](/react/data/mutations/). Learn how to modify data using GraphQL mutations.\n- [**Caching overview**](/react/caching/overview/). Apollo Client's normalized cache enables you to skip network requests entirely when data is already available locally.\n- [**Managing local state**](/react/local-state/local-state-management/). Apollo Client provides APIs for managing both remote and local data, enabling you to consolidate all of your application's state.\n- [**Basic HTTP networking**](/react/networking/basic-http-networking/). Learn how to send custom headers and other authentication metadata in your queries.\n- [**Testing React components**](/react/development-testing/testing/). Test your GraphQL operations without requiring a connection to a server.\n\n## Community integrations\n\nThis documentation set focuses on React, but Apollo Client supports many other libraries and languages:\n\n- JavaScript\n  - [Angular](/react/integrations/integrations/#angular)\n  - [Vue](/react/integrations/integrations/#vue)\n  - [Svelte](/react/integrations/integrations/#svelte)\n  - [Solid.js](/react/integrations/integrations/#solidjs)\n  - [Ember](/react/integrations/integrations/#ember)\n  - [Meteor](https://www.meteor.com) (thanks to [DDP-Apollo](https://github.com/Swydo/ddp-apollo))\n- Web Components\n  - [Apollo Elements](/react/integrations/integrations/#web-components)\n- Native mobile\n  - [Native iOS with Swift](/ios)\n  - [Native Android with Java and Kotlin](/kotlin)\n"
  },
  {
    "path": "docs/source/integrations/integrations.mdx",
    "content": "---\ntitle: View integrations\ndescription: How to use Apollo Client with the view layer your application is developed in!\n---\n\n## React\n\nApollo Client's built-in React support allows you to fetch data from your GraphQL server and use it in building complex and reactive UIs using the React framework. Apollo Client may be used in any context that React may be used. In the browser, in React Native, or in Node.js when you want to server side render.\n\nApollo Client, unlike some other tools in the React ecosystem, requires _no_ complex build setup to get up and running. As long as you have a GraphQL server you can get started building out your application with React immediately. Apollo Client's React functionality works out of the box with both [`create-react-app`](https://github.com/facebookincubator/create-react-app) and [React Native](http://facebook.github.io/react-native) with a single install and with no extra hassle configuring Babel or other JavaScript tools.\n\n### Framework integrations\n\nFor modern React frameworks with server-side rendering, we provide dedicated integration guides:\n\n- **[Next.js App Router](./nextjs)** - For Next.js applications using the App Router with React Server Components\n- **[React Router framework mode](./react-router)** - For React Router 7 applications with streaming SSR\n- **[TanStack Start](./tanstack-start)** - For TanStack Start applications with modern routing\n\nEach guide includes installation steps, configuration, and framework-specific patterns optimized for that environment.\n\n## Vue\n\nA [Vue.js](https://vuejs.org/) integration is maintained by Guillaume Chau ([@Akryum](https://github.com/Akryum)). See the Github [repository](https://github.com/vuejs/apollo) for more details.\n\n## Svelte\n\nA [Svelte](https://svelte.dev) integration is maintained by Tim Hall ([@timhall](https://github.com/timhall)). See the Github [repository](https://github.com/timhall/svelte-apollo) for more details.\n\n## Angular\n\nAn [Angular](https://angular.io) integration is maintained by Kamil Kisiela ([@kamilkisiela](https://github.com/kamilkisiela)). See the [website](https://apollo-angular.com) for more details.\n\n## Solidjs\n\nA [Solid.js](https://www.solidjs.com/) integration is maintained by ([@Torsten85](https://github.com/Torsten85)). See the Github [repository](https://github.com/merged-js/solid-apollo) for more details.\n\n## Ember\n\nAn [Ember](http://emberjs.com/) integration is maintained by Josemar Luedke ([@josemarluedke](https://github.com/josemarluedke)). See the Github [repository](https://github.com/ember-graphql/ember-apollo-client) for more details. The creator of the project is Blake Gentry ([@bgentry](https://github.com/bgentry)).\n\n## Web Components\n\nWeb components are the browser-built-in component APIs. They are defined in a framework-agnostic way, using either vanilla JS or libraries like [Lit](https://lit.dev) or [`hybrids`](https://hybrids.js.org).\n\n- [apollo-elements](https://github.com/apollo-elements/apollo-elements) includes support for Lit, `gluon`, `hybrids`, and Polymer, as well as providing class mixin functions so you can integrate Apollo into vanilla elements or any other web component library. Apollo Elements is maintained by Benny Powers ([@bennypowers](https://github.com/bennypowers)).\n\n## Orbit for Apollo Client\n\n[Orbit for Apollo Client](https://wassim-k.github.io/apollo-orbit/) provides state management abstractions built on top of Apollo Client for React and Angular. [@wassim-k](https://github.com/wassim-k) created and maintains the project.\n"
  },
  {
    "path": "docs/source/integrations/nextjs.mdx",
    "content": "---\ntitle: Next.js App Router\nsubtitle: Integrate Apollo Client in Next.js apps\ndescription: Learn how to integrate Apollo Client in Next.js applications using the App Router with support for React Server Components and Client Components.\n---\n\nThis guide covers integrating Apollo Client in a Next.js application using the App Router architecture with support for both React Server Components (RSC) and Client Components.\n\n## What is supported?\n\n### React Server Components\n\nApollo Client provides a shared client instance across all server components for a single request, preventing duplicate GraphQL requests and optimizing server-side rendering.\n\n### React Client Components\n\nWhen using the `app` directory, client components are rendered both on the server (SSR) and in the browser. Apollo Client enables you to execute GraphQL queries on the server and use the results to hydrate your browser-side cache, delivering fully-rendered pages to users.\n\n## Installation\n\nInstall Apollo Client and the Next.js integration package:\n\n```bash\nnpm install @apollo/client@latest @apollo/client-integration-nextjs graphql rxjs\n```\n\n> **TypeScript users:** For type-safe GraphQL operations, see the [GraphQL Codegen guide](../development-testing/graphql-codegen).\n\n## Setup for React Server Components (RSC)\n\n### Step 1: Create Apollo Client configuration\n\nCreate an `ApolloClient.ts` file in your app directory:\n\n```typescript\nimport { HttpLink } from \"@apollo/client\";\nimport {\n  registerApolloClient,\n  ApolloClient,\n  InMemoryCache,\n} from \"@apollo/client-integration-nextjs\";\n\nexport const { getClient, query, PreloadQuery } = registerApolloClient(() => {\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new HttpLink({\n      // Use an absolute URL for SSR (relative URLs cannot be used in SSR)\n      uri: \"https://your-api.com/graphql\",\n      fetchOptions: {\n        // Optional: Next.js-specific fetch options for caching and revalidation\n        // See: https://nextjs.org/docs/app/api-reference/functions/fetch\n      },\n    }),\n  });\n});\n```\n\n### Step 2: Use in server components\n\nYou can now use the `getClient` function or the `query` shortcut in your server components:\n\n```typescript\nimport { query } from \"./ApolloClient\";\n\nasync function UserProfile({ userId }: { userId: string }) {\n  const { data } = await query({\n    query: GET_USER,\n    variables: { id: userId },\n  });\n\n  return <div>{data.user.name}</div>;\n}\n```\n\n### Override Next.js fetch options\n\nYou can override Next.js-specific `fetch` options per query using `context.fetchOptions`:\n\n```typescript\nconst { data } = await getClient().query({\n  query: GET_USER,\n  context: {\n    fetchOptions: {\n      next: { revalidate: 60 }, // Revalidate every 60 seconds\n    },\n  },\n});\n```\n\n## Setup for Client Components (SSR and browser)\n\n### Step 1: Create Apollo wrapper component\n\nCreate `app/ApolloWrapper.tsx`:\n\n```typescript\n\"use client\";\n\nimport { HttpLink } from \"@apollo/client\";\nimport {\n  ApolloNextAppProvider,\n  ApolloClient,\n  InMemoryCache,\n} from \"@apollo/client-integration-nextjs\";\n\nfunction makeClient() {\n  const httpLink = new HttpLink({\n    // Use an absolute URL for SSR\n    uri: \"https://your-api.com/graphql\",\n    fetchOptions: {\n      // Optional: Next.js-specific fetch options\n      // Note: This doesn't work with `export const dynamic = \"force-static\"`\n    },\n  });\n\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n  });\n}\n\nexport function ApolloWrapper({ children }: React.PropsWithChildren) {\n  return (\n    <ApolloNextAppProvider makeClient={makeClient}>\n      {children}\n    </ApolloNextAppProvider>\n  );\n}\n```\n\n### Step 2: Wrap root layout\n\nWrap your `RootLayout` in the `ApolloWrapper` component in `app/layout.tsx`:\n\n```typescript\nimport { ApolloWrapper } from \"./ApolloWrapper\";\n\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return (\n    <html lang=\"en\">\n      <body>\n        <ApolloWrapper>{children}</ApolloWrapper>\n      </body>\n    </html>\n  );\n}\n```\n\n> **Note:** This works even if your layout is a React Server Component. It ensures all Client Components share the same Apollo Client instance through `ApolloNextAppProvider`.\n\n### Step 3: Use Apollo Client hooks in client components\n\nFor optimal streaming SSR, use suspense-enabled hooks like `useSuspenseQuery` and `useFragment`:\n\n```typescript\n\"use client\";\n\nimport { useSuspenseQuery } from \"@apollo/client/react\";\n\nexport function UserProfile({ userId }: { userId: string }) {\n  const { data } = useSuspenseQuery(GET_USER, {\n    variables: { id: userId },\n  });\n\n  return <div>{data.user.name}</div>;\n}\n```\n\n## Preloading data from RSC to client components\n\nYou can preload data in React Server Components to populate the cache of your Client Components.\n\n### Step 1: Use PreloadQuery in server components\n\n```tsx\nimport { PreloadQuery } from \"./ApolloClient\";\nimport { Suspense } from \"react\";\n\nexport default async function Page() {\n  return (\n    <PreloadQuery query={GET_USER} variables={{ id: \"1\" }}>\n      <Suspense fallback={<>Loading...</>}>\n        <ClientChild />\n      </Suspense>\n    </PreloadQuery>\n  );\n}\n```\n\n### Step 2: Consume with useSuspenseQuery in client components\n\n```tsx\n\"use client\";\n\nimport { useSuspenseQuery } from \"@apollo/client/react\";\n\nexport function ClientChild() {\n  const { data } = useSuspenseQuery(GET_USER, {\n    variables: { id: \"1\" },\n  });\n\n  return <div>{data.user.name}</div>;\n}\n```\n\n> **Important:** Data fetched this way should be considered client data and never referenced in Server Components. `PreloadQuery` prevents mixing server data and client data by creating a separate `ApolloClient` instance.\n\n### Using with useReadQuery\n\nFor advanced use cases, you can use `PreloadQuery` with `useReadQuery` to avoid request waterfalls:\n\n```tsx\n<PreloadQuery query={GET_USER} variables={{ id: \"1\" }}>\n  {(queryRef) => (\n    <Suspense fallback={<>Loading...</>}>\n      <ClientChild queryRef={queryRef} />\n    </Suspense>\n  )}\n</PreloadQuery>;\n```\n\nIn your Client Component:\n\n```tsx\n\"use client\";\n\nimport {\n  useQueryRefHandlers,\n  useReadQuery,\n  QueryRef,\n} from \"@apollo/client/react\";\n\nexport function ClientChild({ queryRef }: { queryRef: QueryRef<TQueryData> }) {\n  const { refetch } = useQueryRefHandlers(queryRef);\n  const { data } = useReadQuery(queryRef);\n\n  return <div>{data.user.name}</div>;\n}\n```\n\n## Handling multipart responses (@defer) in SSR\n\nWhen using the `@defer` directive, `useSuspenseQuery` will only suspend until the initial response is received. To handle deferred data properly, you have three strategies:\n\n### Strategy 1: Use PreloadQuery with useReadQuery\n\n`PreloadQuery` allows deferred data to be fully transported and streamed chunk-by-chunk.\n\n### Strategy 2: Remove @defer fragments\n\nUse `RemoveMultipartDirectivesLink` to strip `@defer` directives from queries during SSR:\n\n```typescript\nimport { RemoveMultipartDirectivesLink } from \"@apollo/client-integration-nextjs\";\n\nnew RemoveMultipartDirectivesLink({\n  stripDefer: true, // Default: true\n});\n```\n\nYou can exclude specific fragments from stripping by labeling them:\n\n```graphql\nquery myQuery {\n  fastField\n  ... @defer(label: \"SsrDontStrip1\") {\n    slowField1\n  }\n}\n```\n\n### Strategy 3: Wait for deferred data\n\nUse `AccumulateMultipartResponsesLink` to debounce the initial response:\n\n```typescript\nimport { AccumulateMultipartResponsesLink } from \"@apollo/client-integration-nextjs\";\n\nnew AccumulateMultipartResponsesLink({\n  cutoffDelay: 100, // Wait up to 100ms for incremental data\n});\n```\n\n### Combined approach: SSRMultipartLink\n\nCombine both strategies with `SSRMultipartLink`:\n\n```typescript\nimport { SSRMultipartLink } from \"@apollo/client-integration-nextjs\";\n\nnew SSRMultipartLink({\n  stripDefer: true,\n  cutoffDelay: 100,\n});\n```\n\n## Testing\n\nReset singleton instances between tests using the `resetApolloClientSingletons` helper:\n\n```typescript\nimport { resetApolloClientSingletons } from \"@apollo/client-integration-nextjs\";\n\nafterEach(resetApolloClientSingletons);\n```\n\n## Debugging\n\nEnable verbose logging in your `app/ApolloWrapper.tsx`:\n\n```typescript\nimport { setLogVerbosity } from \"@apollo/client\";\n\nsetLogVerbosity(\"debug\");\n```\n\n## Important considerations\n\n1. **Separate RSC and SSR queries:** Avoid overlapping queries between RSC and SSR. RSC queries don't update in the browser, while SSR queries can update dynamically as the cache changes.\n\n2. **Use absolute URLs:** Always use absolute URLs in `HttpLink` for SSR, as relative URLs cannot be used in server-side rendering.\n\n3. **Streaming SSR:** For optimal performance, use `useSuspenseQuery` and `useFragment` to take advantage of React 18's streaming SSR capabilities.\n\n4. **Suspense boundaries:** Place `Suspense` boundaries at meaningful places in your UI for the best user experience.\n"
  },
  {
    "path": "docs/source/integrations/react-native.mdx",
    "content": "---\ntitle: Integrating with React Native\n---\n\nYou can use Apollo Client with React Native exactly as you do with React.js. Install it with `npm` like so:\n\n```bash\nnpm install @apollo/client graphql\n```\n\nThen wrap your application in the `ApolloProvider` component, like so:\n\n```jsx\nimport React from \"react\";\nimport { AppRegistry } from \"react-native\";\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\nimport { ApolloProvider } from \"@apollo/client/react\";\n\n// Initialize Apollo Client\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache: new InMemoryCache(),\n});\n\nconst App = () => (\n  <ApolloProvider client={client}>\n    <MyRootComponent />\n  </ApolloProvider>\n);\n\nAppRegistry.registerComponent(\"MyApplication\", () => App);\n```\n\nFor more information on setting up Apollo Client, see [Getting started](../get-started/).\n\n## Example application\n\n[This sample application](https://github.com/GraphQLGuide/guide-react-native) maintained by [The GraphQL Guide](https://graphql.guide/) uses Apollo Client with React Native.\n\n## Apollo Client Devtools\n\n#### 1. Using the VS Code [Apollo GraphQL extension](https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo)\n\n<img\n  class=\"screenshot\"\n  alt=\"Apollo Client Devtools in a VS Code panel\"\n  src=\"../assets/devtools/vscode-panel.png\"\n/>\n\nThe Apollo GraphQL VSCode extension comes with the Apollo Client Devtools bundled, and these can be used with React Native.\n\nSee [Developer tools - Apollo Client Devtools in VS Code](../development-testing/developer-tooling/#apollo-client-devtools-in-vs-code) for setup instructions.\n\n#### 2. Using [React Native Debugger](https://github.com/jhen0409/react-native-debugger)\n\nThe React Native Debugger supports the [Apollo Client Devtools](../development-testing/developer-tooling/#apollo-client-devtools):\n\n1. Install React Native Debugger and open it.\n2. Enable \"Debug JS Remotely\" in your app.\n3. If you don't see the Developer Tools panel or the Apollo tab is missing from it, toggle the Developer Tools by right-clicking anywhere and selecting **Toggle Developer Tools**.\n\n#### 3. Using [Flipper](https://fbflipper.com/)\n\nA community plugin called [React Native Apollo devtools](https://github.com/razorpay/react-native-apollo-devtools) is available for Flipper, which supports viewing cache data.\n\n1.  Install Flipper and open it.\n2.  Go to add plugin and search for `react-native-apollo-devtools` and install it\n3.  Add `react-native-flipper` and `react-native-apollo-devtools-client` as dev dependency to react native app.\n4.  Initialize the plugin with flipper on client side\n\n    ```ts\n    import { apolloDevToolsInit } from \"react-native-apollo-devtools-client\";\n\n    const client = new ApolloClient({\n      // ...\n    });\n\n    if (__DEV__) {\n      apolloDevToolsInit(client);\n    }\n    ```\n\n## Consuming multipart HTTP via text streaming\n\nBy default, React Native ships with a `fetch` implementation built on top of XHR that does not support text streaming.\n\nFor this reason, if you are using _either_ [`@defer`](../data/defer) or [subscriptions over multipart HTTP](../data/subscriptions#subscriptions-via-multipart-http)—features that use text streaming to read multipart HTTP responses—there are additional steps you'll need to take to polyfill this functionality.\n\n1. Install `react-native-fetch-api` and `react-native-polyfill-globals` and save them both as dependencies.\n2. In your application's entrypoint (i.e. `index.js`, `App.js` or similar), import the following three polyfills and call each of the `polyfill*` functions before any application code:\n\n```tsx\nimport { polyfill as polyfillEncoding } from \"react-native-polyfill-globals/src/encoding\";\nimport { polyfill as polyfillReadableStream } from \"react-native-polyfill-globals/src/readable-stream\";\nimport { polyfill as polyfillFetch } from \"react-native-polyfill-globals/src/fetch\";\n\npolyfillReadableStream();\npolyfillEncoding();\npolyfillFetch();\n```\n\n3. Finally, there’s a special option we’ll need to pass to our polyfilled `fetch`. Create an `HttpLink` so we can set the following on our default `fetchOptions`:\n\n```tsx\nconst link = new HttpLink({\n  uri: \"http://localhost:4000/graphql\",\n  fetchOptions: {\n    reactNative: { textStreaming: true },\n  },\n});\n```\n\n> **Note**: if you're still experiencing issues on Android after adding the polyfills above, there may be a library like Flipper that is intercepting requests during local development. Try commenting out `NetworkFlipperPlugin` in e.g. `android/app/src/debug/java/com/<projectname>/ReactNativeFlipper.java`, or running your app in release mode.\n\nNow you're ready to use `@defer` and/or multipart subscriptions over HTTP in your React Native app!\n\n## Troubleshooting\n\n- `Uncaught Error: Cannot read property 'prototype' of undefined`, or similar Metro build error when importing from `@apollo/client`\n\nThis is due to the way [the Metro bundler supports `.cjs` and `.mjs` files](https://github.com/facebook/metro/issues/535#issuecomment-1198071838): it requires additional configuration to _implicitly_ resolve files with these extensions, so `import { ApolloClient, InMemoryCache } from '@apollo/client'` will result in an error. You can amend your import statement to e.g. `import { ApolloClient, InMemoryCache } from '@apollo/client/main.cjs'`, or you can install `@expo/metro-config` and configure their implicit resolution via `metro.config.js` in the root of your project:\n\n```js title=\"metro.config.js\"\nconst { getDefaultConfig } = require(\"@expo/metro-config\");\n\nconst config = getDefaultConfig(__dirname);\n\nconfig.resolver.sourceExts.push(\"cjs\");\n\nmodule.exports = config;\n```\n"
  },
  {
    "path": "docs/source/integrations/react-router.mdx",
    "content": "---\ntitle: React Router framework mode\nsubtitle: Integrate Apollo Client with React Router 7\ndescription: Learn how to integrate Apollo Client in React Router 7 applications with support for modern streaming SSR.\n---\n\nThis guide covers integrating Apollo Client in a React Router 7 application with support for modern streaming SSR.\n\n## Installation\n\nInstall Apollo Client and the React Router integration package:\n\n```bash\nnpm install @apollo/client-integration-react-router @apollo/client graphql rxjs\n```\n\n> **TypeScript users:** For type-safe GraphQL operations, see the [GraphQL Codegen guide](../development-testing/graphql-codegen).\n\n## Setup\n\n### Step 1: Create Apollo configuration\n\nCreate an `app/apollo.ts` file that exports a `makeClient` function and an `apolloLoader`:\n\n```typescript\nimport { HttpLink, InMemoryCache } from \"@apollo/client\";\nimport {\n  createApolloLoaderHandler,\n  ApolloClient,\n} from \"@apollo/client-integration-react-router\";\n\n// `request` will be available on the server during SSR or in loaders, but not in the browser\nexport const makeClient = (request?: Request) => {\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new HttpLink({ uri: \"https://your-graphql-endpoint.com/graphql\" }),\n  });\n};\n\nexport const apolloLoader = createApolloLoaderHandler(makeClient);\n```\n\n> **Important:** `ApolloClient` must be imported from `@apollo/client-integration-react-router`, not from `@apollo/client`.\n\n### Step 2: Reveal entry files\n\nRun the following command to create the entry files if they don't exist:\n\n```bash\nnpx react-router reveal\n```\n\nThis will create `app/entry.client.tsx` and `app/entry.server.tsx`.\n\n### Step 3: Configure client entry\n\nAdjust `app/entry.client.tsx` to wrap your app in `ApolloProvider`:\n\n```typescript\nimport { makeClient } from \"./apollo\";\nimport { ApolloProvider } from \"@apollo/client\";\nimport { StrictMode, startTransition } from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { HydratedRouter } from \"react-router/dom\";\n\nstartTransition(() => {\n  const client = makeClient();\n  hydrateRoot(\n    document,\n    <StrictMode>\n      <ApolloProvider client={client}>\n        <HydratedRouter />\n      </ApolloProvider>\n    </StrictMode>\n  );\n});\n```\n\n### Step 4: Configure server entry\n\nAdjust `app/entry.server.tsx` to wrap your app in `ApolloProvider` during SSR:\n\n```typescript\nimport { makeClient } from \"./apollo\";\nimport { ApolloProvider } from \"@apollo/client\";\n// ... other imports\n\nexport default function handleRequest(\n  request: Request,\n  responseStatusCode: number,\n  responseHeaders: Headers,\n  routerContext: EntryContext\n) {\n  return new Promise((resolve, reject) => {\n    // ... existing code\n\n    const client = makeClient(request);\n\n    const { pipe, abort } = renderToPipeableStream(\n      <ApolloProvider client={client}>\n        <ServerRouter\n          context={routerContext}\n          url={request.url}\n          abortDelay={ABORT_DELAY}\n        />\n      </ApolloProvider>,\n      {\n        [readyOption]() {\n          shellRendered = true;\n          // ... rest of the handler\n        },\n        // ... other options\n      }\n    );\n  });\n}\n```\n\n### Step 5: Add hydration helper\n\nAdd `<ApolloHydrationHelper>` to `app/root.tsx`:\n\n```typescript\nimport { ApolloHydrationHelper } from \"@apollo/client-integration-react-router\";\nimport { Links, Meta, Outlet, Scripts, ScrollRestoration } from \"react-router\";\n\nexport function Layout({ children }: { children: React.ReactNode }) {\n  return (\n    <html lang=\"en\">\n      <head>\n        <meta charSet=\"utf-8\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n        <Meta />\n        <Links />\n      </head>\n      <body>\n        <ApolloHydrationHelper>{children}</ApolloHydrationHelper>\n        <ScrollRestoration />\n        <Scripts />\n      </body>\n    </html>\n  );\n}\n\nexport default function App() {\n  return <Outlet />;\n}\n```\n\n## Usage\n\n### Using apolloLoader with useReadQuery\n\nYou can now use the `apolloLoader` function to create Apollo-enabled loaders for your routes:\n\n```typescript\nimport { gql } from \"@apollo/client\";\nimport { useReadQuery } from \"@apollo/client/react\";\nimport { useLoaderData } from \"react-router\";\nimport type { Route } from \"./+types/my-route\";\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { apolloLoader } from \"./apollo\";\n\n// TypedDocumentNode definition with types\nconst GET_USER: TypedDocumentNode<\n  { user: { id: string; name: string; email: string } },\n  { id: string }\n> = gql`\n  query GetUser($id: ID!) {\n    user(id: $id) {\n      id\n      name\n      email\n    }\n  }\n`;\n\nexport const loader = apolloLoader<Route.LoaderArgs>()(({ preloadQuery }) => {\n  const userQueryRef = preloadQuery(GET_USER, {\n    variables: { id: \"1\" },\n  });\n\n  return {\n    userQueryRef,\n  };\n});\n\nexport default function UserPage() {\n  const { userQueryRef } = useLoaderData<typeof loader>();\n  const { data } = useReadQuery(userQueryRef);\n\n  return (\n    <div>\n      <h1>{data.user.name}</h1>\n      <p>{data.user.email}</p>\n    </div>\n  );\n}\n```\n\n> **Important:** To provide better TypeScript support, `apolloLoader` is a method that you need to call twice: `apolloLoader<LoaderArgs>()(loader)`\n\n### Multiple queries in a loader\n\nYou can preload multiple queries in a single loader:\n\n```typescript\nimport { gql } from \"@apollo/client\";\nimport { useReadQuery } from \"@apollo/client/react\";\nimport { useLoaderData } from \"react-router\";\nimport type { Route } from \"./+types/my-route\";\nimport { apolloLoader } from \"./apollo\";\n\n// TypedDocumentNode definitions omitted for brevity\n\nexport const loader = apolloLoader<Route.LoaderArgs>()(({ preloadQuery }) => {\n  const userQueryRef = preloadQuery(GET_USER, {\n    variables: { id: \"1\" },\n  });\n\n  const postsQueryRef = preloadQuery(GET_POSTS, {\n    variables: { userId: \"1\" },\n  });\n\n  return {\n    userQueryRef,\n    postsQueryRef,\n  };\n});\n\nexport default function UserPage() {\n  const { userQueryRef, postsQueryRef } = useLoaderData<typeof loader>();\n  const { data: userData } = useReadQuery(userQueryRef);\n  const { data: postsData } = useReadQuery(postsQueryRef);\n\n  return (\n    <div>\n      <h1>{userData.user.name}</h1>\n      <h2>Posts</h2>\n      <ul>\n        {postsData.posts.map((post) => (\n          <li key={post.id}>{post.title}</li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n```\n\n## Important considerations\n\n1. **Import ApolloClient from integration package:** Always import `ApolloClient` from `@apollo/client-integration-react-router`, not from `@apollo/client`, to ensure proper SSR hydration.\n\n2. **TypeScript support:** The `apolloLoader` function requires double invocation for proper TypeScript type inference: `apolloLoader<LoaderArgs>()(loader)`.\n\n3. **Request context:** The `makeClient` function receives the `Request` object during SSR and in loaders, but not in the browser. Use this to set up auth headers or other request-specific configuration.\n\n4. **Streaming SSR:** The integration fully supports React's streaming SSR capabilities. Place `Suspense` boundaries strategically for optimal user experience.\n\n5. **Cache hydration:** The `ApolloHydrationHelper` component ensures that data loaded on the server is properly hydrated on the client, preventing unnecessary refetches.\n"
  },
  {
    "path": "docs/source/integrations/tanstack-start.mdx",
    "content": "---\ntitle: TanStack Start\nsubtitle: Integrate Apollo Client with TanStack Start\ndescription: Learn how to integrate Apollo Client in TanStack Start applications with support for modern streaming SSR.\n---\n\nThis guide covers integrating Apollo Client in a TanStack Start application with support for modern streaming SSR.\n\n> **Note:** When using `npx create-tsrouter-app` to create a new TanStack Start application, you can choose Apollo Client in the setup wizard to have all of this configuration automatically set up for you.\n\n## Installation\n\nInstall Apollo Client and the TanStack Start integration package:\n\n```bash\nnpm install @apollo/client-integration-tanstack-start @apollo/client graphql rxjs\n```\n\n> **TypeScript users:** For type-safe GraphQL operations, see the [GraphQL Codegen guide](../development-testing/graphql-codegen).\n\n## Setup\n\n### Step 1: Configure root route with context\n\nIn your `routes/__root.tsx`, change from `createRootRoute` to `createRootRouteWithContext` to provide the right context type:\n\n```typescript\nimport type { ApolloClientIntegration } from \"@apollo/client-integration-tanstack-start\";\nimport {\n  createRootRouteWithContext,\n  Outlet,\n} from \"@tanstack/react-router\";\n\nexport const Route = createRootRouteWithContext<ApolloClientIntegration.RouterContext>()({\n  component: RootComponent,\n});\n\nfunction RootComponent() {\n  return (\n    <html>\n      <head>\n        <meta charSet=\"UTF-8\" />\n        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n        <title>My App</title>\n      </head>\n      <body>\n        <Outlet />\n      </body>\n    </html>\n  );\n}\n```\n\n### Step 2: Set up Apollo Client in router\n\nIn your `router.tsx`, set up your Apollo Client instance and run `routerWithApolloClient`:\n\n```typescript\nimport {\n  routerWithApolloClient,\n  ApolloClient,\n  InMemoryCache,\n} from \"@apollo/client-integration-tanstack-start\";\nimport { HttpLink } from \"@apollo/client\";\nimport { createRouter } from \"@tanstack/react-router\";\nimport { routeTree } from \"./routeTree.gen\";\n\nexport function getRouter() {\n  const apolloClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new HttpLink({ uri: \"https://your-graphql-endpoint.com/graphql\" }),\n  });\n\n  const router = createRouter({\n    routeTree,\n    context: {\n      ...routerWithApolloClient.defaultContext,\n    },\n  });\n\n  return routerWithApolloClient(router, apolloClient);\n}\n```\n\n> **Important:** `ApolloClient` and `InMemoryCache` must be imported from `@apollo/client-integration-tanstack-start`, not from `@apollo/client`.\n\n## Usage\n\n### Option 1: Loader with preloadQuery and useReadQuery\n\nUse the `preloadQuery` function in your route loader to preload data during navigation:\n\n```typescript\nimport { gql } from \"@apollo/client\";\nimport { useReadQuery } from \"@apollo/client/react\";\nimport { createFileRoute } from \"@tanstack/react-router\";\nimport type { TypedDocumentNode } from \"@apollo/client\";\n\n// TypedDocumentNode definition with types\nconst GET_USER: TypedDocumentNode<\n  { user: { id: string; name: string; email: string } },\n  { id: string }\n> = gql`\n  query GetUser($id: ID!) {\n    user(id: $id) {\n      id\n      name\n      email\n    }\n  }\n`;\n\nexport const Route = createFileRoute(\"/user/$userId\")({\n  component: RouteComponent,\n  loader: ({ context: { preloadQuery }, params }) => {\n    const queryRef = preloadQuery(GET_USER, {\n      variables: { id: params.userId },\n    });\n\n    return {\n      queryRef,\n    };\n  },\n});\n\nfunction RouteComponent() {\n  const { queryRef } = Route.useLoaderData();\n  const { data } = useReadQuery(queryRef);\n\n  return (\n    <div>\n      <h1>{data.user.name}</h1>\n      <p>{data.user.email}</p>\n    </div>\n  );\n}\n```\n\n### Option 2: Direct useSuspenseQuery in component\n\nYou can also use Apollo Client's suspenseful hooks directly in your component without a loader:\n\n```typescript\nimport { gql, useSuspenseQuery } from \"@apollo/client/react\";\nimport { createFileRoute } from \"@tanstack/react-router\";\nimport type { TypedDocumentNode } from \"@apollo/client\";\n\n// TypedDocumentNode definition with types\nconst GET_POSTS: TypedDocumentNode<{\n  posts: Array<{ id: string; title: string; content: string }>;\n}> = gql`\n  query GetPosts {\n    posts {\n      id\n      title\n      content\n    }\n  }\n`;\n\nexport const Route = createFileRoute(\"/posts\")({\n  component: RouteComponent,\n});\n\nfunction RouteComponent() {\n  const { data } = useSuspenseQuery(GET_POSTS);\n\n  return (\n    <div>\n      <h1>Posts</h1>\n      <ul>\n        {data.posts.map((post) => (\n          <li key={post.id}>\n            <h2>{post.title}</h2>\n            <p>{post.content}</p>\n          </li>\n        ))}\n      </ul>\n    </div>\n  );\n}\n```\n\n### Multiple queries in a loader\n\nYou can preload multiple queries in a single loader:\n\n```typescript\nimport { gql } from \"@apollo/client\";\nimport { useReadQuery } from \"@apollo/client/react\";\nimport { createFileRoute } from \"@tanstack/react-router\";\n\n// TypedDocumentNode definitions omitted for brevity\n\nexport const Route = createFileRoute(\"/dashboard\")({\n  component: RouteComponent,\n  loader: ({ context: { preloadQuery } }) => {\n    const userQueryRef = preloadQuery(GET_USER, {\n      variables: { id: \"current\" },\n    });\n\n    const statsQueryRef = preloadQuery(GET_STATS, {\n      variables: { period: \"month\" },\n    });\n\n    return {\n      userQueryRef,\n      statsQueryRef,\n    };\n  },\n});\n\nfunction RouteComponent() {\n  const { userQueryRef, statsQueryRef } = Route.useLoaderData();\n  const { data: userData } = useReadQuery(userQueryRef);\n  const { data: statsData } = useReadQuery(statsQueryRef);\n\n  return (\n    <div>\n      <h1>Welcome, {userData.user.name}</h1>\n      <div>\n        <h2>Monthly Stats</h2>\n        <p>Views: {statsData.stats.views}</p>\n        <p>Clicks: {statsData.stats.clicks}</p>\n      </div>\n    </div>\n  );\n}\n```\n\n### Using useQueryRefHandlers for refetching\n\nWhen using `useReadQuery`, you can get refetch functionality from `useQueryRefHandlers`:\n\n> **Important:** Always call `useQueryRefHandlers` before `useReadQuery`. These two hooks interact with the same `queryRef`, and calling them in the wrong order could cause subtle bugs.\n\n```typescript\nimport { useReadQuery, useQueryRefHandlers, QueryRef } from \"@apollo/client/react\";\n\nfunction UserComponent({ queryRef }: { queryRef: QueryRef<GetUserQuery> }) {\n  const { refetch } = useQueryRefHandlers(queryRef);\n  const { data } = useReadQuery(queryRef);\n\n  return (\n    <div>\n      <h1>{data.user.name}</h1>\n      <button onClick={() => refetch()}>Refresh</button>\n    </div>\n  );\n}\n```\n\n## Important considerations\n\n1. **Import from integration package:** Always import `ApolloClient` and `InMemoryCache` from `@apollo/client-integration-tanstack-start`, not from `@apollo/client`, to ensure proper SSR hydration.\n\n2. **Context type:** Use `createRootRouteWithContext<ApolloClientIntegration.RouterContext>()` to provide proper TypeScript types for the `preloadQuery` function in loaders.\n\n3. **Loader vs component queries:**\n\n   - Use `preloadQuery` in loaders when you want to start fetching data before the component renders\n   - Use `useSuspenseQuery` directly in components for simpler cases or when data fetching can wait until render\n\n4. **Streaming SSR:** The integration fully supports React's streaming SSR capabilities. Place `Suspense` boundaries strategically for optimal user experience.\n\n5. **Cache management:** The Apollo Client instance is shared across all routes, so cache updates from one route will be reflected in all routes that use the same data.\n\n6. **Authentication:** Use Apollo Client's `SetContextLink` for dynamic auth tokens.\n\n## Advanced configuration\n\n### Adding authentication\n\nFor authentication in TanStack Start with SSR support, you need to handle both server and client environments differently. Use `createIsomorphicFn` to provide environment-specific implementations:\n\n```typescript\nimport {\n  ApolloClient,\n  InMemoryCache,\n  routerWithApolloClient,\n} from \"@apollo/client-integration-tanstack-start\";\nimport { ApolloLink, HttpLink } from \"@apollo/client\";\nimport { SetContextLink } from \"@apollo/client/link/context\";\nimport { createIsomorphicFn } from \"@tanstack/react-start\";\nimport { createRouter } from \"@tanstack/react-router\";\nimport { getSession, getCookie } from \"@tanstack/react-start/server\";\nimport { routeTree } from \"./routeTree.gen\";\n\n// Create isomorphic link that uses different implementations per environment\nconst createAuthLink = createIsomorphicFn()\n  .server(() => {\n    // Server-only: Can access server-side functions like `getCookies`, `getCookie`, `getSession`, etc. exported from `\"@tanstack/react-start/server\"`\n    return new SetContextLink(async (prevContext) => {\n      return {\n        headers: {\n          ...prevContext.headers,\n          authorization: getCookie(\"Authorization\"),\n        },\n      };\n    });\n  })\n  .client(() => {\n    // Client-only: Can access `localStorage` or other browser APIs\n    return new SetContextLink((prevContext) => {\n      return {\n        headers: {\n          ...prevContext.headers,\n          authorization: localStorage.getItem(\"authToken\") ?? \"\",\n        },\n      };\n    });\n  });\n\nexport function getRouter() {\n  const httpLink = new HttpLink({\n    uri: \"https://your-graphql-endpoint.com/graphql\",\n  });\n\n  const apolloClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.from([createAuthLink(), httpLink]),\n  });\n\n  const router = createRouter({\n    routeTree,\n    context: {\n      ...routerWithApolloClient.defaultContext,\n    },\n  });\n\n  return routerWithApolloClient(router, apolloClient);\n}\n```\n\n> **Important:** The `getRouter` function is called both on the server and client, so it must not contain environment-specific code. Use `createIsomorphicFn` to provide different implementations:\n>\n> - **Server:** Can access server-only functions like `getSession`, `getCookies`, `getCookie` from `@tanstack/react-start/server` to access authentication information in request or session data\n> - **Client:** Can use `localStorage` or other browser APIs to access auth tokens (if setting `credentials: \"include\"` is sufficient, try to prefer that over manually setting auth headers client-side)\n>\n> This ensures your authentication works correctly in both SSR and browser contexts.\n\n### Custom cache configuration\n\n```typescript\nimport {\n  ApolloClient,\n  InMemoryCache,\n} from \"@apollo/client-integration-tanstack-start\";\nimport { HttpLink } from \"@apollo/client\";\nimport { createRouter } from \"@tanstack/react-router\";\nimport { routeTree } from \"./routeTree.gen\";\nimport { routerWithApolloClient } from \"@apollo/client-integration-tanstack-start\";\n\nexport function getRouter() {\n  const apolloClient = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            posts: {\n              merge(existing = [], incoming) {\n                return [...existing, ...incoming];\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: new HttpLink({ uri: \"https://your-graphql-endpoint.com/graphql\" }),\n  });\n\n  const router = createRouter({\n    routeTree,\n    context: {\n      ...routerWithApolloClient.defaultContext,\n    },\n  });\n\n  return routerWithApolloClient(router, apolloClient);\n}\n```\n"
  },
  {
    "path": "docs/source/integrations/webpack.mdx",
    "content": "---\ntitle: Loading queries with Webpack\n---\n\nYou can load GraphQL queries over `.graphql` files using Webpack. The package `graphql-tag` comes with a loader easy to setup and with some benefits:\n\n1. Do not process GraphQL ASTs on client-side\n2. Enable queries to be separated from logic\n\nIn the example below, we create a new file called `currentUser.graphql`:\n\n```graphql\nquery CurrentUserForLayout {\n  currentUser {\n    login\n    avatar_url\n  }\n}\n```\n\nYou can load this file adding a rule in your webpack config file:\n\n```js\nmodule: {\n  rules: [\n    {\n      test: /\\.(graphql|gql)$/,\n      exclude: /node_modules/,\n      loader: 'graphql-tag/loader',\n    },\n  ],\n},\n```\n\nAs you can see, `.graphql` or `.gql` files will be parsed whenever imported:\n\n```js\nimport React, { Component } from 'react';\nimport { graphql } from '@apollo/react-hoc';\nimport currentUserQuery from './currentUser.graphql';\n\nclass Profile extends Component { ... }\nProfile.propTypes = { ... };\n\nexport default graphql(currentUserQuery)(Profile)\n```\n\n## Jest\n\n[Jest](https://facebook.github.io/jest/) can't use the Webpack loaders. To make the same transformation work in Jest, use [jest-graphql-transformer](https://github.com/hamidyfine/jest-graphql-transformer).\n\n## FuseBox\n\n[FuseBox](http://fuse-box.org) can't use the Webpack loaders. To make the same transformation work in FuseBox, use [fuse-box-graphql-plugin](https://github.com/otothea/fuse-box-graphql-plugin).\n\n## React native\n\n[React native](https://facebook.github.io/react-native/) can't use the Webpack loaders. To make the same transformation work in React native, use [babel-plugin-import-graphql](https://github.com/detrohutt/babel-plugin-import-graphql).\n\n## Create-React-App\n\n[create-react-app](https://github.com/facebook/create-react-app/) can't use the Webpack loaders unless ejected. To make the same transformation work in `create-react-app` without ejecting, use [graphql.macro](https://github.com/evenchange4/graphql.macro).\n\n```javascript\nimport { loader } from \"graphql.macro\";\nconst currentUserQuery = loader(\"./currentUser.graphql\");\n```\n\n## Fragments\n\nYou can use and include fragments in .graphql files and have webpack include those dependencies for you, similar to how you would use fragments and queries with the gql tag in plain JS.\n\n```graphql\n#import \"./UserInfoFragment.graphql\"\n\nquery CurrentUserForLayout {\n  currentUser {\n    ...UserInfo\n  }\n}\n```\n\nSee how we import the UserInfo fragment from another .graphql file (same way you'd import modules in JS).\n\nAnd here's an example of defining the fragment in another .graphql file.\n\n```graphql\nfragment UserInfo on User {\n  login\n  avatar_url\n}\n```\n"
  },
  {
    "path": "docs/source/local-state/local-resolvers.mdx",
    "content": "---\ntitle: Local resolvers\ndescription: Manage local data with GraphQL like resolvers\n---\n\nWe've learned how to manage remote data from our GraphQL server with Apollo Client, but what should we do with our local data? We want to be able to access boolean flags and device API results from multiple components in our app, but don't want to maintain a separate Redux or MobX store. Ideally, we would like the Apollo cache to be the single source of truth for all data in our client application.\n\nApollo Client (>= 2.5) has built-in local state handling capabilities that allow you to store your local data inside the Apollo cache alongside your remote data. To access your local data, just query it with GraphQL. You can even request local and server data within the same query!\n\nIn this section, you'll learn how Apollo Client can help simplify local state management in your app. We'll cover how client-side resolvers can help us execute local queries and mutations. You'll also learn how to query and update the cache with the `@client` directive.\n\nPlease note that this documentation is intended to be used to familiarize yourself with Apollo Client's local state management capabilities, and serve as a reference guide. If you're looking for a step by step tutorial outlining how to handle local state with Apollo Client (and leverage other Apollo components to build a fullstack application), please refer to the [full-stack quickstart course](https://www.apollographql.com/tutorials/fullstack-quickstart/introduction).\n\n## Updating local state\n\nThere are two main ways to perform local state mutations. The first way is to directly write to the cache by calling `cache.writeQuery`. Direct writes are great for one-off mutations that don't depend on the data that's currently in the cache, such as writing a single value. The second way is by leveraging the `useMutation` hook with a GraphQL mutation that calls a local client-side resolver. We recommend using resolvers if your mutation depends on existing values in the cache, such as adding an item to a list or toggling a boolean.\n\n### Direct writes\n\nDirect writes to the cache do not require a GraphQL mutation or a resolver function. They leverage your Apollo Client instance directly by accessing the `client` property returned from the `useApolloClient` hook, made available in the `useQuery` hook result, or within the render prop function of the `ApolloConsumer` component. We recommend using this strategy for simple writes, such as writing a string, or one-off writes. It's important to note that direct writes are not implemented as GraphQL mutations under the hood, so you shouldn't include them in your schema. They also do not validate that the data you're writing to the cache is in the shape of valid GraphQL data. If either of these features are important to you, you should opt to use a local resolver instead.\n\n```jsx\nimport React from \"react\";\nimport { useApolloClient } from \"@apollo/client/react\";\n\nimport Link from \"./Link\";\n\nfunction FilterLink({ filter, children }) {\n  const client = useApolloClient();\n  return (\n    <Link\n      onClick={() =>\n        client.writeQuery({\n          query: gql`\n            query GetVisibilityFilter {\n              visibilityFilter\n            }\n          `,\n          data: { visibilityFilter: filter },\n        })\n      }\n    >\n      {children}\n    </Link>\n  );\n}\n```\n\nThe `ApolloConsumer` render prop function is called with a single value, the Apollo Client instance. You can think of the `ApolloConsumer` component as being similar to the `Consumer` component from the [React context API](https://react.dev/reference/react/useContext). From the client instance, you can directly call `client.writeQuery` and pass in the data you'd like to write to the cache.\n\nWhat if we want to immediately subscribe to the data we just wrote to the cache? Let's create an `active` property on the link that marks the link's filter as active if it's the same as the current `visibilityFilter` in the cache. To immediately subscribe to a client-side mutation, we can use `useQuery`. The `useQuery` hook also makes the client instance available in its result object.\n\n```jsx\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nimport Link from \"./Link\";\n\nconst GET_VISIBILITY_FILTER = gql`\n  query GetVisibilityFilter {\n    visibilityFilter @client\n  }\n`;\n\nfunction FilterLink({ filter, children }) {\n  const { data, client } = useQuery(GET_VISIBILITY_FILTER);\n  return (\n    <Link\n      onClick={() =>\n        client.writeQuery({\n          query: GET_VISIBILITY_FILTER,\n          data: { visibilityFilter: filter },\n        })\n      }\n      active={data.visibilityFilter === filter}\n    >\n      {children}\n    </Link>\n  );\n}\n```\n\nYou'll notice in our query that we have a `@client` directive next to our `visibilityFilter` field. This tells Apollo Client to fetch the field data locally (either from the cache or using a local resolver), instead of sending it to our GraphQL server. Once you call `client.writeQuery`, the query result on the render prop function will automatically update. All cache writes and reads are synchronous, so you don't have to worry about loading state.\n\n### Local resolvers\n\nIf you'd like to implement your local state update as a GraphQL mutation, then you'll need to specify a function in your local resolver map. The resolver map is an object with resolver functions for each GraphQL object type. To visualize how this all lines up, it's useful to think of a GraphQL query or mutation as a tree of function calls for each field. These function calls resolve to data or another function call. So when a GraphQL query is run through Apollo Client, it looks for a way to essentially run functions for each field in the query. When it finds an `@client` directive on a field, it turns to its internal resolver map looking for a function it can run for that field.\n\nTo help make local resolvers more flexible, the signature of a resolver function is the exact same as resolver functions on the server built with [Apollo Server](/apollo-server/data/resolvers/). Let's recap the four parameters of a resolver function:\n\n```js\nfieldName: (obj, args, context, info) => result;\n```\n\n1. `obj`: The object containing the result returned from the resolver on the parent field or the `ROOT_QUERY` object in the case of a top-level query or mutation.\n2. `args`: An object containing all of the arguments passed into the field. For example, if you called a mutation with `updateNetworkStatus(isConnected: true)`, the `args` object would be `{ isConnected: true }`.\n3. `context`: The context argument provides additional information without the possibility of name clashes. It takes the following shape:\n   ```ts\n   {\n     // The request context. By default this is of type `DefaultContext`,\n     // but can be changed if a `context` function is provided to LocalState\n     requestContext: TContextValue,\n     // The client instance making the request\n     client: ApolloClient,\n     // Whether the resolver is run as a result of gathering exported variables\n     // or resolving the value as part of the result\n     phase: \"exports\" | \"resolve\"\n   }\n   ```\n   To access the cache, use `context.client.cache`.\n4. `info`: Information about the execution state of the query. You will rarely need to use this value.\n\nLet's take a look at an example of a resolver where we toggle a todo's completed status:\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Mutation: {\n        toggleTodo: (_root, variables, { client }) => {\n          client.cache.modify({\n            id: client.cache.identify({\n              __typename: \"TodoItem\",\n              id: variables.id,\n            }),\n            fields: {\n              completed: (value) => !value,\n            },\n          });\n          return null;\n        },\n      },\n    },\n  }),\n});\n```\n\nTo determine the ID of the entity, pass the `__typename` and primary key fields of the object to the `cache.identify` method. Use the `cache.modify` method to update specific fields within a given entity object.\n\nOnce we toggle the `completed` field, since we don't plan on using the mutation's return result in our UI, we return `null` since all GraphQL types are nullable by default.\n\n### Type safety with LocalState\n\nThe `LocalState` class accepts a `Resolvers` generic that provides autocompletion and type checking against your resolver types to ensure your resolvers are type-safe:\n\n```ts\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { Resolvers } from \"./path/to/local-resolvers-types.ts\";\n\n// LocalState accepts a `Resolvers` generic.\nconst localState = new LocalState<Resolvers>({\n  resolvers: {\n    // Your resolvers will be type-checked against the Resolvers type\n  },\n});\n```\n\nYou can also pass a `ContextValue` generic used to ensure the `context` function returns the correct type. This type is inferred from your resolvers if not provided:\n\n```ts\nnew LocalState<Resolvers, ContextValue>({\n  // The return value of this function will be type-checked\n  context: (options) => ({\n    // ...\n  }),\n  resolvers: {\n    // ...\n  },\n});\n```\n\n#### Generating types for local resolvers\n\nWhen using TypeScript, you can generate resolver types for your local resolvers using the `@apollo/client-graphql-codegen` package. This package provides a specialized GraphQL Code Generator plugin that creates resolver types compatible with Apollo Client's `LocalState`.\n\n##### Installation\n\nInstall the GraphQL Code Generator plugin for local state:\n\n```bash\nnpm install -D @apollo/client-graphql-codegen\n```\n\n##### Configuration\n\nAdd the local-state plugin to your `codegen.ts` configuration. It's recommended to use a separate schema file containing only your local fields to avoid generating resolver types for your entire remote schema:\n\n```ts title=\"codegen.ts\"\nimport type { CodegenConfig } from \"@graphql-codegen/cli\";\nimport type { LocalStatePluginConfig } from \"@apollo/client-graphql-codegen/local-state\";\n\nconst config: CodegenConfig = {\n  // ... your existing configuration\n  generates: {\n    // ... your existing generates\n    \"./src/__generated__/local-resolvers.ts\": {\n      schema: [\"./src/local-schema.graphql\"],\n      plugins: [\"typescript\", \"@apollo/client-graphql-codegen/local-state\"],\n      config: {\n        // Ensures you return a `__typename` for any `@client` fields that\n        // return object or array types\n        nonOptionalTypename: true,\n        // Required if your local schema extends existing schema types\n        baseTypesPath: \"./src/__generated__/graphql\",\n        // If you provide a `context` function to customize the context value,\n        // provide the path or type here\n        contextType: \"./src/context#MyContextType\",\n      } satisfies LocalStatePluginConfig,\n    },\n  },\n};\n\nexport default config;\n```\n\n##### Creating your local schema\n\nCreate a GraphQL schema file that defines your local-only fields:\n\n```graphql title=\"src/local-schema.graphql\"\nextend type Query {\n  isLoggedIn: Boolean!\n  cartItems: [String!]!\n}\n\nextend type Mutation {\n  login(token: String!): Boolean!\n  addToCart(item: String!): [String!]!\n}\n\nextend type Product {\n  isInCart: Boolean!\n}\n```\n\n##### Using generated types\n\nAfter running the code generator, you can use the generated `Resolvers` type with your `LocalState` instance:\n\n```ts\nimport { LocalState } from \"@apollo/client/local-state\";\nimport type { Resolvers } from \"./src/__generated__/local-resolvers\";\n\nconst localState = new LocalState<Resolvers>({\n  resolvers: {\n    Query: {\n      isLoggedIn: () => {\n        return !!localStorage.getItem(\"token\");\n      },\n      cartItems: () => {\n        return JSON.parse(localStorage.getItem(\"cart\") || \"[]\");\n      },\n    },\n    Mutation: {\n      login: (_, { token }) => {\n        localStorage.setItem(\"token\", token);\n        return true;\n      },\n      addToCart: (_, { item }) => {\n        const cart = JSON.parse(localStorage.getItem(\"cart\") || \"[]\");\n        cart.push(item);\n        localStorage.setItem(\"cart\", JSON.stringify(cart));\n        return cart;\n      },\n    },\n    Product: {\n      isInCart: (product) => {\n        const cart = JSON.parse(localStorage.getItem(\"cart\") || \"[]\");\n        return cart.includes(product.id);\n      },\n    },\n  },\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState,\n});\n```\n\nThis approach ensures that your local resolver functions are properly typed and checked against your local schema, providing better development experience and catching type errors at compile time.\n\n### Error handling\n\nThrowing errors in a resolver will set the field value as `null` and add an error to the response's `errors` array. This follows GraphQL's standard error handling behavior:\n\n```ts\nconst localState = new LocalState({\n  resolvers: {\n    Query: {\n      riskyField: () => {\n        throw new Error(\"Something went wrong!\");\n        // This will result in: { data: { riskyField: null }, errors: [...] }\n      },\n    },\n  },\n});\n```\n\n### Data handling\n\n- **Remote result dealiasing**: Remote results are dealiased before they are passed as the parent object to a resolver so that you can access fields by their field name.\n- **Null data handling**: If the server returns `data: null` or does not provide a result, your local resolvers will not be called.\n\nLet's learn how to trigger our `toggleTodo` mutation from our component:\n\n```jsx\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useMutation } from \"@apollo/client/react\";\n\nconst TOGGLE_TODO = gql`\n  mutation ToggleTodo($id: Int!) {\n    toggleTodo(id: $id) @client\n  }\n`;\n\nfunction Todo({ id, completed, text }) {\n  const [toggleTodo] = useMutation(TOGGLE_TODO, { variables: { id } });\n  return (\n    <li\n      onClick={toggleTodo}\n      style={{\n        textDecoration: completed ? \"line-through\" : \"none\",\n      }}\n    >\n      {text}\n    </li>\n  );\n}\n```\n\nFirst, we create a GraphQL mutation that takes the todo's id we want to toggle as its only argument. We indicate that this is a local mutation by marking the field with a `@client` directive. This will tell Apollo Client to call our local `toggleTodo` mutation resolver in order to resolve the field. Then, we create a component with `useMutation` just as we would for a remote mutation. Finally, pass in your GraphQL mutation to your component and trigger it from within the UI in your render prop function.\n\n## Querying local state\n\nQuerying for local data is very similar to querying your GraphQL server. The only difference is that you add a `@client` directive on your local fields to indicate they should be resolved from the Apollo Client cache or a local resolver function. Let's look at an example:\n\n```jsx\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nimport Todo from \"./Todo\";\n\nconst GET_TODOS = gql`\n  query GetTodos {\n    todos @client {\n      id\n      completed\n      text\n    }\n    visibilityFilter @client\n  }\n`;\n\nfunction TodoList() {\n  const {\n    data: { todos, visibilityFilter },\n  } = useQuery(GET_TODOS);\n  return (\n    <ul>\n      {getVisibleTodos(todos, visibilityFilter).map((todo) => (\n        <Todo key={todo.id} {...todo} />\n      ))}\n    </ul>\n  );\n}\n```\n\nHere we create our GraphQL query and add `@client` directives to `todos` and `visibilityFilter`. We then pass the query to the `useQuery` hook. The `@client` directives here let `useQuery` component know that `todos` and `visibilityFilter` should be pulled from the Apollo Client cache or resolved using pre-defined local resolvers. The following sections help explain how both options work in more detail.\n\n> ⚠️ Since the above query runs as soon as the component is mounted, what do we do if there are no todos in the cache or there aren't any local resolvers defined to help calculate `todos`? We need to write an initial state to the cache before the query is run to prevent it from erroring out. Refer to the [Initializing the cache](#initializing-the-cache) section below for more information.\n\n### Initializing the cache\n\nOften, you'll need to write an initial state to the cache so any components querying data before a mutation is triggered don't error out. To accomplish this, you can use `cache.writeQuery` to prep the cache with initial values.\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from \"@apollo/client\";\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  cache,\n  localState: new LocalState({\n    resolvers: {\n      /* ... */\n    },\n  }),\n});\n\ncache.writeQuery({\n  query: gql`\n    query GetTodosNetworkStatusAndFilter {\n      todos\n      visibilityFilter\n      networkStatus {\n        isConnected\n      }\n    }\n  `,\n  data: {\n    todos: [],\n    visibilityFilter: \"SHOW_ALL\",\n    networkStatus: {\n      __typename: \"NetworkStatus\",\n      isConnected: false,\n    },\n  },\n});\n```\n\nSometimes you may need to [reset the store](../api/core/ApolloClient/#ApolloClient.resetStore) in your application, when a user logs out for example. If you call `client.resetStore` anywhere in your application, you will likely want to initialize your cache again. You can do this using the `client.onResetStore` method to register a callback that will call `cache.writeQuery` again.\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from \"@apollo/client\";\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  cache,\n  localState: new LocalState({\n    resolvers: {\n      /* ... */\n    },\n  }),\n});\n\nfunction writeInitialData() {\n  cache.writeQuery({\n    query: gql`\n      query GetTodosNetworkStatusAndFilter {\n        todos\n        visibilityFilter\n        networkStatus {\n          isConnected\n        }\n      }\n    `,\n    data: {\n      todos: [],\n      visibilityFilter: \"SHOW_ALL\",\n      networkStatus: {\n        __typename: \"NetworkStatus\",\n        isConnected: false,\n      },\n    },\n  });\n}\n\nwriteInitialData();\n\nclient.onResetStore(writeInitialData);\n```\n\n### Local data query flow\n\nWhen a query containing `@client` directives is executed, Apollo Client runs through a few sequential steps to try to find a result for the `@client` field. Let's use the following query to walk through the local data look up flow:\n\n```js\nconst GET_LAUNCH_DETAILS = gql`\n  query LaunchDetails($launchId: ID!) {\n    launch(id: $launchId) {\n      isInCart @client\n      site\n      rocket {\n        type\n      }\n    }\n  }\n`;\n```\n\nThis query includes a mixture of both remote and local fields. `isInCart` is the only field marked with an `@client` directive, so it's the field we'll focus on. When Apollo Client executes this query and tries to find a result for the `isInCart` field, it runs through the following steps:\n\n1. Has a resolver function been set for the field name `isInCart` on the `Launch` type? If yes, run and return the result from the resolver function.\n2. If a matching resolver function can't be found, check the Apollo Client cache to see if a `isInCart` value can be found directly or read with a `read` field `TypePolicy`. If so, return that value.\n\nLet's look at both of these steps more closely.\n\n- Resolving `@client` data with the help of local resolvers (step 1 above) is explained in [Handling `@client` fields with resolvers][].\n- Loading `@client` data from the cache (step 2 above) is explained in [Handling `@client` fields with the cache](#handling-client-fields-with-the-cache).\n\n### Handling `@client` fields with resolvers\n\nLocal resolvers are very similar to remote resolvers. Instead of sending your GraphQL query to a remote GraphQL endpoint, which then runs resolver functions against your query to populate and return a result set, Apollo Client runs locally defined resolver functions against any fields marked with the `@client` directive. Let's look at an example:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst GET_CART_ITEMS = gql`\n  query GetCartItems {\n    cartItems @client\n  }\n`;\n\nconst cache = new InMemoryCache();\ncache.writeQuery({\n  query: GET_CART_ITEMS,\n  data: {\n    cartItems: [],\n  },\n});\n\nconst client = new ApolloClient({\n  cache,\n  link: new HttpLink({\n    uri: \"http://localhost:4000/graphql\",\n  }),\n  localState: new LocalState({\n    resolvers: {\n      Launch: {\n        isInCart: (launch, _args, { cache }) => {\n          const { cartItems } = cache.readQuery({ query: GET_CART_ITEMS });\n          return cartItems.includes(launch.id);\n        },\n      },\n    },\n  }),\n});\n\nconst GET_LAUNCH_DETAILS = gql`\n  query LaunchDetails($launchId: ID!) {\n    launch(id: $launchId) {\n      isInCart @client\n      site\n      rocket {\n        type\n      }\n    }\n  }\n`;\n\n// ... run the query using client.query, a <Query /> component, etc.\n```\n\nHere when the `GET_LAUNCH_DETAILS` query is executed, Apollo Client looks for a local resolver associated with the `isInCart` field. Since we've defined a local resolver for the `isInCart` field in the `LocalState` instance, it finds a resolver it can use. This resolver function is run, then the result is calculated and merged in with the rest of the query result (if a local resolver can't be found, Apollo Client will check the cache for a matching field - see [Local data query flow](#local-data-query-flow) for more details).\n\nSetting resolvers through the `LocalState`'s `resolvers` option or through its `addResolvers` method adds resolvers to the internal resolver map (refer to the [Local resolvers](#local-resolvers) section for more details concerning the resolver map). In the above example we added an `isInCart` resolver, for the `Launch` GraphQL object type, to the resolver map. Let's look at the `isInCart` resolver function more closely:\n\n```js\n  resolvers: {\n    Launch: {\n      isInCart: (launch, _args, { client }) => {\n        const { cartItems } = client.readQuery({ query: GET_CART_ITEMS });\n        return cartItems.includes(launch.id);\n      },\n    },\n  },\n```\n\n`launch` holds the data returned from the server for the rest of the query, which means in this case we can use `launch` to get the current launch `id`. We aren't using any arguments in this resolver, so we can skip the second resolver parameter. From the `context` however (the third parameter), we're using the `client` reference to access the cache. So in this resolver, we're making a call directly to the cache to get all cart items, checking to see if any of those loaded cart items matches the parent `launch.id`, and returning `true` / `false` accordingly. The returned boolean is then incorporated back into the result of running the original query.\n\nJust like resolvers on the server, local resolvers are extremely flexible. They can be used to perform any kind of local computation you want, before returning a result for the specified field. You can manually query (or write to) the cache in different ways, call other helper utilities or libraries to prep/validate/clean data, track statistics, call into other data stores to prep a result, etc.\n\n#### Integrating `@client` into remote queries\n\nWhile Apollo Client’s local state handling features can be used to work with local state exclusively, most Apollo based applications are built to work with remote data sources. To address this, Apollo Client supports mixing `@client` based local resolvers with remote queries, as well as using `@client` based fields as arguments to remote queries, in the same request.\n\nThe `@client` directive can be used on any GraphQL selection set or field, to identify that the result of that field should be loaded locally with the help of a local resolver:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst MEMBER_DETAILS = gql`\n  query Member {\n    member {\n      name\n      role\n      isLoggedIn @client\n    }\n  }\n`;\n\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Member: {\n        isLoggedIn() {\n          return someInternalLoginVerificationFunction();\n        },\n      },\n    },\n  }),\n});\n\n// ... run the query using client.query, the <Query /> component, etc.\n```\n\nWhen the above `MEMBER_DETAILS` query is fired by Apollo Client (assuming we're talking to a network based GraphQL API), the `@client` `isLoggedIn` field is first stripped from the document, and the remaining query is sent over the network to the GraphQL API. After the query has been handled by the remote resolvers and the result is passed back to Apollo Client from the API, the `@client` parts of the original query are then run against any defined local resolvers, their results are merged with the network results, and the final resulting data is returned as the response to the original operation. So in the above example, `isLoggedIn` is stripped before the rest of the query is sent and handled by the network API, then when the results come back `isLoggedIn` is calculated by running the `isLoggedIn()` function from the resolver map. Local and network results are merged together, and the final response is made available to the application.\n\nThe `@client` directive can be used with entire selection sets as well:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst MEMBER_DETAILS = gql`\n  query Member {\n    member {\n      name\n      role\n      session @client {\n        isLoggedIn\n        connectionCount\n        errors\n      }\n    }\n  }\n`;\n\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Member: {\n        session() {\n          return {\n            __typename: \"Session\",\n            isLoggedIn: someInternalLoginVerificationFunction(),\n            connectionCount: calculateOpenConnections(),\n            errors: sessionError(),\n          };\n        },\n      },\n    },\n  }),\n});\n```\n\nApollo Client supports the merging of local `@client` results and remote results for Queries, Mutations and Subscriptions.\n\n#### Async local resolvers\n\nApollo Client supports asynchronous local resolver functions. These functions can either be `async` functions or ordinary functions that return a `Promise`. Asynchronous resolvers are useful when they need to return data from an asynchronous API.\n\n> ⚠️ If you would like to hit a REST endpoint from your resolver, [we recommend checking out `apollo-link-rest`](https://github.com/apollographql/apollo-link-rest) instead, which is a more complete solution for using REST endpoints with Apollo Client.\n\nFor React Native and most browser APIs, you should set up a listener in a component lifecycle method and pass in your mutation trigger function as the callback instead of using an async resolver. However, an `async` resolver function is often the most convenient way to consume asynchronous device APIs:\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from \"@apollo/client\";\nimport { CameraRoll } from \"react-native\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Query: {\n        async cameraRoll(_, { assetType }) {\n          try {\n            const media = await CameraRoll.getPhotos({\n              first: 20,\n              assetType,\n            });\n\n            return {\n              ...media,\n              id: assetType,\n              __typename: \"CameraRoll\",\n            };\n          } catch (e) {\n            console.error(e);\n            return null;\n          }\n        },\n      },\n    },\n  }),\n});\n```\n\n[`CameraRoll.getPhotos()`](https://facebook.github.io/react-native/docs/cameraroll.html#getphotos) returns a `Promise` resolving to an object with an `edges` property, which is an array of camera node objects, and a `page_info` property, which is an object with pagination information. This is a great use case for GraphQL, since we can filter down the return value to only the data that our components consume.\n\n```js\nimport { gql } from \"@apollo/client\";\n\nconst GET_PHOTOS = gql`\n  query GetPhotos($assetType: String!) {\n    cameraRoll(assetType: $assetType) @client {\n      id\n      edges {\n        node {\n          image {\n            uri\n          }\n          location {\n            latitude\n            longitude\n          }\n        }\n      }\n    }\n  }\n`;\n```\n\n### Handling `@client` fields with the cache\n\nAs outlined in [Handling `@client` fields with resolvers][], `@client` fields can be resolved with the help of local resolver functions. However, it's important to note that local resolvers are not always required when using an `@client` directive. Fields marked with `@client` can still be resolved locally, by pulling matching values out of the cache directly. For example:\n\n[Handling `@client` fields with resolvers]: #handling-client-fields-with-resolvers\n\n```jsx\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\nimport { ApolloProvider, useQuery } from \"@apollo/client/react\";\n\nimport Pages from \"./pages\";\nimport Login from \"./pages/login\";\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  cache,\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  localState: new LocalState({\n    resolvers: {},\n  }),\n});\n\nconst IS_LOGGED_IN = gql`\n  query IsUserLoggedIn {\n    isLoggedIn @client\n  }\n`;\n\ncache.writeQuery({\n  query: IS_LOGGED_IN,\n  data: {\n    isLoggedIn: !!localStorage.getItem(\"token\"),\n  },\n});\n\nfunction App() {\n  const { data } = useQuery(IS_LOGGED_IN);\n  return data.isLoggedIn ? <Pages /> : <Login />;\n}\n\nReactDOM.render(\n  <ApolloProvider client={client}>\n    <App />\n  </ApolloProvider>,\n  document.getElementById(\"root\")\n);\n```\n\nIn the above example, we first prep the cache using `cache.writeQuery` to store a value for the `isLoggedIn` field. We then run the `IS_LOGGED_IN` query via an Apollo Client `useQuery` hook, which includes an `@client` directive. When Apollo Client executes the `IS_LOGGED_IN` query, it first looks for a local resolver that can be used to handle the `@client` field. When it can't find one, it falls back on trying to pull the specified field out of the cache. So in this case, the `data` value returned by the `useQuery` hook has a `isLoggedIn` property available, which includes the `isLoggedIn` result (`!!localStorage.getItem('token')`) pulled directly from the cache.\n\nPulling `@client` field values directly out of the cache isn't quite as flexible as local resolver functions, since local resolvers can perform extra computations before returning a result. Depending on your application's needs however, loading `@client` fields directly from the cache might be a simpler option. Apollo Client doesn't restrict combining both approaches, so feel free to mix and match. If the need arises, you can pull some `@client` values from the cache, and resolve others with local resolvers, all in the same query.\n\n### Working with fetch policies\n\nBefore Apollo Client executes a query, one of the first things it does is check to see which [`fetchPolicy`](../data/queries/#setting-a-fetch-policy) it has been configured to use. It does this so it knows where it should attempt to resolve the query from first, either the cache or the network. When running a query, Apollo Client treats `@client` based local resolvers just like it does remote resolvers, in that it will adhere to its defined `fetchPolicy` to know where to attempt to pull data from first. When working with local resolvers, it's important to understand how fetch policies impact the running of resolver functions, since by default local resolver functions are not run on every request. This is because the result of running a local resolver is cached with the rest of the query result, and pulled from the cache on the next request. Let's look at an example:\n\n```jsx\nimport React, { Fragment } from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nimport { Loading, Header, LaunchDetail } from \"../components\";\nimport { ActionButton } from \"../containers\";\n\nexport const GET_LAUNCH_DETAILS = gql`\n  query LaunchDetails($launchId: ID!) {\n    launch(id: $launchId) {\n      isInCart @client\n      site\n      rocket {\n        type\n      }\n    }\n  }\n`;\n\nexport default function Launch({ launchId }) {\n  const { loading, error, data } = useQuery(GET_LAUNCH_DETAILS, {\n    variables: { launchId },\n  });\n\n  if (loading) return <Loading />;\n  if (error) return <p>ERROR: {error.message}</p>;\n\n  return (\n    <Fragment>\n      <Header image={data.launch.mission.missionPatch}>\n        {data.launch.mission.name}\n      </Header>\n      <LaunchDetail {...data.launch} />\n      <ActionButton {...data.launch} />\n    </Fragment>\n  );\n}\n```\n\nIn the above example we're using an Apollo Client `useQuery` hook to run the `GET_LAUNCH_DETAILS` query. The `@client` based `isInCart` field is configured to pull its data from the following resolver:\n\n```js\nimport { GET_CART_ITEMS } from \"./pages/cart\";\n\nexport const resolvers = {\n  Launch: {\n    isInCart: (launch, _, { cache }) => {\n      const { cartItems } = cache.readQuery({ query: GET_CART_ITEMS });\n      return cartItems.includes(launch.id);\n    },\n  },\n};\n```\n\nLet's assume we're starting with an empty cache. Since we haven't specified a `fetchPolicy` prop in our `useQuery` call, we're using Apollo Client's default `cache-first` `fetchPolicy`. This means when the `GET_LAUNCH_DETAILS` query is run, it checks the cache first to see if it can find a result. It's important to note that when the cache is checked the entire query is run against the cache, but any `@client` associated local resolvers are skipped (not run). So the cache is queried with the following (it's as if the `@client` directive was never specified):\n\n```graphql\nlaunch(id: $launchId) {\n  isInCart\n  site\n  rocket {\n    type\n  }\n}\n```\n\nIn this case a result can't be extracted from the cache (since our cache is empty), so behind the scenes Apollo Client moves further down the query execution path. At its next step, it essentially splits the original query into two parts - the part that has `@client` fields and the part that will be fired over the network. Both parts are then executed - results are fetched from the network, and results are calculated by running local resolvers. The results from the local resolvers and from the network are then merged together, and the final result is written to the cache and returned. So after our first run, we now have a result in the cache for the original query, that includes data for both the `@client` parts and network parts of the query.\n\nWhen the `GET_LAUNCH_DETAILS` query is run a second time, again since we're using Apollo Client's default `fetchPolicy` of `cache-first`, the cache is checked first for a result. This time a full result can be found for the query, so that result is returned through our `useQuery` call. Our `@client` field local resolvers aren't fired since the result we're looking for can already be extracted from the cache.\n\nIn a lot of situations treating local resolvers just like remote resolvers, by having them adhere to the same `fetchPolicy`, makes a lot of sense. Once you have the data you're looking for, which might have been fetched remotely or calculated using a local resolver, you can cache it and avoid recalculating/re-fetching it again on a subsequent request. But what if you're using local resolvers to run calculations that you need fired on every request? There are a few different ways this can be handled. You can switch your query to use a `fetchPolicy` that forces your entire query to run on each request, like `no-cache` or `network-only`. This will make sure your local resolvers fire on every request, but it will also make sure your network based query components fire on every request. Depending on your use case this might be okay, but what if you want the network parts of your query to leverage the cache, and just want your `@client` parts to run on every request? We'll cover a more flexible option for this in the [Forcing resolvers with `@client(always: true)`](#forcing-resolvers-with-clientalways-true) section.\n\n### Forcing resolvers with `@client(always: true)`\n\nApollo Client leverages its cache to help reduce the network overhead required when constantly making requests for the same data. By default, `@client` based fields leverage the cache in the exact same manner as remote fields. After a local resolver is run, its result is cached alongside any remote results. This way the next time a query is fired that can find its results in the cache, those results are used, and any associated local resolvers are not fired again (until the data is either removed from the cache or the query is updated to use a `no-cache` or `network-only` `fetchPolicy`).\n\nWhile leveraging the cache for both local and remote results can be super helpful in a lot of cases, it's not always the best fit. We might want to use a local resolver to calculate a dynamic value that needs to be refreshed on every request, while at the same time continue to use the cache for the network based parts of our query. To support this use case, Apollo Client's `@client` directive accepts an `always` argument, that when set to `true` will ensure that the associated local resolver is run on every request. Looking at an example:\n\n```jsx\nimport { ApolloClient, InMemoryCache, LocalState, gql } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Query: {\n        isLoggedIn() {\n          return !!localStorage.getItem(\"token\");\n        },\n      },\n    },\n  }),\n});\n\nconst IS_LOGGED_IN = gql`\n  query IsUserLoggedIn {\n    isLoggedIn @client(always: true)\n  }\n`;\n\n// ... run the query using client.query, a <Query /> component, etc.\n```\n\nThe `isLoggedIn` resolver above is checking to see if an authentication token exists in `localStorage`. In this example, we want to make sure that every time the `IS_LOGGED_IN` query is executed, the `isLoggedIn` local resolver is also fired, so that we have the most up to date login information. To do this, we're using a `@client(always: true)` directive in the query, for the `isLoggedIn` field. If we didn't include `always: true`, then the local resolver would fire based on the queries `fetchPolicy`, which means we could be getting back a cached value for `isLoggedIn`. Using `@client(always: true)` ensures that we're always getting the direct result of running the associated local resolver.\n\n> ⚠️ Please consider the impact of using `@client(always: true)` carefully. While forcing a local resolver to run on every request can be useful, if that resolver is computationally expensive or has side effects, you could be negatively impacting your application. We recommend leveraging the cache as much as possible when using local resolvers, to help with application performance. `@client(always: true)` is helpful to have in your tool-belt, but letting local resolvers adhere to a query `fetchPolicy` should be the preferred choice.\n\nWhile `@client(always: true)` ensures that a local resolver is always fired, it's important to note that if a query is using a `fetchPolicy` that leverages the cache first (`cache-first`, `cache-and-network`, `cache-only`), the query is still attempted to be resolved from the cache first, before the local resolver is fired. This happens because `@client(always: true)` use could be mixed with normal `@client` use in the same query, which means we want part of the query to adhere to the defined `fetchPolicy`. The benefit of this is that anything that can be loaded from the cache first is made available to your `@client(always: true)` resolver function, as its [first parameter](#local-resolvers). So even though you've used `@client(always: true)` to identify that you want to always run a specific resolver, within that resolver you can look at the loaded cache values for the query, and decide if you want to proceed with running the resolver.\n\n### Using `@client` fields as variables\n\nApollo Client provides a way to use an `@client` field result as a variable for a selection set or field, in the same operation. So instead of running an `@client` based query first, getting the local result, then running a second query using the loaded local result as a variable, everything can be handled in one request. This is achieved by combining the `@client` directive with the `@export(as: \"variableName\")` directive:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst query = gql`\n  query CurrentAuthorPostCount($authorId: Int!) {\n    currentAuthorId @client @export(as: \"authorId\")\n    postCount(authorId: $authorId)\n  }\n`;\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache,\n  localState: new LocalState({\n    resolvers: {},\n  }),\n});\n\ncache.writeQuery({\n  query: gql`\n    query GetCurrentAuthorId {\n      currentAuthorId\n    }\n  `,\n  data: {\n    currentAuthorId: 12345,\n  },\n});\n\n// ... run the query using client.query, the <Query /> component, etc.\n```\n\nIn the example above, `currentAuthorId` is first loaded from the cache, then passed into the subsequent `postCount` field as the `authorId` variable (specified by the `@export(as: \"authorId\")` directive). The `@export` directive can also be used on specific fields within a selection set, like:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst query = gql`\n  query CurrentAuthorPostCount($authorId: Int!) {\n    currentAuthor @client {\n      name\n      authorId @export(as: \"authorId\")\n    }\n    postCount(authorId: $authorId)\n  }\n`;\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache,\n  localState: new LocalState({\n    resolvers: {},\n  }),\n});\n\ncache.writeQuery({\n  query: gql`\n    query GetCurrentAuthor {\n      currentAuthor {\n        name\n        authorId\n      }\n    }\n  `,\n  data: {\n    currentAuthor: {\n      __typename: \"Author\",\n      name: \"John Smith\",\n      authorId: 12345,\n    },\n  },\n});\n\n// ... run the query using client.query, the <Query /> component, etc.\n```\n\nHere the `authorId` variable is set from the `authorId` field loaded from the cache stored `currentAuthor`. `@export` variable use isn't limited to remote queries; it can also be used to define variables for other `@client` fields or selection sets:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,\n  HttpLink,\n  gql,\n} from \"@apollo/client\";\n\nconst query = gql`\n  query CurrentAuthorPostCount($authorId: Int!) {\n    currentAuthorId @client @export(as: \"authorId\")\n    postCount(authorId: $authorId) @client\n  }\n`;\n\nconst cache = new InMemoryCache();\nconst client = new ApolloClient({\n  cache,\n  localState: new LocalState({\n    resolvers: {\n      Query: {\n        postCount(_, { authorId }) {\n          return authorId === 12345 ? 100 : 0;\n        },\n      },\n    },\n  }),\n});\n\ncache.writeQuery({\n  query: gql`\n    {\n      currentAuthorId\n    }\n  `,\n  data: {\n    currentAuthorId: 12345,\n  },\n});\n\n// ... run the query using client.query, the <Query /> component, etc.\n```\n\nSo here the `currentAuthorId` is loaded from the cache, then passed into the `postCount` local resolver as `authorId`.\n\n**A few important notes about `@export` use:**\n\n1. Apollo Client currently only supports using the `@export` directive to store variables for local data. `@export` must be used with `@client`.\n\n2. `@client @export` use might appear to go against the GraphQL specification, given that the execution order of an operation looks like it could affect the result. From the [Normal and Serial Execution](https://graphql.github.io/graphql-spec/draft/#sec-Normal-and-Serial-Execution) section of the GraphQL spec:\n\n> ... the resolution of fields other than top‐level mutation fields must always be side effect‐free and idempotent, the execution order must not affect the result, and hence the server has the freedom to execute the field entries in whatever order it deems optimal.\n\nApollo Client currently only supports the use of the `@export` directive when mixed with the `@client` directive. It prepares `@export` variables by first running through an operation that has `@client @export` directives, extracting the specified `@export` variables, then attempting to resolve the value of those variables from the local cache or local resolvers. Once a map of variable names to local values is built up, that map is then used to populate the variables passed in when running the server based GraphQL query. The execution order of the server based GraphQL query is not impacted by `@export` use; the variables are prepped and organized before the server query runs, so the specification is being followed.\n\n3. If you define multiple `@export` variables that use the same name, in a single operation, the value of the last `@export` variable will be used as the variable value moving forward. When this happens Apollo Client will log a warning message (dev only).\n\n## Managing the cache\n\nWhen you're using Apollo Client to work with local state, your Apollo cache becomes the single source of truth for all of your local and remote data. The [Apollo cache API](../caching/cache-interaction/) has several methods that can assist you with updating and retrieving data. Let's walk through the most relevant methods, and explore some common use cases for each one.\n\n### cache.writeQuery\n\nThe easiest way to update the cache is with `cache.writeQuery`. Here's how you use it in your resolver map for a simple update:\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from '@apollo/client';\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Mutation: {\n        updateVisibilityFilter: (_, { visibilityFilter }, { cache }) => {\n          cache.writeQuery({\n            query: gql`query GetVisibilityFilter { visibilityFilter }`,\n            data: {\n              __typename: 'Filter',\n              visibilityFilter,\n            },\n          });\n        },\n      },\n    },\n  }),\n};\n```\n\nThe `cache.writeFragment` method allows you to pass in an optional `id` property to write a fragment to an existing object in the cache. This is useful if you want to add some client-side fields to an existing object in the cache.\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from '@apollo/client';\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: {\n      Mutation: {\n        updateUserEmail: (_, { id, email }, { cache }) => {\n          cache.writeFragment({\n            id: cache.identify({ __typename: \"User\", id }),\n            fragment: gql`fragment UserEmail on User { email }`,\n            data: { email },\n          });\n        },\n      },\n    },\n  }),\n};\n```\n\nThe `cache.writeQuery` and `cache.writeFragment` methods should cover most of your needs; however, there are some cases where the data you're writing to the cache depends on the data that's already there. In that scenario, you can either use a combination of `cache.read{Query,Fragment}` followed by `cache.write{Query,Fragment}`, or use `cache.modify({ id, fields })` to update specific fields within the entity object identified by `id`.\n\n### writeQuery and readQuery\n\nSometimes, the data you're writing to the cache depends on data that's already in the cache; for example, you're adding an item to a list or setting a property based on an existing property value. In that case, you should use `cache.modify` to update specific existing fields. Let's look at an example where we add a todo to a list:\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState, gql } from \"@apollo/client\";\n\nlet nextTodoId = 0;\n\nconst cache = new InMemoryCache();\n\ncache.writeQuery({\n  query: gql`query GetTodos { todos { ... } }`,\n  data: { todos: [] },\n});\n\nconst client = new ApolloClient({\n  localState: new LocalState({\n    resolvers: {\n      Mutation: {\n        addTodo: (_, { text }, { cache }) => {\n          const query = gql`\n            query GetTodos {\n              todos @client {\n                id\n                text\n                completed\n              }\n            }\n          `;\n\n          const previous = cache.readQuery({ query });\n          const newTodo = {\n            id: nextTodoId++,\n            text,\n            completed: false,\n            __typename: \"TodoItem\",\n          };\n          const data = {\n            todos: [...previous.todos, newTodo],\n          };\n\n          cache.writeQuery({ query, data });\n          return newTodo;\n        },\n      },\n    },\n  }),\n});\n```\n\nIn order to add our todo to the list, we need the todos that are currently in the cache, which is why we call `cache.readQuery` to retrieve them. `cache.readQuery` will throw an error if the data isn't in the cache, so we need to provide an initial state. This is why we're calling `cache.writeQuery` with the empty array of todos after creating the `InMemoryCache`.\n\n### writeFragment and readFragment\n\n`cache.readFragment` is similar to `cache.readQuery` except you pass in a fragment. This allows for greater flexibility because you can read from any entry in the cache as long as you have its cache key. In contrast, `cache.readQuery` only lets you read from the root of your cache.\n\nLet's go back to our previous todo list example and see how `cache.readFragment` can help us toggle one of our todos as completed.\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  localState: new LocalState({\n    resolvers: {\n      Mutation: {\n        toggleTodo: (_, variables, { cache }) => {\n          const id = `TodoItem:${variables.id}`;\n          const fragment = gql`\n            fragment CompleteTodo on TodoItem {\n              completed\n            }\n          `;\n          const todo = cache.readFragment({ fragment, id });\n          const data = { ...todo, completed: !todo.completed };\n\n          cache.writeFragment({ fragment, id, data });\n          return null;\n        },\n      },\n    },\n  }),\n});\n```\n\nIn order to toggle our todo, we need the todo and its status from the cache, which is why we call `cache.readFragment` and pass in a fragment to retrieve it. The `id` we're passing into `cache.readFragment` refers to its cache key. If you're using the `InMemoryCache` and not overriding the `dataIdFromObject` config property, your cache key should be `__typename:id`.\n\n## Advanced\n\n### Code splitting\n\nDepending on the complexity and size of your local resolvers, you might not always want to define them up front, when you create your initial `ApolloClient` instance. If you have local resolvers that are only needed in a specific part of your application, you can call `client.localState.addResolvers` to dynamically add new resolvers. This can be really useful when leveraging techniques like route based code-splitting.\n\nLet's say we're building a messaging app and have a `/stats` route that is used to return the total number of messages stored locally. If we use `react-loadable` to load our `Stats` component like:\n\n```js\nimport Loadable from \"react-loadable\";\n\nimport Loading from \"./components/Loading\";\n\nexport const Stats = Loadable({\n  loader: () => import(\"./components/stats/Stats\"),\n  loading: Loading,\n});\n```\n\nand wait until our `Stats` component is called to define our local resolvers:\n\n```js\nimport React from \"react\";\nimport { gql } from \"@apollo/client\";\nimport { useApolloClient, useQuery } from \"@apollo/client/react\";\n\nconst GET_MESSAGE_COUNT = gql`\n  query GetMessageCount {\n    messageCount @client {\n      total\n    }\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    messageCount: (_, args, { client }) => {\n      // ... calculate and return the number of messages in\n      // the cache ...\n      return {\n        total: 123,\n        __typename: \"MessageCount\",\n      };\n    },\n  },\n};\n\nexport function MessageCount() {\n  const client = useApolloClient();\n  client.localState.addResolvers(resolvers);\n\n  const {\n    loading,\n    data: { messageCount },\n  } = useQuery(GET_MESSAGE_COUNT);\n\n  if (loading) return \"Loading ...\";\n\n  return <p>Total number of messages: {messageCount.total}</p>;\n}\n```\n\nour local resolver code will only be included in the bundle a user downloads when (if) they access `/stats`. It won't be included in the initial application bundle, which helps keep the size of our initial bundle down, and ultimately helps with download and application startup times.\n\n## API\n\nApollo Client local state handling is baked in, so you don't have to install anything extra. Local state management can be configured during `ApolloClient` instantiation by passing a `LocalState` instance into the `localState` constructor option. Data in the cache can be managed through the `ApolloCache` API.\n\n### LocalState\n\n#### Usage\n\n`LocalState` as a class instance is passed to the `localState` option of the `ApolloClient` constructor.\n\n```js\nimport { ApolloClient, InMemoryCache, LocalState } from '@apollo/client';\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState({\n    resolvers: { ... },\n  }),\n});\n```\n\n#### Methods\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client/local-state!LocalState#addResolvers:member(1)\"\n  headingLevel={5}\n  parameters={false}\n/>\n\n#### Typescript interfaces/types:\n\n```ts\ninterface Resolvers {\n  [key: string]: {\n    [field: string]: (\n      rootValue?: any,\n      args?: any,\n      context?: {\n        requestContext: any;\n        client: ApolloClient;\n        phase: \"exports\" | \"resolve\";\n      },\n      info?: any\n    ) => any;\n  };\n}\n```\n\n### ApolloCache\n\n#### Methods\n\n```js\nimport { InMemoryCache } from \"@apollo/client\";\n\nconst cache = new InMemoryCache();\ncache.writeQuery({\n  query: gql`\n    query MyQuery {\n      isLoggedIn @client\n      cartItems\n    }\n  `,\n  data: {\n    isLoggedIn: !!localStorage.getItem(\"token\"),\n    cartItems: [],\n  },\n});\n```\n\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloCache#writeQuery:member(1)\"\n  headingLevel={5}\n  parameters={false}\n  result={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloCache#readQuery:member(1)\"\n  headingLevel={5}\n  parameters={false}\n  result={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloCache#writeFragment:member(1)\"\n  headingLevel={5}\n  parameters={false}\n  result={false}\n/>\n<FunctionDetails\n  canonicalReference=\"@apollo/client!ApolloCache#readFragment:member(1)\"\n  headingLevel={5}\n  parameters={false}\n  result={false}\n/>\n"
  },
  {
    "path": "docs/source/local-state/local-state-management.mdx",
    "content": "---\ntitle: Managing local state\ndescription: Interacting with local data in Apollo Client\n---\n\nAt its core, Apollo Client is a **state management** library that happens to use GraphQL to interact with a remote server. Naturally, some application state doesn't _require_ a remote server because it's entirely local.\n\nApollo Client enables you to manage local state alongside remotely fetched state, meaning you can interact with _all_ of your application's state with a single API.\n\n## How it works\n\nYou can store your application's local state any way you want (such as in `localStorage` or the Apollo Client cache). You then define the logic that Apollo Client uses to fetch and populate that local data when you query a particular field. You can even include both local _and_ remotely fetched fields in the same query:\n\n```mermaid\nsequenceDiagram\n    participant Apollo Client;\n    participant Cache;\n    participant GraphQL Server;\n\n    Apollo Client->>Cache: Queries local and remote fields;\n    Note over Cache: Calculates local fields;\n    Cache->>GraphQL Server: Queries remote fields;\n    Note over GraphQL Server: Resolves remote fields;\n    GraphQL Server->>Cache: Returns remote fields;\n    Note over Cache: Caches remote fields;\n    Cache->>Apollo Client: Returns ALL fields;\n    Note over Apollo Client: Time passes…;\n    Apollo Client->>Cache: Executes same query;\n    Note over Cache: Calculates local fields;\n    Note over Cache: Fetches remote fields (now cached);\n    Cache->>Apollo Client: Returns ALL fields;\n```\n\nTo support this flow, Apollo Client introduces two complementary mechanisms for managing local state: [field policies](#field-policies-and-local-only-fields) and [reactive variables](#reactive-variables).\n\n## Field policies and local-only fields\n\n**Field policies** enable you to define what happens when you query a particular field, _including fields that aren't defined in your GraphQL server's schema_. By defining field policies for these **local-only fields**, you can populate them with data that's stored anywhere, such as in `localStorage` or [reactive variables](#reactive-variables).\n\nA single GraphQL query can include both local-only fields and remotely fetched fields. In the field policy for each local-only field, you specify a function that defines how that field's value is populated.\n\n[Get started with local-only fields](./managing-state-with-field-policies/)\n\n## Reactive variables\n\n**Reactive variables** enable you to read and write local data anywhere in your application, without needing to use a GraphQL operation to do so. The [field policy](#field-policies-and-local-only-fields) of a local-only field can use a reactive variable to populate the field's current value.\n\nReactive variables _aren't_ stored in the Apollo Client cache, so they don't need to conform to the strict structure of a cached type. You can store anything you want in them.\n\nWhenever the value of a reactive variable changes, Apollo Client automatically detects that change. Every active query with a field that depends on the changed variable automatically updates.\n\n[Get started with reactive variables](./reactive-variables)\n\n## Local resolvers\n\nYou define **local resolvers** to populate and modify local-only fields. These resolvers are similar in structure and purpose to the [resolvers that your GraphQL server defines](/apollo-server/data/resolvers/).\n\n[Learn more about local resolvers](./local-resolvers)\n"
  },
  {
    "path": "docs/source/local-state/managing-state-with-field-policies.mdx",
    "content": "---\ntitle: Local-only fields in Apollo Client\ndescription: Fetch local and remote data with one GraphQL query\n---\n\nYour Apollo Client queries can include **local-only fields** that _aren't_ defined in your GraphQL server's schema:\n\n```graphql {5}\nquery ProductDetails($productId: ID!) {\n  product(id: $productId) {\n    name\n    price\n    isInCart @client # This is a local-only field\n  }\n}\n```\n\nThe values for these fields are calculated locally using any logic you want, such as reading data from `localStorage`.\n\nAs shown, a query can include both local-only fields _and_ fields that are fetched from your GraphQL server.\n\n<Note>\n\n**Important**: Using `@client` fields requires configuring local state in your Apollo Client instance. If you use `@client` fields without configuring local state, you'll get an error like:\n\n```\nQuery 'ProductDetails' contains '@client' fields but local state has not been configured.\n```\n\nTo enable `@client` fields, you must provide a `LocalState` instance to your Apollo Client:\n\n```ts\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  localState: new LocalState(),\n});\n```\n\n</Note>\n\n## Defining\n\nLet's say we're building an e-commerce application. Most of a product's details are stored on our back-end server, but we want to define a `Product.isInCart` boolean field that's local to the client. First, we create a **field policy** for `isInCart`.\n\nA field policy specifies custom logic for how a single GraphQL field is fetched from and written to your Apollo Client cache. You can define field policies for both local-only fields and remotely fetched fields.\n\n> Field policies are primarily documented in [Customizing the behavior of cached fields](../caching/cache-field-behavior/). This article specifically describes how to use them with local-only fields.\n\nYou define your application's field policies in a map that you provide to the constructor of Apollo Client's `InMemoryCache`. Each field policy is a child of a particular _type_ policy (much like the corresponding field is a child of a particular type).\n\nHere's a sample `InMemoryCache` constructor that defines a field policy for `Product.isInCart`:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    // Type policy map\n    Product: {\n      fields: {\n        // Field policy map for the Product type\n        isInCart: {\n          // Field policy for the isInCart field\n          read(_, { variables }) {\n            // The read function for the isInCart field\n            return localStorage.getItem(\"CART\").includes(variables.productId);\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThe field policy above defines a [`read` function](../caching/cache-field-behavior/#the-read-function) for the `isInCart` field. Whenever you query a field that has a `read` function, the cache calls that function to calculate the field's value. In this case, the `read` function returns whether the queried product's ID is in the `CART` array in `localStorage`.\n\nYou can use `read` functions to perform any sort of logic you want, including:\n\n- Manually executing other cache operations\n- Calling helper utilities or libraries to prepare, validate, or sanitize data\n- Fetching data from a separate store\n- Logging usage metrics\n\n> If you query a local-only field that _doesn't_ define a `read` function, Apollo Client performs a default cache lookup for the field. See [Storing local state in the cache](#storing-local-state-in-the-cache) for details.\n\n### Reads are synchronous by design\n\nMany UI frameworks like React (when not using `Suspense`) have synchronous rendering pipelines, therefore it's important for UI components to have immediate access to any existing data. This is why all `read` functions are synchronous, as are the cache's `readQuery` and `readFragment` methods. It is possible, however, to leverage reactive variables and `options.storage` to compose a `read` function that behaves in a manner that resembles an asynchronous action:\n\n<ExpansionPanel title=\"See example\">\n\n```js\nnew InMemoryCache({\n  typePolicies: {\n    Person: {\n      fields: {\n        isInCart: {\n          read(_, { variables, storage }) {\n            if (!storage.var) {\n              storage.var = makeVar(false);\n              setTimeout(() => {\n                storage.var(\n                  localStorage.getItem(\"CART\").includes(variables.productId)\n                );\n              }, 100);\n            }\n            return storage.var();\n          },\n        },\n      },\n    },\n  },\n});\n```\n\n</ExpansionPanel>\n\n## Querying\n\nNow that we've defined a field policy for `isInCart`, we can include the field in a query that _also_ queries our back-end server, like so:\n\n```js {6}\nconst GET_PRODUCT_DETAILS = gql`\n  query ProductDetails($productId: ID!) {\n    product(id: $productId) {\n      name\n      price\n      isInCart @client\n    }\n  }\n`;\n```\n\nThat's it! The `@client` directive tells Apollo Client that `isInCart` is a local-only field. Because `isInCart` is local-only, Apollo Client omits it from the query it sends to our server to fetch `name` and `price`. The final query result is returned only after all local _and_ remote fields are populated.\n\n<Note>\n\nIf you apply the `@client` directive to a field with subfields, the directive is automatically applied to all subfields.\n\n<ExpansionPanel title=\"See example\">\n\n```js {6-9}\nconst GET_PRODUCT_DETAILS = gql`\n query ProductDetails($productId: ID!) {\n   product(id: $productId) {\n     name\n     price\n     purchaseStatus @client {\n       isInCart\n       isOnWishlist\n     }\n   }\n }\n;\n```\n\n</ExpansionPanel>\n\n </Note>\n\n## Storing and mutations\n\nYou can use Apollo Client to query and modify local state, regardless of how you _store_ that state. Apollo Client provides a couple of optional but helpful mechanisms for representing local state:\n\n- [Reactive variables](#storing-local-state-in-reactive-variables)\n- [The Apollo Client cache itself](#storing-local-state-in-the-cache)\n\nIt's tempting to think of local-only mutations as being expressed similarly to other local-only fields. When using previous versions of Apollo Client, developers would define local-only mutations using `@client`. They would then use [local resolvers](./local-resolvers) to handle `client.mutate` / `useMutation` calls. This is no longer the case, however. For Apollo Client version >= 3 users we recommend using [`writeQuery`](../caching/cache-interaction/#writequery), [`writeFragment`](../caching/cache-interaction/#writefragment), or [reactive variables](./reactive-variables/) to manage local state.\n\n### Storing and updating local state with reactive variables\n\nApollo Client [reactive variables](./reactive-variables) are great for representing local state:\n\n- You can read and modify reactive variables from anywhere in your application, without needing to use a GraphQL operation to do so.\n- Unlike the Apollo Client cache, reactive variables don't enforce [data normalization](../caching/overview/#data-normalization), which means you can store data in any format you want.\n- If a field's value depends on the value of a reactive variable, and that variable's value _changes_, **every active query that includes the field automatically refreshes**.\n\n#### Example\n\nReturning to our e-commerce application, let's say we want to fetch a list of the item IDs in a user's cart, and this list is stored locally. The query to do that looks like this:\n\n```js title=\"Cart.js\"\nexport const GET_CART_ITEMS = gql`\n  query GetCartItems {\n    cartItems @client\n  }\n`;\n```\n\nLet's use the `makeVar` function to initialize a reactive variable that stores our local list of cart items:\n\n```js {3} title=\"cache.js\"\nimport { makeVar } from \"@apollo/client\";\n\nexport const cartItemsVar = makeVar([]);\n```\n\nThis initializes a reactive variable with an empty array (you can pass any initial value to `makeVar`). Note that the return value of `makeVar` isn't the variable itself, but rather a _function_. We get the variable's current value by calling `cartItemsVar()`, and we set a _new_ value by calling `cartItemsVar(newValue)`.\n\nNext, let's define the field policy for `cartItems`. As always, we pass this to the constructor of `InMemoryCache`:\n\n```js {5-9} title=\"cache.js\"\nexport const cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        cartItems: {\n          read() {\n            return cartItemsVar();\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThis `read` function returns the value of our reactive variable whenever `cartItems` is queried.\n\nNow, let's create a button component that enables the user to add a product to their cart:\n\n```jsx {7} title=\"AddToCartButton.js\"\nimport { cartItemsVar } from \"./cache\";\n// ... other imports\n\nexport function AddToCartButton({ productId }) {\n  return (\n    <div class=\"add-to-cart-button\">\n      <Button onClick={() => cartItemsVar([...cartItemsVar(), productId])}>\n        Add to Cart\n      </Button>\n    </div>\n  );\n}\n```\n\nOn click, this button updates the value of `cartItemsVar` to append the button's associated `productId`. When this happens, Apollo Client notifies every active query that includes the `cartItems` field.\n\nHere's a `Cart` component that uses the `GET_CART_ITEMS` query and therefore refreshes automatically whenever the value of `cartItemsVar` changes:\n\n```jsx title=\"Cart.js\"\nexport const GET_CART_ITEMS = gql`\n  query GetCartItems {\n    cartItems @client\n  }\n`;\n\nexport function Cart() {\n  const { data, loading, error } = useQuery(GET_CART_ITEMS);\n\n  if (loading) return <Loading />;\n  if (error) return <p>ERROR: {error.message}</p>;\n\n  return (\n    <div class=\"cart\">\n      <Header>My Cart</Header>\n      {data && data.cartItems.length === 0 ?\n        <p>No items in your cart</p>\n      : <Fragment>\n          {data &&\n            data.cartItems.map((productId) => <CartItem key={productId} />)}\n        </Fragment>\n      }\n    </div>\n  );\n}\n```\n\nInstead of querying for `cartItems`, the `Cart` component can read and react to a reactive variable directly with the `useReactiveVar` hook:\n\n```jsx {1,4} title=\"Cart.js\"\nimport { useReactiveVar } from \"@apollo/client/react\";\n\nexport function Cart() {\n  const cartItems = useReactiveVar(cartItemsVar);\n\n  return (\n    <div class=\"cart\">\n      <Header>My Cart</Header>\n      {cartItems.length === 0 ?\n        <p>No items in your cart</p>\n      : <Fragment>\n          {cartItems.map((productId) => (\n            <CartItem key={productId} />\n          ))}\n        </Fragment>\n      }\n    </div>\n  );\n}\n```\n\nAs with the preceding `useQuery` example, whenever the `cartItemsVar` variable is updated, the `Cart` component rerenders.\n\n> **Important:** If you call `cartItemsVar()` instead of `useReactiveVar(cartItemsVar)` in the example above, future variable updates _do not_ cause the `Cart` component to rerender.\n\n### Storing and modifying local state in the cache\n\nStoring local state directly in the Apollo Client cache provides some advantages, but usually requires more code than [using reactive variables](#storing-local-state-in-reactive-variables):\n\n- You don't _have_ to [define a field policy](#defining) for local-only fields that are present in the cache. If you query a field that doesn't define a `read` function, by default Apollo Client attempts to fetch that field's value directly from the cache.\n- When you modify a cached field with [`writeQuery`](../caching/cache-interaction#writequery) or [`writeFragment`](../caching/cache-interaction#writefragment), **every active query that includes the field automatically refreshes**.\n\n#### Example\n\nLet's say our application defines the following query:\n\n```js\nconst IS_LOGGED_IN = gql`\n  query IsUserLoggedIn {\n    isLoggedIn @client\n  }\n`;\n```\n\nThe `isLoggedIn` field of this query is a local-only field. We can use [the `writeQuery` method](../caching/cache-interaction/#writequery) to write a value for this field directly to the Apollo Client cache, like so:\n\n```js\ncache.writeQuery({\n  query: IS_LOGGED_IN,\n  data: {\n    isLoggedIn: !!localStorage.getItem(\"token\"),\n  },\n});\n```\n\nThis writes a boolean value according to whether `localStorage` includes a `token` item, indicating an active session.\n\nNow our application's components can render according to the value of the `isLoggedIn` field, _without_ our needing to define a `read` function for it:\n\n```js\nfunction App() {\n  const { data } = useQuery(IS_LOGGED_IN);\n  return data.isLoggedIn ? <Pages /> : <Login />;\n}\n```\n\nHere's a full example that incorporates the code blocks above:\n\n<ExpansionPanel title=\"Expand example\">\n\n```jsx\nimport React from \"react\";\nimport ReactDOM from \"react-dom\";\nimport { ApolloClient, InMemoryCache, HttpLink, gql } from \"@apollo/client\";\nimport { ApolloProvider, useQuery } from \"@apollo/client/react\";\n\nimport Pages from \"./pages\";\nimport Login from \"./pages/login\";\n\nconst cache = new InMemoryCache();\n\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n  cache,\n});\n\nconst IS_LOGGED_IN = gql`\n  query IsUserLoggedIn {\n    isLoggedIn @client\n  }\n`;\n\ncache.writeQuery({\n  query: IS_LOGGED_IN,\n  data: {\n    isLoggedIn: !!localStorage.getItem(\"token\"),\n  },\n});\n\nfunction App() {\n  const { data } = useQuery(IS_LOGGED_IN);\n  return data.isLoggedIn ? <Pages /> : <Login />;\n}\n\nReactDOM.render(\n  <ApolloProvider client={client}>\n    <App />\n  </ApolloProvider>,\n  document.getElementById(\"root\")\n);\n```\n\n</ExpansionPanel>\n\nNote that even if you _do_ store local data as fields in the Apollo Client cache, you can (and probably should!) still define `read` functions for those fields. A `read` function can execute helpful custom logic, such as returning a default value if a field isn't present in the cache.\n\n### Persisting local state across sessions\n\nBy default, neither a reactive variable nor the `InMemoryCache` persists its state across sessions (for example, if a user refreshes their browser). To persist this state, you need to add logic to do so.\n\nThe `apollo3-cache-persist` library helps you persist and rehydrate the Apollo Client cache between sessions. For details, see [Persisting the cache](../caching/advanced-topics/#persisting-the-cache).\n\nThere is currently no built-in API for persisting reactive variables, but you can write variable values to `localStorage` (or another store) whenever they're modified, and initialize those variables with their stored value (if any) on app load.\n\n## Modifying\n\nThe way you modify the value of a local-only field depends on how you [store that field](#storing):\n\n- **If you're using a [reactive variable](#storing-local-state-in-reactive-variables)**, all you do is set the reactive variable's new value. Apollo Client automatically detects this change and triggers a refresh of every active operation that includes an affected field.\n\n- **If you're [using the cache directly](#storing-local-state-in-the-cache)**, call one of `writeQuery`, `writeFragment`, or `cache.modify` ([all documented here](../caching/cache-interaction/)) to modify cached fields. Like reactive variables, all of these methods trigger a refresh of every affected active operation.\n\n- **If you're using another storage method**, such as `localStorage`, set the field's new value in whatever method you're using. Then, you can force a refresh of every affected operation by calling [`cache.evict`](../caching/garbage-collection/#cacheevict). In your call, provide both the `id` of your field's containing object and the name of the local-only field.\n\n## Using local-only fields as GraphQL variables\n\nIf your GraphQL query uses variables, the local-only fields of that query can provide the _values_ of those variables.\n\nTo do so, you apply the `@export(as: \"variableName\")` directive, like so:\n\n```js {3}\nconst GET_CURRENT_AUTHOR_POST_COUNT = gql`\n  query CurrentAuthorPostCount($authorId: Int!) {\n    currentAuthorId @client @export(as: \"authorId\")\n    postCount(authorId: $authorId)\n  }\n`;\n```\n\nIn the query above, the result of the local-only field `currentAuthorId` is used as the value of the `$authorId` variable that's passed to `postCount`.\n\nYou can do this even if `postCount` is _also_ a local-only field (i.e., if it's also marked as `@client`).\n\n### Considerations for using `@export`\n\n- To use the `@export` directive, a field **must also** use the `@client` directive. In other words, only local-only fields can be used as variable values.\n\n- A field that `@export`s a variable value **must appear before** any fields that _use_ that variable.\n\n- If multiple fields in an operation use the `@export` directive to assign their value to the _same_ variable, the field listed _last_ takes precedence. When this happens in development mode, Apollo Client logs a warning message.\n\n- At first glance, the `@export` directive appears to violate the [GraphQL specification's requirement](https://graphql.github.io/graphql-spec/draft/#sec-Normal-and-Serial-Execution) that the execution order of an operation must not affect its result:\n\n  > …the resolution of fields other than top‐level mutation fields must always be side effect‐free and idempotent, the execution order must not affect the result, and hence the server has the freedom to execute the field entries in whatever order it deems optimal.\n\n  However, all `@export`ed variable values are populated _before_ an operation is sent to a remote server. Only local-only fields can use the `@export` directive, and those fields are stripped from operations before they're transmitted.\n"
  },
  {
    "path": "docs/source/local-state/reactive-variables.mdx",
    "content": "---\ntitle: Reactive variables\ndescription: State containers integrated into Apollo Client's reactivity model\n---\n\nNew in Apollo Client 3, **reactive variables** are a useful mechanism for representing local state outside of the Apollo Client cache. Because they're separate from the cache, reactive variables can store data of any type and structure, and you can interact with them anywhere in your application without using GraphQL syntax.\n\n**Most importantly, modifying a reactive variable triggers an update of every active query that depends on that variable.** Additionally, this updates the React state for components that use the `useReactiveVar` React hook.\n\n> A query \"depends on\" a reactive variable if any of the query's requested fields defines a [`read` function](../caching/cache-field-behavior/#the-read-function) that reads the variable's value.\n\n## Creating\n\nCreate a reactive variable with the `makeVar` method, like so:\n\n```js\nimport { makeVar } from \"@apollo/client\";\n\nconst cartItemsVar = makeVar([]);\n```\n\nThis code creates a reactive variable with an empty array as its initial value.\n\n> **Important:** The return value of `makeVar` is a _function_ that you call to read or modify your reactive variable's value.\n\n## Reading\n\nTo read the value of your reactive variable, call the function returned by `makeVar` with zero arguments:\n\n```js\nconst cartItemsVar = makeVar([]);\n\n// Output: []\nconsole.log(cartItemsVar());\n```\n\n## Modifying\n\nTo modify the value of your reactive variable, call the function returned by `makeVar` with one argument (the variable's new value):\n\n```js\nconst cartItemsVar = makeVar([]);\nconst cartItemIds = [100, 101, 102];\n\ncartItemsVar(cartItemIds);\n\n// Output: [100, 101, 102]\nconsole.log(cartItemsVar());\n\n// Don't mutate an existing object or array.\n// cartItemIds.push(456) will not trigger an update.\n// Instead, pass a new copy:\ncartItemsVar([...cartItemIds, 456]);\n\n// Output: [100, 101, 102, 456]\nconsole.log(cartItemsVar());\n```\n\n## Reacting\n\nAs their name suggests, reactive variables can trigger reactive changes in your application. Whenever you modify the value of a reactive variable, queries that depend on that variable refresh, and your application's UI updates accordingly.\n\nWith the `useReactiveVar` hook, React components can also include reactive variable values in their state directly, _without_ wrapping them in a query.\n\nFor more information, see [Storing local state in reactive variables](./managing-state-with-field-policies/#storing-local-state-in-reactive-variables).\n\n### useReactiveVar hook\n\nThe `useReactiveVar` hook can be used to read from a reactive variable in a way that allows the React component to re-render if/when the variable is next updated.\n\nPreviously, the only way for a reactive variable to trigger a React component re-render was through the use of `useQuery`. Now you don't have to be using `useQuery` to benefit from the reactivity that `ReactiveVar<T>` provides.\n\n```jsx\nimport { makeVar } from \"@apollo/client\";\nimport { useReactiveVar } from \"@apollo/client/react\";\nexport const cartItemsVar = makeVar([]);\n\nexport function Cart() {\n  const cartItems = useReactiveVar(cartItemsVar);\n  // ...\n```\n\n## Example application\n\n[This example to-do list application](https://github.com/apollographql/ac3-state-management-examples/tree/master/apollo-local-state) uses reactive variables to track both the current list of to-do items and the filter that determines which items to display. See [`cache.tsx`](https://github.com/apollographql/ac3-state-management-examples/blob/master/apollo-local-state/src/cache.tsx) in particular.\n"
  },
  {
    "path": "docs/source/migrating/apollo-client-4-migration.mdx",
    "content": "---\ntitle: Migrating to Apollo Client 4.0\n---\n\nThis article walks you through migrating your application to Apollo Client 4.0 from a previous installation of Apollo Client 3.14.\n\n<Note>\n\nIf you are migrating from older versions of Apollo Client 3, we generally recommend updating to Apollo Client 3.14 first.\nApollo Client 3.14 introduces many deprecations and warnings that will help you prepare your application for a smooth migration to Apollo Client 4.0.\n\n</Note>\n\n## What’s new in 4.0\n\n1. Framework & Bundle Improvements\n\n- Framework-agnostic core with React exports moved to `@apollo/client/react`\n- Better ESM support with `exports` field in `package.json`\n- Observable implementation now uses `rxjs` instead of `zen-observable`\n- More features are opt-in to reduce bundle size when not used\n\n2. Enhanced Developer Experience\n\n- TypeScript: Stricter variable requirements, more precise return types, namespaced types, and customizable core types\n- Error Handling: Unified error property, granular error classes, and consistent errorPolicy behavior for all error types\n\nFor a full list of changes, see the [changelog](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md).\n\n## Installation\n\n<Caution>\n\nApollo Client 4.0 is a major-version release that includes breaking changes. If you are updating an existing application to use Apollo Client 4.0, see the [changelog](https://github.com/apollographql/apollo-client/blob/main/CHANGELOG.md) for details about these changes.\n\n</Caution>\n\nInstall Apollo Client 4 along with its peer dependencies with the following command:\n\n```sh showLineNumbers=false\nnpm install @apollo/client@latest graphql rxjs\n```\n\n<Note>\n\n`rxjs` is a new peer dependency with Apollo Client 4.0.\n\n</Note>\n\n## Recommended migration approach\n\nWe recommend following this order to help make your migration as smooth as possible.\n\n### Stage 1: Automated updates\n\n[Run the codemod](#codemod) first to handle import changes automatically.\n\nYou can use the TypeScript-specific codemod or run specific modifications if you prefer a gradual approach.\n\nIf you prefer a manual approach, you can still [update your imports](#updating-imports) manually.\n\n### Stage 2: Required setup changes\n\nThe Apollo Client initialization has changed. Review the [new initialization options](#update-the-initialization-of-apolloclient) and update accordingly.\n\nIf you use `@defer`, you need to [enable incremental delivery](#enable-incremental-delivery-defer).\n\nIf you use data masking, you need to [configure the data masking types](#enable-data-masking-types).\n\n### Stage 3: Changes that may require refactoring\n\nThese changes may require code refactoring depending on your usage.\n\n#### Changes affecting most users:\n\n- **[Core API changes](#core-api-changes)** - Query behavior changes\n- **[Error handling updates](#new-error-handling)** - New error classes and patterns\n- **[TypeScript improvements](#typescript-changes)** - New type locations and patterns\n\n#### Changes affecting React users:\n\n- **[React hook changes](#for-react-users)** - `useLazyQuery`, `useMutation`, `useQuery` updates\n\n#### Changes affecting fewer users:\n\n- **[Link API changes](#link-api-changes)** - If you use custom links\n- **[Local state changes](#local-state-changes)** - If you use `@client` directives\n- **[Testing changes](#testing-related-changes)** - MockedProvider updates\n- **[Bundling changes](#bundling-changes)** - New export patterns and transpilation\n- **[Development mode changes](#development-mode-changes)** - Automatic detection\n\n## Codemod\n\nTo ease the migration process, we have provided a codemod that automatically updates your codebase.\n\n<Note>\n\nThe codemod doesn't update your code with every breaking change. We recommend reading through the full migration guide for any additional changes that need refactoring.\n\n</Note>\n\nThis codemod runs modifications in the following order:\n\n<ol><li>\n\n`legacyEntrypoints` step:\n\n<ul><li>\n\nUpdates CommonJS import statements using the `.cjs` extension to their associated entry point\n\n```ts disableCopy=true\nimport { ApolloClient } from \"@apollo/client/main.cjs\";// [!code --]\nimport { ApolloClient } from \"@apollo/client\";// [!code ++]\n```\n\n</li><li>\n\nUpdates ESM import statements using the `.js` extension to their associated entry point\n\n```ts disableCopy=true\nimport { ApolloClient } from \"@apollo/client/index.js\";// [!code --]\nimport { ApolloClient } from \"@apollo/client\";// [!code ++]\n```\n\n</li></ul>\n\n</li><li>\n\n`imports` step:\n\n<ul><li>\n\nUpdates imports that have moved around\n\n```ts disableCopy=true\nimport { useQuery } from \"@apollo/client\";// [!code --]\nimport { useQuery } from \"@apollo/client/react\";// [!code ++]\n```\n\n</li><li>\n\nUpdates type references that have moved into namespaces.\n\n```ts disableCopy=true\nimport { FetchResult } from \"@apollo/client\";// [!code --]\nimport { ApolloLink } from \"@apollo/client\";// [!code ++]\n// ...\nfn<FetchResult>();// [!code --]\nfn<ApolloLink.Result>();// [!code ++]\n```\n\n</li></ul>\n</li><li>\n\n`links` step:\n\n<ul><li>\n\nUpdates the usage of Apollo-provided links to their associated class implementation.\n\n```ts disableCopy=true\nimport { createHttpLink } from \"@apollo/client\";// [!code --]\nimport { HttpLink } from \"@apollo/client/link/http\";// [!code ++]\n// ...\nconst link = createHttpLink({ uri: \"https://example.com/graphql\" });// [!code --]\nconst link = new HttpLink({ uri: \"https://example.com/graphql\" });// [!code ++]\n```\n\n<Note>\n\nIf you use the `setContext` link, you will need to manually migrate to the `SetContextLink` class because the order of arguments has changed. This is not automatically performed by the codemod.\n\n</Note>\n\n</li><li>\n\nUpdates the usage of `from`, `split` and `concat` functions from `@apollo/client/link` to use the static methods on the `ApolloLink` class. For example:\n\n```ts disableCopy=true\nimport { from } from \"@apollo/client\";// [!code --]\nimport { ApolloLink } from \"@apollo/client\";// [!code ++]\n// ...\nconst link = from([a, b, c]);// [!code --]\nconst link = ApolloLink.from([a, b, c]);// [!code ++]\n```\n\n</li></ul>\n</li><li>\n\n`removals` step:\n\n<ul><li>\n\nUpdates exports removed from Apollo Client to a special `@apollo/client/v4-migration` entrypoint. This is a type-only entrypoint that contains doc blocks with migration instructions for each removed item.\n\n```ts disableCopy=true\nimport { Concast } from \"@apollo/client\";// [!code --]\nimport { Concast } from \"@apollo/client/v4-migration\";// [!code ++]\n```\n\n</li></ul>\n\n<Note>\n\nAny runtime values exported from `@apollo/client/v4-migration` will throw an error at runtime since their implementations do not exist.\n\n</Note>\n\n</li><li>\n\n`clientSetup` step:\n\n<ul><li>\n\nMoves `uri`, `headers` and `credentials` to the `link` option and creates a new `HttpLink` instance\n\n```ts disableCopy=true\nimport { HttpLink } from \"@apollo/client\"; // [!code ++]\n\nnew ApolloClient({\n  uri: \"/graphql\", // [!code --:5]\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\"\n  },\n  link: new HttpLink({ // [!code ++:6]\n    uri: \"/graphql\",\n    credentials: \"include\",\n    headers: {\n      \"x-custom-header\"\n    },\n  })\n})\n```\n\n</li><li>\n\nMoves `name` and `version` into a `clientAwareness` option\n\n```ts disableCopy=true\nnew ApolloClient({\n  name: \"my-client\",// [!code --:2]\n  version: \"1.0.0\",\n  clientAwareness: {// [!code ++:4]\n    name: \"my-client\",\n    version: \"1.0.0\",\n  },\n});\n```\n\n</li><li>\n\nAdds a `localState` option with a new `LocalState` instance, moves the `resolvers` to `LocalState`, and removes the `typeDefs` and `fragmentMatcher` options\n\n```ts disableCopy=true\nimport { LocalState } from \"@apollo/client/local-state\";// [!code ++]\n\nnew ApolloClient({\n  typeDefs,// [!code --]\n  fragmentMatcher: () => true,// [!code --]\n  resolvers: {// [!code --:3]\n    /* ... */\n  },\n  localState: new LocalState({// [!code ++:5]\n    resolvers: {\n      /* ... */\n    },\n  }),\n});\n```\n\n</li><li>\n\nUpdates the `connectToDevTools` option to `devtools.enabled`\n\n```ts disableCopy=true\nnew ApolloClient({\n  connectToDevTools: true,// [!code --]\n  devtools: {// [!code ++:3]\n    enabled: true,\n  },\n});\n```\n\n</li><li>\n\nRenames `disableNetworkFetches` to `prioritizeCacheValues`\n\n```ts disableCopy=true\nnew ApolloClient({\n  disableNetworkFetches: true,// [!code --]\n  prioritizeCacheValues: true,// [!code ++]\n});\n```\n\n</li><li>\n\nAdds a template for global type augmentation to re-enable data masking types when the `dataMasking` option is set to `true`\n\n```ts disableCopy=true\nnew ApolloClient({\n  // [!code ++:8]\n  /*\n  Inserted by Apollo Client 3->4 migration codemod.\n  Keep this comment here if you intend to run the codemod again,\n  to avoid changes from being reapplied.\n  Delete this comment once you are done with the migration.\n  @apollo/client-codemod-migrate-3-to-4 applied\n  */\n  dataMasking: true,\n});\n\n// [!code ++:15]\n/*\nStart: Inserted by Apollo Client 3->4 migration codemod.\nCopy the contents of this block into a \\`.d.ts\\` file in your project\nto enable data masking types.\n*/\nimport \"@apollo/client\";\nimport { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides\n    extends GraphQLCodegenDataMasking.TypeOverrides {}\n}\n/*\nEnd: Inserted by Apollo Client 3->4 migration codemod.\n*/\n```\n\n</li><li>\n\nAdds the `incrementalHandler` option and adds a template for global type augmentation to accordingly type network responses in custom links\n\n```ts disableCopy=true\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";// [!code ++]\n\nnew ApolloClient({\n  // [!code ++:7]\n  /*\n  If you are not using the \\`@defer\\` directive in your application,\n  Inserted by Apollo Client 3->4 migration codemod.\n  you can safely remove this option.\n  */\n  incrementalHandler: new Defer20220824Handler(),\n});\n// [!code ++:14]\n/*\nStart: Inserted by Apollo Client 3->4 migration codemod.\nCopy the contents of this block into a \\`.d.ts\\` file in your project to enable correct response types in your custom links.\nIf you do not use the \\`@defer\\` directive in your application, you can safely remove this block.\n*/\nimport \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n}\n/*\nEnd: Inserted by Apollo Client 3->4 migration codemod.\n*/\n```\n\n</li></ul>\n\n</li></ol>\n\n### Running the codemod\n\n<Note>\n\nThe codemod requires a Node.js version that supports loading ECMAScript modules with `require`. See the table in the [Node.js documentation](https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require) for the versions that support this feature (you might need to expand the \"History\" section to see the table.)\n\n</Note>\n\nTo run the codemod, use the following command:\n\n```sh showLineNumbers=false\nnpx @apollo/client-codemod-migrate-3-to-4 src\n```\n\n<Note>\n\nThis command behaves similarly to [`jscodeshift`](https://github.com/facebook/jscodeshift) with a preselected codemod.\n\n</Note>\n\n<Note>\n\nThis example targets the `src` directory with the codemod. Replace `src` with the file pattern applicable to your file structure if it differs.\n\n</Note>\n\nFor more details on the available options, run the command using the `--help` option.\n\n```sh showLineNumbers=false\nnpx @apollo/client-codemod-migrate-3-to-4 --help\n```\n\n### Using the Codemod with TypeScript\n\nIf you have a TypeScript project, we recommend running the codemod against `.ts` and `.tsx` files separately as those have slightly overlapping syntax and might otherwise be misinterpreted by the codemod.\n\n```sh showLineNumbers=false\nnpx @apollo/client-codemod-migrate-3-to-4 --parser ts --extensions ts src\nnpx @apollo/client-codemod-migrate-3-to-4 --parser tsx --extensions tsx src\n```\n\n### Running specific modifications\n\nIf you prefer to migrate your application more selectively instead of all at once, you can specify specific modifications using the `--codemod` option. For example, to run only the `imports` and `links` modifications, run the following command:\n\n```sh showLineNumbers=false\nnpx @apollo/client-codemod-migrate-3-to-4 --codemod imports --codemod links src\n```\n\nThe following codemods are available:\n\n- `clientSetup` - Updates the options provided to the `ApolloClient` constructor to use their new counterparts\n- `legacyEntrypoints` - Renames import statements that target `.js` or `.cjs` imports to their associated entry point (e.g. `@apollo/client/main.cjs` becomes `@apollo/client`)\n- `imports` - Updates import statements that have moved entry points and updates type references that have moved into a namespace.\n- `links` - Updates provided Apollo Links to their class-based alternative (e.g. `createHttpLink()` becomes `new HttpLink()`).\n- `removals` - Updates import statements that contain removed features to a special `@apollo/client/v4-migration` entry point.\n\n## Updating imports\n\n### Move from manual CJS/ESM imports to `exports`\n\n<Note>\n\nThis section contains instructions for manually updating imports. If you used the [Codemod](#running-the-codemod) to update your imports, you can safely skip this section.\n\n</Note>\n\nApollo Client 4 now includes an `exports` field in the package's `package.json` definition. Instead of importing `.js` or `.cjs` files directly (e.g. `@apollo/client/react/index.js`, `@apollo/client/react/react.cjs`, etc.), you now import from the entrypoint instead (e.g. `@apollo/client/react`).\nYour bundler is aware of the different module formats and uses the `exports` field of the package's `package.json` to resolve the right format.\n\n<details>\n<summary><h3 style=\"display:inline\">List of all changed imports</h3><br/>(click to expand)</summary>\n\nThe following entry points have been renamed:\n\n| Previous entry point           | New entry point          |\n| ------------------------------ | ------------------------ |\n| `@apollo/client/core`          | `@apollo/client`         |\n| `@apollo/client/link/core`     | `@apollo/client/link`    |\n| `@apollo/client/react/context` | `@apollo/client/react`   |\n| `@apollo/client/react/hooks`   | `@apollo/client/react`   |\n| `@apollo/client/testing/core`  | `@apollo/client/testing` |\n\nThe following entry points have been removed:\n\n| Previous entry point                          | Reason                                                                                                               |\n| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |\n| `@apollo/client/react/components`             | The render prop components were already deprecated in Apollo Client 3.x and have been removed in 4.                  |\n| `@apollo/client/react/hoc`                    | The higher order components were already deprecated in Apollo Client 3.x and have been removed in 4.                 |\n| `@apollo/client/react/parser`                 | This module was an implementation detail of the render prop components and HOCs.                                     |\n| `@apollo/client/testing/experimental`         | This is available as [@apollo/graphql-testing-library](https://github.com/apollographql/graphql-testing-library)     |\n| `@apollo/client/utilities/globals`            | This was an implementation detail and has been removed. Some of the exports are now available in other entry points. |\n| `@apollo/client/utilities/subscriptions/urql` | This is supported natively by urql and is no longer included.                                                        |\n\nThe following individual imports have been renamed, moved to new entry points and/or moved into namespaces:\n\n<table>\n<thead>\n<tr><th>Previous entry point</th><th>New entry point</th></tr>\n<tr><td>Previous import name</td><td>New import name</td></tr>\n</thead>\n<tbody>\n<tr><th>`@apollo/client`</th><th>(unchanged)</th></tr>\n<tr><td>`ApolloClientOptions`</td><td>`ApolloClient.Options`</td></tr>\n<tr><td>`DefaultOptions`</td><td>`ApolloClient.DefaultOptions`</td></tr>\n<tr><td>`DevtoolsOptions`</td><td>`ApolloClient.DevtoolsOptions`</td></tr>\n<tr><td>`MutateResult`</td><td>`ApolloClient.MutateResult`</td></tr>\n<tr><td>`MutationOptions`</td><td>`ApolloClient.MutateOptions`</td></tr>\n<tr><td>`QueryOptions`</td><td>`ApolloClient.QueryOptions`</td></tr>\n<tr><td>`RefetchQueriesOptions`</td><td>`ApolloClient.RefetchQueriesOptions`</td></tr>\n<tr><td>`RefetchQueriesResult`</td><td>`ApolloClient.RefetchQueriesResult`</td></tr>\n<tr><td>`SubscriptionOptions`</td><td>`ApolloClient.SubscribeOptions`</td></tr>\n<tr><td>`WatchQueryOptions`</td><td>`ApolloClient.WatchQueryOptions`</td></tr>\n<tr><td>`ApolloQueryResult`</td><td>`ObservableQuery.Result`</td></tr>\n<tr><td>`FetchMoreOptions`</td><td>`ObservableQuery.FetchMoreOptions`</td></tr>\n<tr><td>`SubscribeToMoreOptions`</td><td>`ObservableQuery.SubscribeToMoreOptions`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client`</th><th>`@apollo/client/react`</th></tr>\n<tr><td>`ApolloProvider`</td><td>(unchanged)</td></tr>\n<tr><td>`createQueryPreloader`</td><td>(unchanged)</td></tr>\n<tr><td>`getApolloContext`</td><td>(unchanged)</td></tr>\n<tr><td>`skipToken`</td><td>(unchanged)</td></tr>\n<tr><td>`useApolloClient`</td><td>(unchanged)</td></tr>\n<tr><td>`useBackgroundQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`useFragment`</td><td>(unchanged)</td></tr>\n<tr><td>`useLazyQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`useLoadableQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`useMutation`</td><td>(unchanged)</td></tr>\n<tr><td>`useQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`useQueryRefHandlers`</td><td>(unchanged)</td></tr>\n<tr><td>`useReactiveVar`</td><td>(unchanged)</td></tr>\n<tr><td>`useReadQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`useSubscription`</td><td>(unchanged)</td></tr>\n<tr><td>`useSuspenseFragment`</td><td>(unchanged)</td></tr>\n<tr><td>`useSuspenseQuery`</td><td>(unchanged)</td></tr>\n<tr><td>`ApolloContextValue`</td><td>(unchanged)</td></tr>\n<tr><td>`BackgroundQueryHookFetchPolicy`</td><td>`useBackgroundQuery.FetchPolicy`</td></tr>\n<tr><td>`BackgroundQueryHookOptions`</td><td>`useBackgroundQuery.Options`</td></tr>\n<tr><td>`BaseSubscriptionOptions`</td><td>`useSubscription.Options`</td></tr>\n<tr><td>`Context`</td><td>(unchanged)</td></tr>\n<tr><td>`LazyQueryExecFunction`</td><td>`useLazyQuery.ExecFunction`</td></tr>\n<tr><td>`LazyQueryHookExecOptions`</td><td>`useLazyQuery.ExecOptions`</td></tr>\n<tr><td>`LazyQueryHookOptions`</td><td>`useLazyQuery.Options`</td></tr>\n<tr><td>`LazyQueryResult`</td><td>`useLazyQuery.Result`</td></tr>\n<tr><td>`LazyQueryResultTuple`</td><td>`useLazyQuery.ResultTuple`</td></tr>\n<tr><td>`LoadableQueryHookFetchPolicy`</td><td>`useLoadableQuery.FetchPolicy`</td></tr>\n<tr><td>`LoadableQueryHookOptions`</td><td>`useLoadableQuery.Options`</td></tr>\n<tr><td>`LoadQueryFunction`</td><td>`useLoadableQuery.LoadQueryFunction`</td></tr>\n<tr><td>`MutationFunction`</td><td>(unchanged)</td></tr>\n<tr><td>`MutationFunctionOptions`</td><td>`useMutation.MutationFunctionOptions`</td></tr>\n<tr><td>`MutationHookOptions`</td><td>`useMutation.Options`</td></tr>\n<tr><td>`MutationResult`</td><td>`useMutation.Result`</td></tr>\n<tr><td>`MutationTuple`</td><td>`useMutation.ResultTuple`</td></tr>\n<tr><td>`NoInfer`</td><td>(unchanged)</td></tr>\n<tr><td>`OnDataOptions`</td><td>`useSubscription.OnDataOptions`</td></tr>\n<tr><td>`OnSubscriptionDataOptions`</td><td>`useSubscription.OnSubscriptionDataOptions`</td></tr>\n<tr><td>`PreloadedQueryRef`</td><td>(unchanged)</td></tr>\n<tr><td>`PreloadQueryFetchPolicy`</td><td>(unchanged)</td></tr>\n<tr><td>`PreloadQueryFunction`</td><td>(unchanged)</td></tr>\n<tr><td>`PreloadQueryOptions`</td><td>(unchanged)</td></tr>\n<tr><td>`QueryFunctionOptions`</td><td>`useQuery.Options`</td></tr>\n<tr><td>`QueryHookOptions`</td><td>`useQuery.Options`</td></tr>\n<tr><td>`QueryRef`</td><td>(unchanged)</td></tr>\n<tr><td>`QueryReference`</td><td>`QueryRef`</td></tr>\n<tr><td>`QueryResult`</td><td>`useQuery.Result`</td></tr>\n<tr><td>`QueryTuple`</td><td>`useLazyQuery.ResultTuple`</td></tr>\n<tr><td>`SkipToken`</td><td>(unchanged)</td></tr>\n<tr><td>`SubscriptionDataOptions`</td><td>(unchanged)</td></tr>\n<tr><td>`SubscriptionHookOptions`</td><td>`useSubscription.Options`</td></tr>\n<tr><td>`SubscriptionResult`</td><td>`useSubscription.Result`</td></tr>\n<tr><td>`SuspenseQueryHookFetchPolicy`</td><td>`useSuspenseQuery.FetchPolicy`</td></tr>\n<tr><td>`SuspenseQueryHookOptions`</td><td>`useSuspenseQuery.Options`</td></tr>\n<tr><td>`UseBackgroundQueryResult`</td><td>`useBackgroundQuery.Result`</td></tr>\n<tr><td>`UseFragmentOptions`</td><td>`useFragment.Options`</td></tr>\n<tr><td>`UseFragmentResult`</td><td>`useFragment.Result`</td></tr>\n<tr><td>`UseLoadableQueryResult`</td><td>`useLoadableQuery.Result`</td></tr>\n<tr><td>`UseQueryRefHandlersResult`</td><td>`useQueryRefHandlers.Result`</td></tr>\n<tr><td>`UseReadQueryResult`</td><td>`useReadQuery.Result`</td></tr>\n<tr><td>`UseSuspenseFragmentOptions`</td><td>`useSuspenseFragment.Options`</td></tr>\n<tr><td>`UseSuspenseFragmentResult`</td><td>`useSuspenseFragment.Result`</td></tr>\n<tr><td>`UseSuspenseQueryResult`</td><td>`useSuspenseQuery.Result`</td></tr>\n<tr><td>`VariablesOption`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/cache`</th><th>(unchanged)</th></tr>\n<tr><td>`WatchFragmentOptions`</td><td>`ApolloCache.WatchFragmentOptions`</td></tr>\n<tr><td>`WatchFragmentResult`</td><td>`ApolloCache.WatchFragmentResult`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link`</th><th>`@apollo/client/incremental`</th></tr>\n<tr><td>`ExecutionPatchIncrementalResult`</td><td>`Defer20220824Handler.SubsequentResult`</td></tr>\n<tr><td>`ExecutionPatchInitialResult`</td><td>`Defer20220824Handler.InitialResult`</td></tr>\n<tr><td>`ExecutionPatchResult`</td><td>`Defer20220824Handler.Chunk`</td></tr>\n<tr><td>`IncrementalPayload`</td><td>`Defer20220824Handler.IncrementalDeferPayload`</td></tr>\n<tr><td>`Path`</td><td>`Incremental.Path`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link`</th><th>(unchanged)</th></tr>\n<tr><td>`FetchResult`</td><td>`ApolloLink.Result`</td></tr>\n<tr><td>`GraphQLRequest`</td><td>`ApolloLink.Request`</td></tr>\n<tr><td>`NextLink`</td><td>`ApolloLink.ForwardFunction`</td></tr>\n<tr><td>`Operation`</td><td>`ApolloLink.Operation`</td></tr>\n<tr><td>`RequestHandler`</td><td>`ApolloLink.RequestHandler`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link`</th><th>`graphql`</th></tr>\n<tr><td>`SingleExecutionResult`</td><td>`FormattedExecutionResult`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/batch`</th><th>(unchanged)</th></tr>\n<tr><td>`BatchHandler`</td><td>`BatchLink.BatchHandler`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/context`</th><th>(unchanged)</th></tr>\n<tr><td>`ContextSetter`</td><td>`SetContextLink.LegacyContextSetter`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/error`</th><th>(unchanged)</th></tr>\n<tr><td>`ErrorHandler`</td><td>`ErrorLink.ErrorHandler`</td></tr>\n<tr><td>`ErrorResponse`</td><td>`ErrorLink.ErrorHandlerOptions`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/http`</th><th>`@apollo/client/errors`</th></tr>\n<tr><td>`ServerParseError`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/persisted-queries`</th><th>(unchanged)</th></tr>\n<tr><td>`ErrorResponse`</td><td>`PersistedQueryLink.DisableFunctionOptions`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/remove-typename`</th><th>(unchanged)</th></tr>\n<tr><td>`RemoveTypenameFromVariablesOptions`</td><td>`RemoveTypenameFromVariablesLink.Options`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/utils`</th><th>`@apollo/client/errors`</th></tr>\n<tr><td>`ServerError`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/link/ws`</th><th>(unchanged)</th></tr>\n<tr><td>`WebSocketParams`</td><td>`WebSocketLink.Configuration`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/react`</th><th>`@apollo/client`</th></tr>\n<tr><td>`Context`</td><td>`DefaultContext`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/react`</th><th>(unchanged)</th></tr>\n<tr><td>`QueryReference`</td><td>`QueryRef`</td></tr>\n<tr><td>`ApolloProviderProps`</td><td>`ApolloProvider.Props`</td></tr>\n<tr><td>`BackgroundQueryHookFetchPolicy`</td><td>`useBackgroundQuery.FetchPolicy`</td></tr>\n<tr><td>`BackgroundQueryHookOptions`</td><td>`useBackgroundQuery.Options`</td></tr>\n<tr><td>`UseBackgroundQueryResult`</td><td>`useBackgroundQuery.Result`</td></tr>\n<tr><td>`LazyQueryExecFunction`</td><td>`useLazyQuery.ExecFunction`</td></tr>\n<tr><td>`LazyQueryHookExecOptions`</td><td>`useLazyQuery.ExecOptions`</td></tr>\n<tr><td>`LazyQueryHookOptions`</td><td>`useLazyQuery.Options`</td></tr>\n<tr><td>`LazyQueryResult`</td><td>`useLazyQuery.Result`</td></tr>\n<tr><td>`LazyQueryResultTuple`</td><td>`useLazyQuery.ResultTuple`</td></tr>\n<tr><td>`QueryTuple`</td><td>`useLazyQuery.ResultTuple`</td></tr>\n<tr><td>`LoadableQueryFetchPolicy`</td><td>`useLoadableQuery.FetchPolicy`</td></tr>\n<tr><td>`LoadableQueryHookFetchPolicy`</td><td>`useLoadableQuery.FetchPolicy`</td></tr>\n<tr><td>`LoadableQueryHookOptions`</td><td>`useLoadableQuery.Options`</td></tr>\n<tr><td>`LoadQueryFunction`</td><td>`useLoadableQuery.LoadQueryFunction`</td></tr>\n<tr><td>`UseLoadableQueryResult`</td><td>`useLoadableQuery.Result`</td></tr>\n<tr><td>`MutationFunctionOptions`</td><td>`useMutation.MutationFunctionOptions`</td></tr>\n<tr><td>`MutationHookOptions`</td><td>`useMutation.Options`</td></tr>\n<tr><td>`MutationResult`</td><td>`useMutation.Result`</td></tr>\n<tr><td>`MutationTuple`</td><td>`useMutation.ResultTuple`</td></tr>\n<tr><td>`BaseSubscriptionOptions`</td><td>`useSubscription.Options`</td></tr>\n<tr><td>`OnDataOptions`</td><td>`useSubscription.OnDataOptions`</td></tr>\n<tr><td>`OnSubscriptionDataOptions`</td><td>`useSubscription.OnSubscriptionDataOptions`</td></tr>\n<tr><td>`SubscriptionHookOptions`</td><td>`useSubscription.Options`</td></tr>\n<tr><td>`SubscriptionResult`</td><td>`useSubscription.Result`</td></tr>\n<tr><td>`QueryFunctionOptions`</td><td>`useQuery.Options`</td></tr>\n<tr><td>`QueryHookOptions`</td><td>`useQuery.Options`</td></tr>\n<tr><td>`QueryResult`</td><td>`useQuery.Result`</td></tr>\n<tr><td>`SuspenseQueryHookFetchPolicy`</td><td>`useSuspenseQuery.FetchPolicy`</td></tr>\n<tr><td>`SuspenseQueryHookOptions`</td><td>`useSuspenseQuery.Options`</td></tr>\n<tr><td>`UseSuspenseQueryResult`</td><td>`useSuspenseQuery.Result`</td></tr>\n<tr><td>`UseQueryRefHandlersResult`</td><td>`useQueryRefHandlers.Result`</td></tr>\n<tr><td>`UseFragmentOptions`</td><td>`useFragment.Options`</td></tr>\n<tr><td>`UseFragmentResult`</td><td>`useFragment.Result`</td></tr>\n<tr><td>`UseReadQueryResult`</td><td>`useReadQuery.Result`</td></tr>\n<tr><td>`UseSuspenseFragmentOptions`</td><td>`useSuspenseFragment.Options`</td></tr>\n<tr><td>`UseSuspenseFragmentResult`</td><td>`useSuspenseFragment.Result`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/react`</th><th>`@apollo/client/utilities/internal`</th></tr>\n<tr><td>`NoInfer`</td><td>(unchanged)</td></tr>\n<tr><td>`VariablesOption`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/react/internal`</th><th>`@apollo/client/react`</th></tr>\n<tr><td>`PreloadedQueryRef`</td><td>(unchanged)</td></tr>\n<tr><td>`QueryRef`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/testing`</th><th>(unchanged)</th></tr>\n<tr><td>`MockedRequest`</td><td>`MockLink.MockedRequest`</td></tr>\n<tr><td>`MockedResponse`</td><td>`MockLink.MockedResponse`</td></tr>\n<tr><td>`MockLinkOptions`</td><td>`MockLink.Options`</td></tr>\n<tr><td>`ResultFunction`</td><td>`MockLink.ResultFunction`</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/testing`</th><th>`@apollo/client/testing/react`</th></tr>\n<tr><td>`MockedProvider`</td><td>(unchanged)</td></tr>\n<tr><td>`MockedProviderProps`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/utilities`</th><th>`@apollo/client/utilities/internal`</th></tr>\n<tr><td>`argumentsObjectFromField`</td><td>(unchanged)</td></tr>\n<tr><td>`AutoCleanedStrongCache`</td><td>(unchanged)</td></tr>\n<tr><td>`AutoCleanedWeakCache`</td><td>(unchanged)</td></tr>\n<tr><td>`canUseDOM`</td><td>(unchanged)</td></tr>\n<tr><td>`checkDocument`</td><td>(unchanged)</td></tr>\n<tr><td>`cloneDeep`</td><td>(unchanged)</td></tr>\n<tr><td>`compact`</td><td>(unchanged)</td></tr>\n<tr><td>`createFragmentMap`</td><td>(unchanged)</td></tr>\n<tr><td>`createFulfilledPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`createRejectedPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`dealias`</td><td>(unchanged)</td></tr>\n<tr><td>`decoratePromise`</td><td>(unchanged)</td></tr>\n<tr><td>`DeepMerger`</td><td>(unchanged)</td></tr>\n<tr><td>`filterMap`</td><td>(unchanged)</td></tr>\n<tr><td>`getApolloCacheMemoryInternals`</td><td>(unchanged)</td></tr>\n<tr><td>`getApolloClientMemoryInternals`</td><td>(unchanged)</td></tr>\n<tr><td>`getDefaultValues`</td><td>(unchanged)</td></tr>\n<tr><td>`getFragmentDefinition`</td><td>(unchanged)</td></tr>\n<tr><td>`getFragmentDefinitions`</td><td>(unchanged)</td></tr>\n<tr><td>`getFragmentFromSelection`</td><td>(unchanged)</td></tr>\n<tr><td>`getFragmentQueryDocument`</td><td>(unchanged)</td></tr>\n<tr><td>`getGraphQLErrorsFromResult`</td><td>(unchanged)</td></tr>\n<tr><td>`getInMemoryCacheMemoryInternals`</td><td>(unchanged)</td></tr>\n<tr><td>`getOperationDefinition`</td><td>(unchanged)</td></tr>\n<tr><td>`getOperationName`</td><td>(unchanged)</td></tr>\n<tr><td>`getQueryDefinition`</td><td>(unchanged)</td></tr>\n<tr><td>`getStoreKeyName`</td><td>(unchanged)</td></tr>\n<tr><td>`graphQLResultHasError`</td><td>(unchanged)</td></tr>\n<tr><td>`hasDirectives`</td><td>(unchanged)</td></tr>\n<tr><td>`hasForcedResolvers`</td><td>(unchanged)</td></tr>\n<tr><td>`isArray`</td><td>(unchanged)</td></tr>\n<tr><td>`isDocumentNode`</td><td>(unchanged)</td></tr>\n<tr><td>`isField`</td><td>(unchanged)</td></tr>\n<tr><td>`isNonEmptyArray`</td><td>(unchanged)</td></tr>\n<tr><td>`isNonNullObject`</td><td>(unchanged)</td></tr>\n<tr><td>`isPlainObject`</td><td>(unchanged)</td></tr>\n<tr><td>`makeReference`</td><td>(unchanged)</td></tr>\n<tr><td>`makeUniqueId`</td><td>(unchanged)</td></tr>\n<tr><td>`maybeDeepFreeze`</td><td>(unchanged)</td></tr>\n<tr><td>`mergeDeep`</td><td>(unchanged)</td></tr>\n<tr><td>`mergeDeepArray`</td><td>(unchanged)</td></tr>\n<tr><td>`mergeOptions`</td><td>(unchanged)</td></tr>\n<tr><td>`omitDeep`</td><td>(unchanged)</td></tr>\n<tr><td>`preventUnhandledRejection`</td><td>(unchanged)</td></tr>\n<tr><td>`registerGlobalCache`</td><td>(unchanged)</td></tr>\n<tr><td>`removeDirectivesFromDocument`</td><td>(unchanged)</td></tr>\n<tr><td>`resultKeyNameFromField`</td><td>(unchanged)</td></tr>\n<tr><td>`shouldInclude`</td><td>(unchanged)</td></tr>\n<tr><td>`storeKeyNameFromField`</td><td>(unchanged)</td></tr>\n<tr><td>`stringifyForDisplay`</td><td>(unchanged)</td></tr>\n<tr><td>`toQueryResult`</td><td>(unchanged)</td></tr>\n<tr><td>`DecoratedPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`DeepOmit`</td><td>(unchanged)</td></tr>\n<tr><td>`FragmentMap`</td><td>(unchanged)</td></tr>\n<tr><td>`FragmentMapFunction`</td><td>(unchanged)</td></tr>\n<tr><td>`FulfilledPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`IsAny`</td><td>(unchanged)</td></tr>\n<tr><td>`NoInfer`</td><td>(unchanged)</td></tr>\n<tr><td>`PendingPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`Prettify`</td><td>(unchanged)</td></tr>\n<tr><td>`Primitive`</td><td>(unchanged)</td></tr>\n<tr><td>`RejectedPromise`</td><td>(unchanged)</td></tr>\n<tr><td>`RemoveIndexSignature`</td><td>(unchanged)</td></tr>\n<tr><td>`VariablesOption`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/utilities/global`</th><th>`@apollo/client/utilities/environment`</th></tr>\n<tr><td>`DEV`</td><td>`__DEV__`</td></tr>\n<tr><td>`__DEV__`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/utilities/global`</th><th>`@apollo/client/utilities/internal/globals`</th></tr>\n<tr><td>`global`</td><td>(unchanged)</td></tr>\n<tr><td>`maybe`</td><td>(unchanged)</td></tr>\n</tbody><tbody>\n<tr><th>`@apollo/client/utilities/global`</th><th>`@apollo/client/utilities/invariant`</th></tr>\n<tr><td>`invariant`</td><td>(unchanged)</td></tr>\n<tr><td>`InvariantError`</td><td>(unchanged)</td></tr>\n<tr><td>`newInvariantError`</td><td>(unchanged)</td></tr>\n</tbody>\n</table>\n\n</details>\n\n### Replace removed exports\n\nIf you used the [Codemod](#running-the-codemod) to update your imports, all removed exports moved to the `@apollo/client/v4-migration` entry point. You should get a TypeScript error everywhere you use a removed export. When you hover over the export, you'll get more information about why the export was removed along with migration instructions.\n\nFor a list of all removed imports and recommended actions, see [node_modules/@apollo/client/v4-migration.d.ts](https://app.unpkg.com/@apollo/client@^4.0.0-rc/files/v4-migration.d.ts)\n\n## Update the initialization of `ApolloClient`\n\nSeveral of the constructor options of `ApolloClient` have changed in Apollo Client 4. This section provides instructions on migrating to the new options when initializing your `ApolloClient` instance.\n\n### Explicitly provide `HttpLink`\n\n> This change is performed by the codemod\n\nThe `uri`, `headers`, and `credentials` options used to implicitly create an `HttpLink` have been removed. You now need to create a new `HttpLink` instance and pass it to the `link` option of `ApolloClient`.\n\n```ts\nimport {\n  ApolloClient,\n  InMemoryCache,\n  HttpLink,// [!code ++]\n} from \"@apollo/client/core\";\nconst client = new ApolloClient({\n  // ...\n  link: new HttpLink({// [!code ++]\n    uri: \"https://example.com/graphql\",\n    credentials: \"include\",\n    headers: { \"x-custom-header\": \"value\" },\n  }),// [!code ++]\n  // ...\n});\n```\n\nAlthough the previous options were convenient, it meant all Apollo Client instances were bundled with `HttpLink`, even if it wasn't used in the link chain. This change enables you to use different terminating links without the increase in bundle size needed to include `HttpLink`. Most applications that scale moved away from these options anyways as soon as more complex link chains were needed.\n\n### Migrate client awareness options\n\n> This change is performed by the codemod\n\nThe `name` and `version` options, which are a part of the client awareness feature, have been moved into the `clientAwareness` option.\n\n```ts\nconst client = new ApolloClient({\n  // ...\n  clientAwareness: {// [!code ++]\n    name: \"My Apollo Client App\",\n    version: \"1.0.0\",\n  },// [!code ++]\n  // ...\n});\n```\n\nThis change reduced confusion on what the `name` and `version` options were meant for and provides better future-proofing for additional features that might be added later.\n\n<Note>\n\nThis option only has an effect if you are using the client-awareness-capable `HttpLink` or `BatchHttpLink`, or if you manually combine the `ClientAwarenessLink` with a compatible terminating link.\n\n</Note>\n\n### Update local state\n\n> This change is performed by the codemod\n\nWhen using `@client` fields, you now need to create a new `LocalState` instance and provide it as the `localState` option to the `ApolloClient` constructor.\n\n```ts\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,// [!code ++]\n} from \"@apollo/client/core\";\nconst client = new ApolloClient({\n  // ...\n  localState: new LocalState(),// [!code ++]\n  // ...\n});\n```\n\nAdditionally, if you are using local resolvers with the `resolvers` option, you need to move the `resolvers` option to the `LocalState` constructor instead of the `ApolloClient` constructor.\n\n```ts\nimport {\n  ApolloClient,\n  InMemoryCache,\n  LocalState,// [!code ++]\n} from \"@apollo/client/core\";\nconst client = new ApolloClient({\n  // ...\n  localState: new LocalState({// [!code ++]\n    resolvers: {\n      Query: {\n        myField: () => \"Hello World\",\n      },\n    },\n  }),// [!code ++]\n  // ...\n});\n```\n\nPreviously, all Apollo Client instances were bundled with local state management functionality, even if you didn't use the `@client` directive. This change means local state management is now opt-in and reduces the size of your bundle when you aren't using this feature.\n\n### Change `connectToDevTools`\n\n> This change is performed by the codemod\n\nThe `connectToDevTools` option has been replaced with a new `devtools` option that contains an `enabled` property.\n\n```ts disableCopy=true\nconst client = new ApolloClient({\n  // ...\n  connectToDevTools: true,// [!code --]\n  devtools: { enabled: true },// [!code ++]\n  // ...\n});\n```\n\n### Change `disableNetworkFetches`\n\n> This change is performed by the codemod\n\nThe `disableNetworkFetches` option has been renamed to `prioritizeCacheValues` to better describe its behavior.\n\n```ts disableCopy=true\nconst client = new ApolloClient({\n  // ...\n  disableNetworkFetches: ..., // [!code --]\n  prioritizeCacheValues: ..., // [!code ++]\n  // ...\n});\n```\n\n### Enable incremental delivery (`@defer`)\n\n> This change is performed by the codemod, however you may need to make some additional changes\n\nThe incremental delivery protocol implementation is now configurable and requires you to opt-in to use the proper format. If you currently use `@defer` in your application, you need to configure an incremental handler and provide it to the `incrementalHandler` option to the `ApolloClient` constructor.\n\nSince Apollo Client 3 only supported an older version of the specification, initialize an instance of `Defer20220824Handler` and provide it as the `incrementalHandler` option.\n\n```ts\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";// [!code ++]\nconst client = new ApolloClient({\n  // ...\n  incrementalHandler: new Defer20220824Handler(),// [!code ++]\n  // ...\n});\n```\n\nTo provide accurate TypeScript types, you will also need to tell Apollo Client to use the types associated with the `Defer20220824Handler` in order to provide accurate types for incremental chunks, used with the `ApolloLink.Result` type. This ensures that you properly handle incremental results in your custom links that might access the result directly.\n\nCreate a new `.d.ts` file in your project (e.g. `apollo-client.d.ts`) and add the following content:\n\n```ts title=\"apollo-client.d.ts\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";// [!code highlight]\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}// [!code highlight]\n}\n```\n\n<Note>\n\nApollo Client only provides support for the older incremental specification at this time. Future versions will introduce new incremental handlers to support more recent versions of the specification.\n\n</Note>\n\n## Enable data masking types\n\n> This change is performed by the codemod, however you may need to make some additional changes\n\nIn Apollo Client 4, the data masking types are now configurable to allow for more flexibility when working with different tools like GraphQL Code Generator or `gql.tada` - which might have different typings for data masking.\n\nTo configure the data masking types to be the same as they were in Apollo Client 3, create a `.d.ts` file in your project with the following content:\n\n```ts title=\"apollo-client.d.ts\nimport { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";// [!code highlight]\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides// [!code highlight:2]\n    extends GraphQLCodegenDataMasking.TypeOverrides {}\n}\n```\n\n<Note>\n\nYou can combine multiple `TypeOverrides` of different kinds. For example, you can combine the data masking types with the `Defer20220824Handler` type overrides from the previous section.\n\n```ts title=\"apollo-client.d.ts disableCopy=true\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";// [!code ++]\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}// [!code --]\n  export interface TypeOverrides// [!code ++:3]\n    extends Defer20220824Handler.TypeOverrides,\n      GraphQLCodegenDataMasking.TypeOverrides {}\n}\n```\n\n</Note>\n\n## Core API changes\n\n### New `notifyOnNetworkStatusChange` default value\n\nThe `notifyOnNetworkStatusChange` option now defaults to `true`. This affects React hooks that provide this option (e.g. `useQuery`) and `ObservableQuery` instances created by `client.watchQuery`.\n\nThis change means you might see loading states more often, especially when used with `refetch` or other APIs that cause fetches. If this causes issues, you can revert to the v3 behavior by setting the global default back to `false`.\n\n```ts title=\"Reverting notifyOnNetworkStatusChange to Apollo Client 3 behavior\"\nnew ApolloClient({\n  // ...\n  defaultOptions: {// [!code ++:5]\n    watchQuery: {\n      notifyOnNetworkStatusChange: false,\n    },\n  },\n});\n```\n\n### Immediate `loading` status emitted by `ObservableQuery`\n\nIn line with the change to the default `notifyOnNetworkStatusChange` value, the first value emitted from an `ObservableQuery` instance (created by `client.watchQuery`), sets `loading` to `true` when the query cannot be fulfilled by data in the cache. Previously, the initial loading state was not emitted.\n\n```ts disableCopy=true\nconst observable = client.watchQuery({ query: QUERY });\n\nobservable.subscribe({\n  next: (result) => {\n    // The first result emitted is the loading state\n    console.log(result);\n    /*\n     {\n       data: undefined,\n       dataState: \"empty\"\n       loading: true,\n       networkStatus: NetworkStatus.loading,\n       partial: false\n     }\n     */\n  },\n});\n```\n\n### Tracking of active and inactive queries\n\nIn Apollo Client 3, `ObservableQuery` instances were tracked by the client from the moment they were created until they were unsubscribed from. In cases where the `ObservableQuery` instance was never subscribed to, this caused memory leaks and unintended behavior with APIs such as `refetchQueries` when refetching active queries, because the `ObservableQuery` instances were never properly cleaned up.\n\nIn Apollo Client 4, `ObservableQuery` instances are now tracked by the client only when they are subscribed to until they are unsubscribed from. This allows for more efficient memory management by the garbage collector to free memory if the `ObservableQuery` instance is never subscribed to and no longer referenced by other code. Additionally, this avoids situations where `refetchQueries` might execute unnecessary network requests due to the tracking behavior.\n\nAs a result of this change, the definitions for _active_ and _inactive_ queries have changed.\n\n- A query is considered active if it is observed by at least one subscriber and not in standby\n- A query is considered inactive if it is observed by at least one subscriber and in standby\n- All other `ObservableQuery` instances that don't have at least one subscriber are not tracked or accessible through the client\n\n<Note>\n\nA query is in standby if it is skipped with the `skip` option or `skipToken` in a React hook, or if the `fetchPolicy` is set to `standby`.\n\n</Note>\n\nThis change affects the queries returned by `client.getObservableQueries` or the queries fetched by `refetchQueries` when using the `\"active\"` or `\"all\"` keywords, as these no longer include `ObservableQuery` instances without subscribers.\n\n### Removal of the `canonizeResults` option\n\nThe `canonizeResults` option has been removed because it caused memory leaks. If you use `canonizeResults`, you may see some changes to the object identity of some objects that were previously referentially equal.\n\n```ts disableCopy=true\nuseQuery(QUERY, {\n  canonizeResults: true,// [!code --]\n});\n```\n\n### Subscription deduplication\n\nSubscriptions are now deduplicated when `queryDeduplication` is enabled (the default). Subscriptions that qualify for deduplication attach to the same connection as a previously connected subscription.\n\nTo disable query deduplication, provide `queryDeduplication: false` to the `context` option when creating the subscription.\n\n```ts\n// with React's `useSubscription`\nuseSubscription(SUBSCRIPTION, {\n  context: { queryDeduplication: false },\n});\n\n// with the core API\nconst observable = client.subscribe({\n  query: SUBSCRIPTION,\n  context: { queryDeduplication: false },\n});\n```\n\n<Caution>\n\nSome GraphQL servers emit an initial value when the subscription first connects. A subscription that attaches to an existing connection because of deduplication does not receive an update until the server next emits a value. Depending on the frequency of updates pushed from the server, the deduplicated subscription might wait for an extended period of time before receiving its first value.<br/><br/>\n\nIf you rely on the initial value to read data from the subscription, we recommend disabling query deduplication so that the subscription creates a new connection.\n\n</Caution>\n\n### `ObservableQuery` no longer inherits from `Observable`\n\n`ObservableQuery` instances returned from `client.watchQuery` no longer inherit from `Observable`. This might cause TypeScript errors when using `ObservableQuery` with some RxJS utilities that expect `Observable` instances, such as [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom).\n\nConvert `ObservableQuery` to an `Observable` using the [`from`](https://rxjs.dev/api/index/function/from) function.\n\n```ts\nimport { from } from \"rxjs\";\n\nconst observable = from(observableQuery);\n//    ^? Observable<ObservableQuery.Result<MaybeMasked<TData>>>\n```\n\n<Note>\n\n`ObservableQuery` implements the [`Subscribable`](https://rxjs.dev/api/index/interface/Subscribable) interface, so you can call `subscribe` directly without converting to an `Observable`. It also implements the `pipe` function, so you can chain operators.<br/><br/>\n\nUse `from` only for functions that require an `Observable` instance.\n\n</Note>\n\n### Removal of `Observable` utilities\n\nApollo Client 3 included several utilities for working with `Observable` instances from the `zen-observable` library. Apollo Client 4 removes these utilities in favor of RxJS's operators.\n\n#### `fromError`\n\nUse the [`throwError`](https://rxjs.dev/api/index/function/throwError) function instead.\n\n```ts\nconst observable = fromError(new Error(\"Oops\"));// [!code --]\nconst observable = throwError(() => {// [!code ++:3]\n  return new Error(\"Oops\");\n});\n```\n\n#### `fromPromise`\n\nUse the [`from`](https://rxjs.dev/api/index/function/from) function instead.\n\n```ts\nconst observable = fromPromise(promise);// [!code --]\nconst observable = from(promise);// [!code ++]\n```\n\n#### `toPromise`\n\nUse the [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom) function instead.\n\n```ts\nconst promise = toPromise(observable);// [!code --]\nconst promise = firstValueFrom(observable);// [!code ++]\n```\n\n## New error handling\n\nError handling in Apollo Client 4 has changed significantly to be more predictable and intuitive.\n\n<Tip>\n\nWe recommend reading the [Error handling](../data/error-handling) guide which lists all of the available error classes and provides details on how to check for specific kinds of errors. The following sections only detail the necessary requirements to migrate your existing code but does not cover general error handling.\n\n</Tip>\n\n### Unification of the `error` property\n\nIn Apollo Client 3, many result types returned both the `error` and `errors` properties. This includes the result emitted from `ObservableQuery` and some React hooks such as `useQuery`. This made it difficult to determine which property should be used to determine the source of the error. This was further complicated by the fact that the `errors` property was set only when `errorPolicy` was `all`!\n\nApollo Client 4 unifies all errors into a single `error` property. If you check for `errors`, remove this check and use `error` instead.\n\n```ts\nconst { error, errors } = useQuery(QUERY);// [!code --]\nconst { error } = useQuery(QUERY);// [!code ++]\n\nif (error) {\n  // ...\n} else if (errors) {// [!code --:2]\n  // ...\n}\n```\n\n### Removal of `ApolloError`\n\nIn Apollo Client 3, every error was wrapped in an `ApolloError` instance. This made it difficult to debug the source of the error, especially when reported by error tracking services, because the stack trace pointed to the `ApolloError` class. Additionally, it was unclear whether error types wrapped in `ApolloError` were mutually exclusive because it contained `graphQLErrors`, `protocolErrors`, `networkError`, and `clientErrors` properties that were all optional.\n\nApollo Client 4 removes the `ApolloError` class entirely.\n\n#### Migrate from `graphQLErrors`\n\nGraphQL errors are now encapsulated in a `CombinedGraphQLErrors` instance. You can access the raw GraphQL errors with the `errors` property. To migrate, use `CombinedGraphQLErrors.is(error)` to first check if the error is caused by one or more GraphQL errors, then access the `errors` property.\n\n{/* prettier-ignore */}\n```ts disableCopy=true\nimport { CombinedGraphQLErrors } from \"@apollo/client\"; // [!code ++]\n\nconst { error } = useQuery(QUERY);\n\nif (error.graphQLErrors) { // [!code --]\n  error.graphQLErrors.map((graphQLError) => {/* ... */}); // [!code --]\nif (CombinedGraphQLErrors.is(error)) { // [!code ++]\n  error.errors.map((graphQLError) => {/* ... */}); // [!code ++]\n}\n```\n\n#### Migrate from `networkError`\n\nNetwork errors are no longer wrapped and instead returned as-is. This makes it easier to debug the source of the error as the stack trace now points to the location of the error.\n\nTo migrate, use the `error` property directly.\n\n```ts disableCopy=true\nconst { error } = useQuery(QUERY);\n\nif (error.networkError) { // [!code --]\n  console.log(error.networkError.message); // [!code --]\nif (error) { // [!code ++]\n  console.log(error.message); // [!code ++]\n}\n```\n\n#### Migrate from `protocolErrors`\n\nProtocol errors are now encapsulated in a `CombinedProtocolErrors` instance. You can access the raw protocol errors with the `errors` property. To migrate, use `CombinedProtocolErrors.is(error)` to first check if the error is caused by one or more protocol errors, then access the `errors` property.\n\n{/* prettier-ignore */}\n```ts disableCopy=true\nimport { CombinedProtocolErrors } from \"@apollo/client\"; // [!code ++]\n\nconst { error } = useQuery(QUERY);\n\nif (error.protocolErrors) { // [!code --]\n  error.graphQLErrors.map((graphQLError) => {/* ... */}); // [!code --]\nif (CombinedProtocolErrors.is(error)) { // [!code ++]\n  error.errors.map((graphQLError) => {/* ... */}); // [!code ++]\n}\n```\n\n#### Migrate from `clientErrors`\n\nThe `clientErrors` property was not used by Apollo Client and therefore has no replacement. Any non-GraphQL errors or non-protocol errors are passed through as-is.\n\n### Errors as guaranteed error-like objects\n\nApollo Client 4 guarantees that the `error` property is an `ErrorLike` object, an object with a `message` and `name` property. This avoids the need to check the type of `error` before consuming it. To make such a guarantee, thrown non-error-like values are wrapped.\n\n#### String errors\n\nStrings thrown as errors are wrapped in an `Error` instance for you. The string is set as the error's `message`.\n\n```ts\nconst client = new ApolloClient({\n  link: new ApolloLink(() => {\n    return new Observable((observer) => {\n      // Oops we sent a string instead of wrapping it in an `Error`\n      observer.error(\"Test error\");\n    });\n  }),\n});\n\n// ...\n\nconst { error } = useQuery(query);\n\n// `error` is `new Error(\"Test error\")`\nconsole.log(error.message);\n```\n\n#### Non-error-like types\n\nAll other object types (e.g. symbols, arrays, etc.) or primitives thrown as errors are wrapped in an `UnconventionalError` instance with the [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause) property set to the original object. Additionally, `UnconventionalError` sets its `name` to `UnconventionalError` and its `message` to `\"An error of unexpected shape occurred.\"`.\n\n```ts\nconst client = new ApolloClient({\n  link: new ApolloLink(() => {\n    return new Observable((observer) => {\n      // Oops we sent a string instead of wrapping it in an `Error`\n      observer.error({ message: \"Not a proper error type\" });\n    });\n  }),\n});\n\n// ...\n\nconst { error } = useQuery(query);\n\n// `error` is an `UnconventionalError` instance\nconsole.log(error.message); // => \"An error of unexpected shape occurred.\"\n// The `cause` returns the original object that was thrown\nconsole.log(error.cause); // => { message: \"Not a proper error type\" }\n```\n\n### Network errors adhere to the `errorPolicy`\n\nApollo Client 3 always treated network errors as if the `errorPolicy` was set to `none`. This meant network errors were always thrown even if a different `errorPolicy` was specified.\n\nApollo Client 4 unifies the behavior of network errors and GraphQL errors so that network errors now adhere to the `errorPolicy`. Network errors now resolve promises when the `errorPolicy` is set to anything other than `none`.\n\n#### `errorPolicy`: `all`\n\nThe promise is resolved. The error is accessible on the `error` property.\n\n```ts disableCopy=true\nconst { data, error } = await client.query({ query, errorPolicy: \"all\" });\n\nconsole.log(data); // => undefined\nconsole.log(error); // => new Error(\"...\")\n```\n\n<Note>\n\nNetwork errors always set `data` to `undefined`.\n\n</Note>\n\n#### `errorPolicy`: `ignore`\n\nThe promise is resolved and the error is ignored.\n\n```ts\nconst { data, error } = await client.query({ query, errorPolicy: \"ignore\" });\n\nconsole.log(data); // => undefined\nconsole.log(error); // => undefined\n```\n\n<Note>\n\n`data` is always set to `undefined` because a GraphQL result wasn't returned.\n\n</Note>\n\n### Network errors never terminate `ObservableQuery` or subscription Observables\n\nIn Apollo Client 3, network errors emitted an `error` notification on the `ObservableQuery` instance. Because error notifications terminate observables, this meant you needed special handling to restart the `ObservableQuery` instance so that it listened for new results. Network errors were emitted to the `error` callback.\n\nApollo Client 4 changes this and no longer emits an `error` notification. This ensures `ObservableQuery` doesn't terminate on errors and can continue listening for new results, such as calling `refetch` after an error.\n\nAccess the error on the `error` property emitted in the `next` callback. It is safe to remove the `error` callback entirely as it is no longer used.\n\n```ts\nconst observable = client.watchQuery({ query });\n\nobservable.subscribe({\n  next: (result) => {\n    if (result.error) {// [!code ++:3]\n      // handle error\n    }\n    // ...\n  },\n  error: (error) => {// [!code --:3]\n    // handle error\n  },\n});\n```\n\n<Note>\n\nThe change applies to all Apollo Client observables, including subscriptions created with `client.subscribe()`. GraphQL errors in subscriptions are always delivered through the `next` callback in `result.error`, never through the `error` callback. The subscription only terminates for non-recoverable errors like network failures.\n\n</Note>\n\n### `ServerError` and `ServerParseError` are error classes\n\nApollo Client 3 threw special `ServerError` and `ServerParseError` types when the HTTP response was invalid. These types were plain `Error` instances with some added properties.\n\nApollo Client 4 turns these types into proper error classes. You can check for these types using the `.is` static method available on each error class.\n\n```ts disableCopy=true\nconst { error } = useQuery(QUERY);\n\nif (ServerError.is(error)) {\n  // handle the server error\n}\n\nif (ServerParseError.is(error)) {\n  // handle the server parse error\n}\n```\n\n### `ServerError` no longer parses the response text as JSON\n\nWhen a `ServerError` was thrown, such as when the server returned a non-2xx status code, Apollo Client 3 tried to parse the raw response text into JSON to determine if a valid GraphQL response was returned. If successful, the parsed JSON value was set as the `result` property on the error.\n\nApollo Client 4 more strictly adheres to the [GraphQL over HTTP specification](https://graphql.github.io/graphql-over-http/draft/) and does away with the automatic JSON parsing. As such, the `result` property is no longer accessible and is replaced by the `bodyText` property which contains the value of the raw response text.\n\nIf you relied on the automatic JSON parsing, you will need to `JSON.parse` the `bodyText` instead.\n\n```ts disableCopy=true\nconst { error } = useQuery(QUERY);\n\nif (ServerError.is(error)) {\n  try {\n    const json = JSON.parse(error.bodyText);\n  } catch (e) {\n    // handle invalid JSON\n  }\n}\n```\n\n## Updates to React APIs\n\n### A note about hook usage\n\nApollo Client 4 is more opinionated about how to use it.\nWe believe that React hooks should be used to synchronize data with your component and avoid side effects that don't achieve this goal. As a result, we now recommend the use of core APIs directly in several use cases where synchronization with a component is not needed or intended.\n\nAs an example, if you used `useLazyQuery` to execute queries but don't read the state values returned in the result tuple, we recommend that you now use `client.query` directly. This avoids unnecessary re-renders in your component for state that you don't consume.\n\n```ts disableCopy=true\nconst [execute] = useLazyQuery(MY_QUERY);// [!code --:3]\n// ...\nawait execute({ variables });\nconst client = useApolloClient();// [!code ++:3]\n// ...\nawait client.query({ query: MY_QUERY, variables });\n```\n\n### Changes to `useLazyQuery`\n\n`useLazyQuery` has been rewritten to have more predictable and intuitive behavior based on years of user feedback.\nIn Apollo Client 3, the `useLazyQuery` behaved like the `useQuery` hook after the execute function was called the first time. Changes to options often triggered unintended network requests as a result of this behavior.\n\nIn Apollo Client 4, `useLazyQuery` focuses on user interaction and more predictable data synchronization with the component. Network requests are now initiated only when the execute function is called. This makes it safe to re-render your component with new options provided to `useLazyQuery` without the unintended network requests. New options are used the next time the execute function is called.\n\n#### Changes to the `variables` and `context` options\n\nThe `useLazyQuery` hook no longer accepts the `variables` or `context` options. These options have been moved to the execute function instead. This removes the variable merging behavior which was confusing and hard to predict with the new behavior.\n\nTo migrate, move the `variables` and `context` options from the hook to the execute function:\n\n{/* prettier-ignore */}\n```ts disableCopy=true\nconst [execute, { data }] = useLazyQuery(QUERY, {\n  variables: {/* ... */},// [!code --]\n  context: { /* ... */},// [!code --]\n});\n\nfunction onUserInteraction(){\n  execute({\n    variables: {/* ... */}, // [!code ++]\n    context: {/* ... */}, // [!code ++]\n  })\n}\n```\n\n#### Changes to the execute function\n\nThe `execute` function no longer accepts any other options than `variables` and `context`. Those options should be passed directly to the hook instead.\n\n{/* prettier-ignore */}\n```ts disableCopy=true\nconst [execute, { data }] = useLazyQuery(QUERY, {\n  fetchPolicy: \"no-cache\", // [!code ++]\n});\n// ...\nfunction onUserInteraction(){\n  execute({\n    fetchPolicy: \"no-cache\", // [!code --]\n  })\n}\n```\n\nIf you need to change the value of an option, rerender the component with the new option value before calling the `execute` function again.\n\n<Note>\n\nWhen calling the `execute` function multiple times, the `fetchPolicy` is not reset to `initialFetchPolicy` between executions. This means that subsequent calls to `execute` continue using the fetch policy from the previous execution. This primarily affects you if you're using `nextFetchPolicy` to change the `fetchPolicy` after the initial fetch.\n\n</Note>\n\n#### Executing the query during render\n\nCalling the `execute` function of `useLazyQuery` during render is no longer allowed and will now throw an error.\n\n```ts disableCopy=true\nfunction MyComponent() {\n  const [execute, { data }] = useLazyQuery(QUERY);\n\n  // This throws an error\n  execute();\n\n  return /* ... */;\n}\n```\n\nWe recommend instead migrating to `useQuery` which executes the query during render automatically.\n\n```ts\nfunction MyComponent() {\n  const [execute, { data }] = useLazyQuery(QUERY);// [!code --:2]\n  execute();\n\n  const { data } = useQuery(QUERY);// [!code ++]\n\n  return /* ... */;\n}\n```\n\n<Tip>\n\nWe don't recommend calling the `execute` function in a `useEffect` hook as a replacement. Instead, migrate to `useQuery`. If you need to hold the execution of the query beyond the initial render, consider using the `skip` option.\n\n```ts disableCopy=true\nfunction MyComponent({ dependentValue }) {\n  const [execute, { data }] = useLazyQuery(QUERY);// [!code --]\n\n  useEffect(() => {// [!code --:5]\n    if (dependentValue) {\n      execute();\n    }\n  }, [dependentValue]);\n\n  const { data } = useQuery(QUERY, { skip: !dependentValue });// [!code ++]\n\n  return /* ... */;\n}\n```\n\nCalling `execute` inside a `useEffect` delays the execution of the query unnecessarily. Reserve the use of `useLazyQuery` for user interaction in callback functions.\n\n</Tip>\n\n##### A note about SSR\n\nThis change also means that it is no longer possible to make queries with `useLazyQuery` during SSR. If you need to execute the query during render, use `useQuery` instead.\n\n```ts disableCopy=true\nfunction MySSRComponent() {\n  const [execute, { data, loading, error }] = useLazyQuery(QUERY);// [!code --]\n  execute();// [!code --]\n\n  const { data, loading, error } = useQuery(QUERY);// [!code ++]\n\n  // ...\n}\n```\n\n#### Removal of `onCompleted` and `onError` callbacks\n\nThe `onCompleted` and `onError` callbacks have been removed from the hook options. If you need to execute a side effect when the query completes, `await` the promise returned by the `execute` function and perform side effects there.\n\n{/* prettier-ignore */}\n```ts disableCopy=true\nconst [execute] = useLazyQuery(QUERY, {\n  onCompleted(data) { /* handle success */ }, // [!code --]\n  onError(error) { /* handle error */ }, // [!code --]\n});\n\nasync function onUserInteraction(){\n  await execute({ variables })// [!code --]\n\n  try {// [!code ++:6]\n    const { data } = await execute({ variables })\n    // handle success\n  } catch (error) {\n    // handle error\n  }\n}\n```\n\n#### Changes to behavior for in-flight queries\n\nIn-flight queries are now aborted more frequently. This occurs under two conditions:\n\n- The component unmounts while the query is in flight\n- A new query is started by calling the `execute` function while a previous query is in flight\n\nIn each of these cases, the promise returned by the `execute` function is rejected with an [`AbortError`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException#aborterror). This change means it is no longer possible to run multiple queries simultaneously.\n\nIn some cases, you may need the query to run to completion, even if a new query is started or your component unmounts. In these cases, you can call the `.retain()` function on the promise returned by the `execute` function.\n\n```ts disableCopy=true\nconst [execute] = useLazyQuery(QUERY);\n\nasync function onUserInteraction() {\n  try {\n    const { data } = await execute({ variables });// [!code --]\n    const { data } = await execute({ variables }).retain();// [!code ++]\n  } catch (error) {}\n}\n```\n\n<Note>\n\nEven though in-flight queries run to completion when using `.retain()`, the result returned from the hook only reflects state from the latest call of the `execute` function. Any previously retained queries are not synchronized to the hook state.\n\n</Note>\n\n<Tip>\n\nUsage of `.retain()` can be a sign that you are using `useLazyQuery` to trigger queries and are not interested in synchronizing the result with your component. In that case, we recommend using `client.query` directly.\n\n```ts disableCopy=true\nconst [execute] = useLazyQuery(QUERY);// [!code --]\nconst client = useApolloClient();// [!code ++]\n\nasync function onUserInteraction() {\n  try {\n    const { data } = await execute({ variables }).retain();// [!code --]\n    const { data } = await client.query({ query: QUERY, variables });// [!code ++]\n  } catch (error) {}\n}\n```\n\n</Tip>\n\n#### Changes to promise resolution with errors for the `execute` function\n\nThe promise returned from the `execute` function is now consistently resolved or rejected based on your configured `errorPolicy` when errors are returned. With an `errorPolicy` of `none`, the promise always rejects. With an `errorPolicy` of `all`, the promise always resolves and sets the `error` property on the result. With an `errorPolicy` of `ignore`, the promise always resolves and discards the errors.\n\nPreviously, Apollo Client 3 resolved the promise when GraphQL errors were returned when using an `errorPolicy` of `none`. Network errors always caused the promise to reject, regardless of your configured error policy. This change unifies the error behavior across all error types to ensure errors are handled consistently.\n\nTo migrate code that uses an `errorPolicy` of `none`, wrap the call to `execute` in a `try`/`catch` block and use `CombinedGraphQLErrors.is(error)` to check for GraphQL errors.\n\n```ts disableCopy=true\nconst [execute] = useLazyQuery(QUERY, {\n  errorPolicy: \"none\",\n});\n\nasync function onUserInteraction() {\n  const { data, error } = await execute({ variables });// [!code --:4]\n  if (error.graphQLErrors) {\n    // handle GraphQL errors\n  }\n\n  try {// [!code ++:6]\n    const { data } = await execute({ variables });\n  } catch (error) {\n    if (CombinedGraphQLErrors.is(error)) {\n      // handle GraphQL errors\n    }\n  }\n}\n```\n\nTo migrate code that uses an `errorPolicy` of `all`, read the error from the `error` property returned in the result. You can optionally remove any `try`/`catch` statements because the promise resolves for all error types.\n\n```ts disableCopy=true\nconst [execute] = useLazyQuery(QUERY, {\n  errorPolicy: \"all\",\n});\n\nasync function onUserInteraction() {\n  try {// [!code --:7]\n    const { data } = await execute({ variables });\n  } catch (error) {\n    if (error.graphQLErrors) {\n      // handle GraphQL errors\n    }\n  }\n\n  const { data, error } = await execute({ variables });// [!code ++:4]\n  if (CombinedGraphQLErrors.is(error)) {\n    // handle GraphQL errors\n  }\n}\n```\n\n### Changes to `useMutation`\n\n`useMutation` has been modified to work with our [philosophy](#a-note-about-hook-usage) that React hooks should be used to synchronize hook state with your component.\n\n#### Removal of the `ignoreResults` option\n\nThe `ignoreResults` option of `useMutation` has been removed. If you want to trigger a mutation, but are not interested in synchronizing the result with your component, use `client.mutate` directly.\n\n```ts disableCopy=true\nconst [mutate] = useMutation(MY_MUTATION, { ignoreResults: true });// [!code --]\nconst client = useApolloClient();// [!code ++]\n// ...\nawait mutate({ variables });// [!code --]\nawait client.mutate({ mutation: MY_MUTATION, variables });// [!code ++]\n```\n\n### Changes to `useQuery`\n\n#### New `notifyOnNetworkStatusChange` default value\n\nThe `notifyOnNetworkStatusChange` option now defaults to `true`. This change means you might see loading states more often, especially when used with `refetch` or other APIs that cause fetches. If this causes issues, you can revert to the v3 behavior by setting the global default back to `false`.\n\n```ts\nnew ApolloClient({\n  // ...\n  defaultOptions: {// [!code ++:5]\n    watchQuery: {\n      notifyOnNetworkStatusChange: false,\n    },\n  },\n});\n```\n\n#### Removal of the `onCompleted` and `onError` callbacks\n\nThe `onCompleted` and `onError` callback options have been removed. Their behavior was ambiguous and made it easy to introduce subtle bugs in your application.\n\nYou can read more about this decision and recommendations on what to do instead in the [related GitHub issue](https://github.com/apollographql/apollo-client/issues/12352).\n\n### Changes to `preloadQuery`\n\n#### `toPromise` moved from `queryRef` to the `preloadQuery` function\n\nThe `toPromise` method now exists as a property on the `preloadQuery` function instead of on the `queryRef` object. This change makes `queryRef` objects more serializable for SSR environments.\n\nTo migrate, call `preloadQuery.toPromise` and pass it the `queryRef`.\n\n```ts disableCopy=true\nfunction loader() {\n  const queryRef = preloadQuery(QUERY, options);\n\n  return queryRef.toPromise();// [!code --]\n  return preloadQuery.toPromise(queryRef);// [!code ++]\n}\n```\n\n### Recommended: Avoid using generated hooks\n\nApollo Client 4 comes with a lot of TypeScript improvements to the hook types. If you use generated hooks from a tool such as [GraphQL Codegen's](https://the-guild.dev/graphql/codegen) [`@graphql-codegen/typescript-react-apollo`](https://the-guild.dev/graphql/codegen/plugins/typescript/typescript-react-apollo) plugin, you will not benefit from these improvements since the generated hooks are missing the necessary function overloads to provide critical type safety. We recommend that you stop using generated hooks immediately and create a migration strategy to move away from them.\n\nUse the hooks exported from Apollo Client directly with `TypedDocumentNode` instead.\n\n<Note>\n\nThe GraphQL Codegen team has created a codemod that helps you migrate away from generated hooks. Learn more about migrating your code using the new codemod by watching the [tutorial video](https://www.youtube.com/watch?v=GGmt0hvnQNU).<br/><br/>\n\nNote that the codemod is a separate package and not maintained by the Apollo Client team. Generally, we recommend that you use a manual codegen configuration over the client preset as shown in the video because the client preset includes some features that are incompatible with Apollo Client. If you choose to use the client preset, see our [recommended configuration for the client preset](../development-testing/graphql-codegen#a-note-about-the-client-preset). In the long term, consider using the plugins directly with our [recommended starter configuration](../development-testing/graphql-codegen#recommended-starter-configuration).\n\n</Note>\n\n## TypeScript changes\n\n### Namespaced types\n\nMost types are now colocated with the API that they belong to. This makes them more discoverable, adds consistency to the naming of each type, and provides clear ownership boundaries.\n\nSome examples:\n\n- `FetchResult` is now `ApolloLink.Result`\n- `ApolloClientOptions` is now `ApolloClient.Options`\n- `QueryOptions` is now `ApolloClient.QueryOptions`\n- `ApolloQueryResult` is now `ObservableQuery.Result`\n- `QueryHookOptions` is now `useQuery.Options`\n- `QueryResult` is now `useQuery.Result`\n- `LazyQueryResult` is now `useLazyQuery.Result`\n\nMany of the old, most-used types are still available in Apollo Client 4 (including the examples above), but are now deprecated in favor of the new namespaced types. We suggest running the codemod to update your code to use the new namespaced types.\n\n### Removal of `<TContext>` generic argument\n\nMany APIs in Apollo Client 3 provided a `TContext` generic argument that allowed you to provide the type for the `context` option. However, this generic argument was not consistently applied across all APIs that provided a `context` option and was easily forgotten.\n\nApollo Client 4 removes the `TContext` generic argument in favor of using [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) with the `DefaultContext` interface to provide types for the `context` option. This provides type safety throughout all Apollo Client APIs when using context.\n\nTo define types for your custom context properties, create a TypeScript file and define the `DefaultContext` interface.\n\n```ts title=\"apollo-client.d.ts\"\n// This import is necessary to ensure all Apollo Client imports\n// are still available to the rest of the application.\nimport \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  interface DefaultContext {\n    myProperty?: string;\n    requestId?: number;\n  }\n}\n```\n\n### Removal of `<TCacheShape>` generic argument\n\nThe `TCacheShape` generic argument has been removed from the `ApolloClient` constructor. Most users set this type to `any` which provided little benefit for type safety. APIs that previously relied on `TCacheShape` are now set to `unknown`.\n\nTo migrate, remove the `TCacheShape` generic argument when initializing `ApolloClient`.\n\n```ts\nnew ApolloClient<any>({ // [!code --]\nnew ApolloClient({ // [!code ++]\n  // ...\n});\n```\n\n### Removal of `<TSerialized>` generic argument\n\nThe `TSerialized` generic argument has been removed from the `ApolloCache` abstract class. Most users set this type to `any` which provided little benefit for type safety. APIs that previously relied on `TSerialized` are now set to `unknown`.\n\nTo migrate, remove the `TSerialized` generic argument when referencing `ApolloCache`.\n\n```ts\nconst cache: ApolloCache<any> = ... // [!code --]\nconst cache: ApolloCache = ... // [!code ++]\n```\n\n## Apollo Link changes\n\n### New class-based links\n\nAll links are now available as classes. The old link creator functions are still provided, but are now deprecated and will be removed in a future major version.\n\n| Old link creator              | New link class                    |\n| ----------------------------- | --------------------------------- |\n| `setContext`                  | `SetContextLink`                  |\n| `onError`                     | `ErrorLink`                       |\n| `createHttpLink`              | `HttpLink`                        |\n| `createPersistedQueryLink`    | `PersistedQueryLink`              |\n| `removeTypenameFromVariables` | `RemoveTypenameFromVariablesLink` |\n\n<Caution>\n\nPay attention when migrating from the old `setContext` creator to the new `SetContextLink` class.\nThe argument order for the callback function has changed. To migrate, swap the order of the `prevContext` and `operation` arguments.\n\n```ts disableCopy=true\nimport { setContext } from \"@apollo/client/link/context\"; // [!code --]\nimport { SetContextLink } from \"@apollo/client/link/context\"; // [!code ++]\n\nconst authLink = setContext((operation, prevContext) => { /*...*/ } // [!code --]\nconst authLink = new SetContextLink((prevContext, operation) => { /*...*/ }  // [!code ++]\n```\n\n</Caution>\n\n### Deprecation of bare `empty`, `from`, `concat`, and `split` functions\n\n> This change is performed by the codemod\n\nThe bare `empty`, `from`, `concat`, and `split` functions exported from `@apollo/client` and `@apollo/client/link` are now deprecated in favor of using the equivalent static methods on the `ApolloLink` class.\n\n```ts disableCopy=true\nimport { empty, from, concat, split } from \"@apollo/client\";// [!code --]\nimport { ApolloLink } from \"@apollo/client\";// [!code ++]\n\nconst link = empty();// [!code --]\nconst link = ApolloLink.empty();// [!code ++]\n\nfrom([linkA, linkB]);// [!code --]\nApolloLink.from([linkA, linkB]);// [!code ++]\n\nconcat(linkA, linkB);// [!code --]\nApolloLink.concat(linkA, linkB);// [!code ++]\n\nsplit((operation) => check(operation), linkA, linkB);// [!code --]\nApolloLink.split((operation) => check(operation), linkA, linkB);// [!code ++]\n```\n\n### Updated `concat` behavior\n\nThe static `ApolloLink.concat` method and the `ApolloLink.prototype.concat` method now accept a dynamic number of arguments to allow for concatenation with more than one link. This aligns the API with more familiar APIs such as `Array.prototype.concat` which accepts a variable number of arguments and provides more succinct code.\n\n```ts disableCopy=true\nlink1.concat(link2).concat(link3);// [!code --]\nlink1.concat(link2, link3);// [!code ++]\n```\n\n#### Deprecation of `ApolloLink.concat`\n\nThe static `ApolloLink.concat` is now deprecated in favor of `ApolloLink.from`. With the change to allow for a variable number of arguments, `ApolloLink.concat(a, b)` is now an alias for `ApolloLink.from([a, b])` and provides no additional benefit. `ApolloLink.concat` will be removed in a future major version.\n\n```ts disableCopy=true\nimport { ApolloLink } from \"@apollo/client/link\";\n\nApolloLink.concat(firstLink, secondLink);// [!code --]\nApolloLink.from([firstLink, secondLink]);// [!code ++]\n```\n\n### `from`,`concat`,`split` static and instance methods now require `ApolloLink` instances\n\nThese methods previously accepted `ApolloLink` instances or plain request handler functions as arguments. These APIs have been updated to require `ApolloLink` instances.\n\nTo migrate, wrap the request handler functions in an `ApolloLink` instance.\n\n```ts disableCopy=true\nApolloLink.from(\n  (operation, forward) => {// [!code --:3]\n    /*...*/\n  },\n  new ApolloLink((operation, forward) => {// [!code ++:3]\n    /*...*/\n  }),\n  nextLink\n);\n```\n\n### Changes to `ErrorLink`\n\nThe `ErrorLink` (previously created with `onError`) now uses a single `error` property instead of separate `graphQLErrors`, `networkError`, and `protocolErrors`.\n\nWith built-in error classes, use `ErrorClass.is` to check for specific error types.\nFor external error types like `TypeError`, use `instanceof` or the more modern [`Error.isError`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/isError#instanceof_vs._error.iserror) in combination with a check for `error.name` to check the kind of error.\n\n```ts disableCopy=true\nimport {\n  onError,// [!code --]\n  ErrorLink,// [!code ++]\n} from \"@apollo/client/link/error\";\nimport { CombinedGraphQLErrors, ServerError } from \"@apollo/client\";// [!code ++]\n\nconst errorLink = onError(// [!code --:12]\n  ({ graphQLErrors, networkError, protocolErrors, response }) => {\n    if (graphQLErrors) {\n      graphQLErrors.forEach(({ message }) =>\n        console.log(`GraphQL error: ${message}`)\n      );\n    }\n    if (networkError) {\n      console.log(`Network error: ${networkError.message}`);\n    }\n  }\n);\nconst errorLink = new ErrorLink(({ error, result }) => {// [!code ++:11]\n  if (CombinedGraphQLErrors.is(error)) {\n    error.errors.forEach(({ message }) =>\n      console.log(`GraphQL error: ${message}`)\n    );\n  } else if (ServerError.is(error)) {\n    console.log(`Server error: ${error.message}`);\n  } else if (error) {\n    console.log(`Other error: ${error.message}`);\n  }\n});\n```\n\n<Note>\n\nIf the error thrown in the link chain is not an error-like object, it will be wrapped in an `UnconventionalError` class - so it is always safe to access `error.message` and `error.name` on the `error` object.\n\n</Note>\n\n### Changes to `operation`\n\n#### `operationName` as `undefined` for anonymous queries\n\nThe `operationName` is now set to `undefined` when executing an anonymous query. Anonymous queries were previously set as an empty string.\n\nIf you use string methods on the `operationName`, you may need to check for `undefined` first.\n\n#### New `operation.operationType` property\n\nIn some cases, you might have needed to determine the GraphQL operation type of the request. This is common when using `ApolloLink.split` to route subscription operations to a WebSocket-based link.\n\nA new `operationType` property has been introduced to reduce the boilerplate needed to determine the operation type of the GraphQL document.\n\n```ts disableCopy=true\nimport { getMainDefinition } from \"@apollo/client\";// [!code --]\nimport { OperationTypeNode } from \"graphql\";// [!code ++]\n\nnew ApolloLink((operation, forward) => {\n  const definition = getMainDefinition(query);// [!code --:4]\n  const isSubscription =\n    definition.kind === \"OperationDefinition\" &&\n    definition.operation === \"subscription\";\n\n  const isSubscription =// [!code ++:2]\n    operation.operationType === OperationTypeNode.SUBSCRIPTION;\n});\n```\n\n#### Type safety\n\nThe `context` type can be extended by using declaration merging to allow you to define custom properties used by your links.\n\nFor example, to make your context type-safe for usage with `HttpLink`, place this snippet in a `.d.ts` file in your project:\n\n```ts title=\"apollo-client.d.ts\"\nimport { HttpLink } from \"@apollo/client\";\n\ndeclare module \"@apollo/client\" {\n  interface DefaultContext extends HttpLink.ContextOptions {}\n}\n```\n\nFor more information on how to setup context types, see the [TypeScript](../data/typescript#defining-context-types) guide.\n\n### Changes to `operation.getContext`\n\n#### Readonly context\n\nThe `context` object returned by `operation.getContext()` is now frozen and `Readonly`. This prevents mutations to the context object that aren't propagated to downstream links and could cause subtle bugs.\n\nTo make changes to context, use `operation.setContext()`.\n\n#### Removal of the `cache` property\n\nApollo Client 3 provided a reference to the cache on the context object for use with links via the `cache` property. This property has been removed and replaced with a `client` property on the `operation` which references the `client` instance that initiated the request.\n\nAccess the `cache` through the `client` property instead.\n\n```ts disableCopy=true\nnew ApolloLink((operation, forward) => {\n  const cache = operation.getContext().cache;// [!code --]\n  const cache = operation.client.cache;// [!code ++]\n});\n```\n\n#### Removal of the `getCacheKey` function\n\nApollo Client 3 provided a `getCacheKey` function on the context object to obtain cache IDs. This function has been removed.\n\nUse the `client` property to get access to the `cache.identify` function to identify an object.\n\n```ts disableCopy=true\nnew ApolloLink((operation, forward) => {\n  const cacheID = operation.getContext().getCacheKey(obj);// [!code --]\n  const cacheID = operation.client.cache.identify(obj);// [!code ++]\n});\n```\n\n### `execute` now requires the `client`\n\nIf you use the `execute` function directly to run the link chain, the `execute` function now requires a 3rd argument that provides the `ApolloClient` instance that represents the client that initiated the request.\n\nProvide a context argument with the `client` option to the 3rd argument of the `execute` function.\n\n```ts\nimport { execute } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  // ...\n});\n\nexecute(\n  link,\n  { query /* ... */ },\n  { client }// [!code ++]\n);\n```\n\n<Tip>\n\nIf you use the `execute` function to unit-test custom links, provide a dummy `ApolloClient` instance. The `ApolloClient` instance does not need any special configuration unless your unit tests require it.\n\n</Tip>\n\n#### Observable API changes\n\nIn Apollo Client 4, the underlying `Observable` implementation has changed from using `zen-observable` to using `rxjs` `Observable` instances.\n\nThis can affect custom link implementations that rely on the `Observable` API.\n\nIf you were previously using the `map`, `filter`, `reduce`, `flatMap` or `concat` methods on the `Observable` instances, you will need to update your code to use the `rxjs` equivalents.\n\nAdditionally, if you were using `Observable.of` or `Observable.from`, you will need to use the `rxjs` `of` or `from` functions instead.\n\n```ts disableCopy=true\nimport { of, from, map } from \"rxjs\";// [!code ++]\n\nObservable.of(1, 2, 3);// [!code --]\nof(1, 2, 3);// [!code ++]\nObservable.from([1, 2, 3]);// [!code --]\nfrom([1, 2, 3]);// [!code ++]\nobservable.map((x) => x * 2);// [!code --]\nobservable.pipe(map((x) => x * 2));// [!code ++]\n```\n\nA good way to find the operator you need is to follow the [rxjs operator decision tree](https://rxjs.dev/operator-decision-tree).\n\n## GraphQL over HTTP spec compatibility\n\nThe `HttpLink` and `BatchHttpLink` links have been updated to add stricter compatibility with the [GraphQL over HTTP specification](https://graphql.github.io/graphql-over-http/draft/).\n\nThis change means:\n\n- The default `Accept` header is now `application/graphql-response+json,application/json;q=0.9` for all outgoing requests\n- The `application/graphql-response+json` media type is now supported and the client handles the response according to the [`application/graphql-response+json` behavior](https://graphql.github.io/graphql-over-http/draft/#sec-application-graphql-response-json)\n- The `application/json` media type behaves according to the [`application/json` behavior](https://graphql.github.io/graphql-over-http/draft/#sec-application-json)\n\nThe client now does the following when `application/json` media type is returned.\n\n- The client will throw a `ServerError` when the server encodes a `content-type` using `application/json` and returns a non-200 status code\n- The client will now throw a `ServerError` when the server encodes using any other `content-type` and returns a non-200 status code\n\n<Note>\n\nIf you use a testing utility to mock requests in your test, you may experience different behavior than production if your testing utility responds as `application/json` but your production server responds as `application/graphql-response+json`. If a `content-type` header is not set, the client interprets the response as `application/json` by default.\n\n</Note>\n\n## Local state changes\n\nLocal state management (using `@client` fields) has been removed from core and is now an opt-in feature. This change helps reduce the bundle size of your application if you don't use local state management features.\n\nTo opt-in to use local state management with the `@client` directive, initialize an instance of `LocalState` and provide it as the `localState` option to the `ApolloClient` constructor. Apollo Client will throw an error if a `@client` field is used and `localState` is not provided.\n\n```ts\nimport { LocalState } from \"@apollo/client/local-state\";// [!code ++]\n\nnew ApolloClient({\n  // ...\n  localState: new LocalState(),// [!code ++]\n  // ...\n});\n```\n\n### Local resolvers\n\nThe `resolvers` option has been removed from the `ApolloClient` constructor and is now part of the `LocalState` class. Move local resolvers to the `LocalState` class.\n\n```ts\nnew ApolloClient({\n  resolvers: {...}, // [!code --]\n  localState: new LocalState({\n    resolvers: {...} // [!code ++]\n  })\n});\n```\n\nNow that local resolvers are part of the `LocalState` class, the following resolver methods were removed from the `ApolloClient` class:\n\n- `addResolvers`\n- `getResolvers`\n- `setResolvers`\n\nIf you add resolvers after the initialization of the client, you may continue to do so with your `LocalState` instance using the `addResolvers` method.\n\n```ts\nconst client = new ApolloClient({\n  // ...\n});\n\nclient.addResolvers(resolvers);// [!code --]\nclient.localState.addResolvers(resolvers);// [!code ++]\n```\n\n`getResolvers` and `setResolvers` have been removed without a replacement. Stop using them.\n\n```ts\nconst client = new ApolloClient({\n  // ...\n});\n\nconst resolvers = client.getResolvers();// [!code --]\nclient.setResolvers(resolvers);// [!code --]\n```\n\n#### Resolver context\n\nThe context argument (i.e. the 3rd argument) passed to resolver functions has been updated. Apollo Client 3 spread [request `context`](../api/link/introduction#managing-context) and replaced any passed-in `client` and `cache` properties.\n\nApollo Client 4 moves the request `context` to the `requestContext` key to avoid name clashes and updates the shape of the object. The context argument is now provided with the following object:\n\n```ts\n{\n  // the request context. By default `TContextValue` is of type `DefaultContext`,\n  // but can be changed if a `context` function is provided.\n  requestContext: TContextValue,\n  // The client instance making the request\n  client: ApolloClient,\n  // Whether the resolver is run as a result of gathering exported variables\n  // or resolving the value as part of the result\n  phase: \"exports\" | \"resolve\"\n}\n```\n\nIf you accessed properties from the request context, you will now need to read those properties from the `requestContext` key. If you used the `cache` property, you will need to get the `cache` from the `client` property.\n\n```ts\nnew LocalState({\n  resolvers: {\n    MyType: {\n      myLocalField: (parent, args, { someValue, cache }) { // [!code --]\n      myLocalField: (parent, args, { requestContext, client }) { // [!code ++]\n        const someValue = requestContext.someValue; // [!code ++]\n        const cache = client.cache; // [!code ++]\n      }\n    }\n  }\n})\n```\n\n#### Thrown errors\n\nErrors thrown in local resolvers are now handled properly and predictably. Errors are now added to the `errors` array in the GraphQL response and the field value is set to `null`.\n\nThe following example throws an error in a local resolver.\n\n```ts\nnew LocalState({\n  resolvers: {\n    Query: {\n      localField: () => {\n        throw new Error(\"Could not get localField\");\n      },\n    },\n  },\n});\n```\n\nThis results in the following result:\n\n```ts\n{\n  data: {\n    localField: null,\n  },\n  errors: [\n    {\n      message: \"Could not get localField\",\n      path: [\"localField\"],\n      extensions: {\n        localState: {\n          resolver: \"Query.localField\",\n          cause: new Error(\"Could not get localField\"),\n        },\n      },\n    },\n  ],\n};\n```\n\nAs a result of this change, it is now safe to throw, or allow thrown errors in your resolvers. If your local resolvers catch errors to avoid issues in Apollo Client 3, these can be removed in cases where you want the error to be returned in the GraphQL result.\n\n```ts\nnew LocalState({\n  resolvers: {\n    Query: {\n      localField: () => {\n        try {// [!code --]\n          throw new Error(\"Could not get localField\");\n        } catch (e) {// [!code --]\n          console.log(e);// [!code --]\n        }// [!code --]\n      },\n    },\n  },\n});\n```\n\n#### Returned values\n\nApollo Client 4 now checks the return value of local resolvers to ensure it returns a value or `null`. `undefined` is no longer a valid value.\n\nWhen `undefined` is returned from a local resolver, the value is set to `null` and a warning is logged to the console.\n\nThis example returns `undefined` due to the early return.\n\n```ts\nnew LocalState({\n  resolvers: {\n    Query: {\n      localField: () => {\n        if (someCondition) {\n          return;\n        }\n\n        return \"value\";\n      },\n    },\n  },\n});\n```\n\nThis results in the following result:\n\n```ts\n{\n  data: {\n    localField: null,\n  },\n};\n```\n\nAnd a warning is emitted to the console:\n\n> The 'Query.localField' resolver returned `undefined` instead of a value. This is likely a bug in the resolver. If you didn't mean to return a value, return `null` instead.\n\nInstead, the local resolver should return `null` instead.\n\n```ts\nif (someCondition) {\n  return;// [!code --]\n  return null;// [!code ++]\n}\n```\n\nThe exception is when running local resolvers to get values for exported variables for fields marked with the `@export` directive. For this case, you may return `undefined` to omit the variable from the outgoing request. If you need to know whether to return `undefined` or `null`, use the `phase` property provided to the context argument.\n\n```ts\nnew LocalState({\n  resolvers: {\n    Query: {\n      localField: (parent, args, { phase }) => {\n        // `phase` is \"resolve\" when resolving the field for the response  [!code highlight:4]\n        return phase === \"resolve\" ? null : undefined;\n        // `phase` is \"exports\" when getting variables for `@export` fields.\n        return phase === \"exports\" ? undefined : null;\n      },\n    },\n  },\n});\n```\n\n#### Enforced `__typename`\n\nApollo Client 4 now validates that a `__typename` property is returned from resolvers that return arrays or objects on non-scalar fields. If `__typename` is not included, an error is added to the `errors` array and the field value is set to `null`. This change ensures the object is cached properly to avoid bugs that might otherwise be difficult to track down.\n\nIf your local resolver returns an object or an array for a non-scalar field, make sure it includes the `__typename` field.\n\n```ts\nconst query = gql`\n  query {\n    localUser @client {\n      id\n    }\n  }\n`;\n\nnew LocalState({\n  resolvers: {\n    Query: {\n      localUser: () => ({\n        __typename: \"LocalUser\",// [!code ++]\n        // ...\n      }),\n    },\n  },\n});\n```\n\n#### Behavior changes with `@export` fields\n\nApollo Client 4 adds additional validation to fields and resolvers that use the `@export` directive before the request is sent to the server.\n\n##### Variable definitions\n\nEach `@export` field is now checked to ensure it can be associated with a variable definition in the GraphQL document. If the `@export` directive doesn't include the `as` argument, or the GraphQL document doesn't define a variable definition that matches the name provided to the `as` argument, a `LocalStateError` is thrown.\n\nYou will need to ensure the GraphQL document includes variable definitions for all `@export` fields.\n\n```ts\n// This throws because \"someVar\" is not defined\nconst query = gql`\n  query {\n    field @client @export(as: \"someVar\")\n  }\n`;\n\n// This is valid\nconst query = gql`\n  query ($someVar: String) {\n    field @client @export(as: \"someVar\")\n  }\n`;\n```\n\n##### Required variables\n\nResolvers that return values for required variables are now checked to ensure the value isn't nullable. If a resolver returns `null` or `undefined` for a required variable, a `LocalStateError` is thrown. This would otherwise cause an error on the server.\n\n##### Errors in local resolvers\n\nLocal resolvers are not allowed to throw errors when resolving values for variables to avoid ambiguity on how to handle the error. If an error is thrown from a local resolver, it is wrapped in a `LocalStateError` and rethrown.\n\nSince local resolvers are allowed to throw errors when resolving field data, you can use the `phase` property provided to the context argument to determine whether to rethrow the error or return a different value.\n\n```ts\nnew LocalState({\n  resolvers: {\n    Query: {\n      localField: (parent, args, { phase }) => {\n        try {\n          throw new Error(\"Oops couldn't get local field\");\n        } catch (error) {\n          // Omit the variable value in the request\n          if (phase === \"exports\") {\n            return;\n          }\n\n          // Rethrow the error to add it to the `errors` array\n          throw error;\n        }\n      },\n    },\n  },\n});\n```\n\n##### Handling Local state errors\n\nEach validation error throws an instance of `LocalStateError`. You can check if an error is a result of a local state error by using `LocalStateError.is` method. The error instance provides additional information about the path in the GraphQL document that caused the error.\n\n```ts\nimport { LocalStateError } from \"@apollo/client\";\n\n// ...\n\nconst { error } = useQuery(QUERY);\n\nif (LocalStateError.is(error)) {\n  console.log(error.path, error.message);\n}\n```\n\n### Custom fragment matchers\n\nApollo Client 3 allowed for custom fragment matchers using the `fragmentMatcher` option provided to the `ApolloClient` constructor. This made it possible to add your own custom logic to match fragment spreads used with client field selection sets. Fragment matching is now part of the cache with the `fragmentMatches` API.\n\nApollo Client 4 removes the `fragmentMatcher` option and the associated `setLocalStateFragmentMatcher` method that allows you to set a fragment matcher after the client was initialized. Remove the use of these APIs.\n\n```ts\nconst client = new ApolloClient({\n  fragmentMatcher: (rootValue, typeCondition, context) => true,// [!code --]\n});\n\nclient.setLocalStateFragmentMatcher(() => true);// [!code --]\n```\n\nIf you're using `InMemoryCache`, you're all set. `InMemoryCache` implements `fragmentMatches` for you. We recommend checking your [`possibleTypes` configuration](../data/fragments#using-fragments-with-unions-and-interfaces) to ensure it is up-to-date with your local schema.\n\nIf you're using a custom cache implementation, you will need to check if it [meets the new requirements for custom cache implementations](#new-requirements-for-custom-cache-implementations). `LocalState` requires that the cache implements the `fragmentMatches` API. If the custom cache does not implement `fragmentMatches`, an error is thrown.\n\n## Testing-related changes\n\nA lot of utilities that were previously part of the `@apollo/client/utilities` and `@apollo/client/testing` packages have been removed. They were used for internal testing purposes and we are not using them anymore, so we removed them.\n\n### `MockedProvider` changes\n\n#### Default \"realistic\" `delay`\n\nIf no `delay` is specified in mocks, MockLink now defaults to the `realisticDelay` function, which uses a random delay between 20 and 50ms to ensure tests handle loading states.\n\nIf you want to restore the previous behavior of \"no delay\", you can set it via\n\n```ts\nMockLink.defaultOptions = {\n  delay: 0,\n};\n```\n\n#### Removed `createMockClient` and `mockSingleLink`\n\nThe `createMockClient` and `mockSingleLink` utilities have been removed. Instead, you can now use the `MockLink` class directly to create a mock link and pass it into a new `ApolloClient` instance.\n\n## Bundling changes\n\n### `exports` field in package.json\n\nApollo Client 4 now uses the `exports` field in its `package.json` to define which files are available for import. This means you should now be able to use `import { ApolloClient } from \"@apollo/client\"` instead of `import { ApolloClient } from \"@apollo/client/index.js\"` or `import { ApolloClient } from \"@apollo/client/main.cjs\"`.\n\n### New transpilation target, no shipped polyfills\n\nApollo Client is now transpiled to target a `since 2023, node >= 20, not dead` target. This means that Apollo Client can now use modern JavaScript features without downlevel transpilation, which will generally result in better performance and smaller bundle size.\nWe also have stopped the practice of shipping polyfills.\n\nPlease note that we might bump the transpilation target to more modern targets in upcoming minor versions. See our [versioning policy](../versioning-policy) for more details on the supported environments.\n\nIf you are targeting older browsers or special environments, you might need to adjust your build configuration to transpile the Apollo Client library itself to a lower target, or polyfill the missing features yourself.\n\n### Development mode changes\n\nPreviously, you had to set a global `__DEV__` variable to `false` to disable development mode.\nNow, development mode is primarily controlled by the `development` export condition of the `package.json` exports field. Most modern bundlers should now automatically pick correctly between the development and production version of Apollo Client based on your build environment.\n\nIf your build tooling does not support the `development` or `production` export condition, Apollo Client falls back to the previous behavior, meaning that you can still set the `__DEV__` global variable to `false` to disable development mode in those cases.\n\n## Other notable breaking changes\n\n### New requirements for custom cache implementations\n\nCustom cache implementations must now implement the `fragmentMatches` method, which is required for fragment matching in Apollo Client 4.\n"
  },
  {
    "path": "docs/source/networking/advanced-http-networking.mdx",
    "content": "---\ntitle: Advanced HTTP networking\ndescription: Take full network control with Apollo Link\n---\n\nThe **Apollo Link** library gives you fine-grained control of HTTP requests that are sent by Apollo Client. You can also use it to replace Apollo Client's networking layer with something completely custom, such as a WebSocket transport or mocked server data.\n\nWhen using Apollo Link, you define network behavior as a collection of **link** objects that execute in sequence to control the flow of data. By default, Apollo Client uses Apollo Link's `HttpLink` to send GraphQL queries over HTTP.\n\nApollo Link includes installable, premade links that support a variety of use cases. You can also create your own custom links.\n\n## Customizing request logic\n\nThe following example demonstrates adding a custom link to Apollo Client. This link adds an `Authorization` header to every HTTP request before the `HttpLink` sends it:\n\n```js\nimport {\n  ApolloClient,\n  HttpLink,\n  ApolloLink,\n  InMemoryCache,\n  concat,\n} from \"@apollo/client\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\n\nconst authMiddleware = new ApolloLink((operation, forward) => {\n  // add the authorization to the headers\n  operation.setContext(({ headers = {} }) => ({\n    headers: {\n      ...headers,\n      authorization: localStorage.getItem(\"token\") || null,\n    },\n  }));\n\n  return forward(operation);\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: concat(authMiddleware, httpLink),\n});\n```\n\nThis next example demonstrates providing multiple custom links in an array:\n\n```js\nimport {\n  ApolloClient,\n  HttpLink,\n  ApolloLink,\n  InMemoryCache,\n  from,\n} from \"@apollo/client\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\n\nconst authMiddleware = new ApolloLink((operation, forward) => {\n  // add the authorization to the headers\n  operation.setContext(({ headers = {} }) => ({\n    headers: {\n      ...headers,\n      authorization: localStorage.getItem(\"token\") || null,\n    },\n  }));\n\n  return forward(operation);\n});\n\nconst activityMiddleware = new ApolloLink((operation, forward) => {\n  // add the recent-activity custom header to the headers\n  operation.setContext(({ headers = {} }) => ({\n    headers: {\n      ...headers,\n      \"recent-activity\": localStorage.getItem(\"lastOnlineTime\") || null,\n    },\n  }));\n\n  return forward(operation);\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: from([authMiddleware, activityMiddleware, httpLink]),\n});\n```\n\nIn the example above, the `authMiddleware` link sets each request's `Authorization` header, and the `activityMiddleware` then sets each request's `Recent-Activity` header. Finally, the `HttpLink` sends the modified request.\n\n## Customizing response logic\n\nYou can use Apollo Link to customize Apollo Client's behavior whenever it receives a response from a request.\n\nThe following example demonstrates using [`@apollo/client/link/error`](../api/link/apollo-link-error/) to handle network errors that are included in a response:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  HttpLink,\n  ServerError,\n} from \"@apollo/client\";\nimport { ErrorLink } from \"@apollo/client/link/error\";\n\nimport { logout } from \"./logout\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\n\nconst logoutLink = new ErrorLink(({ error }) => {\n  if (ServerError.is(error) && error.statusCode === 401) {\n    logout();\n  }\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: logoutLink.concat(httpLink),\n});\n```\n\nIn this example, the user is logged out of the application if the server returns a `401` code (unauthorized).\n\n### Modifying response data\n\nYou can create a custom link that edits or removes fields from `response.data`. To do so, you call `map` on the result of the link's `forward(operation)` call. In the `map` function, make the desired changes to `response.data` and then return it:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  HttpLink,\n  ApolloLink,\n} from \"@apollo/client\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\n\nconst formatDateLink = new ApolloLink((operation, forward) => {\n  return forward(operation).map((response) => {\n    if (response.data.date) {\n      response.data.date = new Date(response.data.date);\n    }\n    return response;\n  });\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: formatDateLink.concat(httpLink),\n});\n```\n\nIn the above example, `formatDateLink` changes a `date` field to a Javascript Date object at the top level of each response.\n\nNote that `forward(operation).map(func)` _doesn't_ support asynchronous execution of the `func` mapping function. If you need to make asynchronous modifications, use the `asyncMap` function from `@apollo/client/utilities`, like so:\n\n```js\nimport {\n  ApolloClient,\n  InMemoryCache,\n  HttpLink,\n  ApolloLink,\n} from \"@apollo/client\";\nimport { asyncMap } from \"@apollo/client/utilities\";\n\nimport { usdToEur } from \"./currency\";\n\nconst httpLink = new HttpLink({ uri: \"/graphql\" });\n\nconst usdToEurLink = new ApolloLink((operation, forward) => {\n  return asyncMap(forward(operation), async (response) => {\n    let data = response.data;\n    if (data.price && data.currency === \"USD\") {\n      data.price = await usdToEur(data.price);\n      data.currency = \"EUR\";\n    }\n    return response;\n  });\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: usdToEurLink.concat(httpLink),\n});\n```\n\nIn the example above, `usdToEurLink` uses `asyncMap` to convert the response object's `price` field from USD to EUR using an external API.\n\nWhile this technique can be useful for modifying _existing_ fields (or adding additional objects to lists within `data`), adding _new_ fields to `data` won't work in most cases, because the operation document cannot be safely modified within the `ApolloLink` request pipeline.\n\n## The `HttpLink` object\n\nApollo Client uses `HttpLink` to send GraphQL operations to a server over HTTP. The link supports both POST and GET requests, and it can modify HTTP options on a per-query basis. This comes in handy when implementing authentication, persisted queries, dynamic URIs, and other granular updates.\n\n> If your client doesn't have complex HTTP requirements, you probably don't need to create a custom instance of `HttpLink`. For details, see [Basic HTTP networking](./basic-http-networking/).\n\n### Usage\n\n```js\nimport { HttpLink } from \"@apollo/client\";\n\nconst link = new HttpLink({ uri: \"/graphql\" });\n```\n\n### Constructor options\n\nThe `HttpLink` constructor accepts the following options:\n\n| Options              | Description                                                                                                                                                             |\n| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `uri`                | A string endpoint or function that resolves to the GraphQL server you want to execute operations against. (default: `/graphql`)                                         |\n| `includeExtensions`  | If `true`, you can pass an `extensions` field to your GraphQL server. (default: `false`)                                                                                |\n| `fetch`              | A `fetch`-compatible API for making a request. See [Providing a `fetch` replacement for certain environments](#providing-a-fetch-replacement-for-certain-environments). |\n| `headers`            | An object containing header names and values to include in each request.                                                                                                |\n| `preserveHeaderCase` | If `true`, header values retain their capitalization for non-http-spec-compliant servers. (default: `false`)                                                            |\n| `credentials`        | A string representing the credentials policy to use for the `fetch` call. (valid values: `omit`, `include`, `same-origin`)                                              |\n| `fetchOptions`       | Include this to override the values of certain options that are provided to the `fetch` call.                                                                           |\n| `useGETForQueries`   | If `true`, `HttpLink` uses `GET` requests instead of `POST` requests to execute query operations (but not mutation operations). (default: `false`)                      |\n| `print`              | A function to customize AST formatting in requests. See [Overriding the default `print` function](#overriding-the-default-print-function).                              |\n\n#### Providing a `fetch` replacement for certain environments\n\n`HttpLink` requires that `fetch` is present in your runtime environment. This is the case for React Native and most modern browsers. If you're targeting an environment that _doesn't_ include `fetch` (such as older browsers or the server), you need to pass your own `fetch` to `HttpLink` via its [constructor options](#constructor-options). We recommend using [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) for older browsers and Node.\n\n#### Overriding the default `print` function\n\nThe `print` option is useful for customizing the way `DocumentNode` objects are transformed back into strings before they are sent over the network. If no custom `print` function is provided, the [GraphQL `print` function](https://graphql.org/graphql-js/language/#print) will be used. A custom `print` function should accept an `ASTNode` (typically a `DocumentNode`) and the original `print` function as arguments, and return a string. This option can be used with `stripIgnoredCharacters` to remove whitespace from queries:\n\n```ts\nimport { ASTNode, stripIgnoredCharacters } from \"graphql\";\n\nconst httpLink = new HttpLink({\n  uri: \"/graphql\",\n  print(ast: ASTNode, originalPrint: (ast: ASTNode) => string) {\n    return stripIgnoredCharacters(originalPrint(ast));\n  },\n});\n```\n\n### Overriding options\n\nYou can override most `HttpLink` constructor options on an operation-by-operation basis by modifying the `context` object for the operation. For example, you can set the `headers` field on the `context` to pass custom headers for a particular operation. The `context` also supports the `credentials` field for defining credentials policy, `uri` for changing the endpoint dynamically, and `fetchOptions` to allow generic fetch overrides (i.e., `method: \"GET\"`).\n\nNote that if you set `fetchOptions.method` to `GET`, `HttpLink` follows the [standard GraphQL HTTP GET encoding](http://graphql.org/learn/serving-over-http/#get-request). The query, variables, operation name, and extensions are passed as query parameters instead of in the HTTP request body (because there isn't one). If you to continue to send mutations as non-idempotent `POST` requests, set the top-level `useGETForQueries` option to `true` instead of setting `fetchOptions.method` to `GET`.\n\n`HttpLink` also attaches the response from the `fetch` operation to the context as `response`, so you can access it in another link.\n\nContext options:\n\n| Option         | Description                                                                                                                |\n| -------------- | -------------------------------------------------------------------------------------------------------------------------- |\n| `headers`      | An object containing header names and values to include in each request.                                                   |\n| `credentials`  | A string representing the credentials policy to use for the `fetch` call. (valid values: `omit`, `include`, `same-origin`) |\n| `uri`          | A string endpoint or function that resolves to the GraphQL server you want to execute operations against.                  |\n| `fetchOptions` | Any overrides of the fetch options argument to pass to the `fetch` call.                                                   |\n| `response`     | The raw response from the `fetch` request after it is made.                                                                |\n| `http`         | An object that lets you control fine-grained aspects of `HttpLink` itself, such as persisted queries (see below).          |\n\nThe following example shows how to use the `context` to pass a special header for a single query:\n\n```js\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({ uri: \"/graphql\" }),\n});\n\nclient.query({\n  query: MY_QUERY,\n  context: {\n    // example of setting the headers with context per operation\n    headers: {\n      special: \"Special header value\",\n    },\n  },\n});\n```\n\n### Custom fetching\n\n`HttpLink`'s `fetch` option can be used to wire in custom networking. This is useful if you want to modify the request based on calculated headers, or calculate the URI based on an operation. For example:\n\n**Custom auth:**\n\n```js\nconst customFetch = (uri, options) => {\n  const { header } = Hawk.client.header(\n    \"http://example.com:8000/resource/1?b=1&a=2\",\n    \"POST\",\n    { credentials: credentials, ext: \"some-app-data\" }\n  );\n  options.headers.Authorization = header;\n  return fetch(uri, options);\n};\n\nconst link = new HttpLink({ fetch: customFetch });\n```\n\n**Dynamic URI:**\n\n```js\nconst customFetch = (uri, options) => {\n  const { operationName } = JSON.parse(options.body);\n  return fetch(`${uri}/graph/graphql?opname=${operationName}`, options);\n};\n\nconst link = new HttpLink({ fetch: customFetch });\n```\n\n## Using other links\n\nApollo Link includes many links for specialized use cases, such as the `WebSocketLink` for communicating over WebSocket and the `BatchHttpLink` for combining multiple GraphQL operations in a single HTTP request.\n\nTo learn more about what's available, see the [Apollo Link API documentation](../api/link/introduction/).\n"
  },
  {
    "path": "docs/source/networking/authentication.mdx",
    "content": "---\ntitle: Authentication\n---\n\nUnless all of the data you are loading is completely public, your app has some sort of users, accounts and permissions systems. If different users have different permissions in your application, then you need a way to tell the server which user is associated with each request.\n\nApollo Client uses the ultra flexible [Apollo Link](../api/link/introduction/) that includes several options for authentication.\n\n## Cookie\n\nIf your app is browser based and you are using cookies for login and session management with a backend, tell your network interface to send the cookie along with every request. Pass the credentials option e.g. `credentials: 'same-origin'` if your backend server is the same domain, as shown below, or else `credentials: 'include'` if your backend is a different domain.\n\n```js\nconst link = new HttpLink({\n  uri: \"/graphql\",\n  credentials: \"same-origin\",\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link,\n});\n```\n\nThis option is passed through to the [`fetch` implementation](https://github.com/github/fetch) used by the HttpLink when sending the query.\n\nNote: the backend must also allow credentials from the requested origin. e.g. if using the popular 'cors' package from npm in node.js, the following settings would work in tandem with the above apollo client settings:\n\n```js\n// enable cors\nvar corsOptions = {\n  origin: \"<insert uri of front-end domain>\",\n  credentials: true, // <-- REQUIRED backend setting\n};\napp.use(cors(corsOptions));\n```\n\n## Header\n\nAnother common way to identify yourself when using HTTP is to send along an authorization header. Add an `authorization` header to every HTTP request by chaining together Apollo Links. In this example, we'll pull the login token from `localStorage` every time a request is sent:\n\nReactJS example:\n\n```js\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\nimport { SetContextLink } from \"@apollo/client/link/context\";\n\nconst httpLink = new HttpLink({\n  uri: \"/graphql\",\n});\n\nconst authLink = new SetContextLink(({ headers }) => {\n  // get the authentication token from local storage if it exists\n  const token = localStorage.getItem(\"token\");\n  // return the headers to the context so httpLink can read them\n  return {\n    headers: {\n      ...headers,\n      authorization: token ? `Bearer ${token}` : \"\",\n    },\n  };\n});\n\nconst client = new ApolloClient({\n  link: authLink.concat(httpLink),\n  cache: new InMemoryCache(),\n});\n```\n\nVueJS example:\n\n```js\nimport ApolloClient from \"apollo-client\";\nimport { HttpLink } from \"apollo-link-http\";\nimport { ApolloLink } from \"apollo-link\";\nimport { InMemoryCache } from \"apollo-cache-inmemory\";\nimport { getMainDefinition } from \"apollo-utilities\";\n\nconst httpLink = new HttpLink({ uri: process.env.VUE_APP_API_TARGET });\n\nconst authMiddleware = new ApolloLink((operation, forward) => {\n  // add the authorization to the headers\n  const token = localStorage.getItem(\"token\");\n  operation.setContext({\n    headers: {\n      authorization: token ? `Bearer ${token}` : \"\",\n    },\n  });\n  return forward(operation);\n});\nexport const apolloClient = new ApolloClient({\n  link: authMiddleware.concat(httpLink),\n  cache: new InMemoryCache(),\n});\n```\n\nThe server can use that header to authenticate the user and attach it to the GraphQL execution context, so resolvers can modify their behavior based on a user's role and permissions.\n\n## Reset store on logout\n\nSince Apollo caches all of your query results, it's important to get rid of them when the login state changes.\n\nThe most straightforward way to ensure that the UI and store state reflects the current user's permissions is to call `client.resetStore()` after your login or logout process has completed. This will cause the store to be cleared and all active queries to be refetched. If you just want the store to be cleared and don't want to refetch active queries, use `client.clearStore()` instead. Another option is to reload the page, which will have a similar effect.\n\n```jsx\nconst PROFILE_QUERY = gql`\n  query CurrentUserForLayout {\n    currentUser {\n      login\n      avatar_url\n    }\n  }\n`;\n\nfunction Profile() {\n  const {\n    client,\n    loading,\n    data: { currentUser },\n  } = useQuery(PROFILE_QUERY, { fetchPolicy: \"network-only\" });\n\n  if (loading) {\n    return <p className=\"navbar-text navbar-right\">Loading...</p>;\n  }\n\n  if (currentUser) {\n    return (\n      <span>\n        <p className=\"navbar-text navbar-right\">\n          {currentUser.login}\n          &nbsp;\n          <button\n            onClick={() => {\n              // call your auth logout code then reset store\n              App.logout().then(() => client.resetStore());\n            }}\n          >\n            Log out\n          </button>\n        </p>\n      </span>\n    );\n  }\n\n  return (\n    <p className=\"navbar-text navbar-right\">\n      <a href=\"/login/github\">Log in with GitHub</a>\n    </p>\n  );\n}\n```\n"
  },
  {
    "path": "docs/source/networking/basic-http-networking.mdx",
    "content": "---\ntitle: Basic HTTP networking\ndescription: Communicate with a GraphQL server over HTTP\n---\n\nApollo Client has built-in support for communicating with a GraphQL server over HTTP with `HttpLink`.\nTo set up this communication, provide an `HttpLink` instance as the `link` option to the `ApolloClient` constructor:\n\n```js\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({\n    uri: \"https://api.example.com\",\n  }),\n});\n```\n\nIf you provide this parameter, Apollo Client sends all GraphQL operations (queries and mutations) to the specified URL over HTTP.\n\n## Including credentials in requests\n\n`HttpLink` can include user credentials (basic auth, cookies, etc.) in the HTTP requests it makes to a GraphQL server. By default, credentials are included only if the server is hosted at the same origin as the application using Apollo Client. You can adjust this behavior by providing a value for the `credentials` option to the `HttpLink` constructor:\n\n```js\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({\n    uri: \"https://api.example.com\",\n    // Enable sending cookies over cross-origin requests\n    credentials: \"include\",\n  }),\n});\n```\n\nThe following values for `credentials` are supported:\n\n| Option        | Description                                                                                                                                           |\n| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `same-origin` | Send user credentials (cookies, basic http auth, etc.) if the server's URL is on the same origin as the requesting client. This is the default value. |\n| `omit`        | Never send or receive credentials.                                                                                                                    |\n| `include`     | Always send user credentials (cookies, basic http auth, etc.), even for cross-origin requests.                                                        |\n\nFor more information, see [`Request.credentials`](https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials).\n\n## Customizing request headers\n\nYou can specify the names and values of custom headers to include in every HTTP request to a GraphQL server. To do so, provide the `headers` option to the `HttpLink` constructor, like so:\n\n```js\nimport { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: new HttpLink({\n    uri: \"https://api.example.com\",\n    headers: {\n      authorization: localStorage.getItem(\"token\"),\n      \"client-name\": \"WidgetX Ecom [web]\",\n      \"client-version\": \"1.0.0\",\n    },\n  }),\n});\n```\n\n## API\n\n<InterfaceDetails\n  headingLevel={3}\n  canonicalReference=\"@apollo/client!HttpLink.Options:interface\"\n  displayName=\"HttpLink.Options\"\n  customPropertyOrder={[\"uri\", \"credentials\", \"headers\", \"http\"]}\n/>\n\n<InterfaceDetails\n  headingLevel={3}\n  canonicalReference=\"@apollo/client!HttpLink.ContextOptions:interface\"\n  displayName=\"HttpLink.ContextOptions\"\n/>\n"
  },
  {
    "path": "docs/source/pagination/core-api.mdx",
    "content": "---\ntitle: Core pagination API\ndescription: Fetching and caching paginated results\n---\n\nRegardless of which pagination strategy your GraphQL server uses for a particular list field, your Apollo Client app needs to do the following to query that field effectively:\n\n- Call the [`fetchMore` function](#the-fetchmore-function) to fetch the next page of results when needed\n- [Merge individual pages of results](#merging-paginated-results) into a single list in the Apollo Client cache\n\nThis article describes these core requirements for paginated fields.\n\n## The `fetchMore` function\n\nPagination always involves sending followup queries to your GraphQL server to obtain additional pages of results. In Apollo Client, the recommended way to send these followup queries is with the [`fetchMore`](/react/caching/advanced-topics/#incremental-loading-fetchmore) function. This function is a member of the `ObservableQuery` object returned by `client.watchQuery`, and it's also provided by the `useQuery` hook:\n\n```jsx {11} title=\"FeedWithData.jsx\"\nconst FEED_QUERY = gql`\n  query Feed($offset: Int, $limit: Int) {\n    feed(offset: $offset, limit: $limit) {\n      id\n      # ...\n    }\n  }\n`;\n\nconst FeedWithData() {\n  const { loading, data, fetchMore } = useQuery(FEED_QUERY, {\n    variables: {\n      offset: 0,\n      limit: 10\n    },\n  });\n  // ...continues below...\n}\n```\n\nYou usually call `fetchMore` in response to a user action, such as clicking a button or scrolling to the current \"bottom\" of an infinite-scroll feed.\n\nBy default, `fetchMore` executes a query with the exact same shape and variables as your original query. You can pass new values for the query's `variables` (such as providing a new `offset`) like so:\n\n```jsx {12-16} title=\"FeedWithData.jsx\"\nconst FeedWithData() {\n// ...continuing from above...\n\n// Your component will rerender with loading:true whenever fetchMore is called\n// because notifyOnNetworkStatusChange defaults to true.\nif (loading) return 'Loading...';\n\nreturn (\n    <Feed\n      entries={data.feed || []}\n      onLoadMore={() => fetchMore({\n        variables: {\n          offset: data.feed.length\n        },\n      })}\n    />\n  );\n}\n```\n\nHere, we set the `offset` variable to `feed.length` to fetch items _after_ the last item in our cached list. The `variables` we provide here are shallow merged with the `variables` provided for the original query, which means that variables _omitted_ here (such as `limit`) retain their original value (`10`) in the followup query.\n\nIn addition to `variables`, you can optionally provide an entirely different shape of `query` to execute. This can be useful when `fetchMore` needs to fetch only a single paginated field, but the original query contained unrelated fields.\n\n> Additional examples of using `fetchMore` are provided in the detailed documentation for [offset-based pagination](/react/pagination/offset-based) and [cursor-based pagination](/react/pagination/cursor-based).\n\n**Our `fetchMore` function is ready, but we're not finished!** The cache _doesn't know yet_ that it should merge our followup query's result with the _original_ query's result. Instead, it will store the two results as two completely separate lists. To resolve this, let's move on to [Merging paginated results](#merging-paginated-results).\n\n## Merging paginated results\n\n> The examples in this section use offset-based pagination, but this article applies to all pagination strategies.\n\nAs mentioned above, a [`fetchMore`](#the-fetchmore-function) followup query doesn't automatically merge its result with the _original_ query's cached result. To achieve this behavior, we need to define a **field policy** for our paginated field.\n\n### Why do I need a field policy?\n\nLet's say we have a field in our GraphQL schema that takes an argument:\n\n```graphql {2}\ntype Query {\n  user(id: ID!): User\n}\n```\n\nNow, let's say we execute the following query two times and provide different values for the `$id` variable each time:\n\n```graphql\nquery GetUser($id: ID!) {\n  user(id: $id) {\n    id\n    name\n  }\n}\n```\n\nOur two queries return two entirely different `User` objects. Helpfully, the Apollo Client cache automatically stores these two objects separately, because it sees that _different values_ were provided for at least one field argument (`id`). Otherwise, the cache might overwrite the _first_ `User` object with the _second_ `User` object, and we want to cache both!\n\nNow, let's say we execute _this_ query two times, with different values for the `$offset` variable:\n\n```graphql\nquery Feed($offset: Int, $limit: Int) {\n  feed(offset: $offset, limit: $limit) {\n    id\n    # ...\n  }\n}\n```\n\nIn _this_ case, we're querying a paginated list field twice to obtain two different pages of results, and we want those two pages to be _merged_. But the cache doesn't know that! It sees no difference between this scenario and the `User` scenario above, so it stores the results as two completely separate lists.\n\nWith field policies, we can modify the cache's behavior for individual fields that require it. For example, we can tell the cache _not_ to store separate results for the `feed` field based on the values of `offset` and `limit`. Let's look at how.\n\n### Defining a field policy\n\nA field policy specifies how a particular field in your `InMemoryCache` is read and written. You can define a field policy to merge the results of paginated queries into a single list.\n\n#### Example\n\nHere's the server-side schema for our message feed application that uses offset-based pagination:\n\n```graphql {2}\ntype Query {\n  feed(offset: Int, limit: Int): [FeedItem!]\n}\n\ntype FeedItem {\n  id: String!\n  message: String!\n}\n```\n\nIn our client, we want to define a field policy for `Query.feed` so that all returned pages of the list are merged into a _single_ list in our cache.\n\nWe define our field policy within the `typePolicies` option we provide the `InMemoryCache` constructor:\n\n```js {5-15}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          // Don't cache separate results based on\n          // any of this field's arguments.\n          keyArgs: false,\n\n          // Concatenate the incoming list items with\n          // the existing list items.\n          merge(existing = [], incoming) {\n            return [...existing, ...incoming];\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThis field policy specifies the field's `keyArgs`, along with a **`merge` function**. Both of these configurations are necessary for handling pagination:\n\n- `keyArgs` specifies which of the field's arguments cause the cache to store a _separate_ value for each unique combination of those arguments.\n  - In our case, the cache shouldn't store a separate result based on _any_ argument value (`offset` or `limit`). So, we disable this behavior entirely by passing `false`. An empty array (`keyArgs: []`) also works, but `keyArgs: false` is more expressive, and it results in a cleaner field key within the cache (`feed` in this case).\n  - If a particular argument's value could cause items from an _entirely different list_ to be returned in the field, that argument _should_ be included in `keyArgs`.\n  - For more information, see [Specifying key arguments](/react/caching/cache-field-behavior/#specifying-key-arguments) and [The `keyArgs` API](/react/pagination/key-args).\n- A `merge` function tells the Apollo Client cache how to combine `incoming` data with `existing` cached data for a particular field. Without this function, incoming field values _overwrite_ existing field values by default.\n  - For more information, see [The `merge` function](/react/caching/cache-field-behavior/#the-merge-function).\n\nWith this field policy in place, the cache automatically merges the results of _all_ queries that use the following structure, regardless of argument values:\n\n```ts\n// Client-side query definition\nconst FEED_QUERY = gql`\n  query Feed($offset: Int, $limit: Int) {\n    feed(offset: $offset, limit: $limit) {\n      id\n      message\n    }\n  }\n`;\n```\n\n### Improving the `merge` function\n\nIn [the example above](#example), our `merge` function is a single line:\n\n```js\nmerge(existing = [], incoming) {\n  return [...existing, ...incoming];\n}\n```\n\nThis function makes risky assumptions about the order in which the client requests pages, because it ignores the values of `offset` and `limit`. A more robust `merge` function can use `options.args` to decide where to put `incoming` data relative to `existing` data, like so:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: false,\n          merge(existing, incoming, { args: { offset = 0 } }) {\n            // Slicing is necessary because the existing data is\n            // immutable, and frozen in development.\n            const merged = existing ? existing.slice(0) : [];\n            for (let i = 0; i < incoming.length; ++i) {\n              merged[offset + i] = incoming[i];\n            }\n            return merged;\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nThis logic handles sequential page writes the same way the single-line strategy does, but it can also tolerate repeated, overlapping, or out-of-order writes, without duplicating any list items.\n\n### Updating the query with the fetch more result\n\nAt times the call to `fetchMore` may need to perform additional cache updates for your query. While you can use the [`cache.readQuery`](/react/caching/cache-interaction#readquery) and [`cache.writeQuery`](/react/caching/cache-interaction#writequery) functions to to do this work yourself, it can be cumbsersome to use both of these together.\n\nAs a shortcut, you can provide the `updateQuery` option to `fetchMore` to update your query using the result from the `fetchMore` call.\n\n<Note>\n\n`updateQuery` is not a replacement for your field policy `merge` functions. While you can use `updateQuery` without the need to define a `merge` function, `merge` functions defined for fields in the query will run using the result from `updateQuery`.\n\n</Note>\n\nLet's see the example above using `updateQuery` to merge results together instead of a field policy merge function:\n\n```ts\nfetchMore({\n  variables: { offset: data.feed.length },\n  updateQuery(previousData, { fetchMoreResult, variables: { offset } }) {\n    // Slicing is necessary because the existing data is\n    // immutable, and frozen in development.\n    const updatedFeed = previousData.feed.slice(0);\n    for (let i = 0; i < fetchMoreResult.feed.length; ++i) {\n      updatedFeed[offset + i] = fetchMoreResult.feed[i];\n    }\n    return { ...previousData, feed: updatedFeed };\n  },\n});\n```\n\n<Tip>\n\nWe recommend defining field policies that contain at least a [`keyArgs`](/react/pagination/key-args/) value even when you use `updateQuery`. This prevents fragmenting the data unnecessarily in the cache. Setting `keyArgs` to `false` is adequate for most situations to ignore the `offset` and `limit` arguments and write the paginated data as one big array.\n\n</Tip>\n\n## `read` functions for paginated fields\n\n[As shown above](#defining-a-field-policy), a `merge` function helps you combine paginated query results from your GraphQL server into a single list in your client cache. But what if you also want to configure how that locally cached list is _read_? For that, you can define a **`read` function**.\n\nYou define a `read` function for a field within its [field policy](#defining-a-field-policy), alongside the `merge` function and `keyArgs`. If you define a `read` function for a field, the cache calls that function whenever you query the field, passing the field's existing cached value (if any) as the first argument. In the query response, the field is populated with the `read` function's return value, _instead of_ the existing cached value.\n\n> If a field policy includes both a `merge` function and a `read` function, the default value of `keyArgs` becomes `false` (i.e., _no_ arguments are key arguments). If either function _isn't_ defined, _all_ of the field's arguments are considered key arguments by default. In either case, you can define `keyArgs` yourself to override the default behavior.\n\nA `read` function for a paginated field typically uses one of the following approaches:\n\n- [Re-pagination](#paginated-read-functions), in which the cached list is split back into pages, based on field arguments\n- [_No_ pagination](#non-paginated-read-functions), in which the cached list is always returned in full\n\nAlthough the \"right\" approach varies from field to field, a [non-paginated `read` function](#non-paginated-read-functions) often works best for infinitely scrolling feeds, because it gives your code full control over which elements to display at a given time, without requiring any additional cache reads.\n\n### Paginated `read` functions\n\nThe `read` function for a list field can perform client-side re-pagination for that list. It can even transform a page before returning it, such as by sorting or filtering its elements.\n\nThis capability goes beyond returning the same pages that you fetched from your server, because a `read` function for `offset`/`limit` pagination could read from any available `offset`, with any desired `limit`:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          read(existing, { args: { offset, limit } }) {\n            // A read function should always return undefined if existing is\n            // undefined. Returning undefined signals that the field is\n            // missing from the cache, which instructs Apollo Client to\n            // fetch its value from your GraphQL server.\n            return existing && existing.slice(offset, offset + limit);\n          },\n\n          // The keyArgs list and merge function are the same as above.\n          keyArgs: [],\n          merge(existing, incoming, { args: { offset = 0 } }) {\n            const merged = existing ? existing.slice(0) : [];\n            for (let i = 0; i < incoming.length; ++i) {\n              merged[offset + i] = incoming[i];\n            }\n            return merged;\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nDepending on the assumptions you feel comfortable making, you might want to make this code more defensive. For example, you can provide default values for `offset` and `limit`, in case someone fetches `Query.feed` without providing arguments:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          read(\n            existing,\n            {\n              args: {\n                // Default to returning the entire cached list,\n                // if offset and limit are not provided.\n                offset = 0,\n                limit = existing?.length,\n              } = {},\n            }\n          ) {\n            return existing && existing.slice(offset, offset + limit);\n          },\n          // ... keyArgs, merge ...\n        },\n      },\n    },\n  },\n});\n```\n\nThis style of `read` function takes responsibility for re-paginating your data based on field arguments, essentially inverting the behavior of your `merge` function. This way, your application can query different pages using different arguments.\n\n### Non-paginated `read` functions\n\nThe `read` function for a paginated field can choose to _ignore_ arguments like `offset` and `limit`, and always return the entire list as it exists in the cache. In this case, your application code takes responsibility for slicing the list into pages depending on your needs.\n\nIf you adopt this approach, you might not need to define a `read` function at all, because the cached list can be returned without any processing. That's why the [`offsetLimitPagination` helper function](/react/pagination/offset-based/#the-offsetlimitpagination-helper) is implemented _without_ a `read` function.\n\nRegardless of how you configure `keyArgs`, your `read` (and `merge`) functions can always examine any arguments passed to the field using the `options.args` object. See [The `keyArgs` API](/react/pagination/key-args) for a deeper discussion of how to reason about dividing argument-handling responsibility between `keyArgs` and your `read` or `merge` functions.\n\n## Using `fetchMore` with queries that set a `no-cache` fetch policy\n\n<Note>\n\nWe recommend upgrading to version 3.11.3 or later to address bugs that exhibit unexpected behavior when using `fetchMore` with queries that set `no-cache` fetch policies. Please see pull request [#11974](https://github.com/apollographql/apollo-client/pull/11974) for more information.\n\n</Note>\n\nThe examples shown above use field policies and `merge` functions to update the result of a paginated field. But what about queries that use a `no-cache` fetch policy? Data is not written to the cache, so field policies have no effect.\n\nTo update our query, we provide the `updateQuery` option to the `fetchMore` function.\n\nLet's use the example above, but instead provide the `updateQuery` function to `fetchMore` to update the query.\n\n```ts\nfetchMore({\n  variables: { offset: data.feed.length },\n  updateQuery(previousData, { fetchMoreResult, variables: { offset } }) {\n    // Slicing is necessary because the existing data is\n    // immutable, and frozen in development.\n    const updatedFeed = previousData.feed.slice(0);\n    for (let i = 0; i < fetchMoreResult.feed.length; ++i) {\n      updatedFeed[offset + i] = fetchMoreResult.feed[i];\n    }\n    return { ...previousData, feed: updatedFeed };\n  },\n});\n```\n\n<Note>\n\nAs of Apollo Client version 3.11.3, the `updateQuery` option is required when using `fetchMore` with a `no-cache` fetch policy. This is required to correctly determine how the results should be merged since field policy `merge` functions are ignored. Calling `fetchMore` without an `updateQuery` function will throw an error.\n\n</Note>\n"
  },
  {
    "path": "docs/source/pagination/cursor-based.mdx",
    "content": "---\ntitle: Cursor-based pagination\n---\n\n> We recommend reading [Core pagination API](./core-api) before learning about considerations specific to cursor-based pagination.\n\n## Using list element IDs as cursors\n\nSince numeric offsets within paginated lists can be unreliable, a common improvement is to identify the beginning of a page using some unique identifier that belongs to each element of the list.\n\nIf the list represents a set of elements without duplicates, this identifier could simply be the unique ID of each object, allowing additional pages to be requested using the ID of the last object in the list, together with some `limit` argument. With this approach, the requested `cursor` ID should not appear in the new page, since it identifies the item just before the beginning of the page.\n\nSince the elements of the list could be normalized `Reference` objects, you will probably want to use the `options.readField` helper function to read the `id` field in your `merge` and/or `read` functions:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"type\"],\n\n          merge(existing, incoming, { args: { cursor }, readField }) {\n            const merged = existing ? existing.slice(0) : [];\n            let offset = offsetFromCursor(merged, cursor, readField);\n            // If we couldn't find the cursor, default to appending to\n            // the end of the list, so we don't lose any data.\n            if (offset < 0) offset = merged.length;\n            // Now that we have a reliable offset, the rest of this logic\n            // is the same as in offsetLimitPagination.\n            for (let i = 0; i < incoming.length; ++i) {\n              merged[offset + i] = incoming[i];\n            }\n            return merged;\n          },\n\n          // If you always want to return the whole list, you can omit\n          // this read function.\n          read(\n            existing,\n            { args: { cursor, limit = existing.length }, readField }\n          ) {\n            if (existing) {\n              let offset = offsetFromCursor(existing, cursor, readField);\n              // If we couldn't find the cursor, default to reading the\n              // entire list.\n              if (offset < 0) offset = 0;\n              return existing.slice(offset, offset + limit);\n            }\n          },\n        },\n      },\n    },\n  },\n});\n\nfunction offsetFromCursor(items, cursor, readField) {\n  // Search from the back of the list because the cursor we're\n  // looking for is typically the ID of the last item.\n  for (let i = items.length - 1; i >= 0; --i) {\n    const item = items[i];\n    // Using readField works for both non-normalized objects\n    // (returning item.id) and normalized references (returning\n    // the id field from the referenced entity object), so it's\n    // a good idea to use readField when you're not sure what\n    // kind of elements you're dealing with.\n    if (readField(\"id\", item) === cursor) {\n      // Add one because the cursor identifies the item just\n      // before the first item in the page we care about.\n      return i + 1;\n    }\n  }\n  // Report that the cursor could not be found.\n  return -1;\n}\n```\n\nSince items can be removed from, added to, or moved around within the list without altering their `id` fields, this pagination strategy tends to be more resilient to list mutations than the `offset`-based strategy we saw above.\n\nHowever, this strategy works best when your `merge` function always appends new pages to the existing data, since it doesn't take any precautions to avoid overwriting elements if the `cursor` falls somewhere in the middle of the existing data.\n\n## Using a map to store unique items\n\nIf your paginated field logically represents a _set_ of unique items, you can store it internally using a more convenient data structure than an array.\n\nIn fact, your `merge` function can return internal data in any format you like, as long as your `read` function cooperates by turning that internal representation back into a list:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"type\"],\n\n          // While args.cursor may still be important for requesting\n          // a given page, it no longer has any role to play in the\n          // merge function.\n          merge(existing, incoming, { readField }) {\n            const merged = { ...existing };\n            incoming.forEach((item) => {\n              merged[readField(\"id\", item)] = item;\n            });\n            return merged;\n          },\n\n          // Return all items stored so far, to avoid ambiguities\n          // about the order of the items.\n          read(existing) {\n            return existing && Object.values(existing);\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nWith this internal representation, you no longer have to worry about incoming items overwriting unrelated existing items, because an assignment to the map can only replace an item with the same `id` field.\n\nHowever, this approach leaves an important question unanswered: what `cursor` should we use when requesting the _next_ page? Thanks to the predictable ordering of JavaScript object keys by insertion order, you should be able to use the `id` field of the last element returned by the `read` function as the `cursor` for the next request&mdash;though you're not alone if relying on this behavior makes you nervous. In the next section we'll see a slightly different approach that makes the next `cursor` more explicit.\n\n## Keeping cursors separate from items\n\nPagination cursors are often derived from ID fields of list items, but not always. In cases where the list could have duplicates, or is sorted or filtered according to some criteria, the cursor may need to encode not just a position within the list but also the sorting/filtering logic that produced the list. In such situations, since the cursor does not logically belong to the elements of the list, the cursor may be returned separately from the list:\n\n```jsx\nconst MORE_COMMENTS_QUERY = gql`\n  query MoreComments($cursor: String, $limit: Int!) {\n    moreComments(cursor: $cursor, limit: $limit) {\n      cursor\n      comments {\n        id\n        author\n        text\n      }\n    }\n  }\n`;\n\nfunction CommentsWithData() {\n  const { data, loading, fetchMore } = useQuery(MORE_COMMENTS_QUERY, {\n    variables: { limit: 10 },\n  });\n\n  if (loading) return <Loading />;\n\n  return (\n    <Comments\n      entries={data.moreComments.comments || []}\n      onLoadMore={() =>\n        fetchMore({\n          variables: {\n            cursor: data.moreComments.cursor,\n          },\n        })\n      }\n    />\n  );\n}\n```\n\nTo demonstrate the flexibility of the field policy system, here's an implementation of the `Query.moreComments` field that uses a map internally, but returns an array of unique `comments`:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        moreComments: {\n          keyArgs: false,\n          merge(existing, incoming, { readField }) {\n            const comments = existing ? { ...existing.comments } : {};\n            incoming.comments.forEach((comment) => {\n              comments[readField(\"id\", comment)] = comment;\n            });\n            return {\n              cursor: incoming.cursor,\n              comments,\n            };\n          },\n\n          read(existing) {\n            if (existing) {\n              return {\n                cursor: existing.cursor,\n                comments: Object.values(existing.comments),\n              };\n            }\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nNow there's less ambiguity about where the next `cursor` comes from, because it is explicitly stored and returned as part of the query.\n\n## Relay-style cursor pagination\n\nThe `InMemoryCache` field policy API allows for any conceivable style of pagination, even though some of the simpler approaches have known drawbacks.\n\nIf you were designing a GraphQL client without the flexibility that `read` and `merge` functions provide, you would most likely attempt to standardize around a one-size-fits-all style of pagination that you felt was sophisticated enough to support most use cases. That's the path Relay, another popular GraphQL client, has chosen with their [Cursor Connections Specification](https://facebook.github.io/relay/graphql/connections.htm). As a consequence, a number of public GraphQL APIs have adopted the Relay connection specification to be maximally compatible with Relay clients.\n\nUsing Relay-style connections is similar to cursor-based pagination, but differs in the format of the query response, which affects the way cursors are managed. In addition to `connection.edges`, which is a list of `{ cursor, node }` objects, where each `edge.node` is a list item, Relay provides a `connection.pageInfo` object which gives the cursors of the first and last items in `connection.edges` as `connection.pageInfo.startCursor` and `connection.pageInfo.endCursor`, respectively. The `pageInfo` object also contains the boolean properties `hasPreviousPage` and `hasNextPage`, which can be used to determine if there are more results available (both forwards and backwards):\n\n```jsx\nconst COMMENTS_QUERY = gql`\n  query Comments($cursor: String) {\n    comments(first: 10, after: $cursor) {\n      edges {\n        node {\n          author\n          text\n        }\n      }\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n    }\n  }\n`;\n\nfunction CommentsWithData() {\n  const { data, loading, fetchMore } = useQuery(COMMENTS_QUERY);\n\n  if (loading) return <Loading />;\n\n  const nodes = data.comments.edges.map((edge) => edge.node);\n  const pageInfo = data.comments.pageInfo;\n\n  return (\n    <Comments\n      entries={nodes}\n      onLoadMore={() => {\n        if (pageInfo.hasNextPage) {\n          fetchMore({\n            variables: {\n              cursor: pageInfo.endCursor,\n            },\n          });\n        }\n      }}\n    />\n  );\n}\n```\n\nFortunately, Relay-style pagination can be implemented in Apollo Client using `merge` and `read` functions, which means all the thorny details of connections and `edges` and `pageInfo` can be abstracted away, into a single, reusable helper function:\n\n```js\nimport { relayStylePagination } from \"@apollo/client/utilities\";\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        comments: relayStylePagination(),\n      },\n    },\n  },\n});\n```\n\nWhenever you need to consume a Relay pagination API using Apollo Client, `relayStylePagination` is a great tool to try first, even if you end up copy/pasting its code and making changes to suit your specific needs.\n\nNote that the `relayStylePagination` function generates a field policy with a `read` function that simply returns all available data, ignoring `args`, which makes `relayStylePagination` easier to use with `fetchMore`. This is a [non-paginated `read` function](./core-api/#non-paginated-read-functions). There's nothing stopping you from adapting this `read` function to use `args` to return individual pages, as long as you remember to update the variables of your original query after calling `fetchMore`.\n"
  },
  {
    "path": "docs/source/pagination/key-args.mdx",
    "content": "---\ntitle: Key arguments in Apollo Client\ndescription: Using the keyArgs API\n---\n\n> We recommend reading [Core pagination API](./core-api) before learning about considerations specific to `keyArgs` configuration.\n\nThe Apollo Client cache can store multiple entries for a single schema field. By default, each entry corresponds to a different set of values for the field's arguments.\n\nFor example, consider this `Query.user` field:\n\n```graphql {3}\ntype Query {\n  # Returns whichever User object corresponds to `id`\n  user(id: ID!): User\n}\n```\n\nIf we query for `User`s with `id`s `1` and `2`, the Apollo Client cache stores entries for _both_ like so:\n\n```js {3,6} title=\"Cache\"\n{\n  'ROOT_QUERY': {\n    'user({\"id\":\"1\"})': {\n      '__ref': 'User:1'\n    },\n    'user({\"id\":\"2\"})': {\n      '__ref': 'User:2'\n    }\n  }\n}\n```\n\nAs shown above, each entry's **storage key** includes the corresponding argument values. This means that if _any_ of a field's arguments differ between queries, the storage keys _also_ differ, and those queries result in distinct cache entries.\n\n> If a field has no arguments, its storage key is just its name.\n\nThis default behavior is for safety: the cache doesn't know whether it can _merge_ the values returned for different argument combinations without invalidating data. In the example above, the cache definitely _shouldn't_ merge the results of querying for `User`s with `id`s `1` and `2`.\n\n## Pagination issues\n\nCertain arguments _shouldn't_ cause the Apollo Client cache to store a separate entry. This is almost always the case for arguments related to paginated lists.\n\nConsider this `Query.feed` field:\n\n```graphql {2}\ntype Query {\n  feed(offset: Int, limit: Int, category: Category): [FeedItem!]\n}\n```\n\nThe `offset` and `limit` arguments enable a client to specify which \"page\" of the feed it wants to fetch. In an app with an infinitely scrolling feed, the client might initially fetch the first ten items, then fetch the _next_ ten:\n\n```graphql\n# First query\nquery GetFeedItems {\n  feed(offset: 0, limit: 10, category: \"SPORTS\")\n}\n\n# Second query\nquery GetFeedItems {\n  feed(offset: 10, limit: 10, category: \"SPORTS\")\n}\n```\n\nBut because their argument values differ, these two lists of ten items are cached _separately_ by default. This means that when the second query completes, the returned items _aren't_ appended to the original list in the feed!\n\n```js {3-4,10-11} title=\"Cache\"\n{\n  'ROOT_QUERY': {\n    // First query\n    'feed({\"offset\":\"0\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:1'\n      },\n      // ...additional items...\n    ],\n    // Second query\n    'feed({\"offset\":\"10\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:11'\n      },\n      // ...additional items...\n    ]\n  }\n}\n```\n\nIn this case, we _don't_ want `offset` or `limit` to be included in a cache entry's storage key. Instead, we want the cache to _merge_ the results of the two above queries into a single cache entry that includes the items from both lists.\n\nTo help handle this case, we can [set key arguments](#setting-keyargs) for the field.\n\n## Setting `keyArgs`\n\nA **key argument** is an argument for a GraphQL field that's included in cache storage keys for that field. By default, _all_ GraphQL arguments are key arguments, as shown in our feed example:\n\n```js {3-4,10-11} title=\"Cache\"\n{\n  'ROOT_QUERY': {\n    // First query\n    'feed({\"offset\":\"0\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:1'\n      },\n      // ...additional items...\n    ],\n    // Second query\n    'feed({\"offset\":\"10\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:11'\n      },\n      // ...additional items...\n    ]\n  }\n}\n```\n\nYou can override this default behavior by defining a cache [field policy](../caching/cache-field-behavior) for a particular field:\n\n```js {5-7}\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"category\"],\n        },\n      },\n    },\n  },\n});\n```\n\nThis field policy for `Query.feed` includes a `keyArgs` array, which contains the names of all arguments that the cache _should_ include in its storage keys.\n\nIn this case, we don't want the cache to treat `offset` or `limit` as key arguments, because those arguments don't change _which_ list we're fetching from. However, we _do_ want to treat `category` as a key argument, because we want to store our `SPORTS` feed separately from other feeds (such as `FASHION` or `MUSIC`).\n\nAfter setting `keyArgs` as shown, we end up with a _single_ cache entry for our `SPORTS` feed (note the absence of `offset` and `limit` in the storage key):\n\n```js:title=Cache\n{\n  'ROOT_QUERY': {\n    'feed({\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:1'\n      },\n      // ...additional items from first query...\n      {\n        '__ref': 'FeedItem:11'\n      },\n      // ...additional items from second query...\n    ]\n  }\n}\n```\n\n> **Important:** After you define `keyArgs` for a paginated list field like `Query.feed`, you also need to [define a `merge` function](./core-api/#defining-a-field-policy) for the field. Otherwise, the list returned by the second query will _overwrite_ the first list instead of merging with it.\n\n## Supported values for `keyArgs`\n\nYou can provide the following values for a field's `keyArgs`:\n\n- `false` (indicates that the field has _no_ key arguments)\n- [An array](#keyargs-array) of argument, directive, and variable names\n- [A function](#keyargs-function) (advanced)\n\n### `keyArgs` array\n\nA `keyArgs` array can include the types of values shown below. The storage key for a cached field uses the values of _all_ arguments, directives, and variables included in the array.\n\n- Argument names:\n\n  ```js\n  // Here, category and id are two arguments of the field\n  [\"category\", \"id\"];\n  ```\n\n- _Nested_ argument names for input types with subfields:\n\n  ```js\n  // Here, details is an input type argument\n  // with subfields name and date\n  [\"details\", [\"name\", \"date\"]];\n  ```\n\n- Directive names (indicated with `@`), optionally with one or more of their arguments:\n\n  ```js\n  // Here, @units is a directive that can be applied\n  // to the field, and it has a type argument\n  [\"@units\", [\"type\"]];\n  ```\n\n- Variable names (indicated with `$`):\n\n  ```js\n  // Here, $userId is a variable that's provided to some\n  // operations that include the field\n  [\"$userId\"];\n  ```\n\n### `keyArgs` function (advanced)\n\nYou can define a completely different format for a field's storage key by providing a custom function to `keyArgs`. This function takes the field's arguments and other context as parameters, and it can return any string to use as the storage key (or a dynamically-generated `keyArgs` array).\n\nThis is for advanced use cases. For details, see [`FieldPolicy` API reference](../caching/cache-field-behavior/#fieldpolicy-api-reference).\n\n## Which arguments belong in `keyArgs`?\n\nWhen deciding which of a field's arguments to include in `keyArgs`, it's helpful to start by considering the two extremes: _all_ arguments and _no_ arguments. These initial options help to demonstrate the effects of adding or removing a single argument.\n\n### Using all arguments\n\nIf all arguments are key arguments (this is the default behavior), every distinct combination of argument values for a field results in a distinct cache entry. In other words, changing any argument value results in a different storage key, so the returned value is stored separately. We see this in our pagination example:\n\n```js {3-4,10-11} title=\"Cache\"\n{\n  'ROOT_QUERY': {\n    // First query\n    'feed({\"offset\":\"0\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:1'\n      },\n      // ...additional items...\n    ],\n    // Second query\n    'feed({\"offset\":\"10\",\"limit\":\"10\",\"category\":\"SPORTS\"})': [\n      {\n        '__ref': 'FeedItem:11'\n      },\n      // ...additional items...\n    ]\n  }\n}\n```\n\nWith this approach, Apollo Client can't return a cached value for a field unless _all_ of the field's arguments match a previously cached result. This significantly reduces the cache's hit rate, but it also prevents the cache from returning an incorrect value when differences in arguments are relevant (as with our `User` example):\n\n```js {3,6} title=\"Cache\"\n{\n  'ROOT_QUERY': {\n    'user({\"id\":\"1\"})': {\n      '__ref': 'User:1'\n    },\n    'user({\"id\":\"2\"})': {\n      '__ref': 'User:2'\n    }\n  }\n}\n```\n\n### Using no arguments\n\nIf no arguments are key arguments (you configure this by setting `keyArgs: false`), the field's storage key is just the field's name, without any argument values appended to it. This means that by default, whenever a query returns a value for that field, that value _replaces_ whatever value was already in the cache.\n\nThis default behavior is often undesirable (especially for a paginated list), so you can define `read` and `merge` functions that use argument values to determine how a newly returned value is combined with an _existing_ cached value.\n\n#### Example\n\nRecall this `Query.feed` field from [Pagination issues](#pagination-issues):\n\n```graphql {2}\ntype Query {\n  feed(offset: Int, limit: Int, category: Category): [FeedItem!]\n}\n```\n\nWe originally set `keyArgs: [\"category\"]` for this field to keep feed items from different categories separate. We can achieve the same behavior by setting `keyArgs: false` and defining the following `read` and `merge` functions:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: false,\n\n          read(existing = {}, { args: { offset, limit, category } }) {\n            return existing[category]?.slice(offset, offset + limit);\n          },\n\n          merge(existing = {}, incoming, { args: { category, offset = 0 } }) {\n            const merged =\n              existing[category] ? existing[category].slice(0) : [];\n            for (let i = 0; i < incoming.length; ++i) {\n              merged[offset + i] = incoming[i];\n            }\n            existing[category] = merged;\n            return existing;\n          },\n        },\n      },\n    },\n  },\n});\n```\n\nWith the code above, the value of the `existing` cached value passed to our `read` and `merge` functions is a _map_ of `category` names to `FeedItem` lists. This map enables our single cached field value to store multiple distinct lists. This manual separation is logically equivalent to using `keyArgs: [\"category\"]`, so the extra effort is often unnecessary.\n\nIf we know that feeds with different `category` values have different data, _and_ we know that our `read` function never needs simultaneous access to _multiple_ category feeds, we can safely shift the responsibility for the `category` argument to `keyArgs`. This enables us to simplify our `read` and `merge` functions to handle only one feed at a time.\n\n### Summary\n\nIf the logic for storing and retrieving a field's data is identical for different values of a given argument (like `category` above), and the distinct field values are logically independent from one another, then you should probably add that argument to `keyArgs` to avoid handling it in your `read` and `merge` functions.\n\nBy contrast, arguments that limit, filter, sort, or otherwise reprocess existing field data usually do _not_ belong in `keyArgs`. This is because putting them in `keyArgs` makes storage keys more diverse, reducing cache hit rate and limiting your ability to use different arguments to retrieve different views of the same data.\n\nAs a general rule, `read` and `merge` functions can do almost anything with your cached field data, but `keyArgs` often provide similar functionality with less code complexity. Whenever possible you should prefer the limited, declarative API of `keyArgs` over the unlimited power of functions like `merge` and `read`.\n\n## The `@connection` directive\n\nThe `@connection` directive is a Relay-inspired convention that Apollo Client supports. However, we recommend using `keyArgs` instead, because you can achieve the same effect with a single `keyArgs` configuration, whereas you need to include the `@connection` directive in every query you send to your server.\n\nIn other words, whereas Relay encourages the following `@connection(...)` directive for `Query.feed` queries:\n\n```js\nconst FEED_QUERY = gql`\n  query Feed($category: FeedCategory!, $offset: Int, $limit: Int) {\n    feed(category: $category, offset: $offset, limit: $limit) @connection(\n      key: \"feed\",\n      filter: [\"category\"]\n    ) {\n      edges {\n        node { ... }\n      }\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n    }\n  }\n`;\n```\n\nin Apollo Client, you can use the following query (the same query without the `@connection(...)` directive):\n\n```js\nconst FEED_QUERY = gql`\n  query Feed($category: FeedCategory!, $offset: Int, $limit: Int) {\n    feed(category: $category, offset: $offset, limit: $limit) {\n      edges {\n        node { ... }\n      }\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n    }\n  }\n`;\n```\n\nand instead configure `keyArgs` in your `Query.feed` field policy:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"category\"],\n        },\n      },\n    },\n  },\n});\n```\n\nIf the `Query.feed` field does not have an argument like `category` that you can use in `keyArgs: [...]`, then it might make sense to use the `@connection` directive after all:\n\n```js\nconst FEED_QUERY = gql`\n  query Feed($offset: Int, $limit: Int, $feedKey: String) {\n    feed(offset: $offset, limit: $limit) @connection(key: $feedKey) {\n      edges {\n        node { ... }\n      }\n      pageInfo {\n        endCursor\n        hasNextPage\n      }\n    }\n  }\n`;\n```\n\nIf you execute this query with different values for the `$feedKey` variable, those feed results are stored separately in the cache, whereas normally they would all be stored in the same list.\n\nWhen choosing a `keyArgs` configuration for this `Query.feed` field, you should include the `@connection` directive as if it were an argument (the `@` tells `InMemoryCache` you mean a directive):\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"@connection\", [\"key\"]],\n        },\n      },\n    },\n  },\n});\n```\n\nWith this configuration, your cache uses a `feed:{\"@connection\":{\"key\":...}}` key instead of just `feed` to store separate `{ edges, pageInfo }` objects within the `ROOT_QUERY` object:\n\n```js\nexpect(cache.extract()).toEqual({\n  ROOT_QUERY: {\n    __typename: \"Query\",\n    'feed:{\"@connection\":{\"key\":\"some feed key\"}}': { edges, pageInfo },\n    'feed:{\"@connection\":{\"key\":\"another feed key\"}}': { edges, pageInfo },\n    'feed:{\"@connection\":{\"key\":\"yet another key\"}}': { edges, pageInfo },\n    // ...\n  },\n});\n```\n\nThe `[\"key\"]` in `keyArgs: [\"@connection\", [\"key\"]]` means only the `key` argument to the `@connection` directive is considered, and any other arguments (like `filter`) are ignored. Passing just `key` to `@connection` is usually adequate, but if you want to pass a `filter: [\"someArg\", \"anotherArg\"]` argument as well, you should instead include those argument names directly in `keyArgs`:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          keyArgs: [\"someArg\", \"anotherArg\", \"@connection\", [\"key\"]],\n        },\n      },\n    },\n  },\n});\n```\n\nIf any of these arguments or directives are not provided for the current query, they're omitted from the field key automatically, without error. This means it's generally safe to include more arguments or directives in `keyArgs` than you expect to receive in all cases.\n\n> As mentioned above, if a `keyArgs` array is insufficient to specify your desired field keys, you can alternatively pass a function for `keyArgs`, which takes the `args` object and a `{ typename, field, fieldName, variables }` context parameter. This function can return either a string or a dynamically-generated `keyArgs` array.\n\nAlthough `keyArgs` (and `@connection`) are useful for more than just paginated fields, it's worth noting that `relayStylePagination` configures `keyArgs: false` by default. You can reconfigure this `keyArgs` behavior by passing an alternate value to `relayStylePagination`:\n\n```js\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: relayStylePagination([\"type\", \"@connection\", [\"key\"]]),\n      },\n    },\n  },\n});\n```\n\nIn the unlikely event that a `keyArgs` array is insufficient to capture the identity of a field, remember that you can pass a function for `keyArgs`, which allows you to serialize the `args` object however you want.\n"
  },
  {
    "path": "docs/source/pagination/offset-based.mdx",
    "content": "---\ntitle: Offset-based pagination\n---\n\n> We recommend reading [Core pagination API](./core-api) before learning about considerations specific to offset-based pagination.\n\nWith offset-based pagination, a list field accepts an `offset` argument that indicates _where in the list_ the server should start when returning items for a particular query. The field usually also accepts a `limit` argument that indicates the _maximum_ number of items to return:\n\n```graphql {2}\ntype Query {\n  feed(offset: Int, limit: Int): [FeedItem!]\n}\n\ntype FeedItem {\n  id: ID!\n  message: String!\n}\n```\n\nThis pagination strategy works well for immutable lists, or for lists where each item's index never changes. In other cases, you should avoid it in favor of [cursor-based pagination](./cursor-based/), because moving or removing items can shift offsets. This causes items to be skipped or duplicated if changes occur between paginated queries.\n\nAlthough it has limitations, offset-based pagination is a common pattern in many applications, in part because it's relatively straightforward to implement.\n\n## The `offsetLimitPagination` helper\n\nApollo Client provides an `offsetLimitPagination` helper function that you can use to generate a [field policy](../caching/cache-field-behavior/) for every relevant list field.\n\nThis example uses `offsetLimitPagination` to generate a field policy for `Query.feed`:\n\n```js {2,8} title=\"index.js\"\nimport { InMemoryCache } from \"@apollo/client\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: offsetLimitPagination(),\n      },\n    },\n  },\n});\n```\n\nThis defines a [`merge` function](../caching/cache-field-behavior/#the-merge-function) for the field that handles merging paginated results in the cache for you ([see the source](https://github.com/apollographql/apollo-client/blob/main/src/utilities/policies/pagination.ts#L33-L49)).\n\n### Using with `fetchMore`\n\nIf you use `offsetLimitPagination` to set your feed policy as shown above, then you can use `fetchMore` with `useQuery` like so:\n\n```jsx {17-21} title=\"FeedData.jsx\"\nconst FeedData() {\n  const { loading, data, fetchMore } = useQuery(FEED_QUERY, {\n    variables: {\n      offset: 0,\n      limit: 10\n    },\n  });\n\n  // Your component will rerender with loading:true whenever fetchMore is called\n  // because notifyOnNetworkStatusChange defaults to true.\n  if (loading) return <Loading/>;\n\n  return (\n    <Feed\n      entries={data.feed || []}\n      onLoadMore={() => fetchMore({\n        variables: {\n          offset: data.feed.length\n        },\n      })}\n    />\n  );\n}\n```\n\nBy default, `fetchMore` uses the original query and `variables`, so we only need to pass the variable that's changing: `offset`. When new data is returned from the server, it's automatically merged with any existing `Query.feed` data in the cache. This causes `useQuery` to rerender with the expanded list of data.\n\nIn this example, the `Feed` component receives the _entire cached list_ (`data.feed`) every time it renders, which includes data from all pages received so far. This is a [non-paginated `read` function](./core-api/#non-paginated-read-functions).\n\n### Using with a paginated `read` function\n\nIn [the example above](#using-with-fetchmore), the GraphQL server returns individual pages of results, but each query then returns _all_ cached results received so far. To limit each query's result to _only_ the items you requested, you can include a [paginated `read` function](./core-api/#paginated-read-functions) in your field policy.\n\nBecause the `offsetLimitPagination` helper is currently defining your field policy, you combine your `read` function with the helper's result, like so:\n\n```js {8-13} title=\"index.js\"\nimport { InMemoryCache } from \"@apollo/client\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        feed: {\n          ...offsetLimitPagination(),\n          read(existing, { args }) {\n            // Implement here\n          },\n        },\n      },\n    },\n  },\n});\n```\n\n> For example implementations, see [Paginated `read` functions](./core-api/#paginated-read-functions).\n\nIf you use a paginated `read` function, you probably need to update your `offset` and `limit` variables as required by your use case after you call `fetchMore`. Otherwise, you'll continue rendering only the first page of results.\n\nFor example, to display all the data received so far, you could modify the previous example as follows:\n\n```jsx\nconst FeedData = () => {\n  const [limit, setLimit] = useState(10);\n  const { loading, data, fetchMore } = useQuery(FEED_QUERY, {\n    variables: {\n      offset: 0,\n      limit,\n    },\n  });\n\n  if (loading) return <Loading />;\n\n  return (\n    <Feed\n      entries={data.feed || []}\n      onLoadMore={() => {\n        const currentLength = data.feed.length;\n        fetchMore({\n          variables: {\n            offset: currentLength,\n            limit: 10,\n          },\n        }).then((fetchMoreResult) => {\n          // Update variables.limit for the original query to include\n          // the newly added feed items.\n          setLimit(currentLength + fetchMoreResult.data.feed.length);\n        });\n      }}\n    />\n  );\n};\n```\n\nThis code uses a React `useState` Hook to store the current `limit` value, which it updates by calling `setLimit` in a callback attached to the `Promise` returned by `fetchMore`.\n\nYou could store `offset` in a React `useState` Hook as well, if you need the `offset` to change. Exactly when and how these `variables` change is up to your component, and may not always be the result of calling `fetchMore`, so it makes sense to use React component state to store these variable values.\n\n> If you are not using React and `useQuery`, the `ObservableQuery` object returned by `client.watchQuery` has a method called `setVariables` that you can call to update the original variables.\n\nBecause `fetchMore` requires some extra work to update the original variables if you're using a `read` function that is sensitive to those variables (the second kind of `read` function), it's fair to say `fetchMore` encourages the first kind of `read` function, which simply returns all available data.\n\nHowever, now that you understand your options, there's nothing wrong with moving read-time pagination logic out of your application code and into your field `read` functions. Both kinds of `read` functions have their uses, and both can be made to work with `fetchMore`.\n\n### Setting `keyArgs` with `offsetLimitPagination`\n\nIf a paginated field accepts arguments _besides_ `offset` and `limit`, you might need to [specify the **key arguments**](./key-args/) that indicate whether two result sets belong to the _same_ list or _different_ lists.\n\nTo set `keyArgs` for the field policy generated by `offsetLimitPagination`, provide an array of argument names to the function as a parameter:\n\n```js\nfields {\n  // Results belong to the same list only if both the type\n  // and userId arguments match exactly\n  feed: offsetLimitPagination([\"type\", \"userId\"])\n}\n```\n\nBy default, `offsetLimitPagination` uses `keyArgs: false` (no key arguments).\n"
  },
  {
    "path": "docs/source/pagination/overview.mdx",
    "content": "---\ntitle: Pagination in Apollo Client\ndescription: Overview\n---\n\nGraphQL enables you to fetch exactly the fields you need from your graph, with no unnecessary overhead. This helps keep network responses small and fast.\n\nHowever, GraphQL doesn't automatically _guarantee_ small responses. This is especially apparent when you query a field that contains a **list**. A list can contain infinitely many elements, which can result in an enormous response from a seemingly small query like this one:\n\n```graphql\nquery GetBookTitles {\n  books {\n    title\n  }\n}\n```\n\nIf your graph includes thousands or millions of books, this query probably returns _much_ more data than you need. To resolve this issue, GraphQL servers can **paginate** their list fields.\n\nWhen a client queries a paginated list field, the server returns only a portion (or \"page\") of the list's elements. The client's query includes arguments that indicate _which_ page the server should return:\n\n```mermaid\nsequenceDiagram;\n  Client app->>GraphQL server: query GetBookTitles(offset=0 limit=20)\n  GraphQL server->>Client app: Returns the first 20 list elements\n  Client app->>GraphQL server: query GetBookTitles(offset=20 limit=10)\n  GraphQL server->>Client app: Returns the next 10 list elements\n```\n\nThis diagram shows **offset-based** pagination, in which a client requests a page based on an absolute index in the list (`offset`) and the maximum number of elements to return (`limit`).\n\nThere are many different pagination strategies a server can use for a particular list field: offset-based, cursor-based, page-number-based, forwards, backwards, and so on. Each strategy requires a slightly different set of arguments. Because these strategies can each be useful in different situations, neither Apollo nor the GraphQL specification prescribes a canonical pagination strategy.\n\n## The Apollo Client approach\n\nInstead of recommending a particular pagination strategy, Apollo Client provides flexible cache APIs that help you merge results from a paginated list field, regardless of which pagination strategy your GraphQL server uses. And because you can represent these custom pagination strategies with stateless functions, you can reuse a single function for every list field that uses the same strategy.\n\nReady to start paginating? Start by learning about the [Core pagination API](./core-api).\n"
  },
  {
    "path": "docs/source/performance/babel.mdx",
    "content": "---\ntitle: Compiling queries with Transpilers\n---\n\nIf you prefer co-locating your GraphQL queries in your Javascript files, you typically use the [graphql-tag](https://github.com/apollographql/graphql-tag) library to write them. That requires to process the query strings into a GraphQL AST, which will add to the startup time of your application, especially if you have many queries.\n\nTo avoid this runtime overhead, you can precompile your queries created with `graphql-tag` using transpilers like [Babel](http://babeljs.io/) and [SWC](https://swc.rs). Here are possible ways you can do this:\n\n1. Using [babel-plugin-graphql-tag](#using-babel-plugin-graphql-tag)\n2. Using [graphql-tag-swc-plugin](#using-graphql-tag-swc-plugin)\n3. Using [graphql-tag.macro](#using-graphql-tagmacro)\n4. Using [ts-transform-graphql-tag](#using-ts-transform-graphql-tag) for TypeScript\n\nIf you prefer to keep your GraphQL code in separate files (`.graphql` or `.gql`) you can use [babel-plugin-import-graphql](https://github.com/detrohutt/babel-plugin-import-graphql). This plugin still uses `graphql-tag` under the hood, but transparently. You simply `import` your operations/fragments as if each were an export from your GraphQL file. This carries the same precompilation benefits as the above approaches.\n\n## Using babel-plugin-graphql-tag\n\nThis approach will allow you to use the `graphql-tag` library as usual, and when processing the files with this babel plugin, the calls to that library will be replaced by the precompiled result.\n\nInstall the plugin in your dev dependencies:\n\n```\n# with npm\nnpm install --save-dev babel-plugin-graphql-tag\n\n# or with yarn\nyarn add --dev babel-plugin-graphql-tag\n```\n\nThen add the plugin in your `.babelrc` configuration file:\n\n```\n{\n  \"plugins\": [\n    \"graphql-tag\"\n  ]\n}\n```\n\nAnd that's it! All the usages of `import gql from 'graphql-tag'` will be removed, and the calls to `gql` will be replaced by the compiled version.\n\n## Using graphql-tag-swc-plugin\n\nThis plugin is the same as [babel-plugin-graphql-tag](#using-babel-plugin-graphql-tag) but for [swc](https://swc.rs/), a fast rust based babel alternative.\n\nInstall the plugin in your dev dependencies:\n\n```\n# with npm\nnpm install --save-dev graphql-tag-swc-plugin\n\n# or with yarn\nyarn add --dev graphql-tag-swc-plugin\n```\n\nThen add the plugin in your `.swcrc` configuration file:\n\n```\n{\n  jsc: {\n    experimental: {\n      plugins: [\n        [\"graphql-tag-swc-plugin\",\n          {\n            importSources: [\"@apollo/client\", \"graphql-tag\"],\n            gqlTagIdentifiers: [\"gql\"]\n          },\n        ],\n      ],\n    },\n  },\n}\n```\n\nFor more information on configuration and features, please checkout the [`graphql-tag-swc-plugin`](https://github.com/rishabh3112/graphql-tag-swc-plugin) documentation.\n\n## Using graphql-tag.macro\n\nThis approach is a bit more explicit, since you change all your usages of `graphql-tag` for `graphql-tag.macro`, which exports a `gql` function that you can use the same way as the original one. This macro requires the [babel-macros](https://github.com/kentcdodds/babel-macros) plugin, which will do the same as the previous approach but only on the calls that come from the macro import, leaving regular calls to the `graphql-tag` library untouched.\n\nWhy would you prefer this approach? Mainly because it requires less configuration (`babel-macros` works with all kinds of macros, so if you already had it installed you don't have to do anything else), and also because of the explicitness. You can read more about the rationale of using `babel-macros` [in this blog post](http://babeljs.io/blog/2017/09/11/zero-config-with-babel-macros).\n\nTo use it, provided that you [already have babel-macros installed](https://github.com/kentcdodds/babel-macros#installation) and [configured](https://github.com/kentcdodds/babel-macros/blob/master/other/docs/user.md), you just need to change this:\n\n```js\nimport gql from \"graphql-tag\";\n\nconst query = gql`\n  query HelloWorld {\n    hello {\n      world\n    }\n  }\n`;\n```\n\nto this:\n\n```js\nimport gql from \"graphql-tag.macro\"; // <-- Use the macro\n\nconst query = gql`\n  query HelloWorld {\n    hello {\n      world\n    }\n  }\n`;\n```\n\n## Using babel-plugin-import-graphql\n\nInstall the plugin in your dev dependencies:\n\n```\n# with npm\nnpm install --save-dev babel-plugin-import-graphql\n\n# or with yarn\nyarn add --dev babel-plugin-import-graphql\n```\n\nThen add the plugin in your `.babelrc` configuration file:\n\n```\n{\n  \"plugins\": [\n    \"import-graphql\"\n  ]\n}\n```\n\nNow any `import` statements importing from a GraphQL file type will return a ready-to-use GraphQL DocumentNode object.\n\n```jsx\nimport React, { Component } from \"react\";\nimport { graphql } from \"@apollo/react-hoc\";\nimport myImportedQuery from \"./productsQuery.graphql\";\n// or for files with multiple operations:\n// import { query1, query2 } from './queries.graphql';\n\nclass QueryingComponent extends Component {\n  render() {\n    if (this.props.data.loading) return <h3>Loading...</h3>;\n    return <div>{`This is my data: ${this.props.data.queryName}`}</div>;\n  }\n}\n\nexport default graphql(myImportedQuery)(QueryingComponent);\n```\n\n## Using ts-transform-graphql-tag\n\nInstall the plugin in your dev dependencies:\n\n```\n# with npm\nnpm install --save-dev ts-transform-graphql-tag\n\n# or with yarn\nyarn add --dev ts-transform-graphql-tag\n```\n\nRead the [ts-transform-graphql-tag documentation](https://github.com/firede/ts-transform-graphql-tag) for Webpack or FuseBox usage instructions.\n\n## Fragments\n\nAll of these approaches support the use of fragments.\n\nFor the first two approaches, you can have fragments defined in a different call to `gql` (either in the same file or in a different one). You can then include them into the main query using interpolation, like this:\n\n```js\nimport gql from \"graphql-tag\";\n// or import gql from 'graphql-tag.macro';\n\nconst fragments = {\n  hello: gql`\n    fragment HelloStuff on Hello {\n      universe\n      galaxy\n    }\n  `,\n};\n\nconst query = gql`\n  query HelloWorld {\n    hello {\n      world\n      ...HelloStuff\n    }\n  }\n\n  ${fragments.hello}\n`;\n```\n\nWith `babel-plugin-import-graphql`, you can just include your fragment in your GraphQL file along-side whatever uses it, or even import it from a separate file using the `#import` syntax. See the [README](https://github.com/detrohutt/babel-plugin-import-graphql) for more information.\n"
  },
  {
    "path": "docs/source/performance/optimistic-ui.mdx",
    "content": "---\ntitle: Optimistic mutation results\ndescription: Update your UI before your server responds\n---\n\nIt's often possible to predict the most likely result of a mutation _before_ your GraphQL server returns it. Apollo Client can use this \"most likely result\" to update your UI **optimistically**, making your app feel more responsive to the user.\n\nFor example, let's say we have a blog application that supports the following mutation:\n\n```graphql\ntype Mutation {\n  updateComment(commentId: ID!, content: String!): Comment!\n\n  # ...other mutations...\n}\n```\n\nIf a user edits an existing comment on a post, the app executes the `updateComment` mutation, which returns a `Comment` object with updated `content`.\n\nOur app knows what the updated `Comment` object will probably look like, which means it can optimistically update its UI to display the update _before_ the GraphQL server responds with it. If our app is wrong (e.g., the GraphQL server returns an _unchanged_ `Comment` due to an error), the UI will automatically update to reflect the _actual_ response.\n\n## The `optimisticResponse` option\n\nTo enable this optimistic UI behavior, we provide an `optimisticResponse` option to the [mutate function](../data/mutations/#executing-a-mutation) that we use to execute our mutation.\n\nLet's look at some code:\n\n```jsx {20-26} title=\"CommentPageWithData.jsx\"\n// Mutation definition\nconst UPDATE_COMMENT = gql`\n  mutation UpdateComment($commentId: ID!, $commentContent: String!) {\n    updateComment(commentId: $commentId, content: $commentContent) {\n      id\n      __typename\n      content\n    }\n  }\n`;\n\n// Component definition\nfunction CommentPageWithData() {\n  const [mutate] = useMutation(UPDATE_COMMENT);\n  return (\n    <Comment\n      updateComment={({ commentId, commentContent }) =>\n        mutate({\n          variables: { commentId, commentContent },\n          optimisticResponse: {\n            updateComment: {\n              id: commentId,\n              __typename: \"Comment\",\n              content: commentContent,\n            },\n          },\n        })\n      }\n    />\n  );\n}\n```\n\nAs this example shows, the value of `optimisticResponse` is an object that matches the shape of the mutation response we expect from the server. Importantly, this includes the `Comment`'s `id` and `__typename` fields. The Apollo Client cache uses these values to generate the comment's [unique cache identifier](../caching/cache-configuration/#customizing-cache-ids) (e.g., `Comment:5`).\n\n## Optimistic mutation lifecycle\n\n1. When the code above calls `mutate`, the Apollo Client cache stores a `Comment` object with the field values specified in `optimisticResponse`. _However_, it does not overwrite the _existing_ cached `Comment` with the same cache identifier. Instead, it stores a separate, _optimistic_ version of the object. This ensures that our cached data remains accurate if our `optimisticResponse` is wrong.\n\n2. Apollo Client notifies all active queries that include the modified comment. Those queries automatically update, and their associated components re-render to reflect the optimistic data. Because this doesn't require any network requests, it's nearly instantaneous to the user.\n\n3. Eventually, our server responds with the mutation's _actual_ resulting `Comment` object.\n\n4. The Apollo Client cache removes the optimistic version of the `Comment` object. It also overwrites the _canonical_ cached version with values returned from the server.\n\n5. Apollo Client notifies all affected queries again. The associated components re-render, but if the server's response matches our `optimisticResponse`, this is invisible to the user.\n\n6. If the mutation returns a GraphQL error, Apollo Client discards the optimistic version of the object and rolls back to the previous state.\n\n## Bailing out of an optimistic update\n\nIn some cases you may want to skip an optimistic update. For example, you may want to perform an optimistic update _only_ when certain variables are passed to the mutation. To skip an update, pass a function to the `optimisticResponse` option and return the `IGNORE` sentinel object available on the second argument to bail out of the optimistic update.\n\nConsider this example:\n\n```tsx\nconst UPDATE_COMMENT = gql`\n  mutation UpdateComment($commentId: ID!, $commentContent: String!) {\n    updateComment(commentId: $commentId, content: $commentContent) {\n      id\n      __typename\n      content\n    }\n  }\n`;\n\nfunction CommentPageWithData() {\n  const [mutate] = useMutation(UPDATE_COMMENT);\n\n  return (\n    <Comment\n      updateComment={({ commentId, commentContent }) =>\n        mutate({\n          variables: { commentId, commentContent },\n          optimisticResponse: (vars, { IGNORE }) => {\n            if (commentContent === \"foo\") {\n              // conditionally bail out of optimistic updates\n              return IGNORE;\n            }\n            return {\n              updateComment: {\n                id: commentId,\n                __typename: \"Comment\",\n                content: commentContent,\n              },\n            };\n          },\n        })\n      }\n    />\n  );\n}\n```\n\n## Example: Adding a new object to a list\n\nThe previous example shows how to provide an optimistic result for an object that's _already_ in the Apollo Client cache. But what about a mutation that creates a _new_ object? This works similarly.\n\nThe biggest difference here is that the client doesn't yet have the new object's `id` (or other identifying field). This means you have to provide a temporary value for the `id` so the Apollo Client cache can store the optimistic result as an object of the correct type.\n\nFor example, here's an `optimisticResponse` for an `addTodo` mutation that creates a new item in a user's to-do list:\n\n```js\noptimisticResponse: {\n  addTodo: {\n    id: 'temp-id',\n    __typename: \"Todo\",\n    description: input.value // Obtained from user input\n  }\n}\n```\n\nWhen you execute the mutate function in this case, the Apollo Client cache stores a new `Todo` object with cache identifier `Todo:temp-id`. When the server responds with the new `Todo`'s _actual_ `id`, the optimistic object is removed as usual, and the canonical object is cached.\n\n### View on CodeSandbox\n\nYou can view a full to-do list example on CodeSandbox:\n\n<a href=\"https://codesandbox.io/s/github/apollographql/docs-examples/tree/main/full-stack/todo-list/todo-list-client?fontsize=14&hidenavigation=1&theme=dark\">\n  <img\n    alt=\"Edit todo-list-client\"\n    src=\"https://codesandbox.io/static/img/play-codesandbox.svg\"\n  />\n</a>\n\n> You can also run the example client and server locally by cloning the [`docs-examples` repo](https://github.com/apollographql/docs-examples/tree/main/full-stack/todo-list).\n\nWhen viewing the example, try adding an item to the to-do list. Notice that the item appears in the list instantly, even though the server doesn't _respond_ instantly.\n\nThen, try editing an existing item in the to-do list. Notice that the item _doesn't_ update instantly. That's because the client doesn't provide an `optimisticResponse` for the `updateTodo` mutation. This helps illustrate the improved responsiveness that an `optimisticResponse` provides.\n"
  },
  {
    "path": "docs/source/performance/performance.mdx",
    "content": "---\ntitle: Improving performance in Apollo Client\n---\n\n## Redirecting to cached data\n\nIn some cases, a query might request data that's already present in the Apollo Client cache thanks to a _different_ query that already ran. For example, your UI might have both a list view and a detail view with queries that fetch the same fields from a particular object.\n\nIn cases like these, you can avoid sending your server a followup query that fetches identical data. To learn how, see [Cache redirects](../caching/advanced-topics#cache-redirects).\n\n## Prefetching data\n\nPrefetching involves executing queries for data _before_ that data needs to be rendered. It helps your application's UI feel more responsive to the user.\n\nMost of the time, prefetching involves querying for data as soon as you can guess that a user will _probably_ need it.\n\nFor example, this code snippet calls `client.query` to execute a query when the user hovers over a particular link (to a page that uses the data returned by the query):\n\n<ExpansionPanel title=\"Click to expand\">\n\n```jsx {19-24}\nfunction Feed() {\n  const { loading, error, data, client } = useQuery(GET_DOGS);\n\n  let content;\n  if (loading) {\n    content = <Fetching />;\n  } else if (error) {\n    content = <Error />;\n  } else {\n    content = (\n      <DogList\n        data={data.dogs}\n        renderRow={(type, data) => (\n          <Link\n            to={{\n              pathname: `/${data.breed}/${data.id}`,\n              state: { id: data.id },\n            }}\n            onMouseOver={() =>\n              client.query({\n                query: GET_DOG,\n                variables: { breed: data.breed },\n              })\n            }\n            style={{ textDecoration: \"none\" }}\n          >\n            <Dog {...data} url={data.displayImage} />\n          </Link>\n        )}\n      />\n    );\n  }\n\n  return (\n    <View style={styles.container}>\n      <Header />\n      {content}\n    </View>\n  );\n}\n```\n\n</ExpansionPanel>\n\nWhen the `GET_DOG` query completes, its result is stored in the Apollo Client cache. This means that if the user then clicks the link, the dog's detail page can immediately populate that data from the cache, which feels instantaneous to the user.\n\nIn addition to a mouse hover, here are some other suggestions for situations when prefetching can be helpful:\n\n- During a multi-step flow (such as a wizard), you can preload each _next_ step's data during each _current_ step.\n- If your app's analytics indicate a frequent transition between two particular views, you can use prefetching to optimize for that path.\n- If a region of a page has multiple tabs or slides (such as a carousel), you can preload data for some or all of them to make transitions feel snappier.\n\nA special form of prefetching is [store hydration from the server](./server-side-rendering/#rehydrating-the-client-side-cache), so you might also consider hydrating more data than is actually needed for the first page load to make other interactions faster.\n\nFeel free to submit a PR with suggestions for other preloading opportunities!\n"
  },
  {
    "path": "docs/source/performance/server-side-rendering.mdx",
    "content": "---\ntitle: Server-side rendering\n---\n\n<Note>\nThis page describes manual server side rendering setups with React. If you are using a modern SSR-focused framework like [Next.js](https://nextjs.org/), [React Router Framework mode](https://reactrouter.com/en/main/routers/framework), or [TanStack Start](https://start.tanstack.com/), you need to use one of our Apollo Client Framework integrations instead.\nYou can find these integrations [on GitHub](https://github.com/apollographql/apollo-client-integrations):\n\n- [@apollo/client-integration-nextjs](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/nextjs)\n- [@apollo/client-integration-react-router](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/react-router)\n- [@apollo/client-integration-tanstack-start](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/tanstack-start)\n\n</Note>\n\n**Server-side rendering** (**SSR**) is a performance optimization for modern web apps. It enables you to render your app's initial state to raw HTML and CSS on the server _before_ serving it to a browser. This means users don't have to wait for their browser to download and initialize React (or Angular, Vue, etc.) before content is available:\n\n```mermaid\nsequenceDiagram\n    participant Browser;\n    participant Server;\n\n    Browser->>Server: Requests example.com;\n    Note over Server: Renders initial state of example.com on server;\n    Server->>Browser: Returns raw HTML and CSS;\n    Note over Browser: Displays raw HTML and CSS;\n    Note over Browser: Initializes view layer and \"rehydrates\" it with returned data\n```\n\nApollo Client provides a handy API for using it with server-side rendering, including a function that executes all of the GraphQL queries that are required to render your component tree. You don't need to make any changes to your queries to support this API.\n\n## Differences from client-side rendering\n\nWhen you render your React app on the server side, _most_ of the code is identical to its client-side counterpart, with a few important exceptions:\n\n- You need to use a server-compatible router for React, such as [React Router](https://reactrouter.com/web/guides/server-rendering).\n\n  (In the case of React Router, you wrap your application in a `StaticRouter` component instead of the `BrowserRouter` you use on the client side.)\n\n- You need to replace relative URLs with absolute URLs wherever applicable.\n\n- The initialization of Apollo Client changes slightly, as [described below](#initializing-apollo-client).\n\n## Initializing Apollo Client\n\nHere's an example _server-side_ initialization of Apollo Client:\n\n```js\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  ssrMode: true,\n  link: new HttpLink({\n    uri: \"http://localhost:3010\",\n    credentials: \"same-origin\",\n    headers: {\n      cookie: req.header(\"Cookie\"),\n    },\n  }),\n  cache: new InMemoryCache(),\n});\n```\n\nProvide `ssrMode: true` to prevent Apollo Client from polling on the server. This setting also tells the client to prioritize cache values over network requests when possible.\n\nYou also might need to configure your GraphQL endpoint to accept GraphQL operations from your SSR server (for example, by safelisting its domain or IP). Use absolute URLs for your GraphQL endpoint on the server, because relative network requests can only be made in a browser.\n\n> It's possible and valid for your GraphQL endpoint to be hosted by the _same server_ that's performing SSR. In this case, Apollo Client doesn't need to make network requests to execute queries. For details, see [Avoiding the network for local queries](#avoiding-the-network-for-local-queries).\n\n## Example\n\nLet's look at an example of SSR in a Node.js app. This example uses Express and React Router v4, although it can work with any server middleware and any router that supports SSR.\n\nFirst, here's an example `app.js` file, _without_ the code for rendering React to HTML and CSS:\n\n<ExpansionPanel title=\"Click to expand\">\n\n```jsx title=\"app.js\"\nimport { ApolloClient, HttpLink, InMemoryCache } from \"@apollo/client\";\nimport { ApolloProvider } from \"@apollo/client/react\";\nimport Express from \"express\";\nimport React from \"react\";\nimport { StaticRouter } from \"react-router\";\n\n// File shown below\nimport Layout from \"./routes/Layout\";\n\nconst app = new Express();\napp.use((req, res) => {\n  const client = new ApolloClient({\n    ssrMode: true,\n    link: new HttpLink({\n      uri: \"http://localhost:3010\",\n      credentials: \"same-origin\",\n      headers: {\n        cookie: req.header(\"Cookie\"),\n      },\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const context = {};\n\n  // The client-side App will instead use <BrowserRouter>\n  const App = (\n    <ApolloProvider client={client}>\n      <StaticRouter location={req.url} context={context}>\n        <Layout />\n      </StaticRouter>\n    </ApolloProvider>\n  );\n\n  // TODO: rendering code (see below)\n});\n\napp.listen(basePort, () =>\n  console.log(`app Server is now running on http://localhost:${basePort}`)\n);\n```\n\n</ExpansionPanel>\n\nSo far, whenever this example server receives a request, it first initializes Apollo Client and then creates a React tree that's wrapped with the `ApolloProvider` and `StaticRouter` components. The contents of that tree depend on the request's path and the `StaticRouter`'s defined routes.\n\n<Caution>\n\nIt's important to create an _entirely new instance_ of Apollo Client for each request. Otherwise, your response to a request might include sensitive cached query results from a _previous_ request.\n\n</Caution>\n\n### Executing queries with `prerenderStatic`\n\nYou can instruct Apollo Client to execute all of the queries executed by the `useQuery` or the suspenseful query hooks (like `useSuspenseQuery` and `useBackgroundQuery`) in the React tree's components with the `prerenderStatic` function.\n\nThis function rerenders your React tree until no more network requests are made. When you use suspenseful hooks with a suspense-ready rendering function, the tree is rendered once and suspends while network requests are executed. When you use non-suspenseful hooks (like `useQuery`), this function renders all components, waits for all requests to finish, and then re-renders the tree until no more requests are made.\n\nThe function returns a `Promise` that resolves when all result data is ready in the Apollo Client cache and the final render is complete.\n\n#### Choosing a rendering function\n\n`prerenderStatic` supports multiple React rendering functions:\n\n- **`prerender`** from `react-dom/static` - Recommended for Deno or modern edge runtimes with Web Streams. Supports React Suspense.\n- **`prerenderToNodeStream`** from `react-dom/static` - Recommended for Node.js. Supports React Suspense.\n- **`renderToString`** from `react-dom/server` - Legacy API without Suspense support. Won't work with suspenseful hooks.\n- **`renderToStaticMarkup`** from `react-dom/server` - Legacy API without Suspense support. Slightly faster than `renderToString`, but the result cannot be hydrated.\n\nThe following code replaces the `TODO` comment within the `app.use` call in the example above:\n\n```js title=\"app.js\"\n// Add these imports to the top of the file\nimport { prerenderStatic } from \"@apollo/client/react/ssr\";\nimport { prerenderToNodeStream } from \"react-dom/static\";\n\n// Replace the TODO with this\nprerenderStatic({\n  tree: App,\n  // this is optional if your `App` component contains an <ApolloProvider>\n  context: { client },\n  renderFunction: prerenderToNodeStream,\n}).then(async ({ result }) => {\n  // Extract the entirety of the Apollo Client cache's current state\n  const initialState = client.extract();\n\n  // TODO: Send the response to the client (see below for examples)\n});\n```\n\n#### Sending the response\n\nAfter `prerenderStatic` completes, you need to send the HTML response to the client. The approach depends on the rendering function you chose.\n\n##### Using streaming with `renderToPipeableStream`\n\nFor Node.js environments, you can stream the response to the client using `renderToPipeableStream`. This allows the browser to start displaying content before the entire page is rendered:\n\n```js title=\"app.js\"\nimport { renderToPipeableStream } from \"react-dom/server\";\n\n// After prerenderStatic completes\nprerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: prerenderToNodeStream,\n}).then(async ({ result }) => {\n  const initialState = client.extract();\n\n  // Render the app again with streaming, injecting the Apollo state\n  const { pipe } = renderToPipeableStream(\n    <html>\n      <head>\n        <title>My App</title>\n      </head>\n      <body>\n        <div id=\"root\">\n          <App />\n        </div>\n      </body>\n    </html>,\n    {\n      bootstrapScriptContent: `window.__APOLLO_STATE__=${JSON.stringify(\n        initialState\n      ).replace(/</g, \"\\\\u003c\")}`,\n      bootstrapScripts: [\"/client.js\"],\n      onShellReady() {\n        // Start streaming the response to the browser\n        res.setHeader(\"Content-Type\", \"text/html\");\n        res.statusCode = 200;\n        pipe(res);\n      },\n      onError(error) {\n        console.error(\"Rendering error:\", error);\n      },\n    }\n  );\n});\n```\n\n<Note>\nInstead of rendering `<div id=\"root\"><App /></div>`, you can also render `<div id=\"root\" dangerouslySetInnerHTML={{ __html: result }} />` to avoid rendering the entire tree twice.\nHowever, if you go this approach, React cannot decide on the order in which components are streamed to the browser, which might be suboptimal.\nIn the end, it's a tradeoff between more work on the server and a potential delay in displaying content in the browser that you need to make based on your individual requirements.\n</Note>\n\n<Tip>\nIf you are only using suspenseful hooks (like `useSuspenseQuery` or `useBackgroundQuery`) and no `useQuery` hooks, is also possible to use the [@apollo/client-react-streaming](https://github.com/apollographql/apollo-client-integrations/tree/main/packages/client-react-streaming) package to stream data dynamically while it is fetching, without requiring a first render pass with `prerenderStatic`.\nYou can find an example application that uses this approach in the [integration tests for that package](https://github.com/apollographql/apollo-client-integrations/tree/main/integration-test/vite-streaming).\n</Tip>\n\n<Note>\nThe `replace` call in these examples escapes the `<` character to prevent cross-site scripting attacks that are possible via the presence of `</script>` in a string literal.\n</Note>\n\n##### Using `renderToString` for synchronous rendering\n\nFor simpler use cases or environments without stream support, you can use `renderToString` to render the entire page synchronously:\n\n```js title=\"app.js\"\nimport { renderToString } from \"react-dom/server\";\n\n// After prerenderStatic completes\nprerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: renderToString,\n}).then(async ({ result }) => {\n  const initialState = client.extract();\n\n  // Create a complete HTML document with the cache state\n  const Html = () => (\n    <html>\n      <head>\n        <title>My App</title>\n      </head>\n      <body>\n        <div id=\"root\" dangerouslySetInnerHTML={{ __html: result }} />\n        <script\n          dangerouslySetInnerHTML={{\n            __html: `window.__APOLLO_STATE__=${JSON.stringify(\n              initialState\n            ).replace(/</g, \"\\\\u003c\")};`,\n          }}\n        />\n        <script src=\"/client.js\" />\n      </body>\n    </html>\n  );\n\n  // Render to string and send\n  const html = renderToString(<Html />);\n\n  res.setHeader(\"Content-Type\", \"text/html\");\n  res.status(200);\n  res.send(`<!DOCTYPE html>${html}`);\n  res.end();\n});\n```\n\n<Note>\nThe `replace` call in these examples escapes the `<` character to prevent cross-site scripting attacks that are possible via the presence of `</script>` in a string literal.\n</Note>\n\n#### Advanced options\n\n`prerenderStatic` provides several options to customize the rendering process:\n\n##### Diagnostics\n\nYou can enable diagnostics to detect inefficient rendering structures (like `useQuery` waterfalls) in your app:\n\n```js\nconst { diagnostics } = await prerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: prerenderToNodeStream,\n  diagnostics: true,\n});\n\nconsole.log(`Rendered ${diagnostics.renderCount} times`);\n// If renderCount is high, consider using fragment colocation\n```\n\n**Timeout support**\n\nYou can use an `AbortSignal` to stop the render loop early:\n\n```js\nconst signal = AbortSignal.timeout(2000); // 2 second timeout\n\nconst { result, aborted } = await prerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: (tree) => prerenderToNodeStream(tree, { signal }),\n  signal,\n});\n\nif (aborted) {\n  console.log(\"Render timed out, returning partial result\");\n}\n```\n\n##### Maximum rerenders\n\nIf you have deep `useQuery` waterfalls, you can increase the `maxRerenders` option (default: 50):\n\n```js\nawait prerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: prerenderToNodeStream,\n  maxRerenders: 100,\n});\n```\n\n### Rehydrating the client-side cache\n\nAlthough the server-side cache's state is available in `__APOLLO_STATE__`, it isn't yet available in the _client-side_ cache. `InMemoryCache` provides a helpful `restore` function for **rehydrating** its state with data `extract`ed from another cache instance.\n\nIn your client-side initialization of Apollo Client, you can rehydrate the cache like so:\n\n```js\nconst client = new ApolloClient({\n  cache: new InMemoryCache().restore(window.__APOLLO_STATE__),\n  uri: \"https://example.com/graphql\",\n});\n```\n\nNow when the client-side version of the app runs its initial queries, the data is returned instantly because it's already in the cache!\n\n##### Partial Pre-rendering with `prerender` and `resumeAndPrerender`\n\n<Tip>\n\nIf you work with node streams, use `prerenderToNodeStream` and `resumeAndPrerenderToNodeStream` instead of `prerender` and `resumeAndPrerender`.\n\n</Tip>\n\n<Note>\n\nThe APIs in this section require React 19.2.0 or later.\n\n</Note>\n\nUsing the [`resume`](https://react.dev/reference/react-dom/server/resume) function from `react-dom/server`, you can prerender some parts of your application (e.g., data common to all users) and then resume SSR for the remaining parts (e.g., user-specific data) later.\n\nStart by using `prerender` to render the initial HTML and execute initial queries:\n\n```js\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link,\n});\nconst controller = new AbortController();\nconst promise = prerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: (tree) =>\n    renderFunction(tree, {\n      signal: controller.signal,\n    }),\n  signal: controller.signal,\n});\n```\n\nWhen all fetchable data is ready, call `controller.abort()` to stop the initial render and save the result:\n\n```js\ncontroller.abort();\nconst { result, renderFnResult, aborted } = await promise;\n```\n\nIf `aborted` is `false`, the render completed and you can send the result. If `aborted` is `true`, save the current render result, postponed work, and cache state to resume later:\n\n```js\nconst initialResponse = result; // HTML up to this point\nconst postponed = renderFnResult.postponed; // Postponed render work\nconst cacheState = client.extract(); // Cache state after initial render\n```\n\nTo resume rendering (e.g., in a subsequent request with user-specific data):\n\n```js\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link,\n});\n// Restore the cache state from the first render\nclient.cache.restore(cacheState);\n\nconst controller = new AbortController();\nconst promise = prerenderStatic({\n  tree: App,\n  context: { client },\n  renderFunction: (tree) =>\n    resumeAndPrerender(tree, postponed, {\n      signal: controller.signal,\n    }),\n  signal: controller.signal,\n});\n```\n\nYou can either let the render complete or abort it again for another partial result:\n\n```js\ncontroller.abort(); // or let it complete\nconst { result, renderFnResult, aborted } = await promise;\n```\n\nIf `aborted` is `false`, the render completed and you can send the result. If `aborted` is `true`, save the current render result and postponed work, then repeat the resume step as needed.\n\n> [!NOTE]\n> The `result` from `resumeAndPrerender` does not include HTML from previous renders. You must concatenate the HTML strings from all partial renders to get the complete output.\n\n#### Overriding fetch policies during initialization\n\nIf some of your initial queries use the `network-only` or `cache-and-network` [fetch policy](../data/queries/#setting-a-fetch-policy), you can provide the `ssrForceFetchDelay` option to Apollo Client to skip force-fetching those queries during initialization. This way, even those queries initially run using only the cache:\n\n```js\nconst client = new ApolloClient({\n  cache: new InMemoryCache().restore(window.__APOLLO_STATE__),\n  link,\n  ssrForceFetchDelay: 100, // in milliseconds\n});\n```\n\n## Avoiding the network for local queries\n\nIf your GraphQL endpoint is hosted by the same server that you're rendering from, you can optionally avoid using the network when executing your SSR queries. This is particularly helpful if `localhost` is firewalled in the server's environment (e.g., on Heroku).\n\nWhen creating an Apollo Client on the server, use a [SchemaLink](../api/link/apollo-link-schema/) instead of an `HttpLink`. `SchemaLink` uses your schema and context to run the query immediately, without the need for a network request:\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { SchemaLink } from \"@apollo/client/link/schema\";\n\n// ...\n\nconst client = new ApolloClient({\n  // Instead of HttpLink use SchemaLink here\n  link: new SchemaLink({ schema }),\n  cache: new InMemoryCache(),\n});\n```\n\n## Selectively disabling query execution during SSR\n\nIf you want to prevent a particular query from executing during SSR, use `ssr: false` in that query's options. This is useful for queries that should only run on the client side, such as user-specific data that isn't available during SSR.\n\nWhen `ssr: false` is set, the component receives a result with `loading: true`, `dataState: \"empty\"`, and `data: undefined` during server-side rendering. The query will execute normally once the component hydrates on the client.\n\n```jsx\nfunction ClientOnlyUser() {\n  const { loading, data } = useQuery(GET_USER_WITH_ID, { ssr: false });\n\n  if (loading) {\n    return <span>Loading...</span>;\n  }\n\n  return <span>User: {data?.user?.name || \"Not loaded\"}</span>;\n}\n```\n\n<Note>\n\n`ssr: false` behaves differently than `skip: true`, which prevents the query from executing on both the server and client until `skip` is set to `false`. During SSR, `skip: true` results in `loading: false` and `networkStatus: NetworkStatus.ready`.\n\n</Note>\n\n## Legacy APIs\n\nApollo Client provides two legacy SSR functions that are both replaced by `prerenderStatic`:\n\n- **`getDataFromTree`** - Executes all queries in a component tree and returns when data is ready. Uses `renderToStaticMarkup` by default.\n- **`renderToStringWithData`** - Similar to `getDataFromTree`, but returns the rendered string using `renderToString`.\n\nThese functions are deprecated. Use `prerenderStatic` instead, which offers better flexibility and performance with modern React rendering APIs.\n"
  },
  {
    "path": "docs/source/why-apollo.mdx",
    "content": "---\ntitle: Why Apollo Client?\nsubtitle: Discover why Apollo Client is the ideal choice for managing data with GraphQL\ndescription: Learn how Apollo Client simplifies data management with GraphQL, offers intelligent caching, and unifies remote and local data.\n---\n\nApollo Client is a state management library that simplifies managing remote and local data with GraphQL. Apollo Client's intelligent caching and declarative approach to data fetching can help you iterate faster while writing less code. Additionally, if you need custom functionality, you can create your dream client by building extensions on top of Apollo Client.\n\nLet's jump right into what Apollo Client can offer you! 🚀\n\n## Declarative data fetching\n\nApollo Client handles the request cycle from start to finish, including tracking loading and error states. There's no middleware or boilerplate code to set up before making your first request, and you don't need to worry about transforming or caching responses. All you have to do is describe the data your component needs and let Apollo Client do the heavy lifting. 💪\n\nApollo Client's `useQuery` hook leverages React's [Hooks API](https://react.dev/reference/react) to bind a query to a component, enabling that component to render a query's results immediately. The `useQuery` hook encapsulates the logic for retrieving your data, tracking loading and error states, and updating your UI. This encapsulation makes integrating query results into your presentational components a breeze!\n\nLet's see what this looks like in practice with Apollo Client for React:\n\n```jsx\nfunction ShowDogs() {\n  const { loading, error, data } = useQuery(GET_DOGS);\n  if (error) return <Error />;\n  if (loading) return <Fetching />;\n\n  return <DogList dogs={data.dogs} />;\n}\n```\n\nIn the example above, we're using the `useQuery` hook to fetch dogs from our GraphQL server and display them in a list. Once our data comes back, our `<DogList />` component reactively updates to display the new data.\n\nWhen switching to Apollo Client, you'll find you can remove much of your previous code related to data management. Some teams have reported deleting thousands of lines of code!\n\nThough you'll find yourself writing less code with Apollo Client, that doesn't mean you have to compromise on features. [The `useQuery` hook](./data/queries#usequery-api) supports advanced features like an optimistic UI, refetching, and pagination.\n\n## Combining local & remote data\n\nThousands of developers have told us that Apollo Client excels at managing remote data, equating to roughly 80% of their data needs. But what about local data (e.g., global flags or device API results), which makes up the other 20% of the pie?\n\nApollo Client includes [local state management](local-state/local-state-management/) features straight out of the box, enabling you to use your Apollo cache as the single source of truth for your application's data.\n\nBy using Apollo Client's local state functionality, you can include local fields _and_ remotely fetched fields in the same query:\n\n```js\nconst GET_DOG = gql`\n  query GetDogByBreed($breed: String!) {\n    dog(breed: $breed) {\n      images {\n        url\n        id\n        isLiked @client\n      }\n    }\n  }\n`;\n```\n\nIn the above example, we're querying the [local-only field](./local-state/managing-state-with-field-policies) `isLiked` while fetching data from our GraphQL server. Your components contain local and remote data; now, your queries can too!\n\nManaging your data with Apollo Client lets you take advantage of GraphQL as a unified interface for _all_ of your data. Using the [Apollo Client Devtools](./development-testing/developer-tooling#apollo-client-devtools), you can inspect both your local and remote schemas using GraphiQL.\n\n## Zero-config caching\n\nCaching a graph is no easy task, but we've spent years solving this problem. We've found that _normalization_ is the key to maintaining consistent data across multiple components in an application.\n\nOne of the key features that sets Apollo Client apart from other data management solutions is its local, in-memory, [normalized](./caching/overview#data-normalization) cache.\n\nThe Apollo Client cache is easy to get started with and [configure](./caching/cache-configuration) as you go:\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n});\n```\n\nOnce you've passed your cache to `ApolloClient`, whenever Apollo Client receives query response data, it automatically attempts to identify and store the distinct objects (i.e., those with a `__typename` and an id property) from a query's data into separate entries within its cache.\n\nLet's look at some practical examples of how this caching mechanism can make your application more efficient.\n\nThe below query, `GET_ALL_DOGS`, fetches a list of dogs and information about each dog:\n\n```js\nconst GET_ALL_DOGS = gql`\n  query GetAllDogs {\n    dogs {\n      id\n      breed\n      displayImage\n    }\n  }\n`;\n```\n\nThe below mutation, `UPDATE_DISPLAY_IMAGE`, updates a specified dog's `displayImage` and returns the updated dog:\n\n```js\nconst UPDATE_DISPLAY_IMAGE = gql`\n  mutation UpdateDisplayImage($id: String!, $displayImage: String!) {\n    updateDisplayImage(id: $id, displayImage: $displayImage) {\n      id\n      displayImage\n    }\n  }\n`;\n```\n\nWhen we run the `UPDATE_DISPLAY_IMAGE` mutation, we want to ensure that our dog's image is updated _everywhere_ in our application. We also need to ensure we update any previously cached data about that dog.\n\nOur `UPDATE_DISPLAY_IMAGE` mutation returns the object the mutation modified (i.e., the `id` and `displayImage` of the dog), enabling Apollo Client to automatically overwrite the existing fields of any _previously cached_ object with the same `id`. Tying it all together, if we've already run the `GET_ALL_DOGS` query before Apollo Client runs the `UPDATE_DISPLAY_IMAGE` mutation, it _automatically_ updates the changed dog's `displayImage` in our local cache. ✨\n\n> For more examples of updating a cache with mutations, see [Updating the cache directly](./data/mutations#updating-the-cache-directly).\n\nThe ability to update our cache under the hood can also help in scenarios where we want to avoid _refetching_ information already contained in our cache.\n\nFor example, let's say we want to navigate to the details page for a particular dog. Here's what the query would look like:\n\n```js\nconst GET_DOG = gql`\n  query GetDog {\n    dog(id: \"abc\") {\n      id\n      breed\n      displayImage\n    }\n  }\n`;\n```\n\nIf we've run the above `GET_ALL_DOGS` query at any point, the data for our `GET_DOG` query might _already_ be in our local cache. We can tell Apollo Client where to check first for any cached `Dog` objects, avoiding refetching information if it already exists in our cache.\n\nBelow we define a custom [`FieldPolicy`](./caching/advanced-topics/#cache-redirects) that returns a reference to our previously cached `Dog` object data:\n\n```js\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nconst cache = new InMemoryCache({\n  typePolicies: {\n    Query: {\n      fields: {\n        dog(_, { args, toReference }) {\n          return toReference({\n            __typename: \"Dog\",\n            id: args.id,\n          });\n        },\n      },\n    },\n  },\n});\n\nconst client = new ApolloClient({ cache });\n```\n\nThe above field policy enables our `GET_DOG` query to read previously stored data straight from our cache instead of sending off an unnecessary query.\n\n> Learn more about [Caching in Apollo Client](https://www.apollographql.com/docs/react/caching/overview).\n\n## Vibrant ecosystem\n\nApollo Client is easy to get started with but extensible enough for when you want to build out more advanced features. If you need custom functionality that `@apollo/client` doesn't cover, you can use [Apollo Link's architecture](./api/link/introduction) to create your dream client by building an extension on top of Apollo Client.\n\nWe're always impressed by what our contributors have built on top of Apollo Client. Check out some of our community's extensions below:\n\n- [`apollo3-cache-persist`](https://github.com/apollographql/apollo-cache-persist): Simple persistence for your Apollo cache ([@jamesreggio](https://github.com/jamesreggio)).\n- [`apollo-storybook-decorator`](https://github.com/abhiaiyer91/apollo-storybook-decorator): Wrap your React Storybook stories with Apollo Client ([@abhiaiyer91](https://github.com/abhiaiyer91)).\n- [AppSync by AWS](https://blog.apollographql.com/aws-appsync-powered-by-apollo-df61eb706183): Amazon's real-time GraphQL client uses Apollo Client under the hood.\n- [`apollo-augmented-hooks`](https://github.com/appmotion/apollo-augmented-hooks): Adding additional functionality for Apollo Client's hooks ([appmotion](https://github.com/appmotion)).\n- [`apollo-cache-policies`](https://github.com/NerdWalletOSS/apollo-cache-policies): Extending Apollo Client's cache with support for advanced cache policies ([NerdWalletOSS](https://github.com/NerdWalletOSS)).\n\nWhen you choose to use Apollo Client to manage your data, you also gain the support of our fantastic community. There are thousands of developers in our [community forums](https://community.apollographql.com) for you to share ideas with.\n\nYou can also read articles on best practices and announcements on the frequently updated [Apollo blog](https://blog.apollographql.com/).\n\n## Case studies\n\nCompanies ranging from enterprises to startups trust Apollo Client to power their most critical web and native applications. If you'd like to learn more about how transitioning to GraphQL and Apollo simplified engineers' workflows and improved companies' products, check out these case studies:\n\n- [The New York Times](https://open.nytimes.com/the-new-york-times-now-on-apollo-b9a78a5038c): Learn how The New York Times switched from Relay to Apollo & implemented features in their app such as SSR and persisted queries.\n- [Express](https://blog.apollographql.com/changing-the-architecture-of-express-com-23c950d43323): Easy-to-use pagination with Apollo helped improve the Express eCommerce team's key product pages.\n- [Major League Soccer](https://blog.apollographql.com/reducing-our-redux-code-with-react-apollo-5091b9de9c2a): MLS' switch from Redux to Apollo for state management enabled them to delete nearly all of their Redux code.\n- [Expo](https://blog.apollographql.com/using-graphql-apollo-at-expo-4c1f21f0f115): Developing their React Native app with Apollo enabled the Expo engineers to focus on improving their product instead of writing data fetching logic.\n- [KLM](https://youtu.be/T2njjXHdKqw): Learn how the KLM team scaled their Angular app with GraphQL and Apollo.\n\nIf your company uses Apollo Client in production, we'd love to feature a case study on our blog! Please get in touch via [our community forums](https://community.apollographql.com) so we can learn more about how you're using Apollo. Alternatively, please file a PR if you already have a blog post or a conference talk that you'd like to feature here.\n"
  },
  {
    "path": "docs/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"jsx\": \"preserve\",\n    \"plugins\": [\n      {\n        \"name\": \"@mdx-js/typescript-plugin\"\n      }\n    ]\n  },\n  \"include\": [\"**/*.mdx\", \"**/*.ts\", \"**/*.tsx\"],\n  \"mdx\": {\n    // Enable strict type checking in MDX files.\n    \"checkMdx\": true\n  }\n}\n"
  },
  {
    "path": "eslint-local-rules/canonical-references.ts",
    "content": "import type { TSESTree as AST } from \"@typescript-eslint/types\";\nimport { ESLintUtils } from \"@typescript-eslint/utils\";\nimport type { SourceCode } from \"@typescript-eslint/utils/ts-eslint\";\n\nimport references from \"../docs/public/canonical-references.json\" with { type: \"json\" };\n\nconst referenceSet = new Set(references);\n\nexport const validInheritDoc = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    const source = context.sourceCode;\n    let handled = new Set();\n    return {\n      \"*\"(node) {\n        for (const comment of source.getCommentsBefore(node)) {\n          if (handled.has(comment)) {\n            continue;\n          }\n          handled.add(comment);\n          if (comment.type === \"Block\") {\n            const text = source.getText(comment);\n            let match: RegExpMatchArray | null;\n            if ((match = text.match(/@inheritDoc\\s+([^\\s}]+)/d))) {\n              const canonicalReference = match[1];\n              if (!referenceSet.has(canonicalReference)) {\n                context.report({\n                  node: comment,\n                  loc: locForMatch(source, comment, match, 1),\n                  messageId: \"invalidCanonicalReference\",\n                });\n              }\n            }\n            if (\n              (match = text.match(/@inheritdoc/di)) &&\n              match[0] !== \"@inheritDoc\"\n            ) {\n              const loc = locForMatch(source, comment, match, 0);\n              context.report({\n                node: comment,\n                loc,\n                messageId: \"invalidSpelling\",\n                fix(fixer) {\n                  return fixer.replaceTextRange(\n                    [\n                      source.getIndexFromLoc(loc.start),\n                      source.getIndexFromLoc(loc.end),\n                    ],\n                    \"@inheritDoc\"\n                  );\n                },\n              });\n            }\n          }\n        }\n      },\n    };\n  },\n  meta: {\n    messages: {\n      invalidCanonicalReference: \"Unknown canonical reference.\",\n      invalidSpelling: \"Invalid spelling of @inheritDoc.\",\n    },\n    type: \"problem\",\n    schema: [],\n    fixable: \"code\",\n  },\n  defaultOptions: [],\n});\n\nexport const validMdxCanonicalReferences = ESLintUtils.RuleCreator.withoutDocs({\n  create(context, optionsWithDefault) {\n    return {\n      JSXAttribute(node: AST.JSXAttribute) {\n        if (node.name.name == \"canonicalReference\") {\n          const ref =\n            node.value.type === \"JSXExpressionContainer\" ?\n              node.value.expression\n            : node.value;\n          if (!ref || ref.type !== \"Literal\" || typeof ref.value !== \"string\") {\n            context.report({\n              node: ref || node,\n              messageId: \"shouldBeString\",\n            });\n          } else if (!referenceSet.has(ref.value)) {\n            context.report({\n              node: ref,\n              messageId: \"invalidCanonicalReference\",\n            });\n          }\n        }\n      },\n    };\n  },\n  meta: {\n    messages: {\n      shouldBeString: \"The canonicalReference value should be a string.\",\n      invalidCanonicalReference: \"Unknown canonical reference.\",\n    },\n    type: \"problem\",\n    schema: [],\n  },\n  defaultOptions: [],\n});\n\nfunction locForMatch(\n  source: SourceCode,\n  node: AST.NodeOrTokenData,\n  match: RegExpMatchArray,\n  index: number\n) {\n  return {\n    start: source.getLocFromIndex(\n      source.getIndexFromLoc(node.loc.start) + match.indices[index][0]\n    ),\n    end: source.getLocFromIndex(\n      source.getIndexFromLoc(node.loc.start) + match.indices[index][1]\n    ),\n  };\n}\n"
  },
  {
    "path": "eslint-local-rules/fixtures/file.ts",
    "content": ""
  },
  {
    "path": "eslint-local-rules/fixtures/react.tsx",
    "content": ""
  },
  {
    "path": "eslint-local-rules/fixtures/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"target\": \"esnext\"\n  },\n  \"include\": [\"file.ts\", \"react.tsx\"]\n}\n"
  },
  {
    "path": "eslint-local-rules/forbid-act-in-disabled-act-environment.test.ts",
    "content": "import { rule } from \"./forbid-act-in-disabled-act-environment.ts\";\nimport { ruleTester } from \"./testSetup.ts\";\n\nruleTester.run(\"forbid-act-in-disabled-act-environment\", rule, {\n  valid: [\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n  }\n  () => {\n    act(() => {})\n  }\n    `,\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n  }\n  () => {\n    actAsync(() => {})\n  }\n    `,\n  ],\n  invalid: [\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n      act(() => {})\n    }\n      `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n      actAsync(() => {})\n    }\n    `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n      () => {\n        act(() => {})\n      }\n    }\n      `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n      () => {\n        actAsync(() => {})\n      }\n    }\n    `,\n  ].map((code) => ({\n    code,\n    errors: [{ messageId: \"forbiddenActInNonActEnvironment\" }],\n  })),\n});\n"
  },
  {
    "path": "eslint-local-rules/forbid-act-in-disabled-act-environment.ts",
    "content": "import { ESLintUtils } from \"@typescript-eslint/utils\";\n\nexport const rule = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    let depth = 1;\n    let disabledDepth: number | false = false;\n\n    function EnterFn() {\n      depth++;\n    }\n    function ExitFn() {\n      depth--;\n      if (disabledDepth !== false && disabledDepth > depth) {\n        disabledDepth = false;\n      }\n    }\n\n    return {\n      CallExpression(node) {\n        const directCallee =\n          node.callee.type === \"Identifier\" ? node.callee\n          : node.callee.type === \"MemberExpression\" ? node.callee.property\n          : null;\n\n        if (\n          directCallee?.type === \"Identifier\" &&\n          directCallee.name === \"disableActEnvironment\"\n        ) {\n          if (disabledDepth === false) {\n            disabledDepth = depth;\n          }\n        }\n\n        if (\n          directCallee?.type === \"Identifier\" &&\n          (directCallee.name === \"act\" || directCallee.name === \"actAsync\")\n        ) {\n          if (disabledDepth !== false) {\n            context.report({\n              messageId: \"forbiddenActInNonActEnvironment\",\n              node: node,\n            });\n          }\n        }\n      },\n      ArrowFunctionExpression: EnterFn,\n      FunctionExpression: EnterFn,\n      FunctionDeclaration: EnterFn,\n      \"ArrowFunctionExpression:exit\": ExitFn,\n      \"FunctionExpression:exit\": ExitFn,\n      \"FunctionDeclaration:exit\": ExitFn,\n    };\n  },\n  meta: {\n    messages: {\n      forbiddenActInNonActEnvironment:\n        \"`act` should not be called in a `disableActEnvironment`.\",\n    },\n    type: \"problem\",\n    schema: [],\n  },\n  defaultOptions: [],\n});\n"
  },
  {
    "path": "eslint-local-rules/generics.ts",
    "content": "import { ESLintUtils } from \"@typescript-eslint/utils\";\n\nexport const TVariablesShouldExtendOperationVariables =\n  ESLintUtils.RuleCreator.withoutDocs({\n    create(context) {\n      return {\n        TSTypeParameter(node) {\n          if (node.parent.type !== \"TSTypeParameterDeclaration\") {\n            return;\n          }\n          if (\n            node.name.name === \"TVariables\" &&\n            !(\n              node.constraint &&\n              node.constraint.type === \"TSTypeReference\" &&\n              node.constraint.typeName.type === \"Identifier\" &&\n              node.constraint.typeName.name === \"OperationVariables\"\n            )\n          ) {\n            context.report({\n              messageId: \"TVariablesShouldExtendOperationVariables\",\n              node: node,\n              fix:\n                node.constraint ? undefined : (\n                  (fixer) => {\n                    return fixer.insertTextAfter(\n                      node.name,\n                      \" extends OperationVariables\"\n                    );\n                  }\n                ),\n            });\n          }\n        },\n      };\n    },\n    meta: {\n      messages: {\n        TVariablesShouldExtendOperationVariables:\n          \"`TVariables` should extend `OperationVariables`.\",\n      },\n      type: \"problem\",\n      fixable: \"code\",\n      schema: [],\n    },\n    defaultOptions: [],\n  });\n\nexport const TDataTVariablesOrder = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    return {\n      TSTypeParameter(node) {\n        if (node.parent.type !== \"TSTypeParameterDeclaration\") {\n          return;\n        }\n        if (node.name.name === \"TData\") {\n          const tVariables = node.parent.params.find(\n            (param) => param.name.name === \"TVariables\"\n          );\n          if (\n            tVariables &&\n            node.parent.params.indexOf(tVariables) -\n              node.parent.params.indexOf(node) !==\n              1\n          ) {\n            context.report({\n              messageId: \"TDataTVariablesOrder\",\n              node: node,\n            });\n          }\n        }\n      },\n    };\n  },\n  meta: {\n    messages: {\n      TDataTVariablesOrder:\n        \"`TVariables` should follow directly after `TData`.\",\n    },\n    type: \"problem\",\n    schema: [],\n  },\n  defaultOptions: [],\n});\n"
  },
  {
    "path": "eslint-local-rules/import-from-export.test.ts",
    "content": "import { resolve } from \"node:path\";\n\nimport {\n  importFromExport,\n  importFromInsideOtherExport,\n} from \"./import-from-export.ts\";\nimport { mkRuleTester } from \"./testSetup.ts\";\n\nconst tester = mkRuleTester((config) => {\n  config.languageOptions.parserOptions.tsconfigRootDir = resolve(\n    import.meta.dirname,\n    \"../src/core\"\n  );\n  config.languageOptions.parserOptions.project = resolve(\n    import.meta.dirname,\n    \"../tsconfig.json\"\n  );\n  config.defaultFilenames = {\n    ts: \"ApolloClient.ts\",\n  };\n  return config;\n});\ntester.run(\"import-from-exports\", importFromExport, {\n  valid: [\n    `\n      import { ApolloLink } from \"@apollo/client/link\";\n    `,\n    `\n      import { QueryManager } from \"./QueryManager.js\";\n    `,\n  ],\n  invalid: [\n    {\n      code: `\n        import { ApolloLink } from \"../link/core/index.js\";\n      `,\n      errors: [{ messageId: \"importFromExport\" }],\n      output: `\n        import { ApolloLink } from \"@apollo/client/link\";\n      `,\n    },\n  ],\n});\ntester.run(\"import-from-inside-other-export\", importFromInsideOtherExport, {\n  valid: [\n    `\n      import { ApolloLink } from \"@apollo/client/link\";\n    `,\n    `\n      import { QueryManager } from \"./QueryManager.js\";\n    `,\n  ],\n  invalid: [\n    {\n      code: `\n        import { ApolloLink } from \"../link/core/link.js\";\n      `,\n      errors: [{ messageId: \"importFromInsideOtherExport\" }],\n    },\n  ],\n});\n"
  },
  {
    "path": "eslint-local-rules/import-from-export.ts",
    "content": "import { dirname, join, relative, resolve, sep } from \"node:path\";\n\nimport type { TSESTree as AST } from \"@typescript-eslint/types\";\nimport { ESLintUtils } from \"@typescript-eslint/utils\";\nimport { $ } from \"zx\";\n\nimport pkgJson from \"../package.json\" with { type: \"json\" };\n\nconst entryPoints = Object.fromEntries(\n  Object.entries(pkgJson.exports).flatMap(function map(\n    this: any,\n    [key, value]\n  ) {\n    const path = `@apollo/client/${key.substring(2)}`.replace(/\\/$/, \"\");\n    if (typeof value === \"string\") {\n      return [\n        [\n          resolve(import.meta.dirname, \"..\", value).replace(/\\.ts$/, \".js\"),\n          path,\n        ],\n      ];\n    }\n    return Object.values(value).flatMap((v) => map([key, v]));\n  })\n);\n\nconst entryPointFolders = Object.keys(entryPoints)\n  .map(dirname)\n  .filter(function unique(value, index, array) {\n    return array.indexOf(value) === index;\n  });\n\nfunction findNearestEntryPointFolder(filename: string) {\n  let match: string | undefined = undefined;\n  let lookFor = dirname(filename);\n  while (!match && lookFor.indexOf(sep) != -1) {\n    match = entryPointFolders.find((folder) => folder == lookFor);\n    lookFor = lookFor.split(sep).slice(0, -1).join(sep);\n  }\n  return match;\n}\n\nexport const importFromExport = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    function rule(node: AST.ImportDeclaration | AST.ExportNamedDeclaration) {\n      if (!node.source || !node.source.value.startsWith(\".\")) {\n        return;\n      }\n      const resolvedTarget = resolve(\n        dirname(context.physicalFilename),\n        node.source.value\n      );\n      if (resolvedTarget in entryPoints) {\n        context.report({\n          node: node.source,\n          messageId: \"importFromExport\",\n          fix(fixer) {\n            return fixer.replaceTextRange(\n              node.source.range,\n              `\"${entryPoints[resolvedTarget]}\"`\n            );\n          },\n        });\n      }\n    }\n    return {\n      ImportDeclaration: rule,\n      ExportNamedDeclaration: rule,\n    };\n  },\n  meta: {\n    messages: {\n      importFromExport:\n        \"Don't use relative imports to import from official entrypoints.\",\n    },\n    type: \"problem\",\n    schema: [],\n    fixable: \"code\",\n  },\n  defaultOptions: [],\n});\n\nexport const noDuplicateExports = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    const seenExports = new Map<string, AST.ExportNamedDeclaration>();\n    return {\n      ExportNamedDeclaration(node) {\n        if (!node.source) {\n          return;\n        }\n        const name = node.source.value + \":\" + node.exportKind;\n        const alreadySeen = seenExports.get(name);\n        if (alreadySeen) {\n          context.report({\n            node: node,\n            messageId: \"noDuplicateExports\",\n            *fix(fixer) {\n              for (const specifier of node.specifiers) {\n                yield fixer.insertTextBefore(\n                  alreadySeen.specifiers[0],\n                  context.sourceCode.getText(specifier) + \",\"\n                );\n              }\n              yield fixer.remove(node);\n            },\n          });\n        }\n        seenExports.set(name, node);\n      },\n    };\n  },\n  meta: {\n    messages: {\n      noDuplicateExports:\n        \"Don't use multiple exports statements with the same source.\",\n    },\n    schema: [],\n    type: \"problem\",\n    fixable: \"code\",\n  },\n  defaultOptions: [],\n});\n\nexport const importFromInsideOtherExport = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    const currentFileEntrypoint = findNearestEntryPointFolder(\n      context.physicalFilename\n    );\n    function rule(node: AST.ImportDeclaration | AST.ExportNamedDeclaration) {\n      if (!node.source || !node.source.value.startsWith(\".\")) {\n        return;\n      }\n      const resolvedTarget = resolve(\n        dirname(context.physicalFilename),\n        node.source.value\n      );\n      if (context.options[0].ignoreFrom.includes(resolvedTarget)) {\n        return;\n      }\n      const importEntrypoint = findNearestEntryPointFolder(resolvedTarget);\n      if (currentFileEntrypoint !== importEntrypoint) {\n        context.report({\n          node: node.source,\n          messageId: \"importFromInsideOtherExport\",\n        });\n      }\n    }\n    return {\n      ImportDeclaration: rule,\n      ExportNamedDeclaration: rule,\n    };\n  },\n  meta: {\n    messages: {\n      importFromInsideOtherExport:\n        \"Don't use relative imports to import from internals outside the same entry point.\",\n    },\n    type: \"problem\",\n    schema: [\n      {\n        type: \"object\",\n        properties: {\n          ignoreFrom: {\n            type: \"array\",\n            items: { type: \"string\" },\n          },\n        },\n      },\n    ],\n  },\n  defaultOptions: [\n    {\n      ignoreFrom: [],\n    },\n  ],\n});\n\nconst knownPublicExports: Record<string, string[]> = {};\nfunction getPublicExports(path: string) {\n  if (!(path in knownPublicExports)) {\n    const result = $.sync({\n      cwd: resolve(import.meta.dirname, \"../dist\"),\n    })`node --input-type=module --eval 'console.log(JSON.stringify(Object.keys(await import(\"${path}\")).sort()))'`;\n    knownPublicExports[path] = JSON.parse(result.text()) as string[];\n  }\n  return knownPublicExports[path];\n}\n\n/**\n * to be used in tests, so the test does a\n * `import { InMemoryCache } from \"@apollo/client\";`\n * instead of a\n * `import { InMemoryCache } from \"../inMemoryCache.js\";`\n */\nexport const noInternalImportOfficialExport =\n  ESLintUtils.RuleCreator.withoutDocs({\n    create(context, options) {\n      return {\n        ImportDeclaration(node) {\n          if (!node.source.value.startsWith(\".\")) {\n            return;\n          }\n          const resolvedTarget = resolve(\n            dirname(context.physicalFilename),\n            node.source.value\n          );\n          if (resolvedTarget.includes(\"__tests__\")) {\n            return;\n          }\n          const entry = findNearestEntryPointFolder(resolvedTarget);\n          if (!entry || entry.includes(\"testing\")) {\n            return;\n          }\n          const importEntrypoint = join(\n            \"@apollo/client\",\n            relative(join(import.meta.dirname, \"..\", \"src\"), entry)\n          );\n          const knownExports = getPublicExports(importEntrypoint);\n\n          for (const specifier of node.specifiers) {\n            if (specifier.type == \"ImportSpecifier\") {\n              const name =\n                specifier.imported.type === \"Identifier\" ?\n                  specifier.imported.name\n                : specifier.imported.value;\n              const couldBeImportedFromPublicExport =\n                knownExports.includes(name);\n\n              if (couldBeImportedFromPublicExport) {\n                context.report({\n                  node: node.source,\n                  messageId: \"noInternalImportOfficialExport\",\n                  *fix(fixer) {\n                    yield fixer.insertTextBefore(\n                      node,\n                      `import { ${name} } from \"${importEntrypoint}\";\\n`\n                    );\n                    // duplicates will be fixed by imports/no-duplicates\n\n                    if (node.specifiers.length === 1) {\n                      yield fixer.remove(node);\n                    } else {\n                      yield fixer.remove(specifier);\n                      const comma = context.sourceCode.getTokenAfter(specifier);\n                      if (comma.value === \",\") {\n                        yield fixer.remove(comma);\n                      }\n                    }\n                  },\n                });\n              }\n            }\n          }\n        },\n      };\n    },\n    meta: {\n      messages: {\n        noInternalImportOfficialExport:\n          \"This should be imported from the official entry point, not from the internal file.\",\n      },\n      type: \"problem\",\n      schema: [],\n      fixable: \"code\",\n    },\n    defaultOptions: [],\n  });\n\n/**\n * to be used in tests, so the test imports from the library instead of testing internals\n * (where possible)\n */\nexport const noRelativeImports = ESLintUtils.RuleCreator.withoutDocs({\n  create(context, options) {\n    return {\n      ImportDeclaration(node) {\n        if (!node.source.value.startsWith(\"..\")) {\n          // we're only interested in imports from parent folders outside of the test folder\n          return;\n        }\n        if (node.importKind === \"type\") {\n          // we're okay with internal types for now, although in most cases\n          // they should probably be exports if they are important enough\n          // that we need them for a test\n          return;\n        }\n        const resolvedTarget = resolve(\n          dirname(context.physicalFilename),\n          node.source.value\n        );\n        if (options[0].ignoreFrom.includes(resolvedTarget)) {\n          return;\n        }\n        context.report({\n          node: node.source,\n          messageId: \"noRelativeImports\",\n        });\n      },\n    };\n  },\n  meta: {\n    messages: {\n      noRelativeImports:\n        \"Don't use relative imports in tests, import from official entry points instead.\",\n    },\n    type: \"problem\",\n    schema: [\n      {\n        type: \"object\",\n        properties: {\n          ignoreFrom: {\n            type: \"array\",\n            items: { type: \"string\" },\n          },\n        },\n      },\n    ],\n  },\n  defaultOptions: [\n    {\n      ignoreFrom: [],\n    },\n  ],\n});\n"
  },
  {
    "path": "eslint-local-rules/index.mjs",
    "content": "import {\n  validInheritDoc,\n  validMdxCanonicalReferences,\n} from \"./canonical-references.ts\";\nimport { rule as forbidActInDisabledActEnvironment } from \"./forbid-act-in-disabled-act-environment.ts\";\nimport {\n  importFromExport,\n  importFromInsideOtherExport,\n  noDuplicateExports,\n  noInternalImportOfficialExport,\n  noRelativeImports,\n} from \"./import-from-export.ts\";\nimport { rule as requireDisableActEnvironment } from \"./require-disable-act-environment.ts\";\nimport { rule as requireUsingDisposable } from \"./require-using-disposable.ts\";\nimport {\n  TVariablesShouldExtendOperationVariables,\n  TDataTVariablesOrder,\n} from \"./generics.ts\";\n\n/** @type {import(\"eslint\").ESLint.Plugin['rules']} */\n// @ts-ignore - mismatch between different plugin types, but works\nexport default {\n  \"require-using-disposable\": requireUsingDisposable,\n  \"require-disable-act-environment\": requireDisableActEnvironment,\n  \"forbid-act-in-disabled-act-environment\": forbidActInDisabledActEnvironment,\n  \"import-from-export\": importFromExport,\n  \"import-from-inside-other-export\": importFromInsideOtherExport,\n  \"no-internal-import-official-export\": noInternalImportOfficialExport,\n  \"no-duplicate-exports\": noDuplicateExports,\n  \"no-relative-imports\": noRelativeImports,\n  \"valid-inherit-doc\": validInheritDoc,\n  \"mdx-valid-canonical-references\": validMdxCanonicalReferences,\n  \"variables-should-extend-operation-variables\":\n    TVariablesShouldExtendOperationVariables,\n  \"tdata-tvariables-order\": TDataTVariablesOrder,\n};\n"
  },
  {
    "path": "eslint-local-rules/package.json",
    "content": "{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"test\": \"node --no-warnings --test --watch *.test.ts\"\n  }\n}\n"
  },
  {
    "path": "eslint-local-rules/require-disable-act-environment.test.ts",
    "content": "import { rule } from \"./require-disable-act-environment.ts\";\nimport { ruleTester } from \"./testSetup.ts\";\n\nruleTester.run(\"require-disable-act-environment\", rule, {\n  valid: [\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = someCall()\n    const {} = takeRender()\n  }\n    `,\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n    const {} = renderStream.takeRender()\n  }\n    `,\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = someCall()\n    const {} = takeSnapshot()\n  }\n    `,\n    `\n  () => {\n    using _disabledAct = disableActEnvironment();\n    const {} = renderStream.takeSnapshot()\n  }\n    `,\n    `\n  using _disabledAct = disableActEnvironment();\n  () => {\n    const { takeRender } = someCall()\n    const {} = takeRender()\n  }\n    `,\n    `\n  using _disabledAct = disableActEnvironment();\n  () => {\n    const {} = renderStream.takeRender()\n  }\n    `,\n    `\n  using _disabledAct = disableActEnvironment();\n  () => {\n    const { takeSnapshot } = someCall()\n    const {} = takeSnapshot()\n  }\n    `,\n    `\n  using _disabledAct = disableActEnvironment();\n  () => {\n    const {} = renderStream.takeSnapshot()\n  }\n    `,\n  ],\n  invalid: [\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n    }\n    () => {\n      const { takeRender } = someCall()\n      takeRender()\n    }\n    `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n    }\n    () => {\n      renderStream.takeRender()\n    }\n    `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n    }\n    () => {\n      const { takeSnapshot } = someCall()\n      takeSnapshot()\n    }\n    `,\n    `\n    () => {\n      using _disabledAct = disableActEnvironment();\n    }\n    () => {\n      renderStream.takeSnapshot()\n    }\n    `,\n    `\n    () => {\n      const { takeRender } = someCall()\n      takeRender()\n    }\n    `,\n    `\n    () => {\n      renderStream.takeRender()\n    }\n    `,\n    `\n    () => {\n      const { takeSnapshot } = someCall()\n      takeSnapshot()\n    }\n    `,\n    `\n    () => {\n      renderStream.takeSnapshot()\n    }\n    `,\n  ].map((code) => ({\n    code,\n    errors: [{ messageId: \"missingDisableActEnvironment\" }],\n  })),\n});\n"
  },
  {
    "path": "eslint-local-rules/require-disable-act-environment.ts",
    "content": "import { ESLintUtils } from \"@typescript-eslint/utils\";\nimport type { TSESTree as AST } from \"@typescript-eslint/types\";\n\ntype Fn =\n  | AST.FunctionDeclaration\n  | AST.ArrowFunctionExpression\n  | AST.FunctionExpression;\n\nexport const rule = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    let depth = 1;\n    let disabledDepth: number | false = false;\n\n    function EnterFn() {\n      depth++;\n    }\n    function ExitFn() {\n      depth--;\n      if (disabledDepth !== false && disabledDepth > depth) {\n        disabledDepth = false;\n      }\n    }\n\n    return {\n      CallExpression(node) {\n        const directCallee =\n          node.callee.type === \"Identifier\" ? node.callee\n          : node.callee.type === \"MemberExpression\" ? node.callee.property\n          : null;\n\n        if (\n          directCallee?.type === \"Identifier\" &&\n          directCallee.name === \"disableActEnvironment\"\n        ) {\n          if (disabledDepth === false) {\n            disabledDepth = depth;\n          }\n        }\n\n        if (\n          directCallee?.type === \"Identifier\" &&\n          (directCallee.name === \"takeRender\" ||\n            directCallee.name === \"takeSnapshot\")\n        ) {\n          if (disabledDepth === false) {\n            context.report({\n              messageId: \"missingDisableActEnvironment\",\n              node: node,\n            });\n          }\n        }\n      },\n      ArrowFunctionExpression: EnterFn,\n      FunctionExpression: EnterFn,\n      FunctionDeclaration: EnterFn,\n      \"ArrowFunctionExpression:exit\": ExitFn,\n      \"FunctionExpression:exit\": ExitFn,\n      \"FunctionDeclaration:exit\": ExitFn,\n    };\n  },\n  meta: {\n    messages: {\n      missingDisableActEnvironment:\n        \"Tests using a render stream should call `disableActEnvironment`.\",\n    },\n    type: \"problem\",\n    schema: [],\n  },\n  defaultOptions: [],\n});\n\nfunction findParentFunction(node: AST.Node): Fn | undefined {\n  let parentFunction: AST.Node | undefined = node;\n  while (\n    parentFunction != null &&\n    parentFunction.type !== \"FunctionDeclaration\" &&\n    parentFunction.type !== \"FunctionExpression\" &&\n    parentFunction.type !== \"ArrowFunctionExpression\"\n  ) {\n    parentFunction = parentFunction.parent;\n  }\n  return parentFunction as any;\n}\n"
  },
  {
    "path": "eslint-local-rules/require-using-disposable.test.ts",
    "content": "import { rule } from \"./require-using-disposable.ts\";\nimport { ruleTester } from \"./testSetup.ts\";\n\nruleTester.run(\"require-using-disposable\", rule, {\n  valid: [\n    `\n    function foo(): Disposable {}\n    using bar = foo()\n    `,\n    `\n    function foo(): AsyncDisposable {}\n    await using bar = foo()\n    `,\n  ],\n  invalid: [\n    {\n      code: `\n      function foo(): Disposable {}\n      const bar = foo()\n      `,\n      errors: [{ messageId: \"missingUsing\" }],\n    },\n    {\n      code: `\n      function foo(): AsyncDisposable {}\n      const bar = foo()\n      `,\n      errors: [{ messageId: \"missingAwaitUsing\" }],\n    },\n  ],\n});\n"
  },
  {
    "path": "eslint-local-rules/require-using-disposable.ts",
    "content": "import { ESLintUtils } from \"@typescript-eslint/utils\";\nimport ts from \"typescript\";\nimport * as utils from \"ts-api-utils\";\n\nexport const rule = ESLintUtils.RuleCreator.withoutDocs({\n  create(context) {\n    return {\n      VariableDeclaration(node) {\n        for (const declarator of node.declarations) {\n          if (!declarator.init) continue;\n          const services = ESLintUtils.getParserServices(context);\n          const type = services.getTypeAtLocation(declarator.init);\n          for (const typePart of parts(type)) {\n            if (!utils.isObjectType(typePart) || !typePart.symbol) {\n              continue;\n            }\n            if (\n              // bad check, but will do for now\n              // in the future, we should check for a `[Symbol.disposable]` property\n              // but I have no idea how to do that right now\n              typePart.symbol.escapedName === \"Disposable\" &&\n              node.kind != \"using\"\n            ) {\n              context.report({\n                messageId: \"missingUsing\",\n                node: declarator,\n              });\n            }\n            if (\n              // similarly bad check\n              typePart.symbol.escapedName === \"AsyncDisposable\" &&\n              node.kind != \"await using\"\n            ) {\n              context.report({\n                messageId: \"missingAwaitUsing\",\n                node: declarator,\n              });\n            }\n          }\n        }\n      },\n    };\n  },\n  meta: {\n    messages: {\n      missingUsing:\n        \"Disposables should be allocated with `using <disposable>`.\",\n      missingAwaitUsing:\n        \"AsyncDisposables should be allocated with `await using <disposable>`.\",\n    },\n    type: \"suggestion\",\n    schema: [],\n  },\n  defaultOptions: [],\n});\n\nfunction parts(type: ts.Type): ts.Type[] {\n  return (\n    type.isUnion() ? utils.unionTypeParts(type).flatMap(parts)\n    : type.isIntersection() ? utils.intersectionTypeParts(type).flatMap(parts)\n    : [type]\n  );\n}\n"
  },
  {
    "path": "eslint-local-rules/testSetup.ts",
    "content": "import { RuleTester } from \"@typescript-eslint/rule-tester\";\nimport type { RuleTesterConfig } from \"@typescript-eslint/rule-tester\";\nimport tsParser from \"@typescript-eslint/parser\";\nimport nodeTest from \"node:test\";\n\nRuleTester.it = nodeTest.it;\nRuleTester.itOnly = nodeTest.only;\nRuleTester.describe = nodeTest.describe;\nRuleTester.afterAll = nodeTest.after;\n\nexport function mkRuleTester(\n  wrap: (testerConfig: RuleTesterConfig) => RuleTesterConfig = (x) => x\n) {\n  return new RuleTester(\n    wrap({\n      languageOptions: {\n        parser: tsParser,\n        parserOptions: {\n          project: \"../tsconfig.json\",\n          tsconfigRootDir: import.meta.dirname + \"/fixtures\",\n        },\n      },\n    })\n  );\n}\n\nexport const ruleTester = mkRuleTester();\n"
  },
  {
    "path": "eslint-local-rules/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"nodenext\",\n    \"allowJs\": true,\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"rewriteRelativeImportExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"**/*.ts\"]\n}\n"
  },
  {
    "path": "eslint.config.mjs",
    "content": "if (!process.features.typescript) {\n  throw new Error(\n    `\n    This configuration requires TypeScript support.\n    Run node with --experimental-strip-types.\n\n    If using VSCode, add the following to your settings.json\n    and reload the window (restarting the ESLint Server might not be enough):\n      \"eslint.runtime\": \"/opt/homebrew/bin/node\",\n      \"eslint.execArgv\": [ \"--experimental-strip-types\" ]\n    `\n  );\n}\n\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { defineConfig, globalIgnores } from \"eslint/config\";\nimport typescriptEslint from \"@typescript-eslint/eslint-plugin\";\nimport tsParser from \"@typescript-eslint/parser\";\nimport importPlugin from \"eslint-plugin-import\";\nimport * as mdx from \"eslint-plugin-mdx\";\nimport globals from \"globals\";\nimport reactHooks from \"eslint-plugin-react-hooks\";\nimport testingLibrary from \"eslint-plugin-testing-library\";\n\nimport localRules from \"./eslint-local-rules/index.mjs\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n/**\n * Some rules can be very costly so we only want to run them from CLI, not from the LSP.\n */\nconst runExtendedRules = !!process.env.EXTENDED_RULES;\n\n/** @type {Record<string, import(\"eslint\").ESLint.Plugin>} */\nconst tsPlugins = {\n  import: importPlugin,\n  \"local-rules\": {\n    rules: localRules,\n  },\n  // @ts-ignore - slight mismatch between old and new ESLint plugin types\n  \"@typescript-eslint\": typescriptEslint,\n};\n\nexport default defineConfig([\n  globalIgnores([\"integration-tests/\"]),\n  {\n    files: [\"**/*.ts\", \"**/*.tsx\"],\n    plugins: tsPlugins,\n    ignores: [\"tests.codegen.ts\"],\n\n    languageOptions: {\n      globals: {\n        ...globals.browser,\n        ...globals.node,\n      },\n\n      parser: tsParser,\n      ecmaVersion: \"latest\",\n      sourceType: \"commonjs\",\n    },\n\n    settings: {\n      \"import/parsers\": {\n        \"@typescript-eslint/parser\": [\".ts\", \".tsx\"],\n      },\n      \"import/internal-regex\": \"^@apollo/client\",\n      \"import/resolver\": {\n        typescript: {\n          alwaysTryTypes: true,\n        },\n      },\n    },\n\n    // rules for the whole repo\n    rules: {\n      \"no-restricted-imports\": [\n        \"error\",\n        {\n          paths: [\n            {\n              name: \"@wry/equality\",\n              importNames: [\"default\"],\n              message:\n                \"Please use named export `{ equal }` from @wry/equality instead.\",\n            },\n          ],\n        },\n      ],\n      \"import/no-unresolved\": \"error\",\n      \"import/order\": [\n        \"warn\",\n        {\n          \"newlines-between\": \"always\",\n          groups: [\n            \"builtin\",\n            \"external\",\n            \"internal\",\n            \"parent\",\n            \"sibling\",\n            \"index\",\n          ],\n          alphabetize: {\n            order: \"asc\",\n            orderImportKind: \"asc\",\n            caseInsensitive: true,\n          },\n          named: true,\n        },\n      ],\n      \"local-rules/import-from-export\": \"error\",\n      \"local-rules/import-from-inside-other-export\": [\n        \"warn\",\n        {\n          ignoreFrom: [\n            \"src/version.js\",\n            \"src/invariantErrorCodes.js\",\n            \"src/utilities/caching/getMemoryInternals.js\",\n            \"src/utilities/types/TODO.js\",\n            \"src/utilities/caching/sizes.js\",\n          ].map((file) => path.resolve(__dirname, file)),\n        },\n      ],\n      \"local-rules/no-duplicate-exports\": \"error\",\n      \"@typescript-eslint/consistent-type-imports\": [\n        \"error\",\n        {\n          prefer: \"type-imports\",\n          disallowTypeAnnotations: false,\n          fixStyle: \"separate-type-imports\",\n        },\n      ],\n      \"@typescript-eslint/no-namespace\": [\n        \"error\",\n        {\n          allowDeclarations: true,\n        },\n      ],\n    },\n  },\n  {\n    ...reactHooks.configs.flat[\"recommended-latest\"],\n    files: [\"src/react/**/*.ts\", \"src/react/**/*.tsx\"],\n    ignores: [\"**/__tests__/**/*.*\", \"**/*.d.ts\"],\n  },\n  {\n    files: [\"**/*.ts\", \"**/*.tsx\"],\n    ignores: [\"**/__tests__/**/*.*\", \"**/*.d.ts\"],\n\n    plugins: {\n      ...tsPlugins,\n    },\n\n    languageOptions: {\n      ecmaVersion: 5,\n      sourceType: \"script\",\n\n      parserOptions: {\n        project: [\n          \"./tsconfig.json\",\n          \"./codegen/tsconfig.json\",\n          \"./config/tsconfig.json\",\n          \"./docs/tsconfig.json\",\n          \"./eslint-local-rules/tsconfig.json\",\n          \"./scripts/codemods/data-masking/tsconfig.json\",\n          \"./scripts/codemods/ac3-to-ac4/tsconfig.json\",\n        ],\n      },\n    },\n\n    // rules for source files, but no tests\n    rules: {\n      \"@typescript-eslint/consistent-type-exports\": [\"error\"],\n      \"@typescript-eslint/no-import-type-side-effects\": \"error\",\n      \"@typescript-eslint/no-restricted-types\": [\n        \"error\",\n        {\n          types: {\n            GraphQLError: {\n              message: \"Use GraphQLFormattedError instead\",\n              fixWith: \"GraphQLFormattedError\",\n            },\n\n            ExecutionResult: {\n              message: \"Use FormattedExecutionResult instead\",\n              fixWith: \"FormattedExecutionResult\",\n            },\n          },\n        },\n      ],\n\n      \"no-restricted-syntax\": [\n        \"error\",\n        {\n          selector:\n            \"ImportDeclaration[source.value='react'][importKind!='type'] :matches(ImportSpecifier, ImportDefaultSpecifier)\",\n          message:\n            \"Please only use the namespace import syntax (`import * as React from 'react'`) for React imports!\",\n        },\n        \"ExportAllDeclaration\",\n      ],\n\n      \"import/consistent-type-specifier-style\": [\"error\", \"prefer-top-level\"],\n      \"local-rules/require-using-disposable\": \"error\",\n      \"local-rules/valid-inherit-doc\": \"error\",\n      \"local-rules/variables-should-extend-operation-variables\": \"error\",\n      \"local-rules/tdata-tvariables-order\": \"error\",\n    },\n  },\n  {\n    files: [\n      \"**/__tests__/**/*.[jt]s\",\n      \"**/__tests__/**/*.[jt]sx\",\n      \"**/?(*.)+(test).[jt]s\",\n      \"**/?(*.)+(test).[jt]sx\",\n    ],\n    ...testingLibrary.configs[\"flat/react\"],\n  },\n  {\n    files: [\n      \"**/__tests__/**/*.[jt]s\",\n      \"**/__tests__/**/*.[jt]sx\",\n      \"**/?(*.)+(test).[jt]s\",\n      \"**/?(*.)+(test).[jt]sx\",\n    ],\n\n    plugins: tsPlugins,\n    languageOptions: {\n      ecmaVersion: 5,\n      sourceType: \"script\",\n\n      parserOptions: {\n        project: [\n          \"./tsconfig.tests.json\",\n          \"./eslint-local-rules/tsconfig.json\",\n          \"./scripts/codemods/ac3-to-ac4/tsconfig.tests.json\",\n        ],\n      },\n    },\n\n    // rules for tests only\n    rules: {\n      \"testing-library/prefer-user-event\": \"error\",\n      \"testing-library/no-wait-for-multiple-assertions\": \"off\",\n      \"local-rules/require-using-disposable\": \"error\",\n      \"local-rules/require-disable-act-environment\": \"error\",\n      \"local-rules/forbid-act-in-disabled-act-environment\": \"error\",\n      \"local-rules/import-from-inside-other-export\": \"off\",\n      \"local-rules/no-internal-import-official-export\":\n        runExtendedRules ? \"error\" : \"off\",\n      \"local-rules/no-relative-imports\": [\n        \"error\",\n        {\n          ignoreFrom: [\"src/utilities/caching/sizes.js\"].map((file) =>\n            path.resolve(__dirname, file)\n          ),\n        },\n      ],\n      \"import/no-duplicates\": \"warn\",\n      \"@typescript-eslint/no-floating-promises\": \"warn\",\n    },\n  },\n  {\n    files: [\"scripts/codemods/ac3-to-ac4/**/__tests__/**/*.ts\"],\n    // rules for tests only\n    rules: {\n      \"local-rules/no-relative-imports\": \"off\",\n    },\n  },\n  {\n    basePath: \"docs\",\n    ...mdx.flat,\n    plugins: {\n      ...mdx.flat.plugins,\n      \"local-rules\": {\n        rules: localRules,\n      },\n    },\n    rules: {\n      \"local-rules/mdx-valid-canonical-references\": \"error\",\n    },\n  },\n  {\n    basePath: \"docs\",\n    ...mdx.flatCodeBlocks,\n  },\n]);\n"
  },
  {
    "path": "integration-tests/.gitignore",
    "content": "build/\ntest-results/\n.next\n"
  },
  {
    "path": "integration-tests/.npmrc",
    "content": "hoist=true\n"
  },
  {
    "path": "integration-tests/api.har",
    "content": "{\n  \"log\": {\n    \"version\": \"1.2\",\n    \"creator\": {\n      \"name\": \"Playwright\",\n      \"version\": \"1.35.1\"\n    },\n    \"browser\": {\n      \"name\": \"chromium\",\n      \"version\": \"115.0.5790.24\"\n    },\n    \"entries\": [\n      {\n        \"startedDateTime\": \"2023-06-26T12:46:46.602Z\",\n        \"time\": 2345.774,\n        \"request\": {\n          \"method\": \"POST\",\n          \"url\": \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n          \"httpVersion\": \"HTTP/2.0\",\n          \"cookies\": [],\n          \"headers\": [\n            { \"name\": \":authority\", \"value\": \"main--hack-the-e-commerce.apollographos.net\" },\n            { \"name\": \":method\", \"value\": \"POST\" },\n            { \"name\": \":path\", \"value\": \"/graphql\" },\n            { \"name\": \":scheme\", \"value\": \"https\" },\n            { \"name\": \"accept\", \"value\": \"*/*\" },\n            { \"name\": \"accept-encoding\", \"value\": \"gzip, deflate, br\" },\n            { \"name\": \"accept-language\", \"value\": \"en-GB,en;q=0.9\" },\n            { \"name\": \"content-length\", \"value\": \"85\" },\n            { \"name\": \"content-type\", \"value\": \"application/json\" },\n            { \"name\": \"origin\", \"value\": \"http://localhost:3000\" },\n            { \"name\": \"referer\", \"value\": \"http://localhost:3000/\" },\n            { \"name\": \"sec-ch-ua\", \"value\": \"\\\"Chromium\\\";v=\\\"115\\\", \\\"Not/A)Brand\\\";v=\\\"99\\\"\" },\n            { \"name\": \"sec-ch-ua-mobile\", \"value\": \"?0\" },\n            { \"name\": \"sec-ch-ua-platform\", \"value\": \"\\\"macOS\\\"\" },\n            { \"name\": \"sec-fetch-dest\", \"value\": \"empty\" },\n            { \"name\": \"sec-fetch-mode\", \"value\": \"cors\" },\n            { \"name\": \"sec-fetch-site\", \"value\": \"cross-site\" },\n            { \"name\": \"user-agent\", \"value\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36\" }\n          ],\n          \"queryString\": [],\n          \"headersSize\": -1,\n          \"bodySize\": -1,\n          \"postData\": {\n            \"mimeType\": \"application/json\",\n            \"text\": \"{\\\"variables\\\":{},\\\"extensions\\\":{\\\"clientLibrary\\\":{\\\"name\\\":\\\"@apollo/client\\\",\\\"version\\\":\\\"__VERSION__\\\"}},\\\"query\\\":\\\"{\\\\n  products {\\\\n    id\\\\n    title\\\\n    __typename\\\\n  }\\\\n}\\\"}\",\n            \"params\": []\n          }\n        },\n        \"response\": {\n          \"status\": 200,\n          \"statusText\": \"\",\n          \"httpVersion\": \"HTTP/2.0\",\n          \"cookies\": [],\n          \"headers\": [\n            { \"name\": \"access-control-allow-origin\", \"value\": \"http://localhost:3000\" },\n            { \"name\": \"content-encoding\", \"value\": \"gzip\" },\n            { \"name\": \"content-type\", \"value\": \"application/json\" },\n            { \"name\": \"date\", \"value\": \"Mon, 26 Jun 2023 12:46:48 GMT\" },\n            { \"name\": \"fly-request-id\", \"value\": \"01H3VVW4M7MQ1ECG2YC4RJMFWZ-fra\" },\n            { \"name\": \"server\", \"value\": \"Fly/a0b91024 (2023-06-13)\" },\n            { \"name\": \"vary\", \"value\": \"origin\" },\n            { \"name\": \"via\", \"value\": \"2 fly.io\" }\n          ],\n          \"content\": {\n            \"size\": -1,\n            \"mimeType\": \"application/json\",\n            \"text\": \"{\\\"data\\\":{\\\"products\\\":[{\\\"id\\\":\\\"product:5\\\",\\\"title\\\":\\\"Soft Warm Apollo Beanie\\\",\\\"__typename\\\":\\\"Product\\\"},{\\\"id\\\":\\\"product:2\\\",\\\"title\\\":\\\"Stainless Steel Water Bottle\\\",\\\"__typename\\\":\\\"Product\\\"},{\\\"id\\\":\\\"product:3\\\",\\\"title\\\":\\\"Athletic Baseball Cap\\\",\\\"__typename\\\":\\\"Product\\\"},{\\\"id\\\":\\\"product:4\\\",\\\"title\\\":\\\"Baby Onesies\\\",\\\"__typename\\\":\\\"Product\\\"},{\\\"id\\\":\\\"product:1\\\",\\\"title\\\":\\\"The Apollo T-Shirt\\\",\\\"__typename\\\":\\\"Product\\\"},{\\\"id\\\":\\\"product:6\\\",\\\"title\\\":\\\"The Apollo Socks\\\",\\\"__typename\\\":\\\"Product\\\"}]}}\"\n          },\n          \"headersSize\": -1,\n          \"bodySize\": -1,\n          \"redirectURL\": \"\"\n        },\n        \"cache\": {},\n        \"timings\": { \"send\": -1, \"wait\": -1, \"receive\": 2345.774 }\n      }\n    ]\n  }\n}"
  },
  {
    "path": "integration-tests/browser-esm/html/jsdeliver-esm.html",
    "content": "<!doctype html>\n<html>\n  <head></head>\n  <script type=\"module\">\n    // give playwright time to load\n    await new Promise((r) => setTimeout(r, 100));\n\n    import {\n      ApolloClient,\n      InMemoryCache,\n      gql,\n    } from \"https://cdn.jsdelivr.net/npm/@apollo/client@0.0.0-pr-10915-20230616125401/+esm\";\n    const client = new ApolloClient({\n      uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n      cache: new InMemoryCache(),\n    });\n    client\n      .query({\n        query: gql`\n          query {\n            products {\n              id\n              title\n            }\n          }\n        `,\n      })\n      .then((r) => {\n        const main = document.querySelector(\"main\");\n        const ul = document.createElement(\"ul\");\n        main.replaceChildren(ul);\n        r.data.products.forEach((p) => {\n          const li = document.createElement(\"li\");\n          li.textContent = p.title;\n          ul.appendChild(li);\n        });\n      })\n      .catch(console.error);\n  </script>\n\n  <body>\n    <h1>https://cdn.jsdelivr.net/npm/@apollo/client/+esm</h1>\n    <main>\n      <p>loading</p>\n    </main>\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/browser-esm/html/jspm-prepared.html",
    "content": "<!doctype html>\n<html>\n  <head></head>\n  <script type=\"importmap\">\n    {\n      \"imports\": {\n        \"@apollo/client\": \"https://ga.jspm.io/npm:@apollo/client@0.0.0-pr-10915-20230616125401/index.js\"\n      },\n      \"scopes\": {\n        \"https://ga.jspm.io/\": {\n          \"@wry/equality\": \"https://ga.jspm.io/npm:@wry/equality@0.5.6/lib/index.js\",\n          \"@wry/trie\": \"https://ga.jspm.io/npm:@wry/trie@0.4.3/lib/index.js\",\n          \"graphql\": \"https://ga.jspm.io/npm:graphql@16.6.0/index.mjs\",\n          \"graphql-tag\": \"https://ga.jspm.io/npm:graphql-tag@2.12.6/lib/index.js\",\n          \"optimism\": \"https://ga.jspm.io/npm:optimism@0.18.0/lib/index.js\",\n          \"react\": \"https://ga.jspm.io/npm:react@18.2.0/dev.index.js\",\n          \"symbol-observable\": \"https://ga.jspm.io/npm:symbol-observable@4.0.0/lib/index.js\",\n          \"ts-invariant\": \"https://ga.jspm.io/npm:ts-invariant@0.10.3/lib/invariant.js\",\n          \"ts-invariant/process/index.js\": \"https://ga.jspm.io/npm:ts-invariant@0.10.3/process/index.js\",\n          \"tslib\": \"https://ga.jspm.io/npm:tslib@2.5.3/tslib.es6.mjs\",\n          \"zen-observable-ts\": \"https://ga.jspm.io/npm:zen-observable-ts@1.2.5/module.js\"\n        }\n      }\n    }\n  </script>\n  <script type=\"module\">\n    // give playwright time to load\n    await new Promise((r) => setTimeout(r, 100));\n\n    import { ApolloClient, InMemoryCache, gql } from \"@apollo/client\";\n    const client = new ApolloClient({\n      uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n      cache: new InMemoryCache(),\n    });\n    client\n      .query({\n        query: gql`\n          query {\n            products {\n              id\n              title\n            }\n          }\n        `,\n      })\n      .then((r) => {\n        const main = document.querySelector(\"main\");\n        const ul = document.createElement(\"ul\");\n        main.replaceChildren(ul);\n        r.data.products.forEach((p) => {\n          const li = document.createElement(\"li\");\n          li.textContent = p.title;\n          ul.appendChild(li);\n        });\n      })\n      .catch(console.error);\n  </script>\n\n  <body>\n    <h1>https://ga.jspm.io/npm:@apollo/client/index.js</h1>\n    <main>\n      <p>loading</p>\n    </main>\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/browser-esm/html/unpkg-unmangled.html",
    "content": "<!doctype html>\n<html>\n  <head></head>\n  <script type=\"importmap\">\n    {\n      \"imports\": {\n        \"@apollo/client\": \"https://unpkg.com/@apollo/client@0.0.0-pr-10915-20230616125401/index.js\",\n        \"@wry/equality\": \"https://unpkg.com/@wry/equality@0.5.6/lib/index.js\",\n        \"@wry/trie\": \"https://unpkg.com/@wry/trie@0.4.3/lib/index.js\",\n        \"graphql\": \"https://unpkg.com/graphql@16.6.0/index.mjs\",\n        \"graphql-tag\": \"https://unpkg.com/graphql-tag@2.12.6/lib/index.js\",\n        \"optimism\": \"https://unpkg.com/optimism@0.18.0/lib/index.js\",\n        \"react\": \"https://ga.jspm.io/npm:react@18.2.0/dev.index.js\",\n        \"symbol-observable\": \"https://ga.jspm.io/npm:symbol-observable@4.0.0/lib/index.js\",\n        \"ts-invariant\": \"https://unpkg.com/ts-invariant@0.10.3/lib/invariant.js\",\n        \"ts-invariant/process/index.js\": \"https://unpkg.com/ts-invariant@0.10.3/process/index.js\",\n        \"tslib\": \"https://unpkg.com/tslib@2.5.3/tslib.es6.mjs\",\n        \"zen-observable-ts\": \"https://unpkg.com/zen-observable-ts@1.2.5/module.js\"\n      }\n    }\n  </script>\n  <script type=\"module\">\n    // give playwright time to load\n    await new Promise((r) => setTimeout(r, 100));\n\n    import { ApolloClient, InMemoryCache, gql } from \"@apollo/client\";\n    const client = new ApolloClient({\n      uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n      cache: new InMemoryCache(),\n    });\n    client\n      .query({\n        query: gql`\n          query {\n            products {\n              id\n              title\n            }\n          }\n        `,\n      })\n      .then((r) => {\n        const main = document.querySelector(\"main\");\n        const ul = document.createElement(\"ul\");\n        main.replaceChildren(ul);\n        r.data.products.forEach((p) => {\n          const li = document.createElement(\"li\");\n          li.textContent = p.title;\n          ul.appendChild(li);\n        });\n      })\n      .catch(console.error);\n  </script>\n\n  <body>\n    <h1>https://unpkg.com/@apollo/client/index.js</h1>\n    <main>\n      <p>loading</p>\n    </main>\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/browser-esm/package.json",
    "content": "{\n  \"name\": \"browser-esm\",\n  \"scripts\": {\n    \"serve-app\": \"yarn serve html\",\n    \"test\": \"playwright test\"\n  },\n  \"devDependencies\": {\n    \"shared\": \"workspace:^\",\n    \"playwright\": \"*\",\n    \"@playwright/test\": \"*\",\n    \"serve\": \"*\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/browser-esm/playwright.config.ts",
    "content": "import { baseConfig } from \"shared/playwright.config\";\nimport { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig(baseConfig);\n"
  },
  {
    "path": "integration-tests/browser-esm/tests/playwright/jsdeliver-esm.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture\";\n\ntest(\"Basic Test\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000/jsdeliver-esm.html\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible({ timeout: 10000 });\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/browser-esm/tests/playwright/jspm-prepared.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture\";\n\ntest(\"Basic Test\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000/jspm-prepared.html\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible({ timeout: 10000 });\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/browser-esm/tests/playwright/unpkg-unmangled.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture\";\n\ntest(\"Basic Test\", async ({ withHar }) => {\n  await withHar.goto(\"http://localhost:3000/unpkg-unmangled.html\");\n\n  await expect(withHar.getByText(\"loading\")).toBeVisible();\n  await expect(withHar.getByText(\"loading\")).not.toBeVisible({\n    timeout: 10000,\n  });\n  await expect(withHar.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/cra5/package.json",
    "content": "{\n  \"name\": \"cra5\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\",\n    \"@types/react\": \"^18.2.14\",\n    \"@types/react-dom\": \"^18.2.6\",\n    \"graphql\": \"^16.8.1\",\n    \"react\": \"^18.3.0\",\n    \"react-dom\": \"^18.3.0\",\n    \"react-scripts\": \"5.0.1\",\n    \"rxjs\": \"^7.8.2\",\n    \"typescript\": \"^4.9.5\"\n  },\n  \"scripts\": {\n    \"start\": \"PORT=3000 react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"serve-app\": \"yarn serve -s build\",\n    \"test\": \"playwright test\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"*\",\n    \"playwright\": \"*\",\n    \"serve\": \"*\",\n    \"shared\": \"workspace:^\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/cra5/playwright.config.ts",
    "content": "import { baseConfig } from \"shared/playwright.config\";\nimport { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig(baseConfig);\n"
  },
  {
    "path": "integration-tests/cra5/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/cra5/src/App.tsx",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\n\nimport {\n  gql,\n  InMemoryCache,\n  ApolloClient,\n  ApolloLink,\n  HttpLink,\n} from \"@apollo/client\";\nimport { Observable } from \"rxjs\";\n\nimport { useQuery, ApolloProvider } from \"@apollo/client/react\";\n\nconst delayLink = new ApolloLink((operation, forward) => {\n  return new Observable((observer) => {\n    const handle = setTimeout(() => {\n      forward(operation).subscribe(observer);\n    }, 1000);\n\n    return () => clearTimeout(handle);\n  });\n});\n\nconst httpLink = new HttpLink({\n  uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: ApolloLink.from([delayLink, httpLink]),\n});\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function App() {\n  return (\n    <ApolloProvider client={client}>\n      <Main />\n    </ApolloProvider>\n  );\n}\n\nfunction Main() {\n  const { data } = useQuery(QUERY);\n\n  return data ?\n      <ul>\n        {data?.products.map(({ id, title }) => <li key={id}>{title}</li>)}\n      </ul>\n    : <>loading</>;\n}\n"
  },
  {
    "path": "integration-tests/cra5/src/index.tsx",
    "content": "import React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport App from \"./App\";\n\nconst root = ReactDOM.createRoot(\n  document.getElementById(\"root\") as HTMLElement\n);\nroot.render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);\n"
  },
  {
    "path": "integration-tests/cra5/tests/playwright/apollo-client.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture\";\n\ntest(\"Basic Test\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible();\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/cra5/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "integration-tests/empty.har",
    "content": "{\n  \"log\": {\n    \"version\": \"1.2\",\n    \"creator\": {\n      \"name\": \"Playwright\",\n      \"version\": \"1.35.1\"\n    },\n    \"browser\": {\n      \"name\": \"chromium\",\n      \"version\": \"115.0.5790.24\"\n    },\n    \"entries\": []\n  }\n}"
  },
  {
    "path": "integration-tests/next/next-env.d.ts",
    "content": "/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n/// <reference types=\"next/navigation-types/compat/navigation\" />\n\n// NOTE: This file should not be edited\n// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.\n"
  },
  {
    "path": "integration-tests/next/next.config.js",
    "content": "/** @type {import('next').NextConfig} */\nconst nextConfig = {};\n\nmodule.exports = nextConfig;\n"
  },
  {
    "path": "integration-tests/next/package.json",
    "content": "{\n  \"name\": \"next\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next dev\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"serve-app\": \"npm run start\",\n    \"ci-preparations\": \"pnpm install @apollo/client-integration-nextjs@$(pnpm show @apollo/client-integration-nextjs version)\",\n    \"test\": \"playwright test\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\",\n    \"@apollo/client-integration-nextjs\": \"^0.12.0-alpha.1\",\n    \"@graphql-tools/schema\": \"^10.0.0\",\n    \"@types/node\": \"20.3.1\",\n    \"@types/react\": \"18.2.14\",\n    \"@types/react-dom\": \"18.2.6\",\n    \"deepmerge\": \"^4.3.1\",\n    \"graphql\": \"^16.8.1\",\n    \"lodash\": \"^4.17.21\",\n    \"next\": \"^15.2.1\",\n    \"react\": \"^18.3.0\",\n    \"react-dom\": \"^18.3.0\",\n    \"rxjs\": \"^7.8.2\",\n    \"ts-invariant\": \"^0.10.3\",\n    \"typescript\": \"5.1.3\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"*\",\n    \"@types/lodash\": \"^4.14.195\",\n    \"playwright\": \"*\",\n    \"shared\": \"workspace:^\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/next/playwright.config.ts",
    "content": "import { baseConfig } from \"shared/playwright.config\";\nimport { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig(baseConfig);\n"
  },
  {
    "path": "integration-tests/next/src/app/cc/ApolloWrapper.tsx",
    "content": "\"use client\";\nimport * as React from \"react\";\nimport { ApolloLink, HttpLink, setLogVerbosity } from \"@apollo/client\";\nimport {\n  ApolloNextAppProvider,\n  InMemoryCache,\n  ApolloClient,\n} from \"@apollo/client-integration-nextjs\";\n\nimport { loadErrorMessages, loadDevMessages } from \"@apollo/client/dev\";\nimport { setVerbosity } from \"ts-invariant\";\nimport { schemaLink } from \"@/libs/schemaLink.ts\";\n\n//if (process.env.NODE_ENV === 'development') {\nsetLogVerbosity(\"debug\");\nsetVerbosity(\"debug\");\nloadDevMessages();\nloadErrorMessages();\n//}\n\nexport function ApolloWrapper({ children }: React.PropsWithChildren<{}>) {\n  return (\n    <ApolloNextAppProvider makeClient={makeClient}>\n      {children}\n    </ApolloNextAppProvider>\n  );\n\n  function makeClient() {\n    const httpLink = new HttpLink({\n      uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n    });\n\n    return new ApolloClient({\n      cache: new InMemoryCache(),\n      link:\n        typeof window === \"undefined\" ?\n          (schemaLink as ApolloLink)\n        : (httpLink as ApolloLink),\n    });\n  }\n}\n"
  },
  {
    "path": "integration-tests/next/src/app/cc/layout.tsx",
    "content": "import { ApolloWrapper } from \"./ApolloWrapper.tsx\";\n\nexport default async function Layout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return <ApolloWrapper>{children}</ApolloWrapper>;\n}\n"
  },
  {
    "path": "integration-tests/next/src/app/cc/page.tsx",
    "content": "\"use client\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function Page() {\n  const { data } = useSuspenseQuery(QUERY);\n\n  return (\n    <ul>\n      {data.products.map(({ id, title }) => (\n        <li key={id}>{title}</li>\n      ))}\n    </ul>\n  );\n}\n"
  },
  {
    "path": "integration-tests/next/src/app/client.ts",
    "content": "import { schemaLink } from \"@/libs/schemaLink.ts\";\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { registerApolloClient } from \"@apollo/client-integration-nextjs\";\n\nexport const { getClient } = registerApolloClient(() => {\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: schemaLink,\n  });\n});\n"
  },
  {
    "path": "integration-tests/next/src/app/layout.tsx",
    "content": "export const metadata = {\n  title: \"Create Next App\",\n  description: \"Generated by create next app\",\n};\n\nexport default function RootLayout({\n  children,\n}: {\n  children: React.ReactNode;\n}) {\n  return (\n    <html lang=\"en\">\n      <body>{children}</body>\n    </html>\n  );\n}\n"
  },
  {
    "path": "integration-tests/next/src/app/page.tsx",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport { getClient } from \"./client.ts\";\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default async function Home() {\n  const { data } = await getClient().query({ query: QUERY });\n  return (\n    <ul>{data?.products.map(({ id, title }) => <li key={id}>{title}</li>)}</ul>\n  );\n}\n"
  },
  {
    "path": "integration-tests/next/src/libs/apolloClient.ts",
    "content": "import * as React from \"react\";\nimport type { NormalizedCacheObject } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  HttpLink,\n  InMemoryCache,\n  from,\n  ApolloLink,\n  CombinedGraphQLErrors,\n} from \"@apollo/client\";\nimport { onError } from \"@apollo/client/link/error\";\nimport merge from \"deepmerge\";\nimport isEqual from \"lodash/isEqual\";\nimport type { GetServerSidePropsResult } from \"next\";\nimport { Observable } from \"rxjs\";\nimport { schemaLink } from \"./schemaLink.ts\";\n\nexport const APOLLO_STATE_PROP_NAME = \"__APOLLO_STATE__\";\n\nlet apolloClient: ApolloClient;\n\nconst errorLink = onError(({ error }) => {\n  if (CombinedGraphQLErrors.is(error)) {\n    error.errors.forEach(({ message, locations, path }) =>\n      console.log(\n        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n      )\n    );\n  } else {\n    console.log(`[Network error]: ${error}`);\n  }\n});\n\nconst delayLink = new ApolloLink((operation, forward) => {\n  return new Observable((observer) => {\n    const handle = setTimeout(() => {\n      forward(operation).subscribe(observer);\n    }, 1000);\n\n    return () => clearTimeout(handle);\n  });\n});\n\nconst httpLink = new HttpLink({\n  uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n});\n\nfunction createApolloClient() {\n  return new ApolloClient({\n    ssrMode: typeof window === \"undefined\",\n    link: from([\n      errorLink,\n      delayLink,\n      typeof window === \"undefined\" ?\n        (schemaLink as ApolloLink)\n      : (httpLink as ApolloLink),\n    ]),\n    cache: new InMemoryCache(),\n  });\n}\n\nexport function initializeApollo(\n  initialState: NormalizedCacheObject | null = null\n) {\n  const _apolloClient = apolloClient ?? createApolloClient();\n  // If your page has Next.js data fetching methods that use Apollo Client,\n  //  the initial state gets hydrated here\n  if (initialState) {\n    // Get existing cache, loaded during client side data fetching\n    const existingCache = _apolloClient.extract() as NormalizedCacheObject;\n\n    // Merge the initialState from getStaticProps/getServerSideProps\n    // in the existing cache\n    const data = merge(existingCache, initialState, {\n      // combine arrays using object equality (like in sets)\n      arrayMerge: (destinationArray, sourceArray) => [\n        ...sourceArray,\n        ...destinationArray.filter((d) =>\n          sourceArray.every((s) => !isEqual(d, s))\n        ),\n      ],\n    });\n    // Restore the cache with the merged data\n    _apolloClient.cache.restore(data);\n  }\n  // For SSG and SSR always create a new Apollo Client\n  if (typeof window === \"undefined\") return _apolloClient;\n  // Create the Apollo Client once in the client\n  if (!apolloClient) apolloClient = _apolloClient;\n  return _apolloClient;\n}\n\ninterface ApolloProps {\n  [APOLLO_STATE_PROP_NAME]: NormalizedCacheObject;\n}\n\nexport function addApolloState(\n  client: ApolloClient,\n  pageProps: GetServerSidePropsResult<Partial<ApolloProps>> & {\n    props: Partial<ApolloProps>;\n  }\n) {\n  if (pageProps?.props) {\n    pageProps.props[APOLLO_STATE_PROP_NAME] =\n      client.cache.extract() as NormalizedCacheObject;\n  }\n  return pageProps;\n}\n\nexport function useApollo(pageProps?: ApolloProps) {\n  const state = pageProps?.[APOLLO_STATE_PROP_NAME];\n  const storeRef = React.useRef<ApolloClient>();\n  if (!storeRef.current) {\n    storeRef.current = initializeApollo(state);\n  }\n  return storeRef.current;\n}\n"
  },
  {
    "path": "integration-tests/next/src/libs/schemaLink.ts",
    "content": "import { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport { gql } from \"@apollo/client\";\nimport { SchemaLink } from \"@apollo/client/link/schema\";\n\nconst typeDefs = gql`\n  type Product {\n    id: String!\n    title: String!\n  }\n  type Query {\n    products: [Product!]!\n  }\n`;\n\nconst resolvers = {\n  Query: {\n    products: async () => [\n      {\n        id: \"product:5\",\n        title: \"Soft Warm Apollo Beanie\",\n      },\n      {\n        id: \"product:2\",\n        title: \"Stainless Steel Water Bottle\",\n      },\n      {\n        id: \"product:3\",\n        title: \"Athletic Baseball Cap\",\n      },\n      {\n        id: \"product:4\",\n        title: \"Baby Onesies\",\n      },\n      {\n        id: \"product:1\",\n        title: \"The Apollo T-Shirt\",\n      },\n      {\n        id: \"product:6\",\n        title: \"The Apollo Socks\",\n      },\n    ],\n  },\n};\n\nexport const schema = makeExecutableSchema({\n  typeDefs,\n  resolvers,\n});\n\nexport const schemaLink = new SchemaLink({ schema });\n"
  },
  {
    "path": "integration-tests/next/src/pages/_app.tsx",
    "content": "import { ApolloProvider } from \"@apollo/client/react\";\nimport { useApollo } from \"../libs/apolloClient.ts\";\nimport type { AppProps } from \"next/app\";\n\nexport default function App({ Component, pageProps }: AppProps) {\n  const apolloClient = useApollo(pageProps);\n\n  return (\n    <ApolloProvider client={apolloClient}>\n      <Component {...pageProps} />\n    </ApolloProvider>\n  );\n}\n"
  },
  {
    "path": "integration-tests/next/src/pages/pages-no-ssr.tsx",
    "content": "\"use client\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function Page() {\n  const { data } = useQuery(QUERY);\n\n  if (!data) {\n    return <p>loading</p>;\n  }\n\n  return (\n    <ul>\n      {data.products.map(({ id, title }) => (\n        <li key={id}>{title}</li>\n      ))}\n    </ul>\n  );\n}\n"
  },
  {
    "path": "integration-tests/next/src/pages/pages.tsx",
    "content": "\"use client\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport type { GetStaticProps } from \"next\";\nimport { addApolloState, initializeApollo } from \"@/libs/apolloClient.ts\";\nimport { useQuery } from \"@apollo/client/react\";\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function Page() {\n  const { data } = useQuery(QUERY);\n\n  if (!data) {\n    throw new Error(\"should not happen, we have getServerSideProps!\");\n  }\n\n  return (\n    <ul>\n      {data.products.map(({ id, title }) => (\n        <li key={id}>{title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport const getStaticProps: GetStaticProps = async function () {\n  const apolloClient = initializeApollo();\n\n  await apolloClient.query({\n    query: QUERY,\n  });\n  return addApolloState(apolloClient, {\n    props: {},\n  });\n};\n"
  },
  {
    "path": "integration-tests/next/tests/playwright/apollo-client.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture\";\n\ntest(\"RSC\", async ({ page, blockRequest }) => {\n  await page.goto(\"http://localhost:3000\");\n\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n\ntest(\"CC\", async ({ page, blockRequest }) => {\n  await page.goto(\"http://localhost:3000/cc\");\n\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n\ntest(\"Pages\", async ({ page, blockRequest }) => {\n  await page.goto(\"http://localhost:3000/pages\");\n\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n\ntest(\"Pages without SSR\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000/pages-no-ssr\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible();\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/next/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noEmit\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"preserve\",\n    \"incremental\": true,\n    \"allowImportingTsExtensions\": true,\n    \"plugins\": [\n      {\n        \"name\": \"next\"\n      }\n    ],\n    \"paths\": {\n      \"@/*\": [\"./src/*\"]\n    }\n  },\n  \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\", \".next/types/**/*.ts\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "integration-tests/node/package.json",
    "content": "{\n  \"name\": \"node\",\n  \"version\": \"1.0.0\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"echo Done\",\n    \"test:cjs\": \"node --no-experimental-require-module --trace-require-module=all --test test-cjs.cjs\",\n    \"test:require-esm\": \"node --test test-require-esm.cjs\",\n    \"test:esm\": \"node --test test-esm.mjs\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\",\n    \"react\": \"^18.3.0\",\n    \"react-dom\": \"^18.3.0\"\n  },\n  \"devDependencies\": {\n    \"resolve-esm\": \"^1.4.0\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/node/test-cjs.cjs",
    "content": "const assert = require(\"node:assert\");\nconst path = require(\"node:path\");\nconst { findPackageJSON } = require(\"node:module\");\nconst { realpathSync } = require(\"node:fs\");\n\nconst test = require(\"node:test\");\n\nconst { ApolloClient } = require(\"@apollo/client\");\nconst { useQuery } = require(\"@apollo/client/react\");\nconst { HttpLink } = require(\"@apollo/client/link/http\");\n\nassert(process.features.require_module === false);\n\ntest.suite(\"Node with CJS require\", () => {\n  test(\"import from entry point\", async () => {\n    assert.equal(ApolloClient.name, \"ApolloClient\");\n    assert.equal(useQuery.name, \"useQuery\");\n    assert.equal(HttpLink.name, \"HttpLink\");\n  });\n\n  test(\"module resolution\", () => {\n    const basedir = path\n      .dirname(realpathSync(findPackageJSON(\"@apollo/client\", __filename)))\n      .split(path.sep)\n      .join(path.posix.sep);\n\n    assert.equal(\n      require.resolve(\"@apollo/client\"),\n      path.posix.join(basedir, \"/__cjs/core/index.cjs\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/core\"),\n      path.posix.join(basedir, \"/__cjs/core/index.cjs\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/react\"),\n      path.posix.join(basedir, \"/__cjs/react/index.cjs\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/link/http\"),\n      path.posix.join(basedir, \"/__cjs/link/http/index.cjs\")\n    );\n  });\n});\n"
  },
  {
    "path": "integration-tests/node/test-esm.mjs",
    "content": "import assert from \"node:assert\";\nimport path from \"node:path\";\nimport { findPackageJSON } from \"node:module\";\nimport { fileURLToPath } from \"node:url\";\nimport test from \"node:test\";\nimport { realpathSync } from \"node:fs\";\n\ntest.suite(\"Node with ESM imports\", () => {\n  test(\"import from `.../index.js`\", async () => {\n    const { ApolloClient } = await import(\"@apollo/client/index.js\");\n    const { useQuery } = await import(\"@apollo/client/react/index.js\");\n    const { HttpLink } = await import(\"@apollo/client/link/http/index.js\");\n    assert.equal(ApolloClient.name, \"ApolloClient\");\n    assert.equal(useQuery.name, \"useQuery\");\n    assert.equal(HttpLink.name, \"HttpLink\");\n  });\n\n  test(\"import from entry point\", async () => {\n    const { ApolloClient } = await import(\"@apollo/client\");\n    const { useQuery } = await import(\"@apollo/client/react\");\n    const { HttpLink } = await import(\"@apollo/client/link/http\");\n    assert.equal(ApolloClient.name, \"ApolloClient\");\n    assert.equal(useQuery.name, \"useQuery\");\n    assert.equal(HttpLink.name, \"HttpLink\");\n  });\n\n  test(\"equality between `.../index.js` and entry point\", async () => {\n    assert.equal(\n      await import(\"@apollo/client/index.js\").ApolloClient,\n      await import(\"@apollo/client\").ApolloClient\n    );\n    assert.equal(\n      await import(\"@apollo/client/react/index.js\").useQuery,\n      await import(\"@apollo/client/react\").useQuery\n    );\n    assert.equal(\n      await import(\"@apollo/client/link/http/index.js\").HttpLink,\n      await import(\"@apollo/client/link/http\").HttpLink\n    );\n  });\n\n  const basedir = path\n    .dirname(realpathSync(findPackageJSON(\"@apollo/client\", import.meta.url)))\n    .split(path.sep)\n    .join(path.posix.sep);\n\n  test(\"module resolution (direct import)\", () => {\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/index.js\")),\n      path.posix.join(basedir, \"/legacyEntryPoints/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/core/index.js\")),\n      path.posix.join(basedir, \"/legacyEntryPoints/core/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/react/index.js\")),\n      path.posix.join(basedir, \"/legacyEntryPoints/react/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/link/http/index.js\")),\n      path.posix.join(basedir, \"/legacyEntryPoints/link/http/index.js\")\n    );\n  });\n\n  test(\"module resolution\", () => {\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client\")),\n      path.posix.join(basedir, \"/core/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/core\")),\n      path.posix.join(basedir, \"/core/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/react\")),\n      path.posix.join(basedir, \"/react/index.js\")\n    );\n    assert.equal(\n      fileURLToPath(import.meta.resolve(\"@apollo/client/link/http\")),\n      path.posix.join(basedir, \"/link/http/index.js\")\n    );\n  });\n});\n"
  },
  {
    "path": "integration-tests/node/test-require-esm.cjs",
    "content": "const assert = require(\"node:assert\");\nconst path = require(\"node:path\");\nconst { findPackageJSON } = require(\"node:module\");\nconst test = require(\"node:test\");\nconst { realpathSync } = require(\"node:fs\");\n\nconst { ApolloClient } = require(\"@apollo/client\");\nconst { useQuery } = require(\"@apollo/client/react\");\nconst { HttpLink } = require(\"@apollo/client/link/http\");\n\nassert(process.features.require_module === true);\n\ntest.suite(\"Node with ESM require\", () => {\n  test(\"import from entry point\", async () => {\n    assert.equal(ApolloClient.name, \"ApolloClient\");\n    assert.equal(useQuery.name, \"useQuery\");\n    assert.equal(HttpLink.name, \"HttpLink\");\n  });\n\n  test(\"module resolution\", () => {\n    const basedir = path\n      .dirname(realpathSync(findPackageJSON(\"@apollo/client\", __filename)))\n      .split(path.sep)\n      .join(path.posix.sep);\n\n    assert.equal(\n      require.resolve(\"@apollo/client\"),\n      path.posix.join(basedir, \"/core/index.js\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/core\"),\n      path.posix.join(basedir, \"/core/index.js\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/react\"),\n      path.posix.join(basedir, \"/react/index.js\")\n    );\n    assert.equal(\n      require.resolve(\"@apollo/client/link/http\"),\n      path.posix.join(basedir, \"/link/http/index.js\")\n    );\n  });\n});\n"
  },
  {
    "path": "integration-tests/package.json",
    "content": "{\n  \"name\": \"integration-tests\",\n  \"license\": \"UNLICENSED\",\n  \"pnpm\": {\n    \"overrides\": {\n      \"@playwright/test\": \"1.43.1\",\n      \"playwright\": \"1.43.1\",\n      \"serve\": \"^14.2.0\"\n    }\n  },\n  \"workspaces\": [\n    \"browser-esm\",\n    \"cra4\",\n    \"cra5\",\n    \"next\",\n    \"vite\",\n    \"vite-swc\",\n    \"node\",\n    \"wrapping-library\",\n    \"shared\"\n  ],\n  \"devDependencies\": {\n    \"@types/lodash\": \"^4.14.195\",\n    \"playwright\": \"1.43.1\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/peerdeps-tsc/.gitignore",
    "content": "# explicitly avoiding to check in this one\n# so we run this test always with the latest version\npackage-lock.json\ndist\nnode_modules\n"
  },
  {
    "path": "integration-tests/peerdeps-tsc/package.json",
    "content": "{\n  \"name\": \"peerdeps-tsc\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"test\": \"tsc\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"dependencies\": {\n    \"graphql\": \"^16.0.0\",\n    \"graphql-ws\": \"^5.5.5\",\n    \"@types/react\": \"^18.0.0\",\n    \"@types/react-dom\": \"^18.0.0\",\n    \"subscriptions-transport-ws\": \"^0.11.0\",\n    \"typescript\": \"latest\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/peerdeps-tsc/src/index.ts",
    "content": "export * from \"@apollo/client\";\n"
  },
  {
    "path": "integration-tests/peerdeps-tsc/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es2016\",\n    \"module\": \"commonjs\",\n    \"rootDir\": \"./src\",\n    \"outDir\": \"./dist\",\n    \"declaration\": true,\n    \"sourceMap\": true,\n    \"declarationMap\": true,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n    \"skipLibCheck\": false,\n    \"types\": [\"react\", \"react-dom\"],\n    \"lib\": [\"es2018\", \"dom\"]\n  }\n}\n"
  },
  {
    "path": "integration-tests/pnpm-workspace.yaml",
    "content": "packages:\n  - browser-esm\n  - cra5\n  - next\n  - vite\n  - vite-swc\n  - node\n  - wrapping-library\n  - shared\n"
  },
  {
    "path": "integration-tests/shared/fixture.ts",
    "content": "import { test as base, expect } from \"@playwright/test\";\nimport { version } from \"@apollo/client\";\nimport { readFile, writeFile } from \"node:fs/promises\";\n\nexport const test = base.extend<{\n  withHar: import(\"@playwright/test\").Page;\n  blockRequest: import(\"@playwright/test\").Page;\n}>({\n  page: async ({ page }, use) => {\n    page.on(\"pageerror\", (error) => {\n      expect(error.stack || error).toBe(\"no error\");\n    });\n    await use(page);\n  },\n  withHar: async ({ page }, use) => {\n    let contents = await readFile(\"../api.har\", \"utf-8\");\n    contents = contents.replace(\"__VERSION__\", version);\n    await writeFile(\"../api.har\", contents, \"utf-8\");\n\n    await page.routeFromHAR(\"../api.har\", {\n      url: \"**/graphql\",\n      notFound: \"abort\",\n    });\n    await use(page);\n  },\n  blockRequest: async ({ page }, use) => {\n    await page.routeFromHAR(\"../empty.har\", {\n      url: \"**/graphql\",\n      notFound: \"abort\",\n    });\n    await use(page);\n  },\n});\n"
  },
  {
    "path": "integration-tests/shared/package.json",
    "content": "{\n  \"name\": \"shared\",\n  \"license\": \"UNLICENSED\",\n  \"peerDependencies\": {\n    \"@playwright/test\": \"*\",\n    \"@apollo/client\": \"*\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/shared/playwright.config.ts",
    "content": "export const baseConfig = {\n  webServer: {\n    command: \"yarn serve-app\",\n    url: \"http://localhost:3000\",\n    timeout: 120 * 1000,\n    reuseExistingServer: !process.env.CI,\n  },\n  timeout: 120 * 1000,\n  use: {\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: true,\n  },\n  testDir: \"tests/playwright/\",\n} as const;\n"
  },
  {
    "path": "integration-tests/vite/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + React + TS</title>\n  </head>\n\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/vite/package.json",
    "content": "{\n  \"name\": \"vite\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite --port 3000\",\n    \"build\": \"tsc && vite build\",\n    \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview --port 3000\",\n    \"serve-app\": \"npm run preview\",\n    \"test\": \"playwright test\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\",\n    \"expect-type\": \"^1.2.1\",\n    \"graphql\": \"^16.8.1\",\n    \"react\": \"^18.3.0\",\n    \"react-dom\": \"^18.3.0\",\n    \"rxjs\": \"^7.8.2\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"*\",\n    \"@types/react\": \"^18.0.37\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.59.0\",\n    \"@typescript-eslint/parser\": \"^5.59.0\",\n    \"@vitejs/plugin-react\": \"^4.0.0\",\n    \"eslint\": \"^8.38.0\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"eslint-plugin-react-refresh\": \"^0.3.4\",\n    \"playwright\": \"*\",\n    \"shared\": \"workspace:^\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^4.3.9\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/vite/playwright.config.ts",
    "content": "import { baseConfig } from \"shared/playwright.config.ts\";\nimport { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig(baseConfig);\n"
  },
  {
    "path": "integration-tests/vite/src/ApolloLinkResultType.ts",
    "content": "import type { ApolloLink } from \"@apollo/client\";\nimport { expectTypeOf } from \"expect-type\";\nimport type { FormattedExecutionResult } from \"graphql\";\n\n// ensure that without manual addition to `TypeOverrides`,\n// `ApolloLink.Result` equals `FormattedExecutionResult`\n// with no additional alternatives\n\ntype TData = { foo: string };\ntype TExtensions = { bar: number };\nexpectTypeOf<ApolloLink.Result<TData, TExtensions>>().toEqualTypeOf<\n  FormattedExecutionResult<TData, TExtensions>\n>();\n"
  },
  {
    "path": "integration-tests/vite/src/App.tsx",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\n\nimport {\n  gql,\n  InMemoryCache,\n  ApolloClient,\n  ApolloLink,\n  HttpLink,\n} from \"@apollo/client\";\nimport { Observable } from \"rxjs\";\n\nimport { useQuery, ApolloProvider } from \"@apollo/client/react\";\n\nconst delayLink = new ApolloLink((operation, forward) => {\n  return new Observable((observer) => {\n    const handle = setTimeout(() => {\n      forward(operation).subscribe(observer);\n    }, 1000);\n\n    return () => clearTimeout(handle);\n  });\n});\n\nconst httpLink = new HttpLink({\n  uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: ApolloLink.from([delayLink, httpLink]),\n});\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function App() {\n  return (\n    <ApolloProvider client={client}>\n      <Main />\n    </ApolloProvider>\n  );\n}\n\nfunction Main() {\n  const { data } = useQuery(QUERY);\n\n  return data ?\n      <ul>\n        {data?.products?.map(({ id, title } = {}) => <li key={id}>{title}</li>)}\n      </ul>\n    : <>loading</>;\n}\n"
  },
  {
    "path": "integration-tests/vite/src/enhanceDataStates.ts",
    "content": "import { DeepPartial, HKT } from \"@apollo/client/utilities\";\nimport { ApplyHKT } from \"@apollo/client/utilities/internal\";\nimport { gql, DataValue, TypedDocumentNode } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\nimport { expectTypeOf } from \"expect-type\";\n\ndeclare const complete: unique symbol;\ndeclare const streaming: unique symbol;\n\ntype ExtendedTypedDocumentNode<TCompleteData, TVariables, TStreaming> =\n  TypedDocumentNode<\n    TCompleteData & {\n      [complete]?: TCompleteData;\n      [streaming]?: TStreaming;\n    },\n    TVariables\n  >;\n\ndeclare namespace MyImplementation {\n  interface Complete extends HKT {\n    arg1: unknown; // TData\n    return: this[\"arg1\"] extends { [complete]?: infer TComplete } ? TComplete\n    : this[\"arg1\"];\n  }\n  interface Streaming extends HKT {\n    arg1: unknown; // TData\n    return: this[\"arg1\"] extends { [streaming]?: infer TStreaming } ? TStreaming\n    : DeepPartial<this[\"arg1\"]>;\n  }\n  interface Partial extends HKT {\n    arg1: unknown; // TData\n    return: DeepPartial<ApplyHKT<Complete, this[\"arg1\"]>>;\n  }\n}\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides {\n    Complete: MyImplementation.Complete;\n    Streaming: MyImplementation.Streaming;\n    Partial: MyImplementation.Partial;\n  }\n}\n\ntype CompleteData = {\n  __typename: string;\n  id: string;\n  name: string;\n  age: number;\n  description: string;\n};\ntype StreamingData = {\n  __typename: string;\n  id: string;\n} & (\n  | {\n      name: string;\n      age: number;\n    }\n  | {\n      name?: undefined;\n      age?: undefined;\n    }\n) &\n  (\n    | {\n        description: string;\n      }\n    | {\n        description?: undefined;\n      }\n  );\n\nconst query: ExtendedTypedDocumentNode<\n  CompleteData,\n  { id: string },\n  StreamingData\n> = gql`\n  query GetUser($Id: String!) {\n    user(id: $Id) {\n      __typename\n      id\n      ... @defer {\n        name\n        age\n      }\n      ... @defer {\n        description\n      }\n    }\n  }\n`;\n\nif (1 > 2 /* skip running this */) {\n  type TData =\n    typeof query extends TypedDocumentNode<infer TData, any> ? TData : never;\n  expectTypeOf<DataValue.Complete<TData>>().toEqualTypeOf<CompleteData>();\n  expectTypeOf<DataValue.Streaming<TData>>().toEqualTypeOf<StreamingData>();\n  expectTypeOf<DataValue.Partial<TData>>().toEqualTypeOf<\n    DeepPartial<CompleteData>\n  >();\n\n  const result = useQuery(query, {\n    variables: { id: \"123\" },\n    returnPartialData: true,\n  });\n  if (result.dataState === \"complete\") {\n    expectTypeOf(result.data).toEqualTypeOf<CompleteData>();\n  }\n  if (result.dataState === \"streaming\") {\n    expectTypeOf(result.data).toEqualTypeOf<StreamingData>();\n    if (result.data.name) {\n      expectTypeOf(result.data.name).toEqualTypeOf<string>();\n      expectTypeOf(result.data.age).toEqualTypeOf<number>();\n    } else {\n      expectTypeOf(result.data.name).toEqualTypeOf<string | undefined>();\n      expectTypeOf(result.data.age).toEqualTypeOf<number | undefined>();\n    }\n  }\n  if (result.dataState === \"partial\") {\n    expectTypeOf(result.data).toEqualTypeOf<DeepPartial<CompleteData>>();\n  }\n}\n"
  },
  {
    "path": "integration-tests/vite/src/enhanceMaskingTypes.ts",
    "content": "import { HKT } from \"@apollo/client/utilities\";\n\ntype CustomMaybeMaskedImplementation<TData> = {\n  [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n};\n\ninterface CustomMaybeMaskedType extends HKT {\n  arg1: unknown; // TData\n  return: CustomMaybeMaskedImplementation<this[\"arg1\"]>;\n}\n\nexport interface CustomDataMaskingImplementation {\n  MaybeMasked: CustomMaybeMaskedType;\n}\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides extends CustomDataMaskingImplementation {}\n}\n\nimport { MaybeMasked } from \"@apollo/client\";\n\ntype TestMasked = MaybeMasked<{\n  _id: string;\n  name: string;\n  _description: string;\n  age: number;\n}>;\n\nconst test: TestMasked = {\n  age: 30,\n  name: \"John Doe\",\n  // _id and _description are omitted\n  // @ts-expect-error\n  _id: \"123\",\n  _description: \"A description\",\n};\n\nif (test) {\n  // just referencing _test to ensure it is \"used\" to prevent build errors\n}\n"
  },
  {
    "path": "integration-tests/vite/src/main.tsx",
    "content": "import React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport App from \"./App.tsx\";\n\nReactDOM.createRoot(document.getElementById(\"root\") as HTMLElement).render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);\n"
  },
  {
    "path": "integration-tests/vite/tests/playwright/apollo-client.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture.ts\";\n\ntest(\"Basic Test\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible();\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/vite/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "integration-tests/vite/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "integration-tests/vite/vite.config.ts",
    "content": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n});\n"
  },
  {
    "path": "integration-tests/vite-swc/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + React + TS</title>\n  </head>\n\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "integration-tests/vite-swc/package.json",
    "content": "{\n  \"name\": \"vite-swc\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite --port 3000\",\n    \"build\": \"tsc && vite build\",\n    \"lint\": \"eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0\",\n    \"preview\": \"vite preview --port 3000\",\n    \"serve-app\": \"npm run preview\",\n    \"test\": \"playwright test\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\",\n    \"react\": \"^18.3.0\",\n    \"react-dom\": \"^18.3.0\",\n    \"rxjs\": \"^7.8.2\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"*\",\n    \"@types/react\": \"^18.0.37\",\n    \"@types/react-dom\": \"^18.0.11\",\n    \"@typescript-eslint/eslint-plugin\": \"^5.59.0\",\n    \"@typescript-eslint/parser\": \"^5.59.0\",\n    \"@vitejs/plugin-react-swc\": \"^3.8.0\",\n    \"eslint\": \"^8.38.0\",\n    \"eslint-plugin-react-hooks\": \"^4.6.0\",\n    \"eslint-plugin-react-refresh\": \"^0.3.4\",\n    \"playwright\": \"*\",\n    \"shared\": \"workspace:^\",\n    \"typescript\": \"^5.0.2\",\n    \"vite\": \"^6.2.0\"\n  },\n  \"overrides\": {\n    \"next\": {\n      \"@playwright/test\": \"$@playwright/test\"\n    },\n    \"@apollo/client\": {\n      \"react\": \"$react\",\n      \"react-dom\": \"$react-dom\"\n    }\n  }\n}\n"
  },
  {
    "path": "integration-tests/vite-swc/playwright.config.ts",
    "content": "import { baseConfig } from \"shared/playwright.config.ts\";\nimport { defineConfig } from \"@playwright/test\";\n\nexport default defineConfig(baseConfig);\n"
  },
  {
    "path": "integration-tests/vite-swc/src/App.tsx",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\n\nimport {\n  gql,\n  InMemoryCache,\n  ApolloClient,\n  ApolloLink,\n  HttpLink,\n} from \"@apollo/client\";\nimport { Observable } from \"rxjs\";\n\nimport { useQuery, ApolloProvider } from \"@apollo/client/react\";\n\nconst delayLink = new ApolloLink((operation, forward) => {\n  return new Observable((observer) => {\n    const handle = setTimeout(() => {\n      forward(operation).subscribe(observer);\n    }, 1000);\n\n    return () => clearTimeout(handle);\n  });\n});\n\nconst httpLink = new HttpLink({\n  uri: \"https://main--hack-the-e-commerce.apollographos.net/graphql\",\n});\n\nconst client = new ApolloClient({\n  cache: new InMemoryCache(),\n  link: ApolloLink.from([delayLink, httpLink]),\n});\n\nconst QUERY: TypedDocumentNode<{\n  products: {\n    id: string;\n    title: string;\n  }[];\n}> = gql`\n  query {\n    products {\n      id\n      title\n    }\n  }\n`;\n\nexport default function App() {\n  return (\n    <ApolloProvider client={client}>\n      <Main />\n    </ApolloProvider>\n  );\n}\n\nfunction Main() {\n  const { data } = useQuery(QUERY);\n\n  return data ?\n      <ul>\n        {data?.products.map(({ id, title }) => <li key={id}>{title}</li>)}\n      </ul>\n    : <>loading</>;\n}\n"
  },
  {
    "path": "integration-tests/vite-swc/src/main.tsx",
    "content": "import React from \"react\";\nimport ReactDOM from \"react-dom/client\";\nimport App from \"./App.tsx\";\n\nReactDOM.createRoot(document.getElementById(\"root\") as HTMLElement).render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>\n);\n"
  },
  {
    "path": "integration-tests/vite-swc/tests/playwright/apollo-client.test.ts",
    "content": "import { expect } from \"@playwright/test\";\nimport { test } from \"shared/fixture.ts\";\n\ntest(\"Basic Test\", async ({ page, withHar }) => {\n  await page.goto(\"http://localhost:3000\");\n\n  await expect(page.getByText(\"loading\")).toBeVisible();\n  await expect(page.getByText(\"loading\")).not.toBeVisible();\n  await expect(page.getByText(\"Soft Warm Apollo Beanie\")).toBeVisible();\n});\n"
  },
  {
    "path": "integration-tests/vite-swc/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"ES2020\", \"DOM\", \"DOM.Iterable\"],\n    \"module\": \"ESNext\",\n    \"skipLibCheck\": true,\n\n    /* Bundler mode */\n    \"moduleResolution\": \"bundler\",\n    \"allowImportingTsExtensions\": true,\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n\n    /* Linting */\n    \"strict\": true,\n    \"noUnusedLocals\": true,\n    \"noUnusedParameters\": true,\n    \"noFallthroughCasesInSwitch\": true\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "integration-tests/vite-swc/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"skipLibCheck\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "integration-tests/vite-swc/vite.config.ts",
    "content": "import { defineConfig } from \"vite\";\nimport react from \"@vitejs/plugin-react-swc\";\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n});\n"
  },
  {
    "path": "integration-tests/wrapping-library/package.json",
    "content": "{\n  \"name\": \"wrapping-library\",\n  \"devDependencies\": {\n    \"typescript\": \"^5.7.3\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"3.13.0\"\n  },\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"test\": \"true\"\n  }\n}\n"
  },
  {
    "path": "integration-tests/wrapping-library/src/index.ts",
    "content": "import { TypedDocumentNode, OperationVariables } from \"@apollo/client\";\nimport { useQuery } from \"@apollo/client/react\";\nimport { getMarkupFromTree } from \"@apollo/client/react/ssr\";\nimport { relayStylePagination } from \"@apollo/client/utilities\";\nimport { MockSubscriptionLink, MockLink } from \"@apollo/client/testing\";\n\n/**\n * This file simulates a library re-exporting functions that wrap Apollo Client\n * functionality or exporting objects created with AC utilities.\n *\n * This is here to ensure that with the introduction of the `exports` field,\n * TypeScript compilation errors on declaration emit are avoided.\n */\n\nexport function useWrappedQuery<TData, TVariables extends OperationVariables>(\n  query: TypedDocumentNode<TData, TVariables>,\n  variables: TVariables = {} as TVariables\n) {\n  return useQuery(query, { variables });\n}\n\nexport const fieldPolicy = relayStylePagination();\nexport const mockSubscriptionLink = new MockSubscriptionLink();\nexport const mockLinkWrapper = (\n  ...args: ConstructorParameters<typeof MockLink>\n) => new MockLink(...args);\n\nexport const mockGetMarkupFromTree = (\n  ...options: Parameters<typeof getMarkupFromTree>\n) => getMarkupFromTree(...options);\n"
  },
  {
    "path": "integration-tests/wrapping-library/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"node\",\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"emitDeclarationOnly\": true,\n    \"sourceMap\": true,\n    \"outDir\": \"./dist\",\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n    \"skipLibCheck\": true\n  },\n  \"include\": [\"./src\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "jsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"checkJs\": true,\n    \"strict\": true,\n    \"noImplicitAny\": true,\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"allowImportingTsExtensions\": true\n  },\n  \"include\": [\"**/*.js\", \"**/*.mjs\"]\n}\n"
  },
  {
    "path": "knip.config.js",
    "content": "// @ts-check\n\nimport { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { entryPoints } from \"./config/entryPoints.js\";\n\nconst packageJSON = JSON.parse(readFileSync(\"package.json\", \"utf-8\"));\n\nconst packageEntries = entryPoints.map(({ dirs }) =>\n  join(\"src\", ...dirs, \"index.ts\")\n);\n\nconst scriptEntries = Array.from(\n  Object.values(packageJSON.scripts)\n    .join(\"\\n\")\n    .matchAll(/(config\\/.*?\\.[jt]s)/g)\n)\n  .map((match) => match[1])\n  .filter((value, index, arr) => index === arr.indexOf(value));\n\n/** @type{import('knip').KnipConfig}*/\nconst config = {\n  exclude: [\"optionalPeerDependencies\", \"unresolved\"],\n  entry: /**@type {string[]}*/ ([])\n    .concat(packageEntries)\n    .concat(scriptEntries)\n    .concat([\n      \"src/cache/inmemory/fixPolyfills.native.ts\",\n      \"src/react/types/types.documentation.ts\",\n      \"eslint-local-rules/index.mjs\",\n      \"codegen/local-state/index.ts\",\n      \"codegen/local-state/config.ts\",\n      \"codegen/local-state/plugin.ts\",\n      \"codegen/local-state/visitor.ts\",\n      \"scripts/codemods/ac3-to-ac4/src/util/getAllExports.ts\",\n    ]),\n  project: [\n    \"src/**/*.ts{,x}\",\n    \"config/*.{,c}[jt]s\",\n    \"eslint-local-rules/*.[jt]s\",\n  ],\n  ignore: [\n    \"integration-tests/**/*\",\n    \".yalc/**/*\",\n    \"config/schema.package.json.ts\",\n    \"src/config/jest/resolver.ts\",\n    \"config/listImports.ts\",\n    \"scripts/codemods/**/__testfixtures__/**/*\",\n    // Exports `KeyOptions` used in `matchers/index.d.ts`, but can't pick it up\n    \"src/testing/matchers/toHaveFragmentWatchesOn.ts\",\n  ],\n  ignoreBinaries: [\"jq\"],\n  ignoreDependencies: [\n    /@actions\\/.*/,\n    /@size-limit\\/.*/,\n    \"size-limit-apollo-plugin\",\n    /eslint-.*/,\n    // used by `recast`\n    \"@babel/parser\",\n    // called in a script, but with `xargs`\n    \"tsx\",\n    // TS types referenced by \"rollup-plugin-terser\"\n    \"terser\",\n    // used as a reporter by the `test:coverage` script\n    \"jest-junit\",\n    \"@mdx-js/language-service\",\n  ],\n  jest: {\n    config: \"config/jest.config.js\",\n    entry: [\n      \"src/config/jest/setup.ts\",\n      \"src/testing/matchers/index.d.ts\",\n      \"**/__tests__/**/*.[jt]s?(x)\",\n      \"**/*.test.[jt]s?(x)\",\n      \"src/**/__benches__/*.bench.ts\",\n    ],\n  },\n  typescript: {\n    config: [\n      \"tsconfig.json\",\n      \"eslint-local-rules/tsconfig.json\",\n      \"config/tsconfig.json\",\n    ],\n  },\n};\n\nexport default config;\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@apollo/client\",\n  \"version\": \"4.1.6\",\n  \"description\": \"A fully-featured caching GraphQL client.\",\n  \"private\": true,\n  \"keywords\": [\n    \"apollo\",\n    \"graphql\",\n    \"react\",\n    \"hooks\",\n    \"client\",\n    \"cache\"\n  ],\n  \"author\": \"packages@apollographql.com\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"main\": \"./dist/__cjs/core/index.cjs\",\n  \"module\": \"./dist/core/index.js\",\n  \"types\": \"./dist/core/index.d.ts\",\n  \"sideEffects\": false,\n  \"react-native\": {\n    \"react-dom/server\": false\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/apollographql/apollo-client.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/apollographql/apollo-client/issues\"\n  },\n  \"homepage\": \"https://www.apollographql.com/docs/react/\",\n  \"exports\": {\n    \".\": \"./src/core/index.ts\",\n    \"./cache\": \"./src/cache/index.ts\",\n    \"./core\": \"./src/core/index.ts\",\n    \"./dev\": \"./src/dev/index.ts\",\n    \"./errors\": \"./src/errors/index.ts\",\n    \"./incremental\": \"./src/incremental/index.ts\",\n    \"./link\": \"./src/link/index.ts\",\n    \"./link/batch\": \"./src/link/batch/index.ts\",\n    \"./link/batch-http\": \"./src/link/batch-http/index.ts\",\n    \"./link/client-awareness\": \"./src/link/client-awareness/index.ts\",\n    \"./link/context\": \"./src/link/context/index.ts\",\n    \"./link/error\": \"./src/link/error/index.ts\",\n    \"./link/http\": \"./src/link/http/index.ts\",\n    \"./link/persisted-queries\": \"./src/link/persisted-queries/index.ts\",\n    \"./link/retry\": \"./src/link/retry/index.ts\",\n    \"./link/remove-typename\": \"./src/link/remove-typename/index.ts\",\n    \"./link/schema\": \"./src/link/schema/index.ts\",\n    \"./link/subscriptions\": \"./src/link/subscriptions/index.ts\",\n    \"./link/utils\": \"./src/link/utils/index.ts\",\n    \"./link/ws\": \"./src/link/ws/index.ts\",\n    \"./local-state\": \"./src/local-state/index.ts\",\n    \"./masking\": \"./src/masking/index.ts\",\n    \"./react\": {\n      \"react-server\": \"./src/react/index.react-server.ts\",\n      \"default\": \"./src/react/index.ts\"\n    },\n    \"./react/internal\": \"./src/react/internal/index.ts\",\n    \"./react/internal/compiler-runtime\": \"./src/react/internal/compiler-runtime/index.ts\",\n    \"./react/ssr\": \"./src/react/ssr/index.ts\",\n    \"./testing\": \"./src/testing/index.ts\",\n    \"./testing/react\": \"./src/testing/react/index.ts\",\n    \"./utilities\": \"./src/utilities/index.ts\",\n    \"./utilities/internal\": {\n      \"production\": \"./src/utilities/internal/index.production.ts\",\n      \"default\": \"./src/utilities/internal/index.ts\"\n    },\n    \"./utilities/internal/ponyfills\": {\n      \"react-native\": \"./src/utilities/internal/ponyfills/index.react-native.ts\",\n      \"default\": \"./src/utilities/internal/ponyfills/index.ts\"\n    },\n    \"./utilities/internal/globals\": \"./src/utilities/internal/globals/index.ts\",\n    \"./utilities/subscriptions/relay\": \"./src/utilities/subscriptions/relay/index.ts\",\n    \"./utilities/invariant\": {\n      \"development\": \"./src/utilities/invariant/index.development.ts\",\n      \"default\": \"./src/utilities/invariant/index.ts\"\n    },\n    \"./utilities/environment\": {\n      \"production\": \"./src/utilities/environment/index.production.ts\",\n      \"development\": \"./src/utilities/environment/index.development.ts\",\n      \"default\": \"./src/utilities/environment/index.ts\"\n    },\n    \"./v4-migration\": \"./src/v4-migration.ts\"\n  },\n  \"scripts\": {\n    \"prebuild\": \"npm run clean\",\n    \"build\": \"node config/build.ts\",\n    \"typecheck\": \"tsc --project config/tsconfig.json; tsc --noEmit --project tsconfig.json\",\n    \"postinstall\": \"patch-package\",\n    \"extract-api\": \"npm run clean && node config/build.ts --step=prepareDist --step=addExports --step=typescript --step=inlineInheritDoc --step=deprecateInternals && npm run extract-api:only\",\n    \"extract-api:only\": \"node config/apiExtractor.ts --generate apiReport\",\n    \"clean\": \"rimraf dist coverage lib temp\",\n    \"check:format\": \"prettier --check .\",\n    \"ci:precheck\": \"node config/precheck.ts\",\n    \"format\": \"prettier --write .\",\n    \"lint\": \"EXTENDED_RULES=1 eslint --max-warnings 0 src docs\",\n    \"test\": \"node --expose-gc --experimental-import-meta-resolve --disable-warning=ExperimentalWarning ./node_modules/jest/bin/jest.js --config ./config/jest.config.ts\",\n    \"test:type-benches\": \"find src -name '*.bench.ts' | xargs -n1 tsx\",\n    \"test:debug\": \"node --inspect-brk node_modules/.bin/jest --config ./config/jest.config.ts --runInBand --testTimeout 99999 --logHeapUsage\",\n    \"test:ci\": \"TEST_ENV=ci npm run test:coverage -- --logHeapUsage\",\n    \"test:codegen\": \"npm run build -w codegen && graphql-codegen --config ./tests.codegen.ts\",\n    \"test:watch\": \"jest --config ./config/jest.config.ts --watch\",\n    \"test:memory\": \"npm i && npm run build && cd scripts/memory && npm i && npm test\",\n    \"test:coverage\": \"npm run coverage -- --ci --runInBand --reporters=default --reporters=jest-junit\",\n    \"coverage\": \"node --experimental-import-meta-resolve --no-compilation-cache --expose-gc --max_old_space_size=4096 node_modules/.bin/jest --config ./config/jest.config.ts --logHeapUsage --coverage --watchAll=false\",\n    \"bundlesize\": \"npm run build && node ./config/bundlesize.ts\",\n    \"deploy\": \"cd dist && npm publish --tag next\",\n    \"typedoc\": \"typedoc src/core/index.ts --json docs/public/docs.json\",\n    \"docmodel\": \"npm run clean && node config/build.ts --step=prepareDist --step=addExports --step=typescript --step=inlineInheritDoc --step=deprecateInternals && node config/apiExtractor.ts --main-only --generate docModel\",\n    \"changeset-check\": \"changeset status --verbose --since=origin/main\",\n    \"changeset-publish\": \"npm pkg set 'workspaces[0]'=dist && npm run build && changeset publish\",\n    \"changeset-version\": \"changeset version && npm i\",\n    \"update-size-limits\": \"size-limit --json | jq '. | map(select(.sizeLimit) | { key: .name, value: .size}) | from_entries' | tee .new-size-limits.json; mv .new-size-limits.json .size-limits.json\",\n    \"knip\": \"knip\",\n    \"madge\": \"node ./config/madge.ts\",\n    \"publint\": \"publint run --strict dist\"\n  },\n  \"devEngines\": {\n    \"runtime\": {\n      \"name\": \"node\",\n      \"onFail\": \"error\",\n      \"version\": \">=23.6.0\"\n    },\n    \"packageManager\": {\n      \"name\": \"npm\",\n      \"onFail\": \"error\",\n      \"version\": \">=10.8.2\"\n    }\n  },\n  \"peerDependencies\": {\n    \"graphql\": \"^16.0.0\",\n    \"graphql-ws\": \"^5.5.5 || ^6.0.3\",\n    \"react\": \"^17.0.0 || ^18.0.0 || >=19.0.0-rc\",\n    \"react-dom\": \"^17.0.0 || ^18.0.0 || >=19.0.0-rc\",\n    \"rxjs\": \"^7.3.0\",\n    \"subscriptions-transport-ws\": \"^0.9.0 || ^0.11.0\"\n  },\n  \"peerDependenciesMeta\": {\n    \"graphql-ws\": {\n      \"optional\": true\n    },\n    \"react\": {\n      \"optional\": true\n    },\n    \"react-dom\": {\n      \"optional\": true\n    },\n    \"subscriptions-transport-ws\": {\n      \"optional\": true\n    }\n  },\n  \"dependencies\": {\n    \"@graphql-typed-document-node/core\": \"^3.1.1\",\n    \"@wry/caches\": \"^1.0.0\",\n    \"@wry/equality\": \"^0.5.6\",\n    \"@wry/trie\": \"^0.5.0\",\n    \"graphql-tag\": \"^2.12.6\",\n    \"optimism\": \"^0.18.0\",\n    \"tslib\": \"^2.3.0\"\n  },\n  \"devDependencies\": {\n    \"@actions/github-script\": \"github:actions/github-script#v8.0.0\",\n    \"@arethetypeswrong/cli\": \"0.15.3\",\n    \"@ark/attest\": \"0.28.0\",\n    \"@babel/core\": \"^7.26.9\",\n    \"@babel/parser\": \"7.25.0\",\n    \"@babel/preset-env\": \"^7.26.9\",\n    \"@changesets/changelog-github\": \"0.5.0\",\n    \"@changesets/cli\": \"2.27.7\",\n    \"@graphql-codegen/cli\": \"^5.0.6\",\n    \"@graphql-tools/schema\": \"10.0.4\",\n    \"@jest/expect-utils\": \"30.2.0\",\n    \"@jest/globals\": \"30.2.0\",\n    \"@mdx-js/language-service\": \"^0.7.1\",\n    \"@microsoft/api-extractor\": \"7.49.1\",\n    \"@microsoft/api-extractor-model\": \"7.30.2\",\n    \"@microsoft/tsdoc\": \"0.15.1\",\n    \"@size-limit/esbuild-why\": \"11.1.4\",\n    \"@size-limit/preset-small-lib\": \"11.1.4\",\n    \"@testing-library/dom\": \"10.4.0\",\n    \"@testing-library/jest-dom\": \"6.9.1\",\n    \"@testing-library/react\": \"16.1.0\",\n    \"@testing-library/react-render-stream\": \"2.0.2\",\n    \"@testing-library/user-event\": \"14.5.2\",\n    \"@types/babel__preset-env\": \"^7.10.0\",\n    \"@types/bytes\": \"3.1.4\",\n    \"@types/fetch-mock\": \"7.3.8\",\n    \"@types/jest\": \"30.0.0\",\n    \"@types/jsesc\": \"^3.0.3\",\n    \"@types/lodash\": \"4.17.7\",\n    \"@types/node\": \"^22.10.7\",\n    \"@types/react\": \"19.2.7\",\n    \"@types/react-dom\": \"19.2.3\",\n    \"@types/relay-runtime\": \"14.1.24\",\n    \"@types/use-sync-external-store\": \"0.0.6\",\n    \"@typescript-eslint/eslint-plugin\": \"8.21.0\",\n    \"@typescript-eslint/parser\": \"8.21.0\",\n    \"@typescript-eslint/rule-tester\": \"8.21.0\",\n    \"@typescript-eslint/types\": \"8.21.0\",\n    \"@typescript-eslint/utils\": \"8.21.0\",\n    \"ast-types\": \"0.16.1\",\n    \"babel-plugin-react-compiler\": \"1.0.0\",\n    \"eslint\": \"9.31.0\",\n    \"eslint-import-resolver-typescript\": \"3.7.0\",\n    \"eslint-plugin-import\": \"2.32.0\",\n    \"eslint-plugin-local-rules\": \"3.0.2\",\n    \"eslint-plugin-mdx\": \"^3.6.2\",\n    \"eslint-plugin-react-hooks\": \"7.0.1\",\n    \"eslint-plugin-testing-library\": \"7.1.1\",\n    \"expect\": \"29.7.0\",\n    \"expect-type\": \"1.1.0\",\n    \"fetch-mock\": \"9.11.0\",\n    \"globals\": \"15.14.0\",\n    \"graphql\": \"16.9.0\",\n    \"graphql-17-alpha2\": \"npm:graphql@17.0.0-alpha.2\",\n    \"graphql-17-alpha9\": \"npm:graphql@17.0.0-alpha.9\",\n    \"graphql-ws\": \"6.0.3\",\n    \"jest\": \"30.2.0\",\n    \"jest-environment-jsdom\": \"30.2.0\",\n    \"jest-junit\": \"16.0.0\",\n    \"jest-matcher-utils\": \"30.2.0\",\n    \"jsdom\": \"26.1.0\",\n    \"jsesc\": \"^3.1.0\",\n    \"knip\": \"^5.42.2\",\n    \"lodash\": \"4.17.23\",\n    \"madge\": \"^8.0.0\",\n    \"patch-package\": \"8.0.0\",\n    \"pkg-pr-new\": \"0.0.24\",\n    \"prettier\": \"3.1.1\",\n    \"publint\": \"^0.3.8\",\n    \"react\": \"19.2.3\",\n    \"react-17\": \"npm:react@^17\",\n    \"react-18\": \"npm:react@^18\",\n    \"react-dom\": \"19.2.3\",\n    \"react-dom-17\": \"npm:react-dom@^17\",\n    \"react-dom-18\": \"npm:react-dom@^18\",\n    \"react-error-boundary\": \"4.0.13\",\n    \"recast\": \"0.23.9\",\n    \"rimraf\": \"5.0.9\",\n    \"rxjs\": \"7.8.1\",\n    \"rxjs-min\": \"npm:rxjs@7.3.0\",\n    \"size-limit\": \"11.1.4\",\n    \"size-limit-apollo-plugin\": \"file:config/size-limit\",\n    \"sorcery\": \"^1.0.0\",\n    \"source-map\": \"^0.6.1\",\n    \"sourcemap-validator\": \"^2.1.0\",\n    \"subscriptions-transport-ws\": \"0.11.0\",\n    \"terser\": \"5.31.3\",\n    \"ts-api-utils\": \"2.0.0\",\n    \"ts-jest\": \"29.4.5\",\n    \"tsx\": \"4.19.2\",\n    \"typedoc\": \"0.25.0\",\n    \"typescript\": \"5.7.3\",\n    \"web-streams-polyfill\": \"4.0.0\",\n    \"zx\": \"^8.3.0\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"files\": [\n    \"VERSIONING_POLICY.md\",\n    \"**/*.md\",\n    \"**/*.cjs\",\n    \"**/*.cjs.map\",\n    \"**/*.d.cts\",\n    \"**/*.js\",\n    \"**/*.js.map\",\n    \"**/*.d.ts\",\n    \"**/*.json\"\n  ],\n  \"overrides\": {\n    \"pretty-format\": \"^29.7.0\",\n    \"@testing-library/dom\": \"$@testing-library/dom\",\n    \"jsdom\": \"26.1.0\"\n  },\n  \"workspaces\": [\n    \".\",\n    \"codegen\",\n    \"scripts/codemods/ac3-to-ac4\"\n  ]\n}\n"
  },
  {
    "path": "patches/@changesets+parse+0.4.0.patch",
    "content": "diff --git a/node_modules/@changesets/parse/dist/changesets-parse.cjs.js b/node_modules/@changesets/parse/dist/changesets-parse.cjs.js\nindex 53793c5..ba55435 100644\n--- a/node_modules/@changesets/parse/dist/changesets-parse.cjs.js\n+++ b/node_modules/@changesets/parse/dist/changesets-parse.cjs.js\n@@ -27,7 +27,7 @@ function parseChangesetFile(contents) {\n       releases = Object.entries(yamlStuff).map(([name, type]) => ({\n         name,\n         type\n-      }));\n+      })).filter((({name}) => name[0] !== \"_\"));\n     } else {\n       releases = [];\n     }\ndiff --git a/node_modules/@changesets/parse/dist/changesets-parse.esm.js b/node_modules/@changesets/parse/dist/changesets-parse.esm.js\nindex a48e06b..9ec73ef 100644\n--- a/node_modules/@changesets/parse/dist/changesets-parse.esm.js\n+++ b/node_modules/@changesets/parse/dist/changesets-parse.esm.js\n@@ -19,7 +19,7 @@ function parseChangesetFile(contents) {\n       releases = Object.entries(yamlStuff).map(([name, type]) => ({\n         name,\n         type\n-      }));\n+      })).filter((({name}) => name[0] !== \"_\"));\n     } else {\n       releases = [];\n     }\n"
  },
  {
    "path": "patches/@microsoft+api-extractor+7.49.1.patch",
    "content": "diff --git a/node_modules/@microsoft/api-extractor/lib/analyzer/AstSymbolTable.js b/node_modules/@microsoft/api-extractor/lib/analyzer/AstSymbolTable.js\nindex 9372313..4bdeb78 100644\n--- a/node_modules/@microsoft/api-extractor/lib/analyzer/AstSymbolTable.js\n+++ b/node_modules/@microsoft/api-extractor/lib/analyzer/AstSymbolTable.js\n@@ -526,11 +526,14 @@ class AstSymbolTable {\n                 this._astDeclarationsByDeclaration.set(declaration, astDeclaration);\n             }\n         }\n-        if (options.isExternal !== astSymbol.isExternal) {\n-            throw new node_core_library_1.InternalError(`Cannot assign isExternal=${options.isExternal} for` +\n-                ` the symbol ${astSymbol.localName} because it was previously registered` +\n-                ` with isExternal=${astSymbol.isExternal}`);\n+        if (!options.isExternal || !astSymbol.isExternal) {\n+            astSymbol.isExternal = false\n         }\n+        // if (options.isExternal !== astSymbol.isExternal) {\n+        //     throw new node_core_library_1.InternalError(`Cannot assign isExternal=${options.isExternal} for` +\n+        //         ` the symbol ${astSymbol.localName} because it was previously registered` +\n+        //         ` with isExternal=${astSymbol.isExternal}`);\n+        // }\n         return astSymbol;\n     }\n     /**\n"
  },
  {
    "path": "patches/@testing-library+react+16.1.0.patch",
    "content": "diff --git a/node_modules/@testing-library/react/dist/pure.js b/node_modules/@testing-library/react/dist/pure.js\nindex 7b62fa7..9ad1d9e 100644\n--- a/node_modules/@testing-library/react/dist/pure.js\n+++ b/node_modules/@testing-library/react/dist/pure.js\n@@ -223,7 +223,7 @@ function renderRoot(ui, {\n function render(ui, {\n   container,\n   baseElement = container,\n-  legacyRoot = false,\n+  legacyRoot = React.version.startsWith(\"17\"),\n   queries,\n   hydrate = false,\n   wrapper\n"
  },
  {
    "path": "patches/eslint-plugin-testing-library+7.1.1.patch",
    "content": "diff --git a/node_modules/eslint-plugin-testing-library/dist/rules/render-result-naming-convention.js b/node_modules/eslint-plugin-testing-library/dist/rules/render-result-naming-convention.js\nindex dd77b02..d1a581d 100644\n--- a/node_modules/eslint-plugin-testing-library/dist/rules/render-result-naming-convention.js\n+++ b/node_modules/eslint-plugin-testing-library/dist/rules/render-result-naming-convention.js\n@@ -5,7 +5,7 @@ const utils_1 = require(\"@typescript-eslint/utils\");\n const create_testing_library_rule_1 = require(\"../create-testing-library-rule\");\n const node_utils_1 = require(\"../node-utils\");\n exports.RULE_NAME = 'render-result-naming-convention';\n-const ALLOWED_VAR_NAMES = ['view', 'utils'];\n+const ALLOWED_VAR_NAMES = ['view', 'utils', 'renderStream'];\n const ALLOWED_VAR_NAMES_TEXT = ALLOWED_VAR_NAMES.map((name) => `\\`${name}\\``)\n     .join(', ')\n     .replace(/, ([^,]*)$/, ', or $1');\n"
  },
  {
    "path": "patches/graphql-17-alpha9+17.0.0-alpha.9.patch",
    "content": "diff --git a/node_modules/graphql-17-alpha9/execution/types.d.ts b/node_modules/graphql-17-alpha9/execution/types.d.ts\nindex 48ef2e9..6ef2ab3 100644\n--- a/node_modules/graphql-17-alpha9/execution/types.d.ts\n+++ b/node_modules/graphql-17-alpha9/execution/types.d.ts\n@@ -95,9 +95,8 @@ export interface CompletedResult {\n     errors?: ReadonlyArray<GraphQLError>;\n }\n export interface FormattedCompletedResult {\n-    path: ReadonlyArray<string | number>;\n-    label?: string;\n-    errors?: ReadonlyArray<GraphQLError>;\n+    id: string;\n+    errors?: ReadonlyArray<GraphQLFormattedError>;\n }\n export declare function isPendingExecutionGroup(incrementalDataRecord: IncrementalDataRecord): incrementalDataRecord is PendingExecutionGroup;\n export type CompletedExecutionGroup = SuccessfulExecutionGroup | FailedExecutionGroup;\n"
  },
  {
    "path": "patches/optimism+0.18.0.patch",
    "content": "diff --git a/node_modules/optimism/lib/index.d.ts b/node_modules/optimism/lib/index.d.ts\nindex 06c3327..19868ac 100644\n--- a/node_modules/optimism/lib/index.d.ts\n+++ b/node_modules/optimism/lib/index.d.ts\n@@ -25,7 +25,7 @@ export interface CommonCacheConstructor<TCacheKey, TResult, TArgs extends any[]>\n export type OptimisticWrapOptions<TArgs extends any[], TKeyArgs extends any[] = TArgs, TCacheKey = any, TResult = any> = {\n     max?: number;\n     keyArgs?: (...args: TArgs) => TKeyArgs;\n-    makeCacheKey?: (...args: NoInfer<TKeyArgs>) => TCacheKey | undefined;\n+    makeCacheKey: (...args: NoInfer<TKeyArgs>) => TCacheKey | undefined;\n     normalizeResult?: (newer: TResult, older: TResult) => TResult;\n     subscribe?: (...args: TArgs) => void | (() => any);\n     cache?: CommonCache<NoInfer<TCacheKey>, Entry<NoInfer<TArgs>, NoInfer<TResult>>> | CommonCacheConstructor<NoInfer<TCacheKey>, NoInfer<TResult>, NoInfer<TArgs>>;\n"
  },
  {
    "path": "patches/pretty-format+29.7.0.patch",
    "content": "diff --git a/node_modules/pretty-format/build/index.js b/node_modules/pretty-format/build/index.js\nindex 8d3a562..879eed7 100644\n--- a/node_modules/pretty-format/build/index.js\n+++ b/node_modules/pretty-format/build/index.js\n@@ -103,6 +103,9 @@ function printBasicValue(val, printFunctionName, escapeRegex, escapeString) {\n   if (val === null) {\n     return 'null';\n   }\n+  if (val.name === 'ApolloError' || val.name === 'GraphQLError') {\n+    return null\n+  }\n   const typeOf = typeof val;\n   if (typeOf === 'number') {\n     return printNumber(val);\n"
  },
  {
    "path": "patches/react-dom-17+17.0.2.patch",
    "content": "diff --git a/node_modules/react-dom-17/cjs/react-dom.development.js b/node_modules/react-dom-17/cjs/react-dom.development.js\nindex f0b9ee7..b02eb8e 100644\n--- a/node_modules/react-dom-17/cjs/react-dom.development.js\n+++ b/node_modules/react-dom-17/cjs/react-dom.development.js\n@@ -15728,7 +15728,7 @@ function updateEffectImpl(fiberFlags, hookFlags, create, deps) {\n function mountEffect(create, deps) {\n   {\n     // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n-    if ('undefined' !== typeof jest) {\n+    if (globalThis.IS_REACT_ACT_ENVIRONMENT) {\n       warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n     }\n   }\n@@ -15739,7 +15739,7 @@ function mountEffect(create, deps) {\n function updateEffect(create, deps) {\n   {\n     // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n-    if ('undefined' !== typeof jest) {\n+    if (globalThis.IS_REACT_ACT_ENVIRONMENT) {\n       warnIfNotCurrentlyActingEffectsInDEV(currentlyRenderingFiber$1);\n     }\n   }\n@@ -16130,7 +16130,7 @@ function dispatchAction(fiber, queue, action) {\n \n     {\n       // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n-      if ('undefined' !== typeof jest) {\n+      if (globalThis.IS_REACT_ACT_ENVIRONMENT) {\n         warnIfNotScopedWithMatchingAct(fiber);\n         warnIfNotCurrentlyActingUpdatesInDev(fiber);\n       }\n@@ -25436,7 +25436,7 @@ function updateContainer(element, container, parentComponent, callback) {\n \n   {\n     // $FlowExpectedError - jest isn't a global, and isn't recognized outside of tests\n-    if ('undefined' !== typeof jest) {\n+    if (globalThis.IS_REACT_ACT_ENVIRONMENT) {\n       warnIfUnmockedScheduler(current$1);\n       warnIfNotScopedWithMatchingAct(current$1);\n     }\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"extends\": [\"apollo-open-source\"],\n  \"ignorePaths\": [\"**/integration-tests/**\"],\n  \"dependencyDashboard\": true,\n  \"pathRules\": [\n    {\n      \"paths\": [\"docs/package.json\"],\n      \"extends\": [\"apollo-docs\"]\n    }\n  ],\n  \"packageRules\": [\n    {\n      \"groupName\": \"all @types\",\n      \"groupSlug\": \"all-types\",\n      \"matchPackagePatterns\": [\"@types/*\"]\n    },\n    {\n      \"groupName\": \"all devDependencies\",\n      \"groupSlug\": \"all-dev\",\n      \"matchPackagePatterns\": [\"*\"],\n      \"matchDepTypes\": [\"devDependencies\"]\n    },\n    {\n      \"groupName\": \"all dependencies - patch updates\",\n      \"groupSlug\": \"all-patch\",\n      \"matchPackagePatterns\": [\"*\"],\n      \"matchUpdateTypes\": [\"patch\"]\n    }\n  ],\n  \"ignoreDeps\": [\n    \"typedoc\",\n    \"react-17\",\n    \"react-dom-17\",\n    \"react-18\",\n    \"react-dom-18\",\n    \"@testing-library/react-12\",\n    \"@rollup/plugin-node-resolve\",\n    \"rollup\",\n    \"glob\",\n    \"prettier\",\n    \"eslint-plugin-react-compiler\",\n    \"graphql-17-alpha-2\",\n    \"graphql-17-alpha-9\"\n  ],\n  \"reviewers\": [],\n  \"reviewersFromCodeOwners\": false,\n  \"ignoreReviewers\": [\"team:@apollographql/client-typescript\"]\n}\n"
  },
  {
    "path": "scripts/changesets/categorized/categorize.js",
    "content": "import { glob, readFile, writeFile } from \"node:fs/promises\";\nimport { join, parse } from \"node:path\";\nimport { parseArgs } from \"node:util\";\n\nimport { dump, load } from \"js-yaml\";\n\nconst mdRegex = /\\s*---([^]*?)\\n\\s*---(\\s*(?:\\n|$)[^]*)/;\n\nconst categorizedFile = join(import.meta.dirname, \"categorized.yaml\");\nconst categorized = load(await readFile(categorizedFile, \"utf-8\")) || {};\n\nconst {\n  values: { updateExisting },\n} = parseArgs({\n  options: {\n    updateExisting: {\n      type: \"boolean\",\n      default: false,\n      short: \"u\",\n      description: \"Update the categorized file with new entries\",\n    },\n  },\n});\n\nfor await (const file of glob(\n  join(import.meta.dirname, \"../../../.changeset\", \"*.md\")\n)) {\n  const { name } = parse(file);\n  if (name === \"README\") continue;\n  const content = await readFile(file, \"utf-8\");\n  const match = mdRegex.exec(content);\n  if (!match) {\n    console.error(`File ${file} does not match expected format.`);\n    process.exit(1);\n  }\n  const [, frontmatter, body] = match;\n  const parsed = load(frontmatter) || {};\n  const tags = parsed._tags || [];\n  for (const tag of tags) {\n    categorized[tag] ??= {};\n    if (updateExisting || !categorized[tag][name]) {\n      categorized[tag][name] = body.trim();\n    }\n  }\n}\n\nawait writeFile(categorizedFile, dump(categorized));\n"
  },
  {
    "path": "scripts/changesets/categorized/categorized.yaml",
    "content": "codemod:\n  big-paws-invent: >-\n    Add a codemod that renames old import locations from 3.x entrypoint to their\n    4.x entrypoint.\n\n\n    Run the codemod using the following command:\n\n\n    ```sh\n\n    npx @apollo/client-codemod-migrate-3-to-4 --parser tsx ./src/**/*.{ts,tsx}\n\n    ```\n\n\n    The codemod supports `.js`, `.jsx`, `.ts`, and `.tsx` files.\nbundling:\n  small-kids-film: >-\n    Rework package publish format (#12329, #12382)\n\n\n    We have reworked the way Apollo Client is packaged.\n\n\n    * shipping ESM and CJS\n\n    * fixing up source maps\n\n    * the build targets a modern runtime environment (browserslist query:\n    `\"since 2023, node >= 20, not dead\"`)\n\n    * removed the \"proxy directory\" `package.json` files, e.g.\n    `cache/core/package.json` and `react/package.json`. While these helped with\n    older build tools, modern build tooling uses the `exports` field in the root\n    `package.json` instead and the presence of these files can confuse modern\n    build tooling. If your build tooling still relies on those, please update\n    your imports to import from e.g. `@apollo/client/cache/core/index.js`\n    instead of `@apollo/client/cache/core` - but generally, this should not be\n    necessary.\n\n    * added an `exports` field to `package.json` to expose entry points\n\n    * instead of `globalThis.__DEV__`, Apollo Client now primarily relies on the\n    `development` and `production` exports conditions. It falls back to\n    `globalThis.__DEV__` if the bundler doesn't know these, though.\n  real-gorillas-move: >-\n    Apollo Client now defaults to production mode, not development mode, if the\n\n    environment cannot be determined.\n\n\n    In modern bundlers, this should automatically be handled by the bundler\n    loading\n\n    the bundler with the `development` export condition.\n\n\n    If neither the `production` nor the `development` export condition are\n\n    used by the bundler/runtime, Apollo Client will fall back to\n    `globalThis.__DEV__`\n\n    to determine if it should run in production or development mode.\n\n\n    Unlike Apollo Client 3 though, if `globalThis.__DEV__` is not set to `true`,\n\n    Apollo Client will now default to `production`, not to `development`,\n    behaviour.\n\n\n    This switch to *explicilty* requiring `true` also resolves a situation where\n\n    an HTML element with `id=\"__DEV__\"` would create a global `__DEV__` variable\n\n    with a referent to the DOM element, which in the past was picked up as\n    \"truthy\" and\n\n    would have triggered development mode.\n  perfect-vans-give: |-\n    The `@apollo/client` and `@apollo/client/core` entry points are now equal.\n    In the next major, the `@apollo/client/core` entry point will be removed.\n    Please change imports over from `@apollo/client/core` to `@apollo/client`.\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  nasty-mayflies-smoke: |-\n    Ship React Compiler compiled React hooks in `@apollo/client/react/compiled`.\n\n    We now ship a React-Compiler compiled version of the React hooks in\n    `@apollo/client/react/compiled`.\n\n    This entry point contains everything that `@apollo/client/react` does,\n    so you can use it as a drop-in replacement in your whole application\n    if you choose to use the compiled hooks.\n  rare-houses-prove: Add `react-server` entry point with stubs for normal exports.\n  late-trainers-peel: >-\n    * dropped the deprecated `DEV` export from `@apollo/client/utilities` and\n    `@apollo/client/utilities/globals`\n\n    * moved the `__DEV__` export from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/environment`\n\n    * moved the `invariant`, `newInvariantError` and `InvariantError` exports\n    from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/invariant`\n  light-sloths-end: >-\n    Apollo Client is no longer using `ts-invariant`, but ships with a modified\n    variant of it.\n\n\n    The existing export `setLogVerbosity` from `@apollo/client` is still\n    available and\n\n    now points to this new integration.\n\n    **In most cases, you should be using this export.**\n\n    It will no longer adjust the verbosity of `ts-invariant` and as such no\n    longer\n\n    influence other packages relying on `ts-invariant`.\n\n\n    The new entry point `@apollo/client/utilities/invariant` now exports\n    `invariant`,\n\n    `InvariantError` and `setVerbosity`.\n\n    (Note that these tools are mostly meant to be used by Apollo Client and\n    libraries directly\n\n    based on Apollo Client like the `@apollo/client-integration-*` packages.)\n  sour-guests-poke: >-\n    Remove the `@apollo/client/testing/core` entrypoint in favor of\n    `@apollo/client/testing`.\n  sour-kids-deliver: Rename the `@apollo/client/link/core` entrypoint to `@apollo/client/link`.\npolyfills:\n  cool-bikes-shake: >-\n    Remove polyfills for Object.freeze,seal and preventExtensions in React\n    Native\n\n\n    These polyfills were only necessary until React Native 0.59, which\n\n    [patched the problem](https://github.com/facebook/react-native/pull/21492)\n    on\n\n    the React Native side.\n\n\n    With React Native 0.61, the `Map` function was [completely\n    replaced](https://github.com/facebook/react-native/commit/93b9ac74e59bbe84ea388d7c1879857b4acab114)\n\n    with a native implementation that never had the problems we guarded against.\n  smooth-pens-reply: >-\n    Require environments that support `WeakMap`, `WeakSet` and symbols. Apollo\n    Client would fallback to `Map` and `Set` if the weak versions were not\n    available. This has been removed and expects that these features are\n    available in the source environment.\n\n\n    If you are running in an environment without `WeakMap`, `WeakSet` or\n    symbols, you will need to find appropriate polyfills.\ndependencies:\n  silly-seas-confess: Drop `graphql` v15 as a valid peer dependency.\n  slow-ravens-explain: >-\n    Switch to [RxJS](https://rxjs.dev/) as the observable implementation. `rxjs`\n    is now a peer dependency of Apollo Client which means you will now need to\n    install `rxjs` in addition to `@apollo/client`.\n\n\n    This change is mostly transparent, however transforming values on\n    observables, common in link implementations, differs in RxJS vs\n    `zen-observable`. For example, you could modify values in the link chain\n    emitted from a downstream link by using the `.map` function. In RxJS, this\n    is done with the `.pipe` function and passing a `map` operator instead.\n\n\n    ```ts\n\n    import { map } from \"rxjs\";\n\n\n    const link new ApolloLink((operation, forward) => {\n      return forward(operation).pipe(\n        map((result) => performTransform(result))\n      );\n    });\n\n    ```\n\n\n    For a full list of operators and comprehensive documentation on the\n    capabilities of RxJS, check out the [documentation](https://rxjs.dev/).\n  clean-sheep-hide: |-\n    Drop `rehackt` dependency.\n    We can now directly import from `react` without causing build errors in RSC.\n  gold-planets-cover: Downgrade minimum supported `rxjs` peer dependency version to 7.3.0.\n  light-sloths-end: >-\n    Apollo Client is no longer using `ts-invariant`, but ships with a modified\n    variant of it.\n\n\n    The existing export `setLogVerbosity` from `@apollo/client` is still\n    available and\n\n    now points to this new integration.\n\n    **In most cases, you should be using this export.**\n\n    It will no longer adjust the verbosity of `ts-invariant` and as such no\n    longer\n\n    influence other packages relying on `ts-invariant`.\n\n\n    The new entry point `@apollo/client/utilities/invariant` now exports\n    `invariant`,\n\n    `InvariantError` and `setVerbosity`.\n\n    (Note that these tools are mostly meant to be used by Apollo Client and\n    libraries directly\n\n    based on Apollo Client like the `@apollo/client-integration-*` packages.)\nerrors:\n  good-dolphins-peel: >-\n    Apollo Client no longer wraps errors in `ApolloError`. `ApolloError` has\n    been replaced with separate error classes depending on the cause of the\n    error. As such, APIs that return an `error` property have been updated to\n    use the generic `Error` type. Use `instanceof` to check for more specific\n    error types.\n\n\n    ## Migration guide\n\n\n    `ApolloError` encapsulated 4 main error properties. The type of error would\n    determine which property was set:\n\n    - `graphqlErrors` - Errors returned from the `errors` field by the GraphQL\n    server\n\n    - `networkError` - Any non-GraphQL error that caused the query to fail\n\n    - `protocolErrors` - Transport-level errors that occur during [multipart\n    HTTP\n    subscriptions](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol)\n\n    - `clientErrors` - A space to define custom errors. Mostly unused.\n\n\n    These errors were mutally exclusive, meaning both `networkError` and\n    `graphqlErrors` were never set simultaneously. The following replaces each\n    of these fields from `ApolloError`.\n\n\n    ### `graphqlErrors`\n\n\n    GraphQL errors are now encapsulated in a `CombinedGraphQLErrors` instance.\n    You can access the raw GraphQL errors via the `errors` property.\n\n\n    ```js\n\n    import { CombinedGraphQLErrors } from '@apollo/client';\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    if (error && error instanceof CombinedGraphQLErrors) {\n      console.log(error.errors);\n    }\n\n    ```\n\n\n    ### `networkError`\n\n\n    Network errors are no longer wrapped and are instead passed through\n    directly.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.error(new Error('Test error'));\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // error is `new Error('Test error')`;\n\n    ```\n\n\n    ### `protocolErrors`\n\n\n    Protocol errors are now encapsulated in a `CombinedProtocolErrors` instance.\n    You can access the raw protocol errors via the `errors` property.\n\n\n\n    ```js\n\n    import { CombinedProtocolErrors } from '@apollo/client';\n\n\n    // ...\n\n\n    const { error } = useSubscription(subscription);\n\n\n    if (error && error instanceof CombinedProtocolErrors) {\n      console.log(error.errors);\n    }\n\n    ```\n\n\n    ### `clientErrors`\n\n\n    These were unused by the client and have no replacement. Any non-GraphQL or\n    non-protocol errors are now passed through unwrapped.\n\n\n    ### Strings as errors\n\n\n    If the link sends a string error, Apollo Client will wrap this in an `Error`\n    instance. This ensures `error` properties are guaranteed to be of type\n    `Error`.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          // Oops we sent a string instead of wrapping it in an `Error`\n          observer.error('Test error');\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // The error string is wrapped and returned as `new Error('Test error')`;\n\n    ```\n\n\n    ### Non-error types\n\n\n    If the link chain sends any other object type as an error, Apollo Client\n    will wrap this in an `UnknownError` instance with the\n    [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)\n    set to the original object. This ensures `error` properties are guaranteed\n    to be of type `Error`.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.error({ message: 'Not a proper error type' });\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // error is an `UnknownError` instance. error.cause returns the original\n    object.\n\n    ```\n  curvy-shoes-refuse: >-\n    More strictly adhere to the [GraphQL over HTTP\n    spec](https://graphql.github.io/graphql-over-http/draft/). This change adds\n    support for the `application/graphql-response+json` media type and modifies\n    the behavior of the `application/json` media type.\n\n\n    - The client will parse the response as a well-formed GraphQL response when\n    the server encodes `content-type` using `application/graphql-response+json`\n    with a non-200 status code.\n\n    - The client will now throw a `ServerError` when the server encodes\n    `content-type` using `application/json` and returns a non-200 status code.\n\n    - The client will now throw a `ServerError` when the server encodes using\n    any other `content-type` and returns a non-200 status code.\n\n\n    NOTE: If you use a testing utility to mock requests in your test, you may\n    experience different behavior than production if your testing utility\n    responds as `application/json` but your production server responds as\n    `application/graphql-response+json`. If a `content-type` header is not set,\n    the client interprets the response as `application/json`.\n  four-ghosts-watch: >-\n    Network errors triggered by queries now adhere to the `errorPolicy`. This\n    means that GraphQL errors and network errors now behave the same way.\n    Previously promise-based APIs, such as `client.query`, would reject the\n    promise with the network error even if `errorPolicy` was set to `ignore`.\n    The promise is now resolved with the `error` property set to the network\n    error instead.\n  four-countries-clean: >-\n    Add a static `is` method to error types defined by Apollo Client. `is` makes\n    it simpler to determine whether an error is a specific type, which can be\n    helpful in cases where you'd like to narrow the error type in order to use\n    specific properties from that error.\n\n\n    This change applies to the following error types:\n\n    - `CombinedGraphQLErrors`\n\n    - `CombinedProtocolErrors`\n\n    - `ServerError`\n\n    - `ServerParseError`\n\n    - `UnconventionalError`\n\n\n    **Example**\n\n\n    ```ts\n\n    import { CombinedGraphQLErrors } from \"@apollo/client\";\n\n\n    if (CombinedGraphQLErrors.is(error)) {\n      console.log(error.message);\n      error.errors.forEach((graphQLError) => console.log(graphQLError.message))\n    }\n\n    ```\n  bright-ads-share: >-\n    Removes the `isApolloError` utility function to check if the error object is\n    an `ApolloError` instance. Use `instanceof` to check for more specific error\n    types that replace `ApolloError`.\n  odd-chicken-hide: >-\n    Add the ability to detect if an error was an error was emitted from the link\n    chain. This is useful if your application throws custom errors in other\n    areas of the application and you'd like to differentiate them from errors\n    emitted by the link chain itself.\n\n\n    To detect if an error was emitted from the link chain, use `LinkError.is`.\n\n\n    ```ts\n\n    import { LinkError } from \"@apollo/client\";\n\n\n    client.query({ query }).catch((error) => {\n      if (LinkError.is(error)) {\n        // This error originated from the link chain\n      }\n    });\n\n    ```\n  nervous-fireants-bow: >-\n    Add a `data` property to `CombinedGraphQLErrors` that captures any partial\n    data returned by the GraphQL response when `errors` are also returned.\n  beige-hornets-smash: >-\n    Add an `extensions` property to `CombinedGraphQLErrors` to capture any\n    extensions from the original response.\n  many-papayas-hide: >-\n    `ObservableQuery` will no longer terminate on errors and will instead emit a\n    `next` value with an `error` property. This ensures that `ObservableQuery`\n    instances can continue to receive updates after errors are returned in\n    requests without the need to resubscribe to the observable.\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  old-mangos-grin: >-\n    Fix type of `error` argument on the `onError` option for `subscribeToMore`\n    to `ErrorLike`.\n  calm-seals-relate: >-\n    Remove the deprecated `errors` property from `useQuery` and `useLazyQuery`.\n    Read errors from the `error` property instead.\n  seven-foxes-melt: >-\n    The promise returned when calling the execute function from `useLazyQuery`\n    will now reject when using an `errorPolicy` of `none` when GraphQL errors\n    are returned from the result.\n  clever-islands-talk: >-\n    An error is now thrown when trying to call `fetchMore` on a `cache-only`\n    query.\n  grumpy-vans-type: >-\n    Unify error behavior on mutations for GraphQL errors and network errors by\n    ensuring network errors are subject to the `errorPolicy`. Network errors\n    created when using an `errorPolicy` of `all` will now resolve the promise\n    and be returned on the `error` property of the result, or stripped away when\n    the `errorPolicy` is `none`.\n  little-spoons-kick: >-\n    `client.mutate` now returns a `MutateResult` instead of `FetchResult`. As a\n    result, the `errors` property has been removed in favor of `error` which is\n    set if either a network error occured or GraphQL errors are returned from\n    the server.\n\n\n    `useMutation` now also returns a `MutateResult` instead of a `FetchResult`.\n  poor-eels-punch: >-\n    Mutations no longer report errors if the GraphQL result from the server\n    contains an empty array of errors.\n  giant-bags-share: >-\n    Throw an error for queries and mutations if the link chain completes without\n    emitting a value.\n  many-buses-allow: >-\n    Fix an issue where passing `onError` to `useMutation` would resolve the\n    promise returned by the `mutate` function instead of rejecting when using an\n    `errorPolicy` of `none`.\n  warm-ties-sit: >-\n    Subscriptions no longer emit errors in the `error` callback and instead\n    provide errors on the `error` property on the result passed to the `next`\n    callback. As a result, errors will no longer automatically terminate the\n    connection allowing additional results to be emitted when the connection\n    stays open.\n\n\n    When an error terminates the downstream connection, a `next` event will be\n    emitted with an `error` property followed by a `complete` event instead.\n  forty-shrimps-fry: >-\n    Subscriptions now emit a `SubscribeResult` instead of a `FetchResult`. As a\n    result, the `errors` field has been removed in favor of `error`.\n  tricky-tables-shave: >-\n    GraphQL errors or network errors emitted while using an `errorPolicy` of\n    `ignore` in subscriptions will no longer emit a result if there is no `data`\n    emitted along with the error.\n  real-teachers-peel: >-\n    Unify error behavior on subscriptions for GraphQL errors and network errors\n    by ensuring network errors are subject to the `errorPolicy`. Network errors\n    that terminate the connection will now be emitted on the `error` property\n    passed to the `next` callback followed by a call to the `complete` callback.\n  sharp-glasses-sneeze: >-\n    The `ErrorResponse` object passed to the `disable` and `retry` callback\n    options provided to `createPersistedQueryLink` no longer provides separate\n    `graphQLErrors` and `networkError` properties and instead have been combined\n    to a single `error` property of type `ErrorLike`.\n\n\n\n    ```diff\n\n    // The following also applies to the `retry` function since it has the same\n    signature\n\n    createPersistedQueryLink({\n\n    - disable: ({ graphQLErrors, networkError }) => {\n\n    + disable: ({ error }) => {\n\n    -   if (graphQLErrors) {\n\n    +   if (CombinedGraphQLErrors.is(error)) {\n          // ... handle GraphQL errors\n        }\n\n    -   if (networkError) {\n\n    +   if (error) {\n          // ... handle link errors\n        }\n\n        // optionally check for a specific kind of error\n    -   if (networkError) {\n\n    +   if (ServerError.is(error)) {\n          // ... handle a server error\n        }\n    });\n\n    ```\n\n\n    The `response` property has also been renamed to `result`.\n\n\n    ```diff\n\n    createPersistedQueryLink({\n\n    -  disable: ({ response }) => {\n\n    +  disable: ({ result }) => {\n          // ... handle GraphQL errors\n        }\n      }\n    });\n\n    ```\n  beige-mirrors-talk: >-\n    `onError` link now uses a single `error` property to report the error that\n    caused the link callback to be called. This will be an instance of\n    `CombinedGraphQLErrors` in the event GraphQL errors were emitted from the\n    terminating link, `CombinedProtocolErrors` if the terminating link emitted\n    protocol errors, or the unwrapped error type if any other non-GraphQL error\n    was thrown or emitted.\n\n\n    ```diff\n\n    - const errorLink = onError(({ graphQLErrors, networkError, protocolErrors\n    }) => {\n\n    -   graphQLErrors.forEach(error => console.log(error.message));\n\n    + const errorLink = onError(({ error }) => {\n\n    +   if (error.name === 'CombinedGraphQLErrors') {\n\n    +     error.errors.forEach(rawError => console.log(rawError.message));\n\n    +   }\n\n    });\n\n    ```\n  afraid-penguins-sniff: >-\n    Replace the `result` property on `ServerError` with `bodyText`. `bodyText`\n    is set to the raw string body. `HttpLink` and `BatchHttpLink` no longer try\n    and parse the response body as JSON when a `ServerError` is thrown.\n  cool-kiwis-hunt: >-\n    Add ability to specify message formatter for `CombinedGraphQLErrors` and\n    `CombinedProtocolErrors`. To provide your own message formatter, override\n    the static `formatMessage` property on these classes.\n\n\n    ```ts\n\n    CombinedGraphQLErrors.formatMessage = (errors, { result,\n    defaultFormatMessage }) => {\n      return \"Some formatted message\"\n    };\n\n\n    CombinedProtocolErrors.formatMessage = (errors, { defaultFormatMessage }) =>\n    {\n      return \"Some formatted message\"\n    };\n\n    ```\n  seven-dragons-repair: >-\n    Update format of the error message for `CombinedGraphQLErrors` and\n    `CombinedProtocolErrors` to be more like v3.x.\n\n\n    ```diff\n\n    console.log(error.message);\n\n    - `The GraphQL server returned with errors:\n\n    - - Email not found\n\n    - - Username already in use`\n\n    + `Email not found\n\n    + Username already in use`\n\n    ```\n  healthy-apes-sneeze: >-\n    Remove `fromError` utility function. Use\n    [`throwError`](https://rxjs.dev/api/index/function/throwError) instead.\n  mighty-penguins-wink: >-\n    Removes the `throwServerError` utility function. Now that `ServerError` is\n    an\n\n    `Error` subclass, you can throw these errors directly:\n\n\n    ```js\n\n    import { ServerError } from '@apollo/client';\n\n\n    // instead of\n\n    throwServerError(response, result, 'error message')\n\n\n    // Use\n\n    throw new ServerError('error message', { response, result })\n\n    ```\n  kind-fishes-develop: >-\n    Updates the `ServerError` and `ServerParseError` types to be proper `Error`\n    subclasses. Perviously these were plain `Error` intances with additional\n    properties added at runtime. All properties are retained, but `instanceof`\n    checks now work correctly.\n\n\n    ```js\n\n    import { ServerError, ServerParseError } from '@apollo/client';\n\n\n    if (error instanceof ServerError) {\n      // ...\n    }\n\n\n    if (error instanceof ServerParseError) {\n      // ...\n    }\n\n    ```\nrxjs:\n  slow-ravens-explain: >-\n    Switch to [RxJS](https://rxjs.dev/) as the observable implementation. `rxjs`\n    is now a peer dependency of Apollo Client which means you will now need to\n    install `rxjs` in addition to `@apollo/client`.\n\n\n    This change is mostly transparent, however transforming values on\n    observables, common in link implementations, differs in RxJS vs\n    `zen-observable`. For example, you could modify values in the link chain\n    emitted from a downstream link by using the `.map` function. In RxJS, this\n    is done with the `.pipe` function and passing a `map` operator instead.\n\n\n    ```ts\n\n    import { map } from \"rxjs\";\n\n\n    const link new ApolloLink((operation, forward) => {\n      return forward(operation).pipe(\n        map((result) => performTransform(result))\n      );\n    });\n\n    ```\n\n\n    For a full list of operators and comprehensive documentation on the\n    capabilities of RxJS, check out the [documentation](https://rxjs.dev/).\n  metal-needles-search: >-\n    ObservableQuery: implement the `rxjs` `InteropObservable` interface to\n    ensure `from(observableQuery)` stays possible\n  brave-radios-wait: >-\n    Remove the `asyncMap` utility function. Instead use one of the RxJS\n    operators that creates Observables from promises, such as `from`.\n  gold-planets-cover: Downgrade minimum supported `rxjs` peer dependency version to 7.3.0.\n  healthy-apes-sneeze: >-\n    Remove `fromError` utility function. Use\n    [`throwError`](https://rxjs.dev/api/index/function/throwError) instead.\n  smooth-coins-collect: >-\n    Remove `fromPromise` utility function. Use\n    [`from`](https://rxjs.dev/api/index/function/from) instead.\n  unlucky-sheep-change: >-\n    Remove `toPromise` utility function. Use\n    [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom)\n    instead.\nObservableQuery:\n  __behaviour: null\n  metal-needles-search: >-\n    ObservableQuery: implement the `rxjs` `InteropObservable` interface to\n    ensure `from(observableQuery)` stays possible\n  thin-peas-hear: >-\n    `notifyOnNetworkStatusChange` now defaults to `true`. This means that\n    loading states will be emitted (core API) or rendered (React) by default\n    when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set\n    `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n\n    ```ts\n\n    new ApolloClient({\n      defaultOptions: {\n        watchQuery: {\n          // Use the v3 default\n          notifyOnNetworkStatusChange: false\n        }\n      }\n    })\n\n    ```\n  khaki-keys-deliver: >-\n    An initial loading state is now emitted from `ObservableQuery` when\n    subscribing if `notifyOnNetworkStatusChange` is set to `true`.\n  many-papayas-hide: >-\n    `ObservableQuery` will no longer terminate on errors and will instead emit a\n    `next` value with an `error` property. This ensures that `ObservableQuery`\n    instances can continue to receive updates after errors are returned in\n    requests without the need to resubscribe to the observable.\n  few-crabs-move: >-\n    `ObservableQuery` will now keep previous `data` around when emitting a\n    `loading` state, unless `query` or `variables` changed.\n\n    Note that `@exports` variables are not taken into account for this, so\n    `data` will stay around even if they change.\n  shy-experts-cough: >-\n    `ObservableQuery`s will now only be registered with the `ApolloClient` while\n    they\n\n    have subscribers.\n\n\n    That means that `ApolloClient.getObservableQueries` and\n    `ApolloClient.refetchQueries`\n\n    will only be able to return/refetch queries that have at least one\n    subscriber.\n\n\n    This changes the previous meaning of `active` and `inactive` queries:\n\n    * `inactive` queries are queries with a subscriber that are skipped from a\n      React hook or have a `fetchPolicy` of `standby`\n    * `active` queries are queries with at least one subscriber that are not\n    skipped or in `standby`.\n\n\n    `ObservableQuery`s without subscribers but with an active ongoing network\n    request\n\n    (e.g. caused by calling `reobserve`) will be handled as if they had a\n    subscriber\n\n    for the duration of the query.\n  sixty-bats-cry: >-\n    Reworked the logic for then a loading state is triggered. If the link chain\n    responds synchronously, a loading state will be omitted, otherwise it will\n    be triggered.\n\n    If local resolvers are used, the time window for \"sync vs async\" starts as\n    soon as `@exports` variables are resolved.\n  dirty-trees-pump: >-\n    Unusubscribing from `ObservableQuery` while a request is in flight will no\n    longer terminate the request by unsubscribing from the link observable.\n  gold-sloths-battle: >-\n    Unsubscribing from an `ObservableQuery` before a value has been emitted will\n    remove the query from the tracked list of queries and will no longer be\n    eligible for query deduplication.\n  great-scissors-jam: >-\n    `cache-only` queries will now initialize with `loading: false` and\n    `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n\n    This means `useQuery` will no longer render a short initial loading state\n    before rendering `loading: false` and `ObservableQuery.getCurrentResult()`\n    will now return `loading: false` immediately.\n  sour-colts-tell: >-\n    `ObservableQuery` will now return a `loading: false` state for `fetchPolicy`\n    `standby`, even before subscription\n  __different_fn_behaviour: null\n  twelve-mangos-dance: >-\n    `ObservableQuery.refetch` and `ObservableQuery.reobserve` and the `execute`\n    function of `useLazyQuery` now return a\n\n    `ResultPromise` with an additional `.retain` method.\n\n    If this method is called, the underlying network operation will be kept\n    running even if the `ObservableQuery` itself does\n\n    not require the result anymore, and the Promise will resolve with the final\n    result instead of resolving with an intermediate\n\n    result in the case of early cancellation.\n  wicked-kiwis-buy: >-\n    A call to `ObservableQuery.setVariables` with different variables or a\n    `ObservableQuery.refetch` call will always now guarantee that a value will\n    be emitted from the observable, even if it is deep equal to the previous\n    value.\n  seven-jeans-trade: >-\n    Added a new `.stop` function on `ObservableQuery`.\n\n    Calling this method will unsubscribe all current subscribers by sending a\n    `complete` event from the observable and tear down the `ObservableQuery`.\n  forty-hairs-occur: >-\n    Calling `refetch` with new variables will now set the `networkStatus` to\n    `refetch` instead of `setVariables`.\n  four-tables-cheat: >-\n    `cache-only` queries are no longer refetched when calling\n    `client.reFetchObservableQueries` when `includeStandby` is `true`.\n  lemon-pans-sit: >-\n    `cache-only` queries are now excluded from `client.refetchQueries` in all\n    situations. `cache-only` queries affected by `updateCache` are also excluded\n    from `refetchQueries` when `onQueryUpdated` is not provided.\n  funny-terms-deny: >-\n    `ObservableQuery.variables` can now be reset back to empty when calling\n    `reobserve` with `variables: undefined`. Previously the `variables` key\n    would be ignored so `variables` would remain unchanged.\n  purple-lions-cough: >-\n    `ObservableQuery.setVariables` will now resolve with the last emitted result\n    instead of `undefined` when either the variables match the current variables\n    or there are no subscribers to the query.\n  itchy-chefs-run: >-\n    When passing a `variables` key with the value `undefined`, the value will be\n    replaced by the default value in the query, if it is provided, rather than\n    leave it as `undefined`.\n\n\n    ```ts\n\n    // given this query\n\n    const query = gql`\n      query PaginatedQuery($limit: Int! = 10, $offset: Int) {\n        list(limit: $limit, offset: $offset) {\n          id\n        }\n      }\n    `\n\n\n    const observable = client.query({ query, variables: { limit: 5, offset: 0\n    }});\n\n    console.log(observable.variables) // => { limit: 5, offset: 0 }\n\n\n    observable.reobserve({ variables: { limit: undefined, offset: 10 }})\n\n    // limit is now `10`. This would previously be `undefined`\n\n    console.log(observable.variables) // => { limit: 10, offset: 10 }\n\n    ```\n  __removals: null\n  tidy-squids-poke: >-\n    Removes `ObservableQuery.result()` method. If you use this method and need\n    similar functionality, use the `firstValueFrom` helper in RxJS.\n\n\n    ```ts\n\n    import { firstValueFrom, from } from \"rxjs\";\n\n\n    // The `from` is necessary to turn `observableQuery` into an RxJS observable\n\n    const result = await firstValueFrom(from(observableQuery))\n\n    ```\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  eighty-squids-fix: >-\n    `ObservableQuery.setOptions` has been removed as it was an alias of\n    `reobserve`. Prefer using `reobserve` directly instead.\n\n\n    ```diff\n\n    const observable = client.watchQuery(options);\n\n\n    // Use reobserve to set new options and reevaluate the query\n\n    - observable.setOptions(newOptions);\n\n    + observable.reobserve(newOptions);\n\n    ```\n\n\n    As a result of this change, `reobserve` has been marked for public use and\n    is no longer considered an internal API. The `newNetworkStatus` argument has\n    been removed to facilitate this change.\n  gold-oranges-double: >-\n    Removed `getLastResult`, `getLastError` and `resetLastResults` from\n    `ObservableQuery`\n  kind-crews-warn: >-\n    `ObservableQuery` no longer has a `queryId` property.\n\n    `ApolloClient.getObservableQueries` no longer returns a `Map<string,\n    ObservableQuery>`, but a `Set<ObservableQuery>`.\n  smart-rats-explode: >-\n    Remove `ObservableQuery.resetQueryStoreErrors` method. This method reset\n    some internal state that was not consumed elsewhere in the client and\n    resulted in a no-op.\n  spotty-mugs-poke: >-\n    Dropped the `saveAsLastResult` argument from\n    `ObservableQuery.getCurrentResult`\n  __fixes: null\n  fuzzy-tips-sit: >-\n    Ensure `ObservableQuery` stops polling if switching to a `standby`\n    `fetchPolicy`. When switching back to a non-`standby` `fetchPolicy`, polling\n    will resume.\n  rich-kids-carry: >-\n    Fix type of `data` property on `ApolloQueryResult`. Previously this field\n    was non-optional, non-null `TData`, however at runtime this value could be\n    set to `undefined`. This field is now reported as `TData | undefined`.\n\n\n    This will affect you in a handful of places:\n\n    - The `data` property emitted from the result passed to the `next` callback\n    from `client.watchQuery`\n\n    - Fetch-based APIs that return an `ApolloQueryResult` type such as\n    `observableQuery.refetch`, `observableQuery.fetchMore`, etc.\n  small-cycles-rescue: >-\n    Don't emit a partial cache result from `cache-only` queries when\n    `returnPartialData` is `false`.\n  small-poems-rest: Don't `broadcastQueries` when a query is torn down.\n  stupid-eagles-fetch: >-\n    `cache-only` queries no longer poll when a `pollInterval` is set. Instead a\n    warning is now emitted that polling has no effect. If the `fetchPolicy` is\n    changed to `cache-only` after polling is already active, polling is stopped.\n  tidy-pandas-punch: >-\n    `ObservableQuery.variables` has been updated to return `TVariables` rather\n    than `TVariables | undefined`. This is more consistent with the runtime\n    value where an empty object (`{}`) will be returned when the `variables`\n    option is not provided.\n  __unhandled: null\nobservableQuery.fetchMore:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nobservableQuery.refetch:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nobservableQuery.reobserve:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nobservableQuery.setVariables:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nnetwork_status:\n  beige-kings-grow: >-\n    A `@defer` query that has not yet finished streaming is now considered\n    loading and thus the `loading` flag will be `true` until the response has\n    completed. A new `NetworkStatus.streaming` value has been introduced and\n    will be set as the `networkStatus` while the response is streaming.\n  forty-hairs-occur: >-\n    Calling `refetch` with new variables will now set the `networkStatus` to\n    `refetch` instead of `setVariables`.\n  forty-tomatoes-punch: >-\n    The returned `networkStatus` in `useLazyQuery` is now set to `setVariables`\n    when calling the `useLazyQuery` `execute` function for the first time with\n    variables.\n  great-scissors-jam: >-\n    `cache-only` queries will now initialize with `loading: false` and\n    `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n\n    This means `useQuery` will no longer render a short initial loading state\n    before rendering `loading: false` and `ObservableQuery.getCurrentResult()`\n    will now return `loading: false` immediately.\n  khaki-keys-deliver: >-\n    An initial loading state is now emitted from `ObservableQuery` when\n    subscribing if `notifyOnNetworkStatusChange` is set to `true`.\n  large-plants-know: >-\n    Ensure a loading state is emitted when calling the `execute` function after\n    changing clients in `useLazyQuery`.\n  polite-bees-care: >-\n    `useLazyQuery` will no longer rerender with the loading state when calling\n    the execute function the first time unless the `notifyOnNetworkStatusChange`\n    option is set to `true` (which is the new default).\n\n\n    If you prefer the behavior from 3.x, rerender the component with\n\n    `notifyOnNetworkStatusChange` set to `false` after the execute function is\n\n    called the first time.\n\n\n    ```ts\n\n    function MyComponent() {\n      const [notifyOnNetworkStatusChange, setNotifyOnNetworkStatusChange] = useState(true);\n      const [execute] = useLazyQuery(query, { notifyOnNetworkStatusChange });\n\n      async function runExecute() {\n        await execute();\n\n        // Set to false after the initial fetch to stop receiving notifications\n        // about changes to the loading states.\n        setNotifyOnNetworkStatusChange(false);\n      }\n\n      // ...\n    }\n\n    ```\nfetch_policy:\n  clever-islands-talk: >-\n    An error is now thrown when trying to call `fetchMore` on a `cache-only`\n    query.\n  funny-jeans-invent: >-\n    `ssrMode`, `ssrForceFetchDelay` and `disableNetworkFetches` have been\n    reworked:\n\n\n    Previously, a `ObservableQuery` created by `client.query` or\n    `client.watchQuery`\n\n    while one of those were active would permanently be changed from a\n    `fetchPolicy`\n\n    of `\"network-only\"` or `\"cache-and-network\"` to `\"cache-first\"`, and stay\n    that way\n\n    even long after `disableNetworkFetches` would have been deactivated.\n\n\n    Now, the `ObservableQuery` will keep their original `fetchPolicy`, but\n    queries\n\n    made during `disableNetworkFetches` will just apply the `fetchPolicy`\n    replacement\n\n    at request time, just for that one request.\n\n\n    `ApolloClient.disableNetworkFetches` has been renamed to\n    `ApolloClient.prioritizeCacheValues` to better reflect this behaviour.\n  great-scissors-jam: >-\n    `cache-only` queries will now initialize with `loading: false` and\n    `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n\n    This means `useQuery` will no longer render a short initial loading state\n    before rendering `loading: false` and `ObservableQuery.getCurrentResult()`\n    will now return `loading: false` immediately.\n  loud-cows-raise: >-\n    `useQuery` with `ssr: false` - previously, `skip` had a higher priortity\n    than `ssr: false` while `ssr: false` had a higher priority than\n    `fetchPolicy: \"standby\"` (which is roughly equivalent to `skip`).\n\n\n    This priority has been adjusted so now both `skip` and `fetchPolicy:\n    \"standby\"` have a higher priority than `ssr: false` and will return\n    `loading: false`, while `ssr: false` will only come after those and will\n    return `loading: true` if those are not set.\n  sour-colts-tell: >-\n    `ObservableQuery` will now return a `loading: false` state for `fetchPolicy`\n    `standby`, even before subscription\n  young-snails-grin: >-\n    `client.query` no longer supports a `fetchPolicy` of `standby`. `standby`\n    does not fetch and did not return `data`. `standby` is meant for watched\n    queries where fetching should be on hold.\nfetchMore:\n  mighty-carrots-bathe: >-\n    Allow passing `errorPolicy` option to `fetchMore` and change default value\n    to \"none\".\n  old-melons-double: >-\n    Rework option handling for `fetchMore`.\n\n\n    * Previously, if the `query` option was specified, no options would be\n    inherited\n\n    from the underlying `ObservableQuery`.\n\n    Now, even if `query` is specified, all unspecified options except for\n    `variables` will be inherited from the underlying `ObservableQuery`.\n\n    * If `query` is not specified, `variables` will still be shallowly merged\n    with the `variables` of the underlying `ObservableQuery`. If a `query`\n    option is specified, the `variables` passed to `fetchMore` are used instead.\n\n    * `errorPolicy` of `fetchMore` will now always default to `\"none\"` instead\n    of inherited from the `ObservableQuery` options. This can prevent accidental\n    cache writes of partial data for a paginated query. To opt into receive\n    partial data that may be written to the cache, pass an `errorPolicy` to\n    `fetchMore` to override the default.\npolling:\n  fuzzy-tips-sit: >-\n    Ensure `ObservableQuery` stops polling if switching to a `standby`\n    `fetchPolicy`. When switching back to a non-`standby` `fetchPolicy`, polling\n    will resume.\nApolloClient:\n  brave-moons-juggle: Remove the `typeDefs` option from `ApolloClient`.\n  empty-meals-swim: >-\n    The `ApolloClient` constructor options `name` and `version` that are used to\n\n    configure the client awareness feature have moved onto a `clientAwareness`\n    key.\n\n\n    ```diff\n\n    const client = new ApolloClient({\n      // ..\n    -  name: \"my-app\",\n\n    -  version: \"1.0.0\",\n\n    +  clientAwareness: {\n\n    +    name: \"my-app\",\n\n    +    version: \"1.0.0\",\n\n    +  },\n\n    });\n\n    ```\n  funny-jeans-invent: >-\n    `ssrMode`, `ssrForceFetchDelay` and `disableNetworkFetches` have been\n    reworked:\n\n\n    Previously, a `ObservableQuery` created by `client.query` or\n    `client.watchQuery`\n\n    while one of those were active would permanently be changed from a\n    `fetchPolicy`\n\n    of `\"network-only\"` or `\"cache-and-network\"` to `\"cache-first\"`, and stay\n    that way\n\n    even long after `disableNetworkFetches` would have been deactivated.\n\n\n    Now, the `ObservableQuery` will keep their original `fetchPolicy`, but\n    queries\n\n    made during `disableNetworkFetches` will just apply the `fetchPolicy`\n    replacement\n\n    at request time, just for that one request.\n\n\n    `ApolloClient.disableNetworkFetches` has been renamed to\n    `ApolloClient.prioritizeCacheValues` to better reflect this behaviour.\n  gentle-files-laugh: >-\n    Remove deprecated `connectToDevtools` option from `ApolloClientOptions`. Use\n    `devtools.enabled` instead.\n  gorgeous-chefs-tap: >-\n    Remove the `TCacheShape` generic argument to `ApolloClient`.\n    `client.extract()` now returns `unknown` by default. You will either need to\n    type-cast this to the expected serialized shape, or use the\n    `cache.extract()` directly from the subclass to get more specific types.\n  little-parrots-bow: >-\n    Removes the `resolvers` option from `ApolloClient`. Local resolvers have\n    instead been moved to the new `LocalState` instance which is assigned to the\n    `localState` option in `ApolloClient`. To migrate, move the `resolvers`\n    values into a `LocalState` instance and assign that instance to\n    `localState`.\n\n\n    ```diff\n\n    new ApolloClient({\n\n    - resolvers: { /* ... */ }\n\n    + localState: new LocalState({\n\n    +   resolvers: { /* ... */ }\n\n    + }),\n\n    });\n\n    ```\n  ninety-nails-compete: >-\n    Renamed `client.reFetchObservableQueries` to\n    `client.refetchObservableQueries`.\n\n    `client.reFetchObservableQueries` is still available as an alias, but is now\n\n    deprecated and will be removed in a future major version.\n  olive-cougars-ring: >-\n    Remove local resolvers APIs from `ApolloClient` in favor of `localState`.\n    Methods removed are:\n\n    - `addResolvers`\n\n    - `getResolvers`\n\n    - `setResolvers`\n\n    - `setLocalStateFragmentMatcher`\n  stupid-pumpkins-travel: >-\n    Apollo Client no longer ships with support for `@client` fields\n    out-of-the-box and now must be opt-in. To opt in to use `@client` fields,\n    pass an instantiated `LocalState` instance to the `localState` option. If a\n    query contains `@client` and local state hasn't been configured, an error\n    will be thrown.\n\n\n    ```ts\n\n    import { LocalState } from \"@apollo/client/local-state\";\n\n\n    new ApolloClient({\n      localState: new LocalState(),\n    });\n\n    ```\n  thirty-pens-jump: >-\n    Remove the `fragmentMatcher` option from `ApolloClient`. Custom fragment\n    matchers used with local state are no longer supported. Fragment matching is\n    now performed by the configured `cache` via the `cache.fragmentMatches` API.\n  wicked-queens-lick: >-\n    `ApolloClient.stop()` now cleans up more agressively to prevent memory\n    leaks:\n\n\n    * It will now unsubscribe all active `ObservableQuery` instances by emitting\n    a `completed` event.\n\n    * It will now reject all currently running queries with `\"QueryManager\n    stopped while query was in flight\"`.\n\n    * It will remove all queryRefs from the suspense cache.\n  witty-paws-marry: >-\n    Require the `link` option when instantiating `ApolloClient`. This removes\n    the `uri`, `credentials` and `headers` options from `ApolloClient` in favor\n    of passing an instantiated `HttpLink` directly. To migrate:\n\n\n    **If using `uri`, `credentials`, or `headers` options**\n\n    ```diff\n\n    new ApolloClient({\n      // ...\n    - uri,\n\n    - credentials,\n\n    - headers,\n\n    + link: new HttpLink({ uri, credentials, headers }),\n\n    // or if you prefer the function call approach:\n\n    + link: createHttpLink({ uri, credentials, headers }),\n\n    });\n\n    ```\n\n\n    **If creating a client without the `link` option**\n\n    ```diff\n\n    new ApolloClient({\n      // ...\n    + link: ApolloLink.empty()\n\n    });\n\n    ```\nclient.watchQuery:\n  fluffy-shoes-applaud: Remove deprecated `partialRefetch` option.\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  rich-kids-carry: >-\n    Fix type of `data` property on `ApolloQueryResult`. Previously this field\n    was non-optional, non-null `TData`, however at runtime this value could be\n    set to `undefined`. This field is now reported as `TData | undefined`.\n\n\n    This will affect you in a handful of places:\n\n    - The `data` property emitted from the result passed to the `next` callback\n    from `client.watchQuery`\n\n    - Fetch-based APIs that return an `ApolloQueryResult` type such as\n    `observableQuery.refetch`, `observableQuery.fetchMore`, etc.\n  thin-peas-hear: >-\n    `notifyOnNetworkStatusChange` now defaults to `true`. This means that\n    loading states will be emitted (core API) or rendered (React) by default\n    when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set\n    `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n\n    ```ts\n\n    new ApolloClient({\n      defaultOptions: {\n        watchQuery: {\n          // Use the v3 default\n          notifyOnNetworkStatusChange: false\n        }\n      }\n    })\n\n    ```\nclient.subscribe:\n  forty-shrimps-fry: >-\n    Subscriptions now emit a `SubscribeResult` instead of a `FetchResult`. As a\n    result, the `errors` field has been removed in favor of `error`.\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  pink-ladybugs-cough: >-\n    Subscriptions created by `client.subscribe()` can now be restarted.\n    Restarting a subscription will terminate the connection with the link chain\n    and recreate the request. Restarts also work across deduplicated\n    subscriptions so calling `restart` on an `observable` who's request is\n    deduplicated will restart the connection for each observable.\n\n\n    ```ts\n\n    const observable = client.subscribe({ query: subscription });\n\n\n    // Restart the connection to the link\n\n    observable.restart();\n\n    ```\n  tough-tips-drop: >-\n    Subscriptions are no longer eagerly started after calling\n    `client.subscribe`. To kick off the subscription, you will now need to\n    subscribe to the returned observable.\n\n\n    ```ts\n\n    // Subscriptions are no longer started when calling subscribe on its own.\n\n    const subscriptionObservable = client.subscribe(...);\n\n\n    // Instead, subscribe to the returned observable to kick off the\n    subscription.\n\n    subscriptionObservable.subscribe({\n      next: (value) => console.log(value)\n    });\n\n    ```\n  warm-ties-sit: >-\n    Subscriptions no longer emit errors in the `error` callback and instead\n    provide errors on the `error` property on the result passed to the `next`\n    callback. As a result, errors will no longer automatically terminate the\n    connection allowing additional results to be emitted when the connection\n    stays open.\n\n\n    When an error terminates the downstream connection, a `next` event will be\n    emitted with an `error` property followed by a `complete` event instead.\nclient.query:\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\n  young-snails-grin: >-\n    `client.query` no longer supports a `fetchPolicy` of `standby`. `standby`\n    does not fetch and did not return `data`. `standby` is meant for watched\n    queries where fetching should be on hold.\nclient.mutate:\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  tough-rockets-allow: >-\n    Fix an issue where additional response properties were returned on the\n    result returned from `client.mutate`, such as `@defer` payload fields. These\n    properties are now stripped out to correspond to the TypeScript type.\nclient.refetchObservableQueries:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nclient.resetStore:\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nclient.refetchQueries:\n  lemon-pans-sit: >-\n    `cache-only` queries are now excluded from `client.refetchQueries` in all\n    situations. `cache-only` queries affected by `updateCache` are also excluded\n    from `refetchQueries` when `onQueryUpdated` is not provided.\n  shy-experts-cough: >-\n    `ObservableQuery`s will now only be registered with the `ApolloClient` while\n    they\n\n    have subscribers.\n\n\n    That means that `ApolloClient.getObservableQueries` and\n    `ApolloClient.refetchQueries`\n\n    will only be able to return/refetch queries that have at least one\n    subscriber.\n\n\n    This changes the previous meaning of `active` and `inactive` queries:\n\n    * `inactive` queries are queries with a subscriber that are skipped from a\n      React hook or have a `fetchPolicy` of `standby`\n    * `active` queries are queries with at least one subscriber that are not\n    skipped or in `standby`.\n\n\n    `ObservableQuery`s without subscribers but with an active ongoing network\n    request\n\n    (e.g. caused by calling `reobserve`) will be handled as if they had a\n    subscriber\n\n    for the duration of the query.\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\nclient.getObservableQueries:\n  shy-experts-cough: >-\n    `ObservableQuery`s will now only be registered with the `ApolloClient` while\n    they\n\n    have subscribers.\n\n\n    That means that `ApolloClient.getObservableQueries` and\n    `ApolloClient.refetchQueries`\n\n    will only be able to return/refetch queries that have at least one\n    subscriber.\n\n\n    This changes the previous meaning of `active` and `inactive` queries:\n\n    * `inactive` queries are queries with a subscriber that are skipped from a\n      React hook or have a `fetchPolicy` of `standby`\n    * `active` queries are queries with at least one subscriber that are not\n    skipped or in `standby`.\n\n\n    `ObservableQuery`s without subscribers but with an active ongoing network\n    request\n\n    (e.g. caused by calling `reobserve`) will be handled as if they had a\n    subscriber\n\n    for the duration of the query.\ntypes:\n  cuddly-spiders-tie: >-\n    Remove `TSerialized` generic argument to `ApolloCache`. The `ApolloCache`\n    base cache abstraction now returns `unknown` for `cache.extract` which can\n    be overridden by a cache subclass.\n  curvy-lamps-sing: >-\n    Provide a mechanism to override the DataMasking types.\n\n\n    Up until now, our types `Masked`, `MaskedDocumentNode`, `FragmentType`,\n    `MaybeMasked` and `Unmasked` would assume that you are stictly using the\n    type output format of GraphQL Codegen.\n\n\n    With this change, you can now modify the behaviour of those types if you use\n    a different form of codegen that produces different types for your queries.\n\n\n    A simple implementation that would override the `Masked` type to remove all\n    fields starting with `_` from a type would look like this:\n\n\n    ```ts\n\n    // your actual implementation of `Masked`\n\n    type CustomMaskedImplementation<TData> = {\n      [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n    };\n\n\n    import { HKT } from \"@apollo/client/utilities\";\n\n    // transform this type into a higher kinded type that can be evaulated at a\n    later time\n\n    interface CustomMaskedType extends HKT {\n      arg1: unknown; // TData\n      return: CustomMaskedImplementation<this[\"arg1\"]>;\n    }\n\n\n    // create an \"implementation interface\" for the types you want to override\n\n    export interface CustomDataMaskingImplementation {\n      Masked: CustomMaskedType;\n      // other possible keys: `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked`\n    }\n\n    ```\n\n    then you would use that `CustomDataMaskingImplementation` interface in your\n    project to extend the `TypeOverrides` interface exported by `@apollo/client`\n    with it's functionality:\n\n\n    ```ts\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides extends CustomDataMaskingImplementation {}\n    }\n\n    ```\n\n\n    After that, all internal usage of `Masked` in Apollo Client as well as all\n    usage in your code base will use the new `CustomMaskedType` implementation.\n\n\n    If you don't specify overrides, Apollo Client will still default to the\n    GraphQL Codegen data masking implementation.\n\n    The types for that are also explicitly exported as the\n    `GraphQLCodegenDataMasking` namespace in `@apollo/client/masking`.\n  eleven-candles-smoke: >-\n    Change the `unsafePreviousData` argument on `UpdateQueryMapFn` and\n    `SubscribeToMoreQueryFn` to a `DeepPartial` since the result may contain\n    partial data.\n  forty-shrimps-fry: >-\n    Subscriptions now emit a `SubscribeResult` instead of a `FetchResult`. As a\n    result, the `errors` field has been removed in favor of `error`.\n  fuzzy-plants-approve: |-\n    Remove these incremental-format-specific types:\n\n    * `ExecutionPatchIncrementalResult`\n    * `ExecutionPatchInitialResult`\n    * `ExecutionPatchResult`\n    * `IncrementalPayload`\n    * `Path`\n  gentle-badgers-train: >-\n    `never` is no longer supported as a valid `TVariables` generic argument for\n    APIs that require `variables` as part of its type. Use `Record<string,\n    never>` instead.\n  gorgeous-chefs-tap: >-\n    Remove the `TCacheShape` generic argument to `ApolloClient`.\n    `client.extract()` now returns `unknown` by default. You will either need to\n    type-cast this to the expected serialized shape, or use the\n    `cache.extract()` directly from the subclass to get more specific types.\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  healthy-books-flash: >-\n    The `TData` generic provided to types that return a `dataState` property is\n    now modified by the given `DataState` generic instead of passing a modified\n    `TData` type. For example, a `QueryRef` that could return partial data was\n    defined as `QueryRef<DeepPartial<TData>, TVariables>`. Now `TData` should be\n    provided unmodified and a set of allowed states should be given instead:\n    `QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>`.\n\n\n    To migrate, use the following guide to replace your type with the right set\n    of states (all types listed below are changed the same way):\n\n\n    ```diff\n\n    - QueryRef<TData, TVariables>\n\n    // `QueryRef`'s default is 'complete' | 'streaming' so this can also be left\n    alone if you prefer\n\n    // All other types affected by this change default to all states\n\n    + QueryRef<TData, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming'>\n\n\n    - QueryRef<TData | undefined, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'empty'>\n\n\n    - QueryRef<DeepPartial<TData>, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>\n\n\n    - QueryRef<DeepPartial<TData> | undefined, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial' |\n    'empty'>\n\n    ```\n\n\n    The following types are affected. Provide the allowed `dataState` values to\n    the `TDataState` generic:\n\n    - `ApolloQueryResult`\n\n    - `QueryRef`\n\n    - `PreloadedQueryRef`\n\n    - `useLazyQuery.Result`\n\n    - `useQuery.Result`\n\n    - `useReadQuery.Result`\n\n    - `useSuspenseQuery.Result`\n\n\n    All `*QueryRef` types default to `complete | streaming` states while the\n    rest of the types default to `'complete' | 'streaming' | 'partial' |\n    'empty'` states. You shouldn't need to provide the states unless you need to\n    either allow for partial data/empty values (`*QueryRef`) or a restricted set\n    of states.\n  healthy-ghosts-report: >-\n    The callback function that can be passed to the `ApolloClient.mutate`\n\n    `refetchQueries` option will now receive a `FormattedExecutionResult` with\n    an\n\n    additional `dataState` option that describes if the result is `\"streaming\"`\n\n    or `\"complete\"`.\n\n    This indicates whether the `data` value is of type\n\n    * `Unmasked<TData>` (if `\"complete\"`)\n\n    * `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n  hip-vans-act: >-\n    Default `TVariables` generic type to `OperationVariables` instead of `any`\n    throughout the client in areas that did not yet have the default as such.\n  hungry-bikes-cough: >-\n    Fix type of `variables` returned from `useLazyQuery`. When `called` is\n    `false`, `variables` is now `Partial<TVariables>` instead of `TVariables`.\n  khaki-spies-work: >-\n    Flatten out React hook types. As a result, the base types have been removed.\n    Prefer using the hook types instead. Removed types include:\n\n    - `BaseMutationOptions`\n\n    - `BaseQueryOptions`\n\n    - `BaseSubscriptionOptions`\n\n    - `ObservableQueryFields`\n\n    - `MutationSharedOptions`\n\n    - `QueryFunctionOptions`\n  little-spoons-kick: >-\n    `client.mutate` now returns a `MutateResult` instead of `FetchResult`. As a\n    result, the `errors` property has been removed in favor of `error` which is\n    set if either a network error occured or GraphQL errors are returned from\n    the server.\n\n\n    `useMutation` now also returns a `MutateResult` instead of a `FetchResult`.\n  lucky-sheep-explain: >-\n    Provide an extension to define types for `context` passed to the link chain.\n    To define your own types, use [declaration\n    merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)\n    to add properties to the `DefaultContext` type.\n\n\n    ```ts\n\n    // @apollo-client.d.ts\n\n    // This import is necessary to ensure all Apollo Client imports\n\n    // are still available to the rest of the application.\n\n    import '@apollo/client';\n\n\n    declare module \"@apollo/client\" {\n      interface DefaultContext extends Record<string, any> {\n        myProperty: string;\n      }\n    }\n\n    ```\n\n\n    Links that provide context options can be used with this type to add those\n    context types to `DefaultContext`. For example, to add context options from\n    `HttpLink`, add the following code:\n\n\n    ```ts\n\n    import { HttpLink } from \"@apollo/client\";\n\n\n    declare module \"@apollo/client\" {\n      interface DefaultContext extends HttpLink.ContextOptions {\n        myProperty: string;\n      }\n    }\n\n    ```\n\n\n    At this time, the following built-in links support context options:\n\n    - `HttpLink.ContextOptions`\n\n    - `BatchHttpLink.ContextOptions`\n  modern-feet-do: >-\n    `@apollo/client`, `@apollo/client/core` and `@apollo/client/cache` no longer\n    export an empty `Cache` runtime object. This is meant to be a type-only\n    namespace.\n  moody-lobsters-listen: >-\n    The `Cache.DiffResult<T>` type is now a union type with better type safety\n    for both complete and partial results. Checking `diff.complete` will now\n    narrow the type of `result` depending on whether the value is `true` or\n    `false`.\n\n\n    When `true`, `diff.result` will be a non-null value equal to the `T` generic\n    type. When `false`, `diff.result` now reports `result` as `DeepPartial<T> |\n    null` indicating that fields in the result may be missing (`DeepPartial<T>`)\n    or empty entirely (`null`).\n  new-apes-care: Remove the deprecated `QueryReference` type. Please use `QueryRef` instead.\n  nice-waves-work: >-\n    The result resolved from the promise returned from the execute function in\n    `useLazyQuery` is now an `ApolloQueryResult` type and no longer includes all\n    the fields returned from the `useLazyQuery` hook tuple.\n\n\n    If you need access to the additional properties such as `called`, `refetch`,\n    etc. not included in `ApolloQueryResult`, read them from the hook instead.\n  odd-lemons-relax: >-\n    Rename all React hook result types and options. These types have all moved\n    under a namespace that matches the hook name. For example, `useQuery`\n    exports `useQuery.Options` and `useQuery.Result` types. As such, the old\n    hook types have been deprecated and will be removed in v5.\n  old-mangos-grin: >-\n    Fix type of `error` argument on the `onError` option for `subscribeToMore`\n    to `ErrorLike`.\n  orange-suits-laugh: >-\n    Adjust `useMutation` types to better handle required variables. When\n    required variables are missing, TypeScript will now complain if they are not\n    provided either to the hook or the returned `mutate` function. Providing\n    required variables to `useMutation` will make them optional in the returned\n    `mutate` function.\n  plenty-deers-clean: >-\n    Added a new `Streaming` type that will mark `data` in results while\n    `dataState`\n\n    is `\"streaming\"`.\n\n\n    `Streaming<TData>` defaults to `TData`, but can be overwritten in userland\n    to\n\n    integrate with different codegen dialects.\n\n\n    You can override this type globally - this example shows how to override it\n\n    with `DeepPartial<TData>`:\n\n    ```ts\n\n    import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n\n    type StreamingOverride<TData> = DeepPartial<TData>;\n\n\n    interface StreamingOverrideHKT extends HKT {\n      return: StreamingOverride<this[\"arg1\"]>;\n    }\n\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides {\n        Streaming: StreamingOverrideHKT;\n      }\n    }\n\n    ```\n  poor-spiders-hunt: >-\n    Move `MockLink` types to `MockLink` namespace. This affects the\n    `MockedResponse`, `MockLinkOptions`, and `ResultFunction` types. These types\n    are still exported but are deprecated in favor of the namespace. To migrate,\n    use the types on the `MockLink` namespace instead.\n\n\n    ```diff\n\n    import {\n\n    - MockedResponse,\n\n    - MockLinkOptions,\n\n    - ResultFunction,\n\n    + MockLink\n\n    } from \"@apollo/client/testing\";\n\n\n    - const mocks: MockedResponse = [];\n\n    + const mocks: MockLink.MockedResponse = [];\n\n\n    - const result: ResultFunction = () => {/* ... */ }\n\n    + const result: MockLink.ResultFunction = () => {/* ... */ }\n\n\n    - const options: MockLinkOptions = {}\n\n    + const options: MockLink.Options = {}\n\n    ```\n  proud-walls-shave: >-\n    Overridable types for `dataState: \"complete\"`, `dataState: \"streaming\"` and\n\n    `dataState: \"partial\"` responses.\n\n\n    This adds the `DataValue` namespace exported from Apollo Client with the\n    three\n\n    types `DataValue.Complete`, `DataValue.Streaming` and `DataValue.Partial`.\n\n\n    These types will be used to mark `TData` in the respective states.\n\n\n    * `Complete` defaults to `TData`\n\n    * `Streaming` defaults to `TData`\n\n    * `Partial` defaults to `DeepPartial<TData>`\n\n\n    All three can be overwritten, e.g. to be `DeepReadonly` using higher kinded\n    types\n\n    by following this pattern:\n\n\n    ```ts\n\n    import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n    import { DeepReadonly } from \"some-type-helper-library\";\n\n\n    interface CompleteOverride extends HKT {\n      return: DeepReadonly<this[\"arg1\"]>;\n    }\n\n\n    interface StreamingOverride extends HKT {\n      return: DeepReadonly<this[\"arg1\"]>;\n    }\n\n\n    interface PartialOverride extends HKT {\n      return: DeepReadonly<DeepPartial<this[\"arg1\"]>>;\n    }\n\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides {\n        Complete: CompleteOverride;\n        Streaming: StreamingOverride;\n        Partial: PartialOverride;\n      }\n    }\n\n    ```\n  rich-kids-carry: >-\n    Fix type of `data` property on `ApolloQueryResult`. Previously this field\n    was non-optional, non-null `TData`, however at runtime this value could be\n    set to `undefined`. This field is now reported as `TData | undefined`.\n\n\n    This will affect you in a handful of places:\n\n    - The `data` property emitted from the result passed to the `next` callback\n    from `client.watchQuery`\n\n    - Fetch-based APIs that return an `ApolloQueryResult` type such as\n    `observableQuery.refetch`, `observableQuery.fetchMore`, etc.\n  rude-fans-study: >-\n    Deprecate the `partial` flag on `ApolloQueryResult` and make it a\n    non-optional property. Previously `partial` was only set conditionally if\n    the result emitted was partial. This value is now available with all results\n    that return an `ApolloQueryResult`.\n  selfish-spoons-approve: >-\n    Move internal testing utilities in `@apollo/client/testing` to\n    `@apollo/client/testing/internal` and remove deprecated testing utilities.\n    Some of the testing utilities exported from the `@apollo/client/testing`\n    endpoint were not considered stable. As a result of this change, testing\n    utilities or types exported from `@apollo/client/testing` are now considered\n    stable and will not undergo breaking changes.\n\n\n    The following APIs were removed. To migrate, update usages of the following\n    APIs as such:\n\n\n    **`createMockClient`**\n\n\n    ```diff\n\n    - const client = createMockClient(data, query, variables);\n\n    + const client = new ApolloClient({\n\n    +   cache: new InMemoryCache(),\n\n    +   link: new MockLink([\n\n    +     {\n\n    +       request: { query, variables },\n\n    +       result: { data },\n\n    +     }\n\n    +   ]),\n\n    + });\n\n    ```\n\n\n    **`mockObservableLink`**\n\n\n    ```diff\n\n    - const link = mockObservableLink();\n\n    + const link = new MockSubscriptionLink();\n\n    ```\n\n\n    **`mockSingleLink`**\n\n\n    ```diff\n\n    - const link = mockSingleLink({\n\n    -   request: { query, variables },\n\n    -   result: { data },\n\n    - });\n\n    + const link = new MockLink([\n\n    +   {\n\n    +     request: { query, variables },\n\n    +     result: { data },\n\n    +   }\n\n    + ]);\n\n    ```\n  short-tomatoes-attend: >-\n    Remove `TContext` generic argument from all types that use it. `TContext` is\n    replaced with `DefaultContext` which can be modified using declaration\n    merging.\n  sixty-bears-bathe: >-\n    The `FetchMoreQueryOptions` type has been inlined into `FetchMoreOptions`,\n    and\n\n    `FetchMoreQueryOptions` has been removed.\n  sour-donuts-sit: >-\n    Prioritize usage of `FormattedExecutionResult` over `FetchResult` where\n    applicable.\n\n\n    Many APIs used `FetchResult` in place of `FormattedExecutionResult`, which\n    could\n\n    cause inconsistencies.\n\n\n    * `FetchResult` is now used to refer to an unhandled \"raw\" result as\n    returned from\n      a link.\n      This can also include incremental results that use a different format.\n    * `FormattedExecutionResult` from the `graphql` package is now used to\n    represent\n      the execution of a standard GraphQL request without incremental results.\n\n    If your custom links access the `data` property, you might need to first\n    check if\n\n    the result is a standard GraphQL result by using the\n    `isFormattedExecutionResult`\n\n    helper from `@apollo/client/utilities`.\n  tidy-pandas-punch: >-\n    `ObservableQuery.variables` has been updated to return `TVariables` rather\n    than `TVariables | undefined`. This is more consistent with the runtime\n    value where an empty object (`{}`) will be returned when the `variables`\n    option is not provided.\n  young-phones-fold: >-\n    Default the `TData` generic type to `unknown` in all APIs that use a `TData`\n    generic argument such as `useQuery`, `client.query`, etc.\n  rude-crabs-eat: >-\n    The `operation` argument to the callback passed to `SetContextLink` is now\n    of type `SetContextLink.SetContextOperation` which is an `Operation` without\n    the `getContext` or `setContext` functions. Previously the type of\n    `operation` was `GraphQLRequest` which had access to a `context` property.\n    The `context` property was always `undefined` and could result in bugs when\n    using it instead of the `prevContext` argument.\n\n\n    This change means the `operation` argument now contains an accessible\n    `client` property.\ndataState:\n  healthy-books-flash: >-\n    The `TData` generic provided to types that return a `dataState` property is\n    now modified by the given `DataState` generic instead of passing a modified\n    `TData` type. For example, a `QueryRef` that could return partial data was\n    defined as `QueryRef<DeepPartial<TData>, TVariables>`. Now `TData` should be\n    provided unmodified and a set of allowed states should be given instead:\n    `QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>`.\n\n\n    To migrate, use the following guide to replace your type with the right set\n    of states (all types listed below are changed the same way):\n\n\n    ```diff\n\n    - QueryRef<TData, TVariables>\n\n    // `QueryRef`'s default is 'complete' | 'streaming' so this can also be left\n    alone if you prefer\n\n    // All other types affected by this change default to all states\n\n    + QueryRef<TData, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming'>\n\n\n    - QueryRef<TData | undefined, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'empty'>\n\n\n    - QueryRef<DeepPartial<TData>, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial'>\n\n\n    - QueryRef<DeepPartial<TData> | undefined, TVariables>\n\n    + QueryRef<TData, TVariables, 'complete' | 'streaming' | 'partial' |\n    'empty'>\n\n    ```\n\n\n    The following types are affected. Provide the allowed `dataState` values to\n    the `TDataState` generic:\n\n    - `ApolloQueryResult`\n\n    - `QueryRef`\n\n    - `PreloadedQueryRef`\n\n    - `useLazyQuery.Result`\n\n    - `useQuery.Result`\n\n    - `useReadQuery.Result`\n\n    - `useSuspenseQuery.Result`\n\n\n    All `*QueryRef` types default to `complete | streaming` states while the\n    rest of the types default to `'complete' | 'streaming' | 'partial' |\n    'empty'` states. You shouldn't need to provide the states unless you need to\n    either allow for partial data/empty values (`*QueryRef`) or a restricted set\n    of states.\n  healthy-ghosts-report: >-\n    The callback function that can be passed to the `ApolloClient.mutate`\n\n    `refetchQueries` option will now receive a `FormattedExecutionResult` with\n    an\n\n    additional `dataState` option that describes if the result is `\"streaming\"`\n\n    or `\"complete\"`.\n\n    This indicates whether the `data` value is of type\n\n    * `Unmasked<TData>` (if `\"complete\"`)\n\n    * `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n  plenty-deers-clean: >-\n    Added a new `Streaming` type that will mark `data` in results while\n    `dataState`\n\n    is `\"streaming\"`.\n\n\n    `Streaming<TData>` defaults to `TData`, but can be overwritten in userland\n    to\n\n    integrate with different codegen dialects.\n\n\n    You can override this type globally - this example shows how to override it\n\n    with `DeepPartial<TData>`:\n\n    ```ts\n\n    import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n\n    type StreamingOverride<TData> = DeepPartial<TData>;\n\n\n    interface StreamingOverrideHKT extends HKT {\n      return: StreamingOverride<this[\"arg1\"]>;\n    }\n\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides {\n        Streaming: StreamingOverrideHKT;\n      }\n    }\n\n    ```\n  proud-walls-shave: >-\n    Overridable types for `dataState: \"complete\"`, `dataState: \"streaming\"` and\n\n    `dataState: \"partial\"` responses.\n\n\n    This adds the `DataValue` namespace exported from Apollo Client with the\n    three\n\n    types `DataValue.Complete`, `DataValue.Streaming` and `DataValue.Partial`.\n\n\n    These types will be used to mark `TData` in the respective states.\n\n\n    * `Complete` defaults to `TData`\n\n    * `Streaming` defaults to `TData`\n\n    * `Partial` defaults to `DeepPartial<TData>`\n\n\n    All three can be overwritten, e.g. to be `DeepReadonly` using higher kinded\n    types\n\n    by following this pattern:\n\n\n    ```ts\n\n    import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n\n    import { DeepReadonly } from \"some-type-helper-library\";\n\n\n    interface CompleteOverride extends HKT {\n      return: DeepReadonly<this[\"arg1\"]>;\n    }\n\n\n    interface StreamingOverride extends HKT {\n      return: DeepReadonly<this[\"arg1\"]>;\n    }\n\n\n    interface PartialOverride extends HKT {\n      return: DeepReadonly<DeepPartial<this[\"arg1\"]>>;\n    }\n\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides {\n        Complete: CompleteOverride;\n        Streaming: StreamingOverride;\n        Partial: PartialOverride;\n      }\n    }\n\n    ```\n  ten-sloths-punch: >-\n    The `mutationResult` option passed to the `updateQueries` callback now has\n    an\n\n    additional property, `dataState` with possible values of `\"complete\"` and\n    `\"streaming\"`.\n\n    This indicates whether the `data` value is of type\n\n    * `Unmasked<TData>` (if `\"complete\"`)\n\n    * `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\n  wild-carpets-exercise: >-\n    Add a new `dataState` property that determines the completeness of the\n    `data` property. `dataState` helps narrow the type of `data`. `dataState` is\n    now emitted from `ObservableQuery` and returned from all React hooks that\n    return a `data` property.\n\n\n    The `dataState` values are:\n\n\n    - `empty`: No data could be fulfilled from the cache or the result is\n    incomplete. `data` is `undefined`.\n\n    - `partial`: Some data could be fulfilled from the cache but `data` is\n    incomplete. This is only possible when `returnPartialData` is `true`.\n\n    - `streaming`: `data` is incomplete as a result of a deferred query and the\n    result is still streaming in.\n\n    - `complete`: `data` is a fully satisfied query result fulfilled either from\n    the cache or network.\n\n\n    Example:\n\n\n    ```ts\n\n    const { data, dataState } = useQuery<TData>(query);\n\n\n    if (dataState === 'empty') {\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n\n\n    if (dataState === 'partial') {\n      expectTypeOf(data).toEqualTypeOf<DeepPartial<TData>>();\n    }\n\n\n    if (dataState === 'streaming') {\n      expectTypeOf(data).toEqualTypeOf<TData>();\n    }\n\n\n    if (dataState === 'complete') {\n      expectTypeOf(data).toEqualTypeOf<TData>();\n    }\n\n    ```\nqueries:\n  empty-rats-cough: Aliasing any other field to `__typename` is now forbidden.\n  hot-seahorses-film: >-\n    Aliasing a field to an alias beginning with `__ac_` is now forbidden - this\n    namespace is now reserved for internal use.\n  itchy-chefs-run: >-\n    When passing a `variables` key with the value `undefined`, the value will be\n    replaced by the default value in the query, if it is provided, rather than\n    leave it as `undefined`.\n\n\n    ```ts\n\n    // given this query\n\n    const query = gql`\n      query PaginatedQuery($limit: Int! = 10, $offset: Int) {\n        list(limit: $limit, offset: $offset) {\n          id\n        }\n      }\n    `\n\n\n    const observable = client.query({ query, variables: { limit: 5, offset: 0\n    }});\n\n    console.log(observable.variables) // => { limit: 5, offset: 0 }\n\n\n    observable.reobserve({ variables: { limit: undefined, offset: 10 }})\n\n    // limit is now `10`. This would previously be `undefined`\n\n    console.log(observable.variables) // => { limit: 10, offset: 10 }\n\n    ```\nmutations:\n  ten-sloths-punch: >-\n    The `mutationResult` option passed to the `updateQueries` callback now has\n    an\n\n    additional property, `dataState` with possible values of `\"complete\"` and\n    `\"streaming\"`.\n\n    This indicates whether the `data` value is of type\n\n    * `Unmasked<TData>` (if `\"complete\"`)\n\n    * `Streaming<Unmasked<TData>>` (if `\"streaming\"`)\ndata_masking:\n  curvy-lamps-sing: >-\n    Provide a mechanism to override the DataMasking types.\n\n\n    Up until now, our types `Masked`, `MaskedDocumentNode`, `FragmentType`,\n    `MaybeMasked` and `Unmasked` would assume that you are stictly using the\n    type output format of GraphQL Codegen.\n\n\n    With this change, you can now modify the behaviour of those types if you use\n    a different form of codegen that produces different types for your queries.\n\n\n    A simple implementation that would override the `Masked` type to remove all\n    fields starting with `_` from a type would look like this:\n\n\n    ```ts\n\n    // your actual implementation of `Masked`\n\n    type CustomMaskedImplementation<TData> = {\n      [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n    };\n\n\n    import { HKT } from \"@apollo/client/utilities\";\n\n    // transform this type into a higher kinded type that can be evaulated at a\n    later time\n\n    interface CustomMaskedType extends HKT {\n      arg1: unknown; // TData\n      return: CustomMaskedImplementation<this[\"arg1\"]>;\n    }\n\n\n    // create an \"implementation interface\" for the types you want to override\n\n    export interface CustomDataMaskingImplementation {\n      Masked: CustomMaskedType;\n      // other possible keys: `MaskedDocumentNode`, `FragmentType`, `MaybeMasked` and `Unmasked`\n    }\n\n    ```\n\n    then you would use that `CustomDataMaskingImplementation` interface in your\n    project to extend the `TypeOverrides` interface exported by `@apollo/client`\n    with it's functionality:\n\n\n    ```ts\n\n    declare module \"@apollo/client\" {\n      export interface TypeOverrides extends CustomDataMaskingImplementation {}\n    }\n\n    ```\n\n\n    After that, all internal usage of `Masked` in Apollo Client as well as all\n    usage in your code base will use the new `CustomMaskedType` implementation.\n\n\n    If you don't specify overrides, Apollo Client will still default to the\n    GraphQL Codegen data masking implementation.\n\n    The types for that are also explicitly exported as the\n    `GraphQLCodegenDataMasking` namespace in `@apollo/client/masking`.\nsubscriptions:\n  rare-apes-drive: >-\n    Deduplicating subscription operations is now supported. Previously it was\n    possible to deduplicate a subscription only if the new subscription was\n    created before a previously subscribed subscription emitted any values. As\n    soon as a value was emitted from a subscription, new subscriptions would\n    create new connections. Deduplication is now active for as long as a\n    subscription connection is open (i.e. the source observable hasn't emitted a\n    `complete` or `error` notification yet.)\n\n\n    To disable deduplication and force a new connection, use the\n    `queryDeduplication` option in `context` like you would a query operation.\n\n\n    As a result of this change, calling the `restart` function returned from\n    `useSubscription` will now restart the connection on deduplicated\n    subscriptions.\nLocalState:\n  flat-readers-invite: >-\n    Introduce a new GraphQL Codegen plugin aimed at creating resolver types for\n    `LocalState`. This plugin is similar to\n    `@graphql-codegen/typescript-resolvers` but tailored to provide types that\n    work with `LocalState`.\n\n\n    To use the plugin, install `@apollo/client-graphql-codegen` and add the\n    following to your codegen config:\n\n\n    ```ts\n\n    // codegen.ts\n\n\n    const config: CodegenConfig = {\n      // ...\n      generates: {\n        \"./path/to/local/resolvers.ts\": {\n          schema: [\n            \"./path/to/localSchema.graphql\",\n          ],\n          plugins: [\n            \"typescript\",\n            \"@apollo/client-graphql-codegen/local-state\",\n          ],\n          // ...\n        }\n      }\n    }\n\n    ```\n\n\n    This will generate a `Resolvers` type in the generated file that can be used\n    to provide type information to `LocalState`.\n\n\n    ```ts\n\n    import type { Resolvers } from \"./path/to/resolvers-types.ts\";\n\n\n    const localState = new LocalState<Resolvers>({\n      // ...\n    });\n\n    ```\n\n\n    It is also recommended to add the following config:\n\n    ```ts\n\n    // codegen.ts\n\n    import type { LocalStatePluginConfig } from\n    \"@apollo/client-graphql-codegen/local-state\";\n\n\n    const config: CodegenConfig = {\n      // ...\n      generates: {\n        \"./path/to/local/resolvers.ts\": {\n          config: {\n            // Ensures you return a `__typename` for any `@client` fields that\n            // return object or array types\n            nonOptionalTypename: true,\n\n            // Required if your localSchema extends existing schema types.\n            baseTypesPath: \"./relative/path/to/base/schema/types\",\n\n            // If you provide a `context` function to customize the context value,\n            // provide the path or type here.\n            contextType: \"./path/to/contextValue#ContextValue\",\n          } satisfies LocalStatePluginConfig\n        }\n      }\n    }\n\n    ```\n\n\n    NOTE: It is recommended that the schema file passed to the `schema` option\n    is your local schema, not your entire app schema in order to only generate\n    resolver types for your local fields, otherwise the plugin will generate\n    resolver types for your entire remote schema as well.\n  funny-boats-wink: >-\n    Revamp local resolvers and fix several issues from the existing `resolvers`\n    option.\n\n    - Throwing errors in a resolver will set the field value as `null` and add\n    an error to the response's `errors` array.\n\n    - Remote results are dealiased before they are passed as the parent object\n    to a resolver so that you can access fields by their field name.\n\n    - You can now specify a `context` function that you can use to customize the\n    `requestContext` given to resolvers.\n\n    - The `LocalState` class accepts a `Resolvers` generic that provides\n    autocompletion and type checking against your resolver types to ensure your\n    resolvers are type-safe.\n\n    - `data: null` is now handled correctly and does not call your local\n    resolvers when the server does not provide a result.\n\n    - Additional warnings have been added to provide hints when resolvers behave\n    unexpectedly.\n\n\n    ```ts\n\n    import { LocalState } from \"@apollo/client/local-state\";\n\n\n    import { Resolvers } from \"./path/to/local-resolvers-types.ts\";\n\n\n    // LocalState now accepts a `Resolvers` generic.\n\n    const localState = new LocalState<Resolvers>({\n      // The return value of this funciton\n      context: (options) => ({\n        // ...\n      }),\n      resolvers: {\n        // ...\n      }\n    });\n\n\n    // You may also pass a `ContextValue` generic used to ensure the `context`\n\n    // function returns the correct type. This type is inferred from your\n    resolvers\n\n    // if not provided.\n\n    new LocalState<Resolvers, ContextValue>({\n      // ...\n    });\n\n    ```\n  kind-taxis-thank: >-\n    Don't warn about a missing resolver if a `@client` does not have a\n    configured resolver. It is possible the cache contains a `read` function for\n    the field and the warning added confusion.\n\n\n    Note that `read` functions without a defined resolver will receive the\n    `existing` argument as `null` instead of `undefined` even when data hasn't\n    been written to the cache. This is because `LocalState` sets a default value\n    of `null` when a resolver is not defined to ensure that the field contains a\n    value in case a `read` function is not defined rather than omitting the\n    field entirely.\n  little-parrots-bow: >-\n    Removes the `resolvers` option from `ApolloClient`. Local resolvers have\n    instead been moved to the new `LocalState` instance which is assigned to the\n    `localState` option in `ApolloClient`. To migrate, move the `resolvers`\n    values into a `LocalState` instance and assign that instance to\n    `localState`.\n\n\n    ```diff\n\n    new ApolloClient({\n\n    - resolvers: { /* ... */ }\n\n    + localState: new LocalState({\n\n    +   resolvers: { /* ... */ }\n\n    + }),\n\n    });\n\n    ```\n  olive-cougars-ring: >-\n    Remove local resolvers APIs from `ApolloClient` in favor of `localState`.\n    Methods removed are:\n\n    - `addResolvers`\n\n    - `getResolvers`\n\n    - `setResolvers`\n\n    - `setLocalStateFragmentMatcher`\n  strong-rivers-fry: >-\n    The resolver function's `context` argument (the 3rd argument) has changed to\n    provide additional information without the possibility of name clashes.\n    Previously the `context` argument would spread request context and override\n    the `client` and `cache` properties to give access to both inside of a\n    resolver. The `context` argument takes now takes the following shape:\n\n\n    ```ts\n\n    {\n      // the request context. By default `TContextValue` is of type `DefaultContext`,\n      // but can be changed if a `context` function is provided.\n      requestContext: TContextValue,\n      // The client instance making the request\n      client: ApolloClient,\n      // Whether the resolver is run as a result of gathering exported variables\n      // or resolving the value as part of the result\n      phase: \"exports\" | \"resolve\"\n    }\n\n    ```\n\n\n    To migrate, pull any request context from `requestContext` and the `cache`\n    from the `client` property:\n\n\n    ```diff\n\n    new LocalState({\n      resolvers: {\n        Query: {\n    -     myResolver: (parent, args, { someValue, cache }) => {\n\n    +     myResolver: (parent, args, { requestContext, client }) => {\n\n    +       const someValue = requestContext.someValue;\n\n    +       const cache = client.cache;\n          }\n        }\n      }\n    });\n\n    ```\n  stupid-pumpkins-travel: >-\n    Apollo Client no longer ships with support for `@client` fields\n    out-of-the-box and now must be opt-in. To opt in to use `@client` fields,\n    pass an instantiated `LocalState` instance to the `localState` option. If a\n    query contains `@client` and local state hasn't been configured, an error\n    will be thrown.\n\n\n    ```ts\n\n    import { LocalState } from \"@apollo/client/local-state\";\n\n\n    new ApolloClient({\n      localState: new LocalState(),\n    });\n\n    ```\n  thirty-pens-jump: >-\n    Remove the `fragmentMatcher` option from `ApolloClient`. Custom fragment\n    matchers used with local state are no longer supported. Fragment matching is\n    now performed by the configured `cache` via the `cache.fragmentMatches` API.\ncodegen:\n  flat-readers-invite: >-\n    Introduce a new GraphQL Codegen plugin aimed at creating resolver types for\n    `LocalState`. This plugin is similar to\n    `@graphql-codegen/typescript-resolvers` but tailored to provide types that\n    work with `LocalState`.\n\n\n    To use the plugin, install `@apollo/client-graphql-codegen` and add the\n    following to your codegen config:\n\n\n    ```ts\n\n    // codegen.ts\n\n\n    const config: CodegenConfig = {\n      // ...\n      generates: {\n        \"./path/to/local/resolvers.ts\": {\n          schema: [\n            \"./path/to/localSchema.graphql\",\n          ],\n          plugins: [\n            \"typescript\",\n            \"@apollo/client-graphql-codegen/local-state\",\n          ],\n          // ...\n        }\n      }\n    }\n\n    ```\n\n\n    This will generate a `Resolvers` type in the generated file that can be used\n    to provide type information to `LocalState`.\n\n\n    ```ts\n\n    import type { Resolvers } from \"./path/to/resolvers-types.ts\";\n\n\n    const localState = new LocalState<Resolvers>({\n      // ...\n    });\n\n    ```\n\n\n    It is also recommended to add the following config:\n\n    ```ts\n\n    // codegen.ts\n\n    import type { LocalStatePluginConfig } from\n    \"@apollo/client-graphql-codegen/local-state\";\n\n\n    const config: CodegenConfig = {\n      // ...\n      generates: {\n        \"./path/to/local/resolvers.ts\": {\n          config: {\n            // Ensures you return a `__typename` for any `@client` fields that\n            // return object or array types\n            nonOptionalTypename: true,\n\n            // Required if your localSchema extends existing schema types.\n            baseTypesPath: \"./relative/path/to/base/schema/types\",\n\n            // If you provide a `context` function to customize the context value,\n            // provide the path or type here.\n            contextType: \"./path/to/contextValue#ContextValue\",\n          } satisfies LocalStatePluginConfig\n        }\n      }\n    }\n\n    ```\n\n\n    NOTE: It is recommended that the schema file passed to the `schema` option\n    is your local schema, not your entire app schema in order to only generate\n    resolver types for your local fields, otherwise the plugin will generate\n    resolver types for your entire remote schema as well.\ncache:\n  moody-lobsters-listen: >-\n    The `Cache.DiffResult<T>` type is now a union type with better type safety\n    for both complete and partial results. Checking `diff.complete` will now\n    narrow the type of `result` depending on whether the value is `true` or\n    `false`.\n\n\n    When `true`, `diff.result` will be a non-null value equal to the `T` generic\n    type. When `false`, `diff.result` now reports `result` as `DeepPartial<T> |\n    null` indicating that fields in the result may be missing (`DeepPartial<T>`)\n    or empty entirely (`null`).\n  rare-dingos-doubt: >-\n    Remove the check and warning for `cache.fragmentMatches` when applying data\n    masking. `cache.fragmentMatches` is a required API and data masking may\n    crash when `cache.fragmentMatches` does not exist.\n  serious-items-develop: >-\n    Third-party caches must now implement the `fragmentMatches` API.\n    Additionally `fragmentMatches` must be able to handle both\n    `InlineFragmentNode` and `FragmentDefinitionNode` nodes.\n\n\n    ```ts\n\n    class MyCache extends ApolloCache {\n      // This is now required\n      public fragmentMatches(\n        fragment: InlineFragmentNode | FragmentDefinitionNode,\n        typename: string\n      ): boolean {\n        return // ... logic to determine if typename matches fragment\n      }\n    }\n\n    ```\n  yellow-cats-judge: >-\n    ### Changes for users of `InMemoryCache`\n\n\n    `cache.diff` no longer throws when `returnPartialData` is set to `false`\n    without a complete result. Instead, `cache.diff` will return `null` when it\n    is unable to read a full cache result.\n\n\n    If you use `cache.diff` directly with `returnPartialData: false`, remove the\n    `try`/`catch` block and replace with a check for `null`.\n\n\n    ### Changes for third-party cache implementations\n\n\n    The client now expects `cache.diff` to return `null` instead of throwing\n    when the cache returns an incomplete result and `returnPartialData` is\n    `false`. The internal `try`/`catch` blocks have been removed around\n    `cache.diff`. If your cache implementation throws for incomplete results,\n    please update this to return `null`.\n  pretty-rocks-behave: >-\n    Deprecate second argument to `readFragment` and `readQuery` - `optimistic`\n    should be passed as part of the object in the first argument instead.\n  calm-frogs-remain: >-\n    Removes the `addTypename` option from `InMemoryCache` and `MockedProvider`.\n    `__typename` is now always added to the outgoing query document when using\n    `InMemoryCache` and cannot be disabled.\n\n\n    If you are using `<MockedProvider />` with `addTypename={false}`, ensure\n    that your mocked responses include a `__typename` field. This will ensure\n    cache normalization kicks in and behaves more like production.\n  eleven-moons-heal: Remove deprecated `resultCacheMaxSize` option from `InMemoryCache` options.\nInMemoryCache:\n  tall-cups-suffer: >-\n    ### Changes for users of `InMemoryCache`\n\n\n    `cache.diff` now returns `null` instead of an empty object (`{}`) when\n    `returnPartialData` is `true` and the result is empty.\n\n\n    If you use `cache.diff` directly with `returnPartialData: true`, you will\n    need to check for `null` before accessing any other fields on the `result`\n    property. A non-null value indicates that at least one field was present in\n    the cache for the given query document.\n\n\n    ### Changes for third-party cache implementations\n\n\n    The client now expects `cache.diff` to return `null` instead of an empty\n    object when there is no data that can be fulfilled from the cache and\n    `returnPartialData` is `true`. If your cache implementation returns an empty\n    object, please update this to return `null`.\n  yellow-cats-judge: >-\n    ### Changes for users of `InMemoryCache`\n\n\n    `cache.diff` no longer throws when `returnPartialData` is set to `false`\n    without a complete result. Instead, `cache.diff` will return `null` when it\n    is unable to read a full cache result.\n\n\n    If you use `cache.diff` directly with `returnPartialData: false`, remove the\n    `try`/`catch` block and replace with a check for `null`.\n\n\n    ### Changes for third-party cache implementations\n\n\n    The client now expects `cache.diff` to return `null` instead of throwing\n    when the cache returns an incomplete result and `returnPartialData` is\n    `false`. The internal `try`/`catch` blocks have been removed around\n    `cache.diff`. If your cache implementation throws for incomplete results,\n    please update this to return `null`.\nimports:\n  afraid-grapes-call: Export `gql` from the `@apollo/client/react` entrypoint.\n  clean-sloths-travel: Export the `IgnoreModifier` type from `@apollo/client/cache`.\n  dirty-cobras-change: >-\n    Move most of the utilities in `@apollo/client/utilities` to\n    `@apollo/client/utilities/internal`. Many of the utilities exported from the\n    `@apollo/client/utilities` endpoint were not considered stable.\n\n\n    As a result of this change, utilities or types exported from\n    `@apollo/client/utilities` are now documented and considered stable and will\n    not undergo breaking changes.\n  dirty-eagles-poke: >-\n    Removed the `@apollo/client/react/context` and `@apollo/client/react/hooks`\n    entry points. Please use `@apollo/client/react` instead.\n  late-trainers-peel: >-\n    * dropped the deprecated `DEV` export from `@apollo/client/utilities` and\n    `@apollo/client/utilities/globals`\n\n    * moved the `__DEV__` export from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/environment`\n\n    * moved the `invariant`, `newInvariantError` and `InvariantError` exports\n    from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/invariant`\n  perfect-vans-give: |-\n    The `@apollo/client` and `@apollo/client/core` entry points are now equal.\n    In the next major, the `@apollo/client/core` entry point will be removed.\n    Please change imports over from `@apollo/client/core` to `@apollo/client`.\ntesting:\n  afraid-moons-arrive: >-\n    Allow mocked responses passed to `MockLink` to accept a callback for the\n    `delay` option. The `delay` callback will be given the current operation\n    which can be used to determine what delay should be used for the mock.\n  calm-frogs-remain: >-\n    Removes the `addTypename` option from `InMemoryCache` and `MockedProvider`.\n    `__typename` is now always added to the outgoing query document when using\n    `InMemoryCache` and cannot be disabled.\n\n\n    If you are using `<MockedProvider />` with `addTypename={false}`, ensure\n    that your mocked responses include a `__typename` field. This will ensure\n    cache normalization kicks in and behaves more like production.\n  early-eggs-develop: >-\n    Introduce a new `realisticDelay` helper function for use with the `delay`\n    callback for mocked responses used with `MockLink`. `realisticDelay` will\n    generate a random value between 20 and 50ms to provide an experience closer\n    to unpredictable network latency. `realisticDelay` can be configured with a\n    `min` and `max` to set different thresholds if the defaults are not\n    sufficient.\n\n\n    ```ts\n\n    import { realisticDelay } from '@apollo/client/testing';\n\n\n    new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: 'Hello' }},\n        delay: realisticDelay()\n      },\n      {\n        request: { query },\n        result: { data: { greeting: 'Hello' }},\n        delay: realisticDelay({ min: 10, max: 100 })\n      },\n    ]);\n\n    ```\n  friendly-olives-refuse: >-\n    Remove the `@apollo/client/testing/experimental` test utilities. Use\n    [GraphQL Testing\n    Library](https://github.com/apollographql/graphql-testing-library) instead.\n  ninety-bags-bake: >-\n    Mocked responses passed to `MockLink` now accept a callback for the\n    `request.variables` option. This is used to determine if the mock should be\n    matched for a set of request variables. With this change, the\n    `variableMatcher` option has been removed in favor of passing a callback to\n    `variables`. Update by moving the callback function from `variableMatcher`\n    to `request.variables`.\n\n\n    ```diff\n\n    new MockLink([\n      {\n        request: {\n          query,\n    +     variables: (requestVariables) => true\n        },\n    -   variableMatcher: (requestVariables) => true\n      }\n    ]);\n\n    ```\n  short-months-complain: >-\n    Throw an error when a client-only query is used in a mocked response passed\n    to `MockLink`.\n  sour-guests-poke: >-\n    Remove the `@apollo/client/testing/core` entrypoint in favor of\n    `@apollo/client/testing`.\n  swift-rivers-share: >-\n    Default the `delay` for all mocked responses passed to `MockLink` using\n    `realisticDelay`. This ensures your test handles loading states by default\n    and is not reliant on a specific timing.\n\n\n    If you would like to restore the old behavior, use a global default delay of\n    `0`.\n\n\n    ```ts\n\n    MockLink.defaultOptions = {\n      delay: 0\n    }\n\n    ```\n  wicked-forks-double: >-\n    Remove `newData` option for mocked responses passed to `MockLink` or the\n    `mocks` option on `MockedProvider`. This option was undocumented and was\n    nearly identical to using the `result` option as a callback.\n\n\n    To replicate the old behavior of `newData`, use `result` as a callback and\n    add the `maxUsageCount` option with a value set to\n    `Number.POSITIVE_INFINITY`.\n\n\n    **with `MockLink`**\n\n    ```diff\n\n    new MockLink([\n      {\n        request: { query, variables },\n    -   newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   maxUsageCount: Number.POSITIVE_INFINITY,\n      }\n    ])\n\n    ```\n\n\n    **with `MockedProvider`**\n\n    ```diff\n\n    <MockedProvider\n      mocks={[\n        {\n          request: { query, variables },\n    -     newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     maxUsageCount: Number.POSITIVE_INFINITY,\n        }\n      ]}\n    />\n\n    ```\n  shaggy-pugs-add: >-\n    Add ability to specify a default `delay` for all mocked responses passed to\n    `MockLink`. This `delay` can be configured globally (all instances of\n    `MockLink` will use the global defaults), or per-instance (all mocks in a\n    single instance will use the defaults). A `delay` defined on a single mock\n    will supercede all default delays. Per-instance defaults supercede global\n    defaults.\n\n\n    **Global defaults**\n\n\n    ```ts\n\n    MockLink.defaultOptions = {\n      // Use a default delay of 20ms for all mocks in all instances without a specified delay\n      delay: 20,\n\n      // altenatively use a callback which will be executed for each mock\n      delay: () => getRandomNumber(),\n\n      // or use the built-in `realisticDelay`. This is the default\n      delay: realisticDelay(),\n    }\n\n    ```\n\n\n    **Per-instance defaults**\n\n\n    ```ts\n\n    new MockLink(\n      [\n        // Use the default delay\n        {\n          request: { query },\n          result: { data: { greeting: 'Hello' }},\n        },\n        {\n          request: { query },\n          result: { data: { greeting: 'Hello' }},\n          // Override the default for this mock\n          delay: 10\n        },\n      ],\n      {\n        defaultOptions: {\n          // Use a default delay of 20ms for all mocks without a specified delay\n          delay: 20,\n\n          // altenatively use a callback which will be executed for each mock\n          delay: () => getRandomNumber(),\n\n          // or use the built-in `realisticDelay`. This is the default\n          delay: realisticDelay(),\n        }\n      }\n    );\n\n    ```\nlinks:\n  afraid-moons-arrive: >-\n    Allow mocked responses passed to `MockLink` to accept a callback for the\n    `delay` option. The `delay` callback will be given the current operation\n    which can be used to determine what delay should be used for the mock.\n  beige-houses-fail: >-\n    The `includeExtensions` option of `HttpLink` and `BatchHttpLink` now\n    defaults\n\n    to `true`.\n\n\n    If `includeExtensions` is `true`, but `extensions` is not set or empty,\n    extensions\n\n    will not be included in outgoing requests.\n  beige-mirrors-talk: >-\n    `onError` link now uses a single `error` property to report the error that\n    caused the link callback to be called. This will be an instance of\n    `CombinedGraphQLErrors` in the event GraphQL errors were emitted from the\n    terminating link, `CombinedProtocolErrors` if the terminating link emitted\n    protocol errors, or the unwrapped error type if any other non-GraphQL error\n    was thrown or emitted.\n\n\n    ```diff\n\n    - const errorLink = onError(({ graphQLErrors, networkError, protocolErrors\n    }) => {\n\n    -   graphQLErrors.forEach(error => console.log(error.message));\n\n    + const errorLink = onError(({ error }) => {\n\n    +   if (error.name === 'CombinedGraphQLErrors') {\n\n    +     error.errors.forEach(rawError => console.log(rawError.message));\n\n    +   }\n\n    });\n\n    ```\n  curvy-flies-accept: >-\n    The `getCacheKey` function is no longer available from\n    `operation.getContext()` in the link chain. Use\n    `operation.client.cache.identify(obj)` in the link chain instead.\n  early-eggs-develop: >-\n    Introduce a new `realisticDelay` helper function for use with the `delay`\n    callback for mocked responses used with `MockLink`. `realisticDelay` will\n    generate a random value between 20 and 50ms to provide an experience closer\n    to unpredictable network latency. `realisticDelay` can be configured with a\n    `min` and `max` to set different thresholds if the defaults are not\n    sufficient.\n\n\n    ```ts\n\n    import { realisticDelay } from '@apollo/client/testing';\n\n\n    new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: 'Hello' }},\n        delay: realisticDelay()\n      },\n      {\n        request: { query },\n        result: { data: { greeting: 'Hello' }},\n        delay: realisticDelay({ min: 10, max: 100 })\n      },\n    ]);\n\n    ```\n  fuzzy-seahorses-hunt: >-\n    Remove code that strips `@client` fields in `HttpLink` and `BatchHttpLink`.\n    This was unused code since core handles removing `@client` fields and should\n    have no observable change.\n  gentle-waves-cough: >-\n    The `cache` and `forceFetch` properties are no longer available on context\n    when calling `operation.getContext()`. `cache` can be accessed through the\n    `operation` with `operation.client.cache` instead. `forceFetch` has been\n    replaced with `queryDeduplication` which specifies whether\n    `queryDeduplication` was enabled for the request or not.\n  giant-apes-thank: >-\n    Remove the `onError` and `setOnError` methods from `ApolloLink`. `onError`\n    was only used by `MockLink` to rewrite errors if `setOnError` was used.\n  giant-bags-share: >-\n    Throw an error for queries and mutations if the link chain completes without\n    emitting a value.\n  khaki-bears-destroy: >-\n    Adds enhanced client awareness to the client.\n\n\n    `HttpLink` and `BatchHttpLink` will now per default send information about\n    the\n\n    client library you are using in `extensions`.\n\n\n    This could look like this:\n\n\n    ```json\n\n    {\n      \"query\": \"query GetUser($id: ID!) { user(id: $id) { __typename id name } }\",\n      \"variables\": {\n        \"id\": 5\n      },\n      \"extensions\": {\n        \"clientLibrary\": {\n          \"name\": \"@apollo/client\",\n          \"version\": \"4.0.0\"\n        }\n      }\n    }\n\n    ```\n\n\n    This feature can be disabled by passing `enhancedClientAwareness: {\n    transport: false }` to your\n\n    `ApolloClient`,  `HttpLink` or `BatchHttpLink` constructor options.\n  khaki-coats-prove: >-\n    The new `SetContextLink` flips the `prevContext` and `operation` arguments\n    in the callback. The `setContext` function has remained unchanged.\n\n\n    ```diff\n\n    - new SetContextLink((operation, prevContext) => {\n\n    + new SetContextLink((prevContext, operation) => {\n      // ...\n    })\n\n    ```\n  lazy-baboons-rescue: >-\n    Slightly rework multipart response parsing.\n\n\n    This removes last incremental-protocol-specific details from `HttpLink` and\n    `BatchHttpLink`.\n  lucky-sheep-explain: >-\n    Provide an extension to define types for `context` passed to the link chain.\n    To define your own types, use [declaration\n    merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html)\n    to add properties to the `DefaultContext` type.\n\n\n    ```ts\n\n    // @apollo-client.d.ts\n\n    // This import is necessary to ensure all Apollo Client imports\n\n    // are still available to the rest of the application.\n\n    import '@apollo/client';\n\n\n    declare module \"@apollo/client\" {\n      interface DefaultContext extends Record<string, any> {\n        myProperty: string;\n      }\n    }\n\n    ```\n\n\n    Links that provide context options can be used with this type to add those\n    context types to `DefaultContext`. For example, to add context options from\n    `HttpLink`, add the following code:\n\n\n    ```ts\n\n    import { HttpLink } from \"@apollo/client\";\n\n\n    declare module \"@apollo/client\" {\n      interface DefaultContext extends HttpLink.ContextOptions {\n        myProperty: string;\n      }\n    }\n\n    ```\n\n\n    At this time, the following built-in links support context options:\n\n    - `HttpLink.ContextOptions`\n\n    - `BatchHttpLink.ContextOptions`\n  mighty-penguins-wink: >-\n    Removes the `throwServerError` utility function. Now that `ServerError` is\n    an\n\n    `Error` subclass, you can throw these errors directly:\n\n\n    ```js\n\n    import { ServerError } from '@apollo/client';\n\n\n    // instead of\n\n    throwServerError(response, result, 'error message')\n\n\n    // Use\n\n    throw new ServerError('error message', { response, result })\n\n    ```\n  ninety-bags-bake: >-\n    Mocked responses passed to `MockLink` now accept a callback for the\n    `request.variables` option. This is used to determine if the mock should be\n    matched for a set of request variables. With this change, the\n    `variableMatcher` option has been removed in favor of passing a callback to\n    `variables`. Update by moving the callback function from `variableMatcher`\n    to `request.variables`.\n\n\n    ```diff\n\n    new MockLink([\n      {\n        request: {\n          query,\n    +     variables: (requestVariables) => true\n        },\n    -   variableMatcher: (requestVariables) => true\n      }\n    ]);\n\n    ```\n  odd-chicken-hide: >-\n    Add the ability to detect if an error was an error was emitted from the link\n    chain. This is useful if your application throws custom errors in other\n    areas of the application and you'd like to differentiate them from errors\n    emitted by the link chain itself.\n\n\n    To detect if an error was emitted from the link chain, use `LinkError.is`.\n\n\n    ```ts\n\n    import { LinkError } from \"@apollo/client\";\n\n\n    client.query({ query }).catch((error) => {\n      if (LinkError.is(error)) {\n        // This error originated from the link chain\n      }\n    });\n\n    ```\n  perfect-ducks-reflect: >-\n    `ApolloLink.execute` now requires a third argument which provides the\n    `client` that initiated the request to the link chain. If you use `execute`\n    directly, add a third argument with a `client` property:\n\n\n    ```ts\n\n    ApolloLink.execute(link, operation, { client });\n\n\n    // or if you import the `execute` function directly:\n\n    execute(link, operation, { client });\n\n    ```\n  rich-turtles-clap: >-\n    `HttpLink` and `BatchHttpLink` no longer emit a `next` notification with the\n    JSON-parsed response body when a well-formed GraphQL response is returned\n    and a `ServerError` is thrown.\n  rude-crabs-eat: >-\n    The `operation` argument to the callback passed to `SetContextLink` is now\n    of type `SetContextLink.SetContextOperation` which is an `Operation` without\n    the `getContext` or `setContext` functions. Previously the type of\n    `operation` was `GraphQLRequest` which had access to a `context` property.\n    The `context` property was always `undefined` and could result in bugs when\n    using it instead of the `prevContext` argument.\n\n\n    This change means the `operation` argument now contains an accessible\n    `client` property.\n  rude-parrots-suffer: >-\n    Add the new `ClientAwarenessLink`.\n\n\n    This link is already included in `HttpLink` and `BatchHttpLink` to enable\n    the\n\n    \"client awareness\" and \"enhanced client awareness\" features, but you can\n    also use\n\n    `ClientAwarenessLink` directly in your link chain to combine it with other\n\n    terminating links.\n\n\n    If you want to save the bundle size that `ClientAwarenessLink` adds to\n    `HttpLink`\n\n    and `BatchHttpLink`, you can use `BaseHttpLink` or `BaseBatchHttpLink`\n    instead.\n\n    These links come without the `ClientAwarenessLink` included.\n\n\n    For example:\n\n    ```diff\n\n    import {\n      ApolloClient,\n    -  HttpLink,\n\n    } from \"@apollo/client\";\n\n    +import { BaseHttpLink } from \"@apollo/client/link/http\";\n\n\n    const client = new ApolloClient({\n\n    -  link: new HttpLink({\n\n    +  link: new BaseHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    ```\n  seven-schools-carry: >-\n    Add a `client` property to the `operation` passed to the link chain. This\n    `client` is set as the `client` making the request to the link chain.\n  shaggy-pugs-add: >-\n    Add ability to specify a default `delay` for all mocked responses passed to\n    `MockLink`. This `delay` can be configured globally (all instances of\n    `MockLink` will use the global defaults), or per-instance (all mocks in a\n    single instance will use the defaults). A `delay` defined on a single mock\n    will supercede all default delays. Per-instance defaults supercede global\n    defaults.\n\n\n    **Global defaults**\n\n\n    ```ts\n\n    MockLink.defaultOptions = {\n      // Use a default delay of 20ms for all mocks in all instances without a specified delay\n      delay: 20,\n\n      // altenatively use a callback which will be executed for each mock\n      delay: () => getRandomNumber(),\n\n      // or use the built-in `realisticDelay`. This is the default\n      delay: realisticDelay(),\n    }\n\n    ```\n\n\n    **Per-instance defaults**\n\n\n    ```ts\n\n    new MockLink(\n      [\n        // Use the default delay\n        {\n          request: { query },\n          result: { data: { greeting: 'Hello' }},\n        },\n        {\n          request: { query },\n          result: { data: { greeting: 'Hello' }},\n          // Override the default for this mock\n          delay: 10\n        },\n      ],\n      {\n        defaultOptions: {\n          // Use a default delay of 20ms for all mocks without a specified delay\n          delay: 20,\n\n          // altenatively use a callback which will be executed for each mock\n          delay: () => getRandomNumber(),\n\n          // or use the built-in `realisticDelay`. This is the default\n          delay: realisticDelay(),\n        }\n      }\n    );\n\n    ```\n  sharp-glasses-sneeze: >-\n    The `ErrorResponse` object passed to the `disable` and `retry` callback\n    options provided to `createPersistedQueryLink` no longer provides separate\n    `graphQLErrors` and `networkError` properties and instead have been combined\n    to a single `error` property of type `ErrorLike`.\n\n\n\n    ```diff\n\n    // The following also applies to the `retry` function since it has the same\n    signature\n\n    createPersistedQueryLink({\n\n    - disable: ({ graphQLErrors, networkError }) => {\n\n    + disable: ({ error }) => {\n\n    -   if (graphQLErrors) {\n\n    +   if (CombinedGraphQLErrors.is(error)) {\n          // ... handle GraphQL errors\n        }\n\n    -   if (networkError) {\n\n    +   if (error) {\n          // ... handle link errors\n        }\n\n        // optionally check for a specific kind of error\n    -   if (networkError) {\n\n    +   if (ServerError.is(error)) {\n          // ... handle a server error\n        }\n    });\n\n    ```\n\n\n    The `response` property has also been renamed to `result`.\n\n\n    ```diff\n\n    createPersistedQueryLink({\n\n    -  disable: ({ response }) => {\n\n    +  disable: ({ result }) => {\n          // ... handle GraphQL errors\n        }\n      }\n    });\n\n    ```\n  short-months-complain: >-\n    Throw an error when a client-only query is used in a mocked response passed\n    to `MockLink`.\n  sour-donuts-sit: >-\n    Prioritize usage of `FormattedExecutionResult` over `FetchResult` where\n    applicable.\n\n\n    Many APIs used `FetchResult` in place of `FormattedExecutionResult`, which\n    could\n\n    cause inconsistencies.\n\n\n    * `FetchResult` is now used to refer to an unhandled \"raw\" result as\n    returned from\n      a link.\n      This can also include incremental results that use a different format.\n    * `FormattedExecutionResult` from the `graphql` package is now used to\n    represent\n      the execution of a standard GraphQL request without incremental results.\n\n    If your custom links access the `data` property, you might need to first\n    check if\n\n    the result is a standard GraphQL result by using the\n    `isFormattedExecutionResult`\n\n    helper from `@apollo/client/utilities`.\n  sour-kids-deliver: Rename the `@apollo/client/link/core` entrypoint to `@apollo/client/link`.\n  stupid-paws-jam: |-\n    The `response` property in `onError` link has been renamed to `result`.\n\n    ```diff\n    - onError(({ response }) => {\n    + onError(({ result }) => {\n        // ...\n    });\n    ```\n  swift-rivers-share: >-\n    Default the `delay` for all mocked responses passed to `MockLink` using\n    `realisticDelay`. This ensures your test handles loading states by default\n    and is not reliant on a specific timing.\n\n\n    If you would like to restore the old behavior, use a global default delay of\n    `0`.\n\n\n    ```ts\n\n    MockLink.defaultOptions = {\n      delay: 0\n    }\n\n    ```\n  tame-doors-shop: >-\n    Remove workarounds for streaming with non-WhatWG response bodies to reduce\n    bundle size.\n\n\n    This removes support for `fetch` implementations that return Node Streams,\n    Async Iterators or Blob instances as `Response.body`.\n\n\n    In the WhatWG Fetch specification,\n    [`Response.body`](https://fetch.spec.whatwg.org/#body) is specified as a\n    WhatWG [ReadableStream](https://streams.spec.whatwg.org/#readablestream).\n\n\n    At this point in time, this is natively supported in browsers, `node` and\n    React Native (via\n    [react-native-fetch-api](https://www.npmjs.com/package/react-native-fetch-api),\n    see our [setup instructions for React\n    Native](https://www.apollographql.com/docs/react/integrations/react-native#consuming-multipart-http-via-text-streaming)).\n\n\n    If you are using an older `fetch` polyfill that deviates from the spec, this\n    might not be compatible - for example,\n    [node-fetch](https://github.com/node-fetch/node-fetch?tab=readme-ov-file#interface-body)\n    returns a node `Readable` instead of a `ReadableStream`.\n\n    In those cases, please switch to a compatible alternative such as the\n    `node`-native `fetch`, or `undici`.\n  tame-rice-explain: >-\n    Adds an `accept` option to `HttpOptions` that allows to add additional\n    `Accept` headers to be merged in without overriding user-specified or\n    default accept headers.\n  thirty-lemons-rhyme: >-\n    Add `operationType` to `operation` in `ApolloLink`. This means that\n    determining whether a `query` is a specific operation type can now be\n    compared with this property instead of using `getMainDefinition`.\n\n\n    ```diff\n\n    - import { getMainDefinition } from \"@apollo/client/utilities\";\n\n    + import { OperationTypeNode } from \"graphql\";\n\n\n    ApolloLink.split(\n\n    - ({ query }) => {\n\n    -   const definition = getMainDefinition(query);\n\n    -   return (\n\n    -     definition.kind === 'OperationDefinition' &&\n\n    -     definition.operation === 'subscription'\n\n    -   );\n\n    -   return\n\n    - },\n\n    + ({ operationType }) => {\n\n    +   return operationType === OperationTypeNode.SUBSCRIPTION;\n\n    + },\n      conditionTrueLink,\n      conditionFalseLink,\n    );\n\n    ```\n  weak-owls-buy: >-\n    All links are now available as classes. The old creator functions have been\n    deprecated.\n\n\n    Please migrate these function calls to class creations:\n\n\n    ```diff\n\n    import {\n\n    - setContext\n\n    + SetContextLink\n\n    } from \"@apollo/client/link/context\"\n\n\n    -const link = setContext(...)\n\n    +const link = new SetContextLink(...)\n\n    ```\n\n\n    ```diff\n\n    import {\n\n    - createHttpLink\n\n    + HttpLink\n\n    } from \"@apollo/client/link/http\"\n\n\n    -const link = createHttpLink(...)\n\n    +const link = new HttpLink(...)\n\n    ```\n\n\n    ```diff\n\n    import {\n\n    - createPersistedQueryLink\n\n    + PersistedQueryLink\n\n    } from \"@apollo/client/link/persisted-queries\"\n\n\n    -const link = createPersistedQueryLink(...)\n\n    +const link = new PersistedQueryLink(...)\n\n    ```\n\n\n    ```diff\n\n    import {\n\n    - removeTypenameFromVariables\n\n    + RemoveTypenameFromVariablesLink\n\n    } from \"@apollo/client/link/remove-typename\"\n\n\n    -const link = removeTypenameFromVariables(...)\n\n    +const link = new RemoveTypenameFromVariablesLink(...)\n\n    ```\n  wicked-forks-double: >-\n    Remove `newData` option for mocked responses passed to `MockLink` or the\n    `mocks` option on `MockedProvider`. This option was undocumented and was\n    nearly identical to using the `result` option as a callback.\n\n\n    To replicate the old behavior of `newData`, use `result` as a callback and\n    add the `maxUsageCount` option with a value set to\n    `Number.POSITIVE_INFINITY`.\n\n\n    **with `MockLink`**\n\n    ```diff\n\n    new MockLink([\n      {\n        request: { query, variables },\n    -   newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   maxUsageCount: Number.POSITIVE_INFINITY,\n      }\n    ])\n\n    ```\n\n\n    **with `MockedProvider`**\n\n    ```diff\n\n    <MockedProvider\n      mocks={[\n        {\n          request: { query, variables },\n    -     newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     maxUsageCount: Number.POSITIVE_INFINITY,\n        }\n      ]}\n    />\n\n    ```\n  young-moons-admire: >-\n    Fixed a bug in `PersistedQueryLink` where the `persistedQuery` extension\n    would still be sent after a `PersistedQueryNotSupported` if\n    `includeExtensions` was enabled on `HttpLink`.\nfeatures:\n  khaki-bears-destroy: >-\n    Adds enhanced client awareness to the client.\n\n\n    `HttpLink` and `BatchHttpLink` will now per default send information about\n    the\n\n    client library you are using in `extensions`.\n\n\n    This could look like this:\n\n\n    ```json\n\n    {\n      \"query\": \"query GetUser($id: ID!) { user(id: $id) { __typename id name } }\",\n      \"variables\": {\n        \"id\": 5\n      },\n      \"extensions\": {\n        \"clientLibrary\": {\n          \"name\": \"@apollo/client\",\n          \"version\": \"4.0.0\"\n        }\n      }\n    }\n\n    ```\n\n\n    This feature can be disabled by passing `enhancedClientAwareness: {\n    transport: false }` to your\n\n    `ApolloClient`,  `HttpLink` or `BatchHttpLink` constructor options.\n  pink-ladybugs-cough: >-\n    Subscriptions created by `client.subscribe()` can now be restarted.\n    Restarting a subscription will terminate the connection with the link chain\n    and recreate the request. Restarts also work across deduplicated\n    subscriptions so calling `restart` on an `observable` who's request is\n    deduplicated will restart the connection for each observable.\n\n\n    ```ts\n\n    const observable = client.subscribe({ query: subscription });\n\n\n    // Restart the connection to the link\n\n    observable.restart();\n\n    ```\n  rude-parrots-suffer: >-\n    Add the new `ClientAwarenessLink`.\n\n\n    This link is already included in `HttpLink` and `BatchHttpLink` to enable\n    the\n\n    \"client awareness\" and \"enhanced client awareness\" features, but you can\n    also use\n\n    `ClientAwarenessLink` directly in your link chain to combine it with other\n\n    terminating links.\n\n\n    If you want to save the bundle size that `ClientAwarenessLink` adds to\n    `HttpLink`\n\n    and `BatchHttpLink`, you can use `BaseHttpLink` or `BaseBatchHttpLink`\n    instead.\n\n    These links come without the `ClientAwarenessLink` included.\n\n\n    For example:\n\n    ```diff\n\n    import {\n      ApolloClient,\n    -  HttpLink,\n\n    } from \"@apollo/client\";\n\n    +import { BaseHttpLink } from \"@apollo/client/link/http\";\n\n\n    const client = new ApolloClient({\n\n    -  link: new HttpLink({\n\n    +  link: new BaseHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    ```\n  rare-apes-drive: >-\n    Deduplicating subscription operations is now supported. Previously it was\n    possible to deduplicate a subscription only if the new subscription was\n    created before a previously subscribed subscription emitted any values. As\n    soon as a value was emitted from a subscription, new subscriptions would\n    create new connections. Deduplication is now active for as long as a\n    subscription connection is open (i.e. the source observable hasn't emitted a\n    `complete` or `error` notification yet.)\n\n\n    To disable deduplication and force a new connection, use the\n    `queryDeduplication` option in `context` like you would a query operation.\n\n\n    As a result of this change, calling the `restart` function returned from\n    `useSubscription` will now restart the connection on deduplicated\n    subscriptions.\ngraphql_over_http:\n  afraid-penguins-sniff: >-\n    Replace the `result` property on `ServerError` with `bodyText`. `bodyText`\n    is set to the raw string body. `HttpLink` and `BatchHttpLink` no longer try\n    and parse the response body as JSON when a `ServerError` is thrown.\n  curvy-shoes-refuse: >-\n    More strictly adhere to the [GraphQL over HTTP\n    spec](https://graphql.github.io/graphql-over-http/draft/). This change adds\n    support for the `application/graphql-response+json` media type and modifies\n    the behavior of the `application/json` media type.\n\n\n    - The client will parse the response as a well-formed GraphQL response when\n    the server encodes `content-type` using `application/graphql-response+json`\n    with a non-200 status code.\n\n    - The client will now throw a `ServerError` when the server encodes\n    `content-type` using `application/json` and returns a non-200 status code.\n\n    - The client will now throw a `ServerError` when the server encodes using\n    any other `content-type` and returns a non-200 status code.\n\n\n    NOTE: If you use a testing utility to mock requests in your test, you may\n    experience different behavior than production if your testing utility\n    responds as `application/json` but your production server responds as\n    `application/graphql-response+json`. If a `content-type` header is not set,\n    the client interprets the response as `application/json`.\n  old-avocados-cover: >-\n    Adjusted the accept header for multipart requests according to the new\n    GraphQL over HTTP spec with these changes:\n\n\n    ```diff\n\n    -multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json\n\n    +multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/graphql-response+json,application/json;q=0.9\n\n    ```\n\n\n    ```diff\n\n    -multipart/mixed;deferSpec=20220824,application/json\n\n    +multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\n\n    ```\n  popular-games-sleep: Changes the default `Accept` header to `application/graphql-response+json`.\n  real-onions-drive: >-\n    Change the default `Accept` header to\n    `application/graphql-response+json,application/json;q=0.9`.\n  rich-turtles-clap: >-\n    `HttpLink` and `BatchHttpLink` no longer emit a `next` notification with the\n    JSON-parsed response body when a well-formed GraphQL response is returned\n    and a `ServerError` is thrown.\ndefer:\n  beige-kings-grow: >-\n    A `@defer` query that has not yet finished streaming is now considered\n    loading and thus the `loading` flag will be `true` until the response has\n    completed. A new `NetworkStatus.streaming` value has been introduced and\n    will be set as the `networkStatus` while the response is streaming.\n  lazy-baboons-rescue: >-\n    Slightly rework multipart response parsing.\n\n\n    This removes last incremental-protocol-specific details from `HttpLink` and\n    `BatchHttpLink`.\n  slimy-adults-attend: >-\n    The incremental delivery (`@defer` support) implementation is now pluggable.\n\n\n    `ApolloClient` now per default ships without an incremental format\n    implementation\n\n    and allows you to swap in the format that you want to use.\n\n\n    Usage looks like this:\n\n\n    ```ts\n\n    import {\n      // this is the default\n      NotImplementedHandler,\n      // this implements the `@defer` transport format that ships with Apollo Router\n      Defer20220824Handler,\n      // this implements the `@defer` transport format that ships with GraphQL 17.0.0-alpha.2\n      GraphQL17Alpha2Handler,\n    } from \"@apollo/client/incremental\";\n\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache({ /*...*/ }),\n      link: new HttpLink({ /*...*/ }),\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    ```\n\n\n    We will add handlers for other response formats that can be swapped this way\n\n    during the lifetime of Apollo Client 4.0.\nreact:\n  clever-zebras-mate: Drop support for React 16.\n  rare-houses-prove: Add `react-server` entry point with stubs for normal exports.\n  real-turtles-boil: Enable React compiler for hooks in ESM builds.\nuseQuery:\n  beige-spiders-hope: >-\n    When updating `skip` from `false` to `true` in `useQuery`, retain `data` if\n    it is available rather than setting it to `undefined`.\n  calm-seals-relate: >-\n    Remove the deprecated `errors` property from `useQuery` and `useLazyQuery`.\n    Read errors from the `error` property instead.\n  fluffy-shoes-applaud: Remove deprecated `partialRefetch` option.\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  great-scissors-jam: >-\n    `cache-only` queries will now initialize with `loading: false` and\n    `networkStatus: NetworkStatus.ready` when there is no data in the cache.\n\n\n    This means `useQuery` will no longer render a short initial loading state\n    before rendering `loading: false` and `ObservableQuery.getCurrentResult()`\n    will now return `loading: false` immediately.\n  light-apes-rescue: >-\n    `useQuery` no longer returns `reobserve` as part of its result. It was\n    possible to use `reobserve` to set new options on the underlying\n    `ObservableQuery` instance which differed from the options passed to the\n    hook. This could result in unexpected results. Instead prefer to rerender\n    the hook with new options.\n  loud-cows-raise: >-\n    `useQuery` with `ssr: false` - previously, `skip` had a higher priortity\n    than `ssr: false` while `ssr: false` had a higher priority than\n    `fetchPolicy: \"standby\"` (which is roughly equivalent to `skip`).\n\n\n    This priority has been adjusted so now both `skip` and `fetchPolicy:\n    \"standby\"` have a higher priority than `ssr: false` and will return\n    `loading: false`, while `ssr: false` will only come after those and will\n    return `loading: true` if those are not set.\n  many-seas-call: >-\n    Changing most options when rerendering `useQuery` will no longer trigger a\n    `reobserve` which may cause network fetches. Instead, the changed options\n    will be applied to the next cache update or fetch.\n\n\n    Options that now trigger a `reobserve` when changed between renders are:\n\n    - `query`\n\n    - `variables`\n\n    - `skip`\n\n    - Changing `fetchPolicy` to or from `standby`\n  nervous-goats-allow: >-\n    Removes the `defaultOptions` option from `useQuery`. Use options directly or\n    use the global `ApolloClient` `defaultOptions`.\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  slimy-ants-bake: \"`useQuery`: only advance `previousData` if `data` actually changed\"\n  strange-walls-march: >-\n    The `error` property is no longer present when `skip` is `true` in\n    `useQuery`.\n  thin-peas-hear: >-\n    `notifyOnNetworkStatusChange` now defaults to `true`. This means that\n    loading states will be emitted (core API) or rendered (React) by default\n    when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set\n    `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n\n    ```ts\n\n    new ApolloClient({\n      defaultOptions: {\n        watchQuery: {\n          // Use the v3 default\n          notifyOnNetworkStatusChange: false\n        }\n      }\n    })\n\n    ```\n  tough-olives-fry: >-\n    Ensure `useQuery` rerenders when `notifyOnNetworkStatusChange` is `false`\n    and a `refetch` that changes variables returns a result deeply equal to\n    previous variables.\n  tough-taxis-smoke: >-\n    Remove the `onCompleted` and `onError` callbacks from `useQuery` and\n    `useLazyQuery`.\n\n\n    See [#12352](https://github.com/apollographql/apollo-client/issues/12352)\n    for more context on this change.\n  unlucky-kiwis-sell: Remove the `called` property from `useQuery`.\nuseLazyQuery:\n  calm-seals-relate: >-\n    Remove the deprecated `errors` property from `useQuery` and `useLazyQuery`.\n    Read errors from the `error` property instead.\n  empty-rabbits-move: >-\n    The `previousData` property on `useLazyQuery` will now change only when\n    `data` changes. Previously `previousData` would change to the same value as\n    `data` while the query was loading.\n  forty-tomatoes-punch: >-\n    The returned `networkStatus` in `useLazyQuery` is now set to `setVariables`\n    when calling the `useLazyQuery` `execute` function for the first time with\n    variables.\n  hungry-bikes-cough: >-\n    Fix type of `variables` returned from `useLazyQuery`. When `called` is\n    `false`, `variables` is now `Partial<TVariables>` instead of `TVariables`.\n  large-plants-know: >-\n    Ensure a loading state is emitted when calling the `execute` function after\n    changing clients in `useLazyQuery`.\n  light-dolphins-taste: >-\n    `useLazyQuery` no longer supports SSR environments and will now throw if the\n    `execute` function is called in SSR. If you need to run a query in an SSR\n    environment, use `useQuery` instead.\n  lucky-hats-push: >-\n    The execute function returned from `useLazyQuery` now only supports the\n    `context` and `variables` options. This means that passing options supported\n    by the hook no longer override the hook value.\n\n\n    To change options, rerender the component with new options. These options\n    will take effect with the next query execution.\n  mean-lizards-think: >-\n    Ensure `useLazyQuery` does not return a `partial` property which is not\n    specified by the result type.\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  nice-waves-work: >-\n    The result resolved from the promise returned from the execute function in\n    `useLazyQuery` is now an `ApolloQueryResult` type and no longer includes all\n    the fields returned from the `useLazyQuery` hook tuple.\n\n\n    If you need access to the additional properties such as `called`, `refetch`,\n    etc. not included in `ApolloQueryResult`, read them from the hook instead.\n  polite-bees-care: >-\n    `useLazyQuery` will no longer rerender with the loading state when calling\n    the execute function the first time unless the `notifyOnNetworkStatusChange`\n    option is set to `true` (which is the new default).\n\n\n    If you prefer the behavior from 3.x, rerender the component with\n\n    `notifyOnNetworkStatusChange` set to `false` after the execute function is\n\n    called the first time.\n\n\n    ```ts\n\n    function MyComponent() {\n      const [notifyOnNetworkStatusChange, setNotifyOnNetworkStatusChange] = useState(true);\n      const [execute] = useLazyQuery(query, { notifyOnNetworkStatusChange });\n\n      async function runExecute() {\n        await execute();\n\n        // Set to false after the initial fetch to stop receiving notifications\n        // about changes to the loading states.\n        setNotifyOnNetworkStatusChange(false);\n      }\n\n      // ...\n    }\n\n    ```\n  purple-balloons-accept: >-\n    If the `execute` function of `useLazyQuery` is executed, previously started\n    queries\n\n    from the same `useLazyQuery` usage will be rejected with an `AbortError`\n    unless\n\n    `.retain()` is called on the promise returned by previous `execute` calls.\n\n\n    Please keep in mind that `useLazyQuery` is primarily meant as a means to\n    synchronize\n\n    your component to the status of a query and that it's purpose it not to make\n    a\n\n    series of network calls.\n\n    If you plan on making a series of network calls without the need to\n    synchronize\n\n    the result with your component, consider using `ApolloClient.query` instead.\n  rich-eagles-cross: >-\n    The `reobserve` option is no longer available in the result returned from\n    `useLazyQuery`. This was considered an internal API and should not be used\n    directly.\n  seven-foxes-melt: >-\n    The promise returned when calling the execute function from `useLazyQuery`\n    will now reject when using an `errorPolicy` of `none` when GraphQL errors\n    are returned from the result.\n  shaggy-singers-tickle: >-\n    Remove `context` from `useLazyQuery` hook options. If used, `context` must\n    now be provided to the `execute` function. `context` will reset to `{}` if\n    not provided as an option to `execute`.\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  soft-mails-clean: >-\n    `useLazyQuery` no longer supports calling the execute function in render and\n    will now throw. If you need to execute the query immediately, use `useQuery`\n    instead or move the call to a `useEffect`.\n  sour-pillows-guess: >-\n    The `defaultOptions` and `initialFetchPolicy` options are no longer\n    supported with `useLazyQuery`.\n\n\n    If you use `defaultOptions`, pass those options directly to the hook\n    instead. If you use `initialFetchPolicy`, use `fetchPolicy` instead.\n  strange-seahorses-impress: >-\n    `useLazyQuery` no longer supports `variables` in the hook options and\n    therefore no longer performs variable merging. The execute function must now\n    be called with `variables` instead.\n\n\n    ```ts\n\n    function MyComponent() {\n      const [execute] = useLazyQuery(query);\n\n      function runExecute() {\n        execute({ variables: { ... }});\n      }\n    }\n\n    ```\n\n\n    This change means the execute function returned from `useLazyQuery` is more\n    type-safe. The execute function will require you to pass a `variables`\n    option if the query type includes required variables.\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\n  thin-peas-hear: >-\n    `notifyOnNetworkStatusChange` now defaults to `true`. This means that\n    loading states will be emitted (core API) or rendered (React) by default\n    when calling `refetch`, `fetchMore`, etc. To maintain the old behavior, set\n    `notifyOnNetworkStatusChange` to `false` in `defaultOptions`.\n\n\n    ```ts\n\n    new ApolloClient({\n      defaultOptions: {\n        watchQuery: {\n          // Use the v3 default\n          notifyOnNetworkStatusChange: false\n        }\n      }\n    })\n\n    ```\n  tough-taxis-smoke: >-\n    Remove the `onCompleted` and `onError` callbacks from `useQuery` and\n    `useLazyQuery`.\n\n\n    See [#12352](https://github.com/apollographql/apollo-client/issues/12352)\n    for more context on this change.\n  twelve-mangos-dance: >-\n    `ObservableQuery.refetch` and `ObservableQuery.reobserve` and the `execute`\n    function of `useLazyQuery` now return a\n\n    `ResultPromise` with an additional `.retain` method.\n\n    If this method is called, the underlying network operation will be kept\n    running even if the `ObservableQuery` itself does\n\n    not require the result anymore, and the Promise will resolve with the final\n    result instead of resolving with an intermediate\n\n    result in the case of early cancellation.\n  twenty-snakes-sort: >-\n    `useLazyQuery` will now only execute the query when the execute function is\n    called. Previously `useLazyQuery` would behave like `useQuery` after the\n    first call to the execute function which means changes to options might\n    perform network requests.\n\n\n    You can now safely rerender `useLazyQuery` with new options which will take\n    effect the next time you manually trigger the query.\nuseBackgroundQuery:\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseSuspenseQuery:\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseApolloClient:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseFragment:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseLoadableQuery:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseQueryRefHandlers:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseReactiveVar:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseReadQuery:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseMutation:\n  curvy-pianos-count: >-\n    Remove deprecated `ignoreResults` option from `useMutation`. If you don't\n    want to synchronize component state with the mutation, use `useApolloClient`\n    to access your client instance and use `client.mutate` directly.\n  many-buses-allow: >-\n    Fix an issue where passing `onError` to `useMutation` would resolve the\n    promise returned by the `mutate` function instead of rejecting when using an\n    `errorPolicy` of `none`.\n  orange-suits-laugh: >-\n    Adjust `useMutation` types to better handle required variables. When\n    required variables are missing, TypeScript will now complain if they are not\n    provided either to the hook or the returned `mutate` function. Providing\n    required variables to `useMutation` will make them optional in the returned\n    `mutate` function.\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\nuseSubscription:\n  eleven-kangaroos-jump: Remove `variables` from the result returned from `useSubscription`.\n  great-roses-jog: >-\n    The `variables` option used with various APIs are now enforced more\n    consistently across the client when `TVariables` contains required\n    variables. If required `variables` are not provided, TypeScript will now\n    complain that it requires a `variables` option.\n\n\n    This change affects the following APIs:\n\n    - `client.query`\n\n    - `client.mutate`\n\n    - `client.subscribe`\n\n    - `client.watchQuery`\n\n    - `useBackgroundQuery`\n\n    - `useQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  slimy-chicken-melt: >-\n    Remove deprecated `onSubscriptionData` and `onSubscriptionComplete`\n    callbacks from `useSubscription`. Use `onData` and `onComplete` instead.\n  warm-ties-sit: >-\n    Subscriptions no longer emit errors in the `error` callback and instead\n    provide errors on the `error` property on the result passed to the `next`\n    callback. As a result, errors will no longer automatically terminate the\n    connection allowing additional results to be emitted when the connection\n    stays open.\n\n\n    When an error terminates the downstream connection, a `next` event will be\n    emitted with an `error` property followed by a `complete` event instead.\ncreateQueryPreloader:\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  six-jars-fix: >-\n    `queryRef`s created by `preloadQuery` no longer have a `.toPromise()`\n    function. Instead `preloadQuery` now has a `toPromise` function that accepts\n    a queryRef and will resolve when the underlying promise has been resolved.\n\n\n    ```diff\n\n    const queryRef = preloadQuery(query, options);\n\n\n    - await queryRef.toPromise();\n\n    + await preloadQuery.toPromise(queryRef);\n\n    ```\nssr:\n  funny-jeans-invent: >-\n    `ssrMode`, `ssrForceFetchDelay` and `disableNetworkFetches` have been\n    reworked:\n\n\n    Previously, a `ObservableQuery` created by `client.query` or\n    `client.watchQuery`\n\n    while one of those were active would permanently be changed from a\n    `fetchPolicy`\n\n    of `\"network-only\"` or `\"cache-and-network\"` to `\"cache-first\"`, and stay\n    that way\n\n    even long after `disableNetworkFetches` would have been deactivated.\n\n\n    Now, the `ObservableQuery` will keep their original `fetchPolicy`, but\n    queries\n\n    made during `disableNetworkFetches` will just apply the `fetchPolicy`\n    replacement\n\n    at request time, just for that one request.\n\n\n    `ApolloClient.disableNetworkFetches` has been renamed to\n    `ApolloClient.prioritizeCacheValues` to better reflect this behaviour.\n  light-dolphins-taste: >-\n    `useLazyQuery` no longer supports SSR environments and will now throw if the\n    `execute` function is called in SSR. If you need to run a query in an SSR\n    environment, use `useQuery` instead.\n  loud-cows-raise: >-\n    `useQuery` with `ssr: false` - previously, `skip` had a higher priortity\n    than `ssr: false` while `ssr: false` had a higher priority than\n    `fetchPolicy: \"standby\"` (which is roughly equivalent to `skip`).\n\n\n    This priority has been adjusted so now both `skip` and `fetchPolicy:\n    \"standby\"` have a higher priority than `ssr: false` and will return\n    `loading: false`, while `ssr: false` will only come after those and will\n    return `loading: true` if those are not set.\n  tame-points-work: >-\n    Add a new method for static SSR of React components, `prerenderStatic`.\n\n    The old methods, `getDataFromTree`, `getMarkupFromTree` and\n    `renderToStringWithData`\n\n    have been deprecated in favor of `prerenderStatic`.\n\n\n    If used with React 19 and the `prerender` or `prerenderToNodeStream` apis\n    from\n\n    `react-dom/static`, this method can now be used to SSR-prerender\n    suspense-enabled\n\n    hook APIs.\n  thick-books-grin: Split out SSR-specific code from useQuery hook, remove RenderPromises\nbugfix:\n  many-buses-allow: >-\n    Fix an issue where passing `onError` to `useMutation` would resolve the\n    promise returned by the `mutate` function instead of rejecting when using an\n    `errorPolicy` of `none`.\n  tough-olives-fry: >-\n    Ensure `useQuery` rerenders when `notifyOnNetworkStatusChange` is `false`\n    and a `refetch` that changes variables returns a result deeply equal to\n    previous variables.\n  tough-rockets-allow: >-\n    Fix an issue where additional response properties were returned on the\n    result returned from `client.mutate`, such as `@defer` payload fields. These\n    properties are now stripped out to correspond to the TypeScript type.\n  young-moons-admire: >-\n    Fixed a bug in `PersistedQueryLink` where the `persistedQuery` extension\n    would still be sent after a `PersistedQueryNotSupported` if\n    `includeExtensions` was enabled on `HttpLink`.\ndebugging:\n  real-gorillas-move: >-\n    Apollo Client now defaults to production mode, not development mode, if the\n\n    environment cannot be determined.\n\n\n    In modern bundlers, this should automatically be handled by the bundler\n    loading\n\n    the bundler with the `development` export condition.\n\n\n    If neither the `production` nor the `development` export condition are\n\n    used by the bundler/runtime, Apollo Client will fall back to\n    `globalThis.__DEV__`\n\n    to determine if it should run in production or development mode.\n\n\n    Unlike Apollo Client 3 though, if `globalThis.__DEV__` is not set to `true`,\n\n    Apollo Client will now default to `production`, not to `development`,\n    behaviour.\n\n\n    This switch to *explicilty* requiring `true` also resolves a situation where\n\n    an HTML element with `id=\"__DEV__\"` would create a global `__DEV__` variable\n\n    with a referent to the DOM element, which in the past was picked up as\n    \"truthy\" and\n\n    would have triggered development mode.\nremovals:\n  brave-moons-juggle: Remove the `typeDefs` option from `ApolloClient`.\n  brave-radios-wait: >-\n    Remove the `asyncMap` utility function. Instead use one of the RxJS\n    operators that creates Observables from promises, such as `from`.\n  bright-ads-share: >-\n    Removes the `isApolloError` utility function to check if the error object is\n    an `ApolloError` instance. Use `instanceof` to check for more specific error\n    types that replace `ApolloError`.\n  calm-frogs-remain: >-\n    Removes the `addTypename` option from `InMemoryCache` and `MockedProvider`.\n    `__typename` is now always added to the outgoing query document when using\n    `InMemoryCache` and cannot be disabled.\n\n\n    If you are using `<MockedProvider />` with `addTypename={false}`, ensure\n    that your mocked responses include a `__typename` field. This will ensure\n    cache normalization kicks in and behaves more like production.\n  chatty-planes-grin: Remove deprecated `resetApolloContext` export\n  clean-sheep-hide: |-\n    Drop `rehackt` dependency.\n    We can now directly import from `react` without causing build errors in RSC.\n  clever-zebras-mate: Drop support for React 16.\n  cool-bikes-shake: >-\n    Remove polyfills for Object.freeze,seal and preventExtensions in React\n    Native\n\n\n    These polyfills were only necessary until React Native 0.59, which\n\n    [patched the problem](https://github.com/facebook/react-native/pull/21492)\n    on\n\n    the React Native side.\n\n\n    With React Native 0.61, the `Map` function was [completely\n    replaced](https://github.com/facebook/react-native/commit/93b9ac74e59bbe84ea388d7c1879857b4acab114)\n\n    with a native implementation that never had the problems we guarded against.\n  curvy-flies-accept: >-\n    The `getCacheKey` function is no longer available from\n    `operation.getContext()` in the link chain. Use\n    `operation.client.cache.identify(obj)` in the link chain instead.\n  curvy-pianos-count: >-\n    Remove deprecated `ignoreResults` option from `useMutation`. If you don't\n    want to synchronize component state with the mutation, use `useApolloClient`\n    to access your client instance and use `client.mutate` directly.\n  dirty-cobras-change: >-\n    Move most of the utilities in `@apollo/client/utilities` to\n    `@apollo/client/utilities/internal`. Many of the utilities exported from the\n    `@apollo/client/utilities` endpoint were not considered stable.\n\n\n    As a result of this change, utilities or types exported from\n    `@apollo/client/utilities` are now documented and considered stable and will\n    not undergo breaking changes.\n  dirty-eagles-poke: >-\n    Removed the `@apollo/client/react/context` and `@apollo/client/react/hooks`\n    entry points. Please use `@apollo/client/react` instead.\n  eighty-squids-fix: >-\n    `ObservableQuery.setOptions` has been removed as it was an alias of\n    `reobserve`. Prefer using `reobserve` directly instead.\n\n\n    ```diff\n\n    const observable = client.watchQuery(options);\n\n\n    // Use reobserve to set new options and reevaluate the query\n\n    - observable.setOptions(newOptions);\n\n    + observable.reobserve(newOptions);\n\n    ```\n\n\n    As a result of this change, `reobserve` has been marked for public use and\n    is no longer considered an internal API. The `newNetworkStatus` argument has\n    been removed to facilitate this change.\n  eleven-kangaroos-jump: Remove `variables` from the result returned from `useSubscription`.\n  eleven-moons-heal: Remove deprecated `resultCacheMaxSize` option from `InMemoryCache` options.\n  fluffy-shoes-applaud: Remove deprecated `partialRefetch` option.\n  fresh-moose-hope: Remove the `iterateObserversSafely` utility function.\n  friendly-olives-refuse: >-\n    Remove the `@apollo/client/testing/experimental` test utilities. Use\n    [GraphQL Testing\n    Library](https://github.com/apollographql/graphql-testing-library) instead.\n  fuzzy-plants-approve: |-\n    Remove these incremental-format-specific types:\n\n    * `ExecutionPatchIncrementalResult`\n    * `ExecutionPatchInitialResult`\n    * `ExecutionPatchResult`\n    * `IncrementalPayload`\n    * `Path`\n  fuzzy-seahorses-hunt: >-\n    Remove code that strips `@client` fields in `HttpLink` and `BatchHttpLink`.\n    This was unused code since core handles removing `@client` fields and should\n    have no observable change.\n  gentle-files-laugh: >-\n    Remove deprecated `connectToDevtools` option from `ApolloClientOptions`. Use\n    `devtools.enabled` instead.\n  gentle-waves-cough: >-\n    The `cache` and `forceFetch` properties are no longer available on context\n    when calling `operation.getContext()`. `cache` can be accessed through the\n    `operation` with `operation.client.cache` instead. `forceFetch` has been\n    replaced with `queryDeduplication` which specifies whether\n    `queryDeduplication` was enabled for the request or not.\n  giant-apes-thank: >-\n    Remove the `onError` and `setOnError` methods from `ApolloLink`. `onError`\n    was only used by `MockLink` to rewrite errors if `setOnError` was used.\n  gold-oranges-double: >-\n    Removed `getLastResult`, `getLastError` and `resetLastResults` from\n    `ObservableQuery`\n  good-dolphins-peel: >-\n    Apollo Client no longer wraps errors in `ApolloError`. `ApolloError` has\n    been replaced with separate error classes depending on the cause of the\n    error. As such, APIs that return an `error` property have been updated to\n    use the generic `Error` type. Use `instanceof` to check for more specific\n    error types.\n\n\n    ## Migration guide\n\n\n    `ApolloError` encapsulated 4 main error properties. The type of error would\n    determine which property was set:\n\n    - `graphqlErrors` - Errors returned from the `errors` field by the GraphQL\n    server\n\n    - `networkError` - Any non-GraphQL error that caused the query to fail\n\n    - `protocolErrors` - Transport-level errors that occur during [multipart\n    HTTP\n    subscriptions](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol)\n\n    - `clientErrors` - A space to define custom errors. Mostly unused.\n\n\n    These errors were mutally exclusive, meaning both `networkError` and\n    `graphqlErrors` were never set simultaneously. The following replaces each\n    of these fields from `ApolloError`.\n\n\n    ### `graphqlErrors`\n\n\n    GraphQL errors are now encapsulated in a `CombinedGraphQLErrors` instance.\n    You can access the raw GraphQL errors via the `errors` property.\n\n\n    ```js\n\n    import { CombinedGraphQLErrors } from '@apollo/client';\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    if (error && error instanceof CombinedGraphQLErrors) {\n      console.log(error.errors);\n    }\n\n    ```\n\n\n    ### `networkError`\n\n\n    Network errors are no longer wrapped and are instead passed through\n    directly.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.error(new Error('Test error'));\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // error is `new Error('Test error')`;\n\n    ```\n\n\n    ### `protocolErrors`\n\n\n    Protocol errors are now encapsulated in a `CombinedProtocolErrors` instance.\n    You can access the raw protocol errors via the `errors` property.\n\n\n\n    ```js\n\n    import { CombinedProtocolErrors } from '@apollo/client';\n\n\n    // ...\n\n\n    const { error } = useSubscription(subscription);\n\n\n    if (error && error instanceof CombinedProtocolErrors) {\n      console.log(error.errors);\n    }\n\n    ```\n\n\n    ### `clientErrors`\n\n\n    These were unused by the client and have no replacement. Any non-GraphQL or\n    non-protocol errors are now passed through unwrapped.\n\n\n    ### Strings as errors\n\n\n    If the link sends a string error, Apollo Client will wrap this in an `Error`\n    instance. This ensures `error` properties are guaranteed to be of type\n    `Error`.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          // Oops we sent a string instead of wrapping it in an `Error`\n          observer.error('Test error');\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // The error string is wrapped and returned as `new Error('Test error')`;\n\n    ```\n\n\n    ### Non-error types\n\n\n    If the link chain sends any other object type as an error, Apollo Client\n    will wrap this in an `UnknownError` instance with the\n    [`cause`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause)\n    set to the original object. This ensures `error` properties are guaranteed\n    to be of type `Error`.\n\n\n    ```js\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.error({ message: 'Not a proper error type' });\n        })\n      })\n    })\n\n\n    // ...\n\n\n    const { error } = useQuery(query);\n\n\n    // error is an `UnknownError` instance. error.cause returns the original\n    object.\n\n    ```\n  gorgeous-chefs-tap: >-\n    Remove the `TCacheShape` generic argument to `ApolloClient`.\n    `client.extract()` now returns `unknown` by default. You will either need to\n    type-cast this to the expected serialized shape, or use the\n    `cache.extract()` directly from the subclass to get more specific types.\n  healthy-apes-sneeze: >-\n    Remove `fromError` utility function. Use\n    [`throwError`](https://rxjs.dev/api/index/function/throwError) instead.\n  hot-cycles-notice: >-\n    Remove the deprecated `graphql`, `withQuery`, `withMutation`,\n    `withSubscription`, and `withApollo` hoc components. Use the provided React\n    hooks instead.\n  itchy-drinks-refuse: Remove `itAsync` test utility.\n  khaki-spies-work: >-\n    Flatten out React hook types. As a result, the base types have been removed.\n    Prefer using the hook types instead. Removed types include:\n\n    - `BaseMutationOptions`\n\n    - `BaseQueryOptions`\n\n    - `BaseSubscriptionOptions`\n\n    - `ObservableQueryFields`\n\n    - `MutationSharedOptions`\n\n    - `QueryFunctionOptions`\n  kind-crews-warn: >-\n    `ObservableQuery` no longer has a `queryId` property.\n\n    `ApolloClient.getObservableQueries` no longer returns a `Map<string,\n    ObservableQuery>`, but a `Set<ObservableQuery>`.\n  late-trainers-peel: >-\n    * dropped the deprecated `DEV` export from `@apollo/client/utilities` and\n    `@apollo/client/utilities/globals`\n\n    * moved the `__DEV__` export from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/environment`\n\n    * moved the `invariant`, `newInvariantError` and `InvariantError` exports\n    from `@apollo/client/utilities/globals` to\n    `@apollo/client/utilities/invariant`\n  light-apes-rescue: >-\n    `useQuery` no longer returns `reobserve` as part of its result. It was\n    possible to use `reobserve` to set new options on the underlying\n    `ObservableQuery` instance which differed from the options passed to the\n    hook. This could result in unexpected results. Instead prefer to rerender\n    the hook with new options.\n  little-parrots-bow: >-\n    Removes the `resolvers` option from `ApolloClient`. Local resolvers have\n    instead been moved to the new `LocalState` instance which is assigned to the\n    `localState` option in `ApolloClient`. To migrate, move the `resolvers`\n    values into a `LocalState` instance and assign that instance to\n    `localState`.\n\n\n    ```diff\n\n    new ApolloClient({\n\n    - resolvers: { /* ... */ }\n\n    + localState: new LocalState({\n\n    +   resolvers: { /* ... */ }\n\n    + }),\n\n    });\n\n    ```\n  little-spoons-kick: >-\n    `client.mutate` now returns a `MutateResult` instead of `FetchResult`. As a\n    result, the `errors` property has been removed in favor of `error` which is\n    set if either a network error occured or GraphQL errors are returned from\n    the server.\n\n\n    `useMutation` now also returns a `MutateResult` instead of a `FetchResult`.\n  lucky-hats-push: >-\n    The execute function returned from `useLazyQuery` now only supports the\n    `context` and `variables` options. This means that passing options supported\n    by the hook no longer override the hook value.\n\n\n    To change options, rerender the component with new options. These options\n    will take effect with the next query execution.\n  mighty-penguins-wink: >-\n    Removes the `throwServerError` utility function. Now that `ServerError` is\n    an\n\n    `Error` subclass, you can throw these errors directly:\n\n\n    ```js\n\n    import { ServerError } from '@apollo/client';\n\n\n    // instead of\n\n    throwServerError(response, result, 'error message')\n\n\n    // Use\n\n    throw new ServerError('error message', { response, result })\n\n    ```\n  modern-feet-do: >-\n    `@apollo/client`, `@apollo/client/core` and `@apollo/client/cache` no longer\n    export an empty `Cache` runtime object. This is meant to be a type-only\n    namespace.\n  nervous-goats-allow: >-\n    Removes the `defaultOptions` option from `useQuery`. Use options directly or\n    use the global `ApolloClient` `defaultOptions`.\n  new-apes-care: Remove the deprecated `QueryReference` type. Please use `QueryRef` instead.\n  nice-donkeys-reflect: >-\n    Remove the `errors` property from the results emitted from `ObservableQuery`\n    or returned from `client.query`. Read errors from the `error` property\n    instead.\n  nice-dots-matter: >-\n    Removed the `parser` cache. The functionality has been replaced in a way\n    that doesn't need caching.\n  olive-cougars-ring: >-\n    Remove local resolvers APIs from `ApolloClient` in favor of `localState`.\n    Methods removed are:\n\n    - `addResolvers`\n\n    - `getResolvers`\n\n    - `setResolvers`\n\n    - `setLocalStateFragmentMatcher`\n  purple-bears-flash: >-\n    Removed the `@apollo/client/react/parser` entry point. There is no\n    replacement.\n  rich-eagles-cross: >-\n    The `reobserve` option is no longer available in the result returned from\n    `useLazyQuery`. This was considered an internal API and should not be used\n    directly.\n  selfish-spoons-approve: >-\n    Move internal testing utilities in `@apollo/client/testing` to\n    `@apollo/client/testing/internal` and remove deprecated testing utilities.\n    Some of the testing utilities exported from the `@apollo/client/testing`\n    endpoint were not considered stable. As a result of this change, testing\n    utilities or types exported from `@apollo/client/testing` are now considered\n    stable and will not undergo breaking changes.\n\n\n    The following APIs were removed. To migrate, update usages of the following\n    APIs as such:\n\n\n    **`createMockClient`**\n\n\n    ```diff\n\n    - const client = createMockClient(data, query, variables);\n\n    + const client = new ApolloClient({\n\n    +   cache: new InMemoryCache(),\n\n    +   link: new MockLink([\n\n    +     {\n\n    +       request: { query, variables },\n\n    +       result: { data },\n\n    +     }\n\n    +   ]),\n\n    + });\n\n    ```\n\n\n    **`mockObservableLink`**\n\n\n    ```diff\n\n    - const link = mockObservableLink();\n\n    + const link = new MockSubscriptionLink();\n\n    ```\n\n\n    **`mockSingleLink`**\n\n\n    ```diff\n\n    - const link = mockSingleLink({\n\n    -   request: { query, variables },\n\n    -   result: { data },\n\n    - });\n\n    + const link = new MockLink([\n\n    +   {\n\n    +     request: { query, variables },\n\n    +     result: { data },\n\n    +   }\n\n    + ]);\n\n    ```\n  serious-moons-juggle: >-\n    `client.query` no longer supports `notifyOnNetworkStatusChange` in options.\n    An error will be thrown if this option is set. The effects of this option\n    were not observable by `client.query` since `client.query` emits a single\n    result.\n  shiny-carrots-invent: Remove `subscribeAndCount` testing utility from `@apollo/client/testing`.\n  short-jokes-jam: >-\n    Moves all React-related exports to the `@apollo/client/react` entrypoint and\n    out of the main `@apollo/client` entrypoint. This prevents the need to\n    install React in order to use the core client.\n\n\n    The following is a list of exports available in `@apollo/client` that should\n    now import from `@apollo/client/react`.\n\n    - `ApolloConsumer`\n\n    - `ApolloProvider`\n\n    - `createQueryPreloader`\n\n    - `getApolloContext`\n\n    - `skipToken`\n\n    - `useApolloClient`\n\n    - `useBackgroundQuery`\n\n    - `useFragment`\n\n    - `useLazyQuery`\n\n    - `useLoadableQuery`\n\n    - `useMutation`\n\n    - `useQuery`\n\n    - `useQueryRefHandlers`\n\n    - `useReactiveVar`\n\n    - `useReadQuery`\n\n    - `useSubscription`\n\n    - `useSuspenseQuery`\n\n\n    The following is a list of exports available in `@apollo/client/testing`\n    that should now import from `@apollo/client/testing/react`:\n\n    - `MockedProvider`\n  silly-knives-exist: >-\n    Removes the `urql` multipart subscriptions utilities. Use the native\n    multipart subscriptions support in `urql` instead.\n  silly-seas-confess: Drop `graphql` v15 as a valid peer dependency.\n  six-jars-fix: >-\n    `queryRef`s created by `preloadQuery` no longer have a `.toPromise()`\n    function. Instead `preloadQuery` now has a `toPromise` function that accepts\n    a queryRef and will resolve when the underlying promise has been resolved.\n\n\n    ```diff\n\n    const queryRef = preloadQuery(query, options);\n\n\n    - await queryRef.toPromise();\n\n    + await preloadQuery.toPromise(queryRef);\n\n    ```\n  sixty-bears-bathe: >-\n    The `FetchMoreQueryOptions` type has been inlined into `FetchMoreOptions`,\n    and\n\n    `FetchMoreQueryOptions` has been removed.\n  slimy-chicken-melt: >-\n    Remove deprecated `onSubscriptionData` and `onSubscriptionComplete`\n    callbacks from `useSubscription`. Use `onData` and `onComplete` instead.\n  small-buttons-rhyme: >-\n    Remove the deprecated `canonizeResults` option. It was prone to memory\n    leaks. As such, some results that were referentially equal when\n    `canonizeResults` option was set to `true` no longer retain the same object\n    identity.\n  smart-rats-explode: >-\n    Remove `ObservableQuery.resetQueryStoreErrors` method. This method reset\n    some internal state that was not consumed elsewhere in the client and\n    resulted in a no-op.\n  smooth-coins-collect: >-\n    Remove `fromPromise` utility function. Use\n    [`from`](https://rxjs.dev/api/index/function/from) instead.\n  sour-pillows-guess: >-\n    The `defaultOptions` and `initialFetchPolicy` options are no longer\n    supported with `useLazyQuery`.\n\n\n    If you use `defaultOptions`, pass those options directly to the hook\n    instead. If you use `initialFetchPolicy`, use `fetchPolicy` instead.\n  stupid-pumpkins-travel: >-\n    Apollo Client no longer ships with support for `@client` fields\n    out-of-the-box and now must be opt-in. To opt in to use `@client` fields,\n    pass an instantiated `LocalState` instance to the `localState` option. If a\n    query contains `@client` and local state hasn't been configured, an error\n    will be thrown.\n\n\n    ```ts\n\n    import { LocalState } from \"@apollo/client/local-state\";\n\n\n    new ApolloClient({\n      localState: new LocalState(),\n    });\n\n    ```\n  tall-bikes-develop: >-\n    Remove `resetResultIdentities` option from `InMemoryCache.gc()`. This\n    affected object canonization which has been removed.\n  tender-swans-flash: >-\n    Remove `loading`, `networkStatus`, and `partial` properties on all\n    promise-based query APIs. These properties were mostly static and were\n    unnecessary since promise resolution guaranteed that the query was not\n    longer loading.\n\n\n    This affects the following APIs:\n\n    - `client.query`\n\n    - `client.refetchQueries`\n\n    - `client.reFetchObservableQueries`\n\n    - `client.resetStore`\n\n    - `observableQuery.fetchMore`\n\n    - `observableQuery.refetch`\n\n    - `observableQuery.reobserve`\n\n    - `observableQuery.setVariables`\n\n    - The `useLazyQuery` `execute` function\n  tidy-squids-poke: >-\n    Removes `ObservableQuery.result()` method. If you use this method and need\n    similar functionality, use the `firstValueFrom` helper in RxJS.\n\n\n    ```ts\n\n    import { firstValueFrom, from } from \"rxjs\";\n\n\n    // The `from` is necessary to turn `observableQuery` into an RxJS observable\n\n    const result = await firstValueFrom(from(observableQuery))\n\n    ```\n  tough-taxis-smoke: >-\n    Remove the `onCompleted` and `onError` callbacks from `useQuery` and\n    `useLazyQuery`.\n\n\n    See [#12352](https://github.com/apollographql/apollo-client/issues/12352)\n    for more context on this change.\n  unlucky-kiwis-sell: Remove the `called` property from `useQuery`.\n  unlucky-sheep-change: >-\n    Remove `toPromise` utility function. Use\n    [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom)\n    instead.\n  wicked-forks-double: >-\n    Remove `newData` option for mocked responses passed to `MockLink` or the\n    `mocks` option on `MockedProvider`. This option was undocumented and was\n    nearly identical to using the `result` option as a callback.\n\n\n    To replicate the old behavior of `newData`, use `result` as a callback and\n    add the `maxUsageCount` option with a value set to\n    `Number.POSITIVE_INFINITY`.\n\n\n    **with `MockLink`**\n\n    ```diff\n\n    new MockLink([\n      {\n        request: { query, variables },\n    -   newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +   maxUsageCount: Number.POSITIVE_INFINITY,\n      }\n    ])\n\n    ```\n\n\n    **with `MockedProvider`**\n\n    ```diff\n\n    <MockedProvider\n      mocks={[\n        {\n          request: { query, variables },\n    -     newData: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     result: (variables) => ({ data: { greeting: \"Hello \" +\n    variables.greeting } }),\n\n    +     maxUsageCount: Number.POSITIVE_INFINITY,\n        }\n      ]}\n    />\n\n    ```\n  witty-paws-marry: >-\n    Require the `link` option when instantiating `ApolloClient`. This removes\n    the `uri`, `credentials` and `headers` options from `ApolloClient` in favor\n    of passing an instantiated `HttpLink` directly. To migrate:\n\n\n    **If using `uri`, `credentials`, or `headers` options**\n\n    ```diff\n\n    new ApolloClient({\n      // ...\n    - uri,\n\n    - credentials,\n\n    - headers,\n\n    + link: new HttpLink({ uri, credentials, headers }),\n\n    // or if you prefer the function call approach:\n\n    + link: createHttpLink({ uri, credentials, headers }),\n\n    });\n\n    ```\n\n\n    **If creating a client without the `link` option**\n\n    ```diff\n\n    new ApolloClient({\n      // ...\n    + link: ApolloLink.empty()\n\n    });\n\n    ```\n  young-turtles-explode: >-\n    Remove the deprecated `Query`, `Mutation`, and `Subscription` components.\n    Use the provided React hooks instead.\n  mean-lizards-think: >-\n    Ensure `useLazyQuery` does not return a `partial` property which is not\n    specified by the result type.\n  ninety-bags-bake: >-\n    Mocked responses passed to `MockLink` now accept a callback for the\n    `request.variables` option. This is used to determine if the mock should be\n    matched for a set of request variables. With this change, the\n    `variableMatcher` option has been removed in favor of passing a callback to\n    `variables`. Update by moving the callback function from `variableMatcher`\n    to `request.variables`.\n\n\n    ```diff\n\n    new MockLink([\n      {\n        request: {\n          query,\n    +     variables: (requestVariables) => true\n        },\n    -   variableMatcher: (requestVariables) => true\n      }\n    ]);\n\n    ```\n  thirty-pens-jump: >-\n    Remove the `fragmentMatcher` option from `ApolloClient`. Custom fragment\n    matchers used with local state are no longer supported. Fragment matching is\n    now performed by the configured `cache` via the `cache.fragmentMatches` API.\nother:\n  itchy-roses-accept: >-\n    Use an an empty object (`{}`) rather than an object with `null` prototype\n    (`Object.create(null)`) in all areas that instantiate objects.\nignore:\n  fresh-swans-remain: >-\n    Fix a bug where the new `operationType` property wasn't passed into\n    `operation`.\n  friendly-walls-think: Version bump only to release latest as `rc`.\n  lucky-camels-compete: Export `getMainDefinition` from `@apollo/client/utilities`.\n  lucky-donkeys-behave: Version bump only to release latest as `rc`.\n  silent-lobsters-try: Version bump only for codegen to release as `rc`.\n  slimy-maps-press: Fix up the 4.0 CommonJS build\n  real-turtles-boil: Enable React compiler for hooks in ESM builds.\n  bright-ads-share: >-\n    Removes the `isApolloError` utility function to check if the error object is\n    an `ApolloError` instance. Use `instanceof` to check for more specific error\n    types that replace `ApolloError`.\n"
  },
  {
    "path": "scripts/changesets/categorized/package.json",
    "content": "{\n  \"name\": \"categorized\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"dependencies\": {\n    \"js-yaml\": \"^4.1.0\"\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/README.md",
    "content": "# Migrating `import`s from Apollo Client 2.x to 3.x\n\nThis directory contains a [jscodeshift](https://www.npmjs.com/package/jscodeshift)-based\ntransform for translating `import` declarations and package names from\nApollo Client 2.x to Apollo Client 3.x, following the [migration guide](https://www.apollographql.com/docs/react/migrating/apollo-client-3-migration/).\n\nWhile this transform should simplify the migration process by removing\nsome manual effort, you should nevertheless check the results carefully,\nand use version control to recover your original code if anything goes\nwrong. We welcome issues and pull requests to improve this transform.\n\n## Running the transform\n\nTo run the transform over a directory of source files, first install\n`jscodeshift` using `npm i --save-dev jscodeshift`, then choose among the\nfollowing commands to run, depending on the types of files you have:\n\n```sh\n# To transform all .js files:\nnpx jscodeshift \\\n  -t apollo-client/scripts/codemods/ac2-to-ac3/imports.js \\\n  --extensions js \\\n  source-directory\n\n# To transform all .ts files:\nnpx jscodeshift \\\n  -t apollo-client/scripts/codemods/ac2-to-ac3/imports.js \\\n  --extensions ts --parser ts \\\n  source-directory\n\n# To transform all .tsx files:\nnpx jscodeshift \\\n  -t apollo-client/scripts/codemods/ac2-to-ac3/imports.js \\\n  --extensions tsx --parser tsx \\\n  source-directory\n```\n\nNote that the `apollo-client` directory here is intended to be a checkout\nof [this repository](https://github.com/apollographql/apollo-client/).\n\n## Kicking the tires\n\nTo see how the transform handles some example source files, run the\nfollowing commands in this directory (within a checkout of the Apollo\nClient repository):\n\n```sh\nnpm install\nnpx jscodeshift -t imports.js --extensions js examples\nnpx jscodeshift -t imports.js --extensions ts --parser ts examples\nnpx jscodeshift -t imports.js --extensions tsx --parser tsx examples\n```\n\nRunning `git diff` after these commands will display the changes made by\nthe transform.\n\n## Known limitations\n\nThis transform does not currently handle\n\n- `export ... from \"apollo-*\"` declarations\n- `import * as namespace from \"apollo-*\"` declarations\n- Imports from the older `react-apollo` package\n- Checking for proper usage of moved imports\n\nIf you discover other shortcomings, please feel free to suggest additions\nto this list, or submit a PR that adds additional examples demonstrating\nthe problem, or try your hand at improving the transform.\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/examples/client-and-cache.ts",
    "content": "import Client from \"apollo-client\";\nimport { InMemoryCache, InMemoryCacheConfig } from \"apollo-cache-inmemory\";\nimport gql from \"graphql-tag\";\n\nconst client = new Client({\n  cache: new InMemoryCache({} as InMemoryCacheConfig),\n});\n\nclient.query({\n  query: gql`\n    query {\n      __typename\n    }\n  `,\n});\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/examples/link-packages.js",
    "content": "import { ApolloLink, Observable } from \"apollo-link\";\nimport { HttpLink } from \"apollo-link-http\";\nimport { BatchLink } from \"apollo-link-batch\";\nimport { BatchHttpLink } from \"apollo-link-batch-http\";\nimport { setContext } from \"apollo-link-context\";\nimport { ErrorLink } from \"apollo-link-error\";\nimport {\n  VERSION,\n  createPersistedQueryLink,\n} from \"apollo-link-persisted-queries\";\nimport { RetryLink } from \"apollo-link-retry\";\nimport { WebSocketLink } from \"apollo-link-ws\";\n// This package was unusual for having a default export.\nimport SchemaLink from \"apollo-link-schema\";\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/examples/react-packages.tsx",
    "content": "import { useQuery } from \"@apollo/react-hooks\";\nimport { graphql, withApollo, ChildProps } from \"@apollo/react-hoc\";\nimport { MockProvider } from \"@apollo/react-testing\";\n\nimport {\n  getDataFromTree,\n  getMarkupFromTree,\n  renderToStringWithData,\n} from \"@apollo/react-ssr\";\n\nimport { Query, Mutation, Subscription } from \"@apollo/react-components\";\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/imports.js",
    "content": "/**\n * This jscodeshift transform takes care of some of the rote things you'll\n * need to do while migrating from v2 to v3. See README.md for usage\n * instructions and further explanation.\n *\n * Original author: @dminkovsky (PR #6486)\n * Contributors: @jcreighton @benjamn\n * Reviewers: @hwillson @bnjmnt4n\n */\nexport default function transformer(file, api) {\n  const j = api.jscodeshift;\n\n  const source = j(file.source);\n\n  renameOrCreateApolloClientImport();\n\n  moveSpecifiersToApolloClient(\"react-apollo\");\n  moveSpecifiersToApolloClient(\"@apollo/react-common\");\n  moveSpecifiersToApolloClient(\"@apollo/react-hooks\");\n  moveSpecifiersToApolloClient(\"apollo-cache\");\n  moveSpecifiersToApolloClient(\"apollo-cache-inmemory\");\n  moveSpecifiersToApolloClient(\"apollo-link\");\n  moveSpecifiersToApolloClient(\"apollo-link-http\");\n  moveSpecifiersToApolloClient(\"apollo-link-http-common\");\n\n  renameDefaultSpecifier(getImport(\"graphql-tag\"), \"gql\");\n  moveSpecifiersToApolloClient(\"graphql-tag\");\n\n  renameImport(\"@apollo/react-components\", \"@apollo/client/react/components\");\n  renameImport(\"@apollo/react-hoc\", \"@apollo/client/react/hoc\");\n  renameImport(\"@apollo/react-ssr\", \"@apollo/client/react/ssr\");\n  renameImport(\"@apollo/react-testing\", \"@apollo/client/testing\");\n  renameImport(\"apollo-utilities\", \"@apollo/client/utilities\");\n\n  renameDefaultSpecifier(getImport(\"apollo-link-schema\"), \"SchemaLink\");\n  [\n    \"batch\",\n    \"batch-http\",\n    \"context\",\n    \"error\",\n    \"persisted-queries\",\n    \"retry\",\n    \"schema\",\n    \"ws\",\n  ].forEach((link) =>\n    renameImport(`apollo-link-${link}`, `@apollo/client/link/${link}`)\n  );\n\n  removeApolloClientImportIfEmpty();\n\n  return source.toSource();\n\n  function renameOrCreateApolloClientImport() {\n    const ac3Import = getImport(\"@apollo/client\");\n    if (ac3Import.size()) {\n      return;\n    }\n\n    const ac2Import = getImport(\"apollo-client\");\n    if (ac2Import.size()) {\n      renameDefaultSpecifier(ac2Import, \"ApolloClient\");\n      renameImport(\"apollo-client\", \"@apollo/client\");\n    } else {\n      source\n        .find(j.ImportDeclaration)\n        .at(0)\n        .insertBefore(() =>\n          j.importDeclaration([], j.literal(\"@apollo/client\"))\n        );\n    }\n  }\n\n  function removeApolloClientImportIfEmpty() {\n    const ac3Import = getImport(\"@apollo/client\");\n    if (ac3Import.size() && !ac3Import.get(\"specifiers\", \"length\").value) {\n      ac3Import.remove();\n    }\n  }\n\n  function moveSpecifiersToApolloClient(moduleName) {\n    const moduleImport = getImport(moduleName);\n\n    if (moduleImport.size()) {\n      const clientImports = getImport(\"@apollo/client\");\n      const specifiersToAdd = moduleImport.get(\"specifiers\").value;\n      clientImports.get(\"specifiers\").push(...specifiersToAdd);\n    }\n\n    moduleImport.remove();\n  }\n\n  function renameImport(oldModuleName, newModuleName) {\n    getImport(oldModuleName)\n      .find(j.Literal)\n      .replaceWith((path) => ({\n        ...path.value,\n        value: newModuleName,\n      }));\n  }\n\n  function getImport(moduleName) {\n    return source.find(j.ImportDeclaration, {\n      source: { value: moduleName },\n    });\n  }\n\n  function renameDefaultSpecifier(moduleImport, name) {\n    function replacer(path) {\n      return path.value.local.name === name ?\n          j.importSpecifier(j.identifier(name))\n        : j.importSpecifier(j.identifier(name), path.value.local);\n    }\n\n    // Handle ordinary (no-{}s) default imports.\n    moduleImport.find(j.ImportDefaultSpecifier).replaceWith(replacer);\n\n    // Handle { default as Foo } default imports.\n    moduleImport\n      .find(j.ImportSpecifier, {\n        imported: {\n          name: \"default\",\n        },\n      })\n      .replaceWith(replacer);\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac2-to-ac3/package.json",
    "content": "{\n  \"private\": true,\n  \"devDependencies\": {\n    \"jscodeshift\": \"0.16.1\"\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/CHANGELOG.md",
    "content": "# @apollo/client-codemod-migrate-3-to-4\n\n## 1.0.2\n\n### Patch Changes\n\n- [#12879](https://github.com/apollographql/apollo-client/pull/12879) [`56b2094`](https://github.com/apollographql/apollo-client/commit/56b20945a2c3d3fb227d5ede3b705a5c58801b7d) Thanks [@phryneas](https://github.com/phryneas)! - Fix an issue where `networkStatus` would not be moved into the correct package.\n\n## 1.0.1\n\n### Patch Changes\n\n- [#12866](https://github.com/apollographql/apollo-client/pull/12866) [`0d1614a`](https://github.com/apollographql/apollo-client/commit/0d1614a9dfca2b1bcf4ea40095cc9018d6314532) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Export `isNetworkStatusInFlight` from `@apollo/client/utilities`. Add `isNetworkStatusSettled` to `@apollo/client/utilities` and re-export it from `@apollo/client` with a deprecation.\n\n## 1.0.0\n\n### Major Changes\n\n- [#12727](https://github.com/apollographql/apollo-client/pull/12727) [`b845906`](https://github.com/apollographql/apollo-client/commit/b8459062caae96447b4867be75a853aa1943ec31) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a codemod that renames old import locations from 3.x entrypoint to their 4.x entrypoint.\n\n  Run the codemod using the following command:\n\n  ```sh\n  npx @apollo/client-codemod-migrate-3-to-4 --parser tsx ./src/**/*.{ts,tsx}\n  ```\n\n  The codemod supports `.js`, `.jsx`, `.ts`, and `.tsx` files.\n\n- [#12851](https://github.com/apollographql/apollo-client/pull/12851) [`32bc830`](https://github.com/apollographql/apollo-client/commit/32bc8302f1a8a2107da275e72a20d64014247618) Thanks [@phryneas](https://github.com/phryneas)! - Add a new `clientSetup` codemod step which applies the following steps from the migration guide to your Apollo Client setup code:\n  - Moves `uri`, `headers` and `credentials` to the `link` option and creates a new `HttpLink` instance\n  - Moves `name` and `version` into a `clientAwareness` option\n  - Adds a `localState` option with a new `LocalState` instance, moves `resolvers`, and removes `typeDefs` and `fragmentMatcher` options\n  - Changes the `connectToDevTools` option to `devtools.enabled`\n  - Renames `disableNetworkFetches` to `prioritizeCacheValues`\n  - If `dataMasking` is enabled, adds a template for global type augmentation to re-enable data masking types\n  - Adds the `incrementalHandler` option and adds a template for global type augmentation to accordingly type network responses in custom links\n\n### Minor Changes\n\n- [#12818](https://github.com/apollographql/apollo-client/pull/12818) [`d1e9503`](https://github.com/apollographql/apollo-client/commit/d1e9503eb58325529f0f0dc8b0cb07cf05431ee3) Thanks [@phryneas](https://github.com/phryneas)! - Extend `imports` codemod, add new `links` and `removals` (via #12838) codemods.\n\n### Patch Changes\n\n- [#12846](https://github.com/apollographql/apollo-client/pull/12846) [`71ccfb5`](https://github.com/apollographql/apollo-client/commit/71ccfb5226937b14d4d4f59c46eea2a8cacd6700) Thanks [@phryneas](https://github.com/phryneas)! - Add a new `legacyEntryPoints` transformation step that moves imports from old legacy entry points like `@apollo/client/main.cjs` or `@apollo/client/react/react.cjs` to the new entry points like `@apollo/client` or `@apollo/client/react`.\n\n- [#12775](https://github.com/apollographql/apollo-client/pull/12775) [`454ec78`](https://github.com/apollographql/apollo-client/commit/454ec78b751853da07243174a6f9bdc4535e7e8f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't export `gql` from `@apollo/client/react` entrypoint. Import from `@apollo/client` instead.\n\n- [#12858](https://github.com/apollographql/apollo-client/pull/12858) [`6440e8b`](https://github.com/apollographql/apollo-client/commit/6440e8bc6c42ed2f97ccabac987e10f3c81d90b4) Thanks [@phryneas](https://github.com/phryneas)! - adjust the `clientSetup` codemod so that it removes the `TCacheShape` type argument from all `ApolloClient` usages (types and constructor calls).\n\n## 1.0.0-rc.3\n\n### Major Changes\n\n- [#12851](https://github.com/apollographql/apollo-client/pull/12851) [`32bc830`](https://github.com/apollographql/apollo-client/commit/32bc8302f1a8a2107da275e72a20d64014247618) Thanks [@phryneas](https://github.com/phryneas)! - Add a new `clientSetup` codemod step which applies the following steps from the migration guide to your Apollo Client setup code:\n  - Moves `uri`, `headers` and `credentials` to the `link` option and creates a new `HttpLink` instance\n  - Moves `name` and `version` into a `clientAwareness` option\n  - Adds a `localState` option with a new `LocalState` instance, moves `resolvers`, and removes `typeDefs` and `fragmentMatcher` options\n  - Changes the `connectToDevTools` option to `devtools.enabled`\n  - Renames `disableNetworkFetches` to `prioritizeCacheValues`\n  - If `dataMasking` is enabled, adds a template for global type augmentation to re-enable data masking types\n  - Adds the `incrementalHandler` option and adds a template for global type augmentation to accordingly type network responses in custom links\n\n### Patch Changes\n\n- [#12846](https://github.com/apollographql/apollo-client/pull/12846) [`71ccfb5`](https://github.com/apollographql/apollo-client/commit/71ccfb5226937b14d4d4f59c46eea2a8cacd6700) Thanks [@phryneas](https://github.com/phryneas)! - Add a new `legacyEntryPoints` transformation step that moves imports from old legacy entry points like `@apollo/client/main.cjs` or `@apollo/client/react/react.cjs` to the new entry points like `@apollo/client` or `@apollo/client/react`.\n\n## 1.0.0-rc.2\n\n### Minor Changes\n\n- [#12818](https://github.com/apollographql/apollo-client/pull/12818) [`d1e9503`](https://github.com/apollographql/apollo-client/commit/d1e9503eb58325529f0f0dc8b0cb07cf05431ee3) Thanks [@phryneas](https://github.com/phryneas)! - Extend `imports` codemod, add new `links` and `removals` (via #12838) codemods.\n\n## 1.0.0-rc.1\n\n### Patch Changes\n\n- [#12775](https://github.com/apollographql/apollo-client/pull/12775) [`454ec78`](https://github.com/apollographql/apollo-client/commit/454ec78b751853da07243174a6f9bdc4535e7e8f) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Don't export `gql` from `@apollo/client/react` entrypoint. Import from `@apollo/client` instead.\n\n## 1.0.0-rc.0\n\n### Major Changes\n\n- [#12727](https://github.com/apollographql/apollo-client/pull/12727) [`b845906`](https://github.com/apollographql/apollo-client/commit/b8459062caae96447b4867be75a853aa1943ec31) Thanks [@jerelmiller](https://github.com/jerelmiller)! - Add a codemod that renames old import locations from 3.x entrypoint to their 4.x entrypoint.\n\n  Run the codemod using the following command:\n\n  ```sh\n  npx @apollo/client-codemod-migrate-3-to-4 --parser tsx ./src/**/*.{ts,tsx}\n  ```\n\n  The codemod supports `.js`, `.jsx`, `.ts`, and `.tsx` files.\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/README.md",
    "content": "## Using this codemod\n\nYou can run this codemod with the following command:\n\n```bash\nnpx @apollo/client-codemod-migrate-3-to-4 --parser ts file1.ts file2.ts\n```\n\nif you want to only run a specific codemod:\n\n```bash\nnpx @apollo/client-codemod-migrate-3-to-4 --parser ts file1.ts file2.ts  --codemod imports\n```\n\n### Available codemods:\n\nIn the order they will be applied per default if you don't manually specify a codemod:\n\n- `legacyEntryPoints`: Moves imports from old legacy entry points like `@apollo/client/main.cjs` or `@apollo/client/react/react.cjs` to the new entry points like `@apollo/client` or `@apollo/client/react`.\n- `imports`: Moves imports that have been moved or renamed in Apollo Client 4. Also moves types into namespace imports where applicable.\n- `links`: Moves `split`, `from`, `concat` and `empty` onto the `ApolloLink` namespace, changes function link invocations like `createHttpLink(...)` to their class equivalents like (`new HttpLink(...)`).\n  Does not change `setContext((operation, prevContext) => {})` to `new ContextLink((prevContext, operation) => {})` - this requires manual intervention, as the order of callback arguments is flipped and this is not reliable codemoddable.\n- `removals`: Points all imports of values or types that have been removed in Apollo Client 4 to the `@apollo/client/v4-migration` entry point. That entry point contains context for each removal, oftentimes with migration instructions.\n- `clientSetup`: Applies the following steps from the migration guide to your Apollo Client setup code\n  - Moves `uri`, `headers` and `credentials` to the `link` option and creates a new `HttpLink` instance\n  - Moves `name` and `version` into a `clientAwareness` option\n  - Adds a `localState` option with a new `LocalState` instance, moves `resolvers`, and removes `typeDefs` and `fragmentMatcher` options\n  - Changes the `connectToDevTools` option to `devtools.enabled`\n  - Renames `disableNetworkFetches` to `prioritizeCacheValues`\n  - If `dataMasking` is enabled, adds a template for global type augmentation to re-enable data masking types\n  - Adds the `incrementalHandler` option and adds a template for global type augmentation to accordingly type network responses in custom links\n  - Removes the `TCacheShape` type argument from all `ApolloClient` usages (types and constructor calls)\n\n### Usage against TypeScript/TSX\n\nThere is some syntax overlap between TypeScript and TypeScript-JSX files, so you might need to run the Codemod against both file extensions separately to avoid errors:\n\n```sh\nnpx @apollo/client-codemod-migrate-3-to-4 --parser ts --ignore-pattern=\"*.{tsx,d.ts}\" file1.ts file2.ts\nnpx @apollo/client-codemod-migrate-3-to-4 --parser tsx --ignore-pattern=\"*.ts\" file1.ts file2.ts\n```\n\n### Using the Codemod from a specific PR\n\n```sh\nnpx https://pkg.pr.new/apollographql/apollo-client/@apollo/client-codemod-migrate-3-to-4@12733 --parser ts file1.ts file2.ts\n```\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/package.json",
    "content": "{\n  \"name\": \"@apollo/client-codemod-migrate-3-to-4\",\n  \"version\": \"1.0.2\",\n  \"description\": \"Apollo Client Codemod to migrate from version 3 to version 4\",\n  \"keywords\": [\n    \"apollo\",\n    \"client\",\n    \"graphql\",\n    \"codemod\"\n  ],\n  \"author\": \"packages@apollographql.com\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"sideEffects\": false,\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/apollographql/apollo-client.git\",\n    \"directory\": \"codegen\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/apollographql/apollo-client/issues\"\n  },\n  \"homepage\": \"https://www.apollographql.com/docs/react/\",\n  \"exports\": {\n    \".\": \"./dist/index.js\",\n    \"./imports\": \"./dist/imports.js\"\n  },\n  \"files\": [\n    \"dist\",\n    \"README.md\"\n  ],\n  \"bin\": {\n    \"apollo-client-codemod-migrate-3-to-4\": \"./dist/cli.js\"\n  },\n  \"scripts\": {\n    \"prebuild\": \"npm run clean\",\n    \"clean\": \"rimraf dist\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"prepack\": \"npm run build\",\n    \"publint\": \"publint run --strict .\",\n    \"test\": \"NODE_OPTIONS='--import ./src/devLoader.js' vitest run\",\n    \"test:watch\": \"NODE_OPTIONS='--import ./src/devLoader.js' vitest watch\",\n    \"local:cli\": \"node --import ./src/devLoader.js src/cli.ts\"\n  },\n  \"dependencies\": {\n    \"jscodeshift\": \"17.3.0\"\n  },\n  \"devDependencies\": {\n    \"@types/jscodeshift\": \"^17.3.0\",\n    \"@types/node\": \"20.9.0\",\n    \"diff\": \"^8.0.2\",\n    \"typescript\": \"^5.2.2\",\n    \"vitest\": \"^1.0.1\"\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/runLocally.sh",
    "content": "#!/usr/bin/env bash\nbabelconfig () {\ncat <<'EOF'\n{\n  \"sourceType\": \"module\",\n  \"allowImportExportEverywhere\": true,\n  \"allowReturnOutsideFunction\": true,\n  \"startLine\": 1,\n  \"tokens\": true,\n  \"plugins\": [\n    \"typescript\",\n    \"jsx\",\n    \"asyncGenerators\",\n    \"decoratorAutoAccessors\",\n    \"bigInt\",\n    \"classPrivateMethods\",\n    \"classPrivateProperties\",\n    \"classProperties\",\n    \"decorators-legacy\",\n    \"doExpressions\",\n    \"dynamicImport\",\n    \"exportDefaultFrom\",\n    \"exportExtensions\",\n    \"exportNamespaceFrom\",\n    \"functionBind\",\n    \"functionSent\",\n    \"importAttributes\",\n    \"importMeta\",\n    \"nullishCoalescingOperator\",\n    \"numericSeparator\",\n    \"objectRestSpread\",\n    \"optionalCatchBinding\",\n    \"optionalChaining\",\n    [\"pipelineOperator\", { \"proposal\": \"minimal\" }],\n    \"throwExpressions\",\n    \"explicitResourceManagement\"\n  ]\n}\nEOF\n}\n\nnode --import ./src/devLoader.js ./src/cli.js --parser babylon --parser-config=<(babelconfig) ../../../${1:-src}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/@types/jscodeshift.d.ts",
    "content": "declare module \"jscodeshift/dist/testUtils\" {\n  import { Transform } from \"jscodeshift\";\n\n  export function defineInlineTest(\n    module: Transform,\n    options: Record<string, unknown>,\n    input: string,\n    expectedOutput: string,\n    testName?: string\n  ): void;\n\n  export function defineTest(\n    dirName: string,\n    transformName: string,\n    options: Record<string, unknown> | null,\n    testFilePrefix?: string,\n    testOptions?: {\n      parser?: \"babel\" | \"babylon\" | \"flow\" | \"ts\" | \"tsx\" | (string & {});\n    }\n  ): void;\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__testfixtures__/imports.input.ts",
    "content": "/* eslint-disable import/order */\n\nimport type { QueryReference, QueryHookOptions } from \"@apollo/client\";\nconst queryRef: QueryReference = {} as any;\nconst queryOptions: QueryHookOptions = {} as any;\n\nimport type { ApolloProviderProps } from \"@apollo/client/react\";\nconst providerProps: ApolloProviderProps = {} as any;\n\nimport type { ErrorResponse } from \"@apollo/client/link/error\";\nconst response: ErrorResponse = {} as any;\n\nimport { useQuery, ApolloProvider } from \"@apollo/client\";\n\nimport type { LoadQueryFunction } from \"@apollo/client\";\n\nimport { getApolloContext } from \"@apollo/client/react/context\";\n\nimport { omitDeep } from \"@apollo/client/utilities\";\n\nimport type { ContextSetter } from \"@apollo/client/link/context\";\nconst contextSetter: ContextSetter = (() => {}) as any;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__testfixtures__/imports.output.ts",
    "content": "/* eslint-disable import/order */\n\n\n\nconst queryRef: QueryRef = {} as any;\nconst queryOptions: useQuery.Options = {} as any;\n\nimport type { QueryRef, useLoadableQuery } from \"@apollo/client/react\";\nconst providerProps: ApolloProvider.Props = {} as any;\n\nimport type { ErrorLink } from \"@apollo/client/link/error\";\nconst response: ErrorLink.ErrorHandlerOptions = {} as any;\n\nimport { getApolloContext, ApolloProvider, useQuery } from \"@apollo/client/react\";\nimport { omitDeep } from \"@apollo/client/utilities/internal\";\n\nimport type { SetContextLink } from \"@apollo/client/link/context\";\nconst contextSetter: SetContextLink.LegacyContextSetter = (() => {}) as any;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/__snapshots__/exports.test.ts.snap",
    "content": "// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html\n\nexports[`all exports > @apollo/client 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  ApolloClientOptions,\n-  DefaultOptions,\n   ApolloClient,\n-  mergeOptions,\n-  FetchMoreOptions,\n   ObservableQuery,\n-  QueryOptions,\n-  WatchQueryOptions,\n-  MutationOptions,\n-  SubscriptionOptions,\n   FetchPolicy,\n   WatchQueryFetchPolicy,\n   MutationFetchPolicy,\n   RefetchWritePolicy,\n   ErrorPolicy,\n   FetchMoreQueryOptions,\n-  SubscribeToMoreOptions,\n   SubscribeToMoreFunction,\n   UpdateQueryMapFn,\n   UpdateQueryOptions,\n   SubscribeToMoreUpdateQueryFn,\n@@  @@\n   StoreObject,\n   DocumentTransform,\n   Observable,\n   isReference,\n-  makeReference,\n   setLogVerbosity,\n   gql,\n   resetCaches,\n   disableFragmentWarnings,\n@@  @@\n   RefetchQueryDescriptor,\n   InternalRefetchQueryDescriptor,\n   RefetchQueriesInclude,\n   InternalRefetchQueriesInclude,\n-  RefetchQueriesOptions,\n   RefetchQueriesPromiseResults,\n-  RefetchQueriesResult,\n   InternalRefetchQueriesOptions,\n   InternalRefetchQueriesResult,\n   InternalRefetchQueriesMap,\n   PureQueryOptions,\n   OperationVariables,\n-  ApolloQueryResult,\n   MutationQueryReducer,\n   MutationQueryReducersMap,\n   MutationUpdaterFn,\n   MutationUpdaterFunction,\n@@  @@\n   concat,\n   execute,\n   ApolloLink,\n   DocumentNode,\n-  Path,\n-  ExecutionPatchInitialResult,\n-  IncrementalPayload,\n-  ExecutionPatchIncrementalResult,\n   ApolloPayloadResult,\n-  ExecutionPatchResult,\n-  GraphQLRequest,\n-  Operation,\n-  SingleExecutionResult,\n-  FetchResult,\n-  NextLink,\n-  RequestHandler,\n   ServerParseError,\n   parseAndCheckHttpResponse,\n   ClientParseError,\n   serializeFetchParameter,\n@@  @@\n   selectURI,\n   createHttpLink,\n   HttpLink,\n   rewriteURIForGET,\n-  ApolloContextValue,\n-  ApolloProvider,\n   ApolloConsumer,\n-  getApolloContext,\n   resetApolloContext,\n   IDocumentDefinition,\n   DocumentType,\n   operationName,\n   parser,\n-  PreloadQueryOptions,\n-  PreloadQueryFetchPolicy,\n-  PreloadQueryFunction,\n-  createQueryPreloader,\n-  useQuery,\n-  UseSuspenseQueryResult,\n-  useSuspenseQuery,\n-  UseBackgroundQueryResult,\n-  useBackgroundQuery,\n-  UseSuspenseFragmentResult,\n-  UseSuspenseFragmentOptions,\n-  useSuspenseFragment,\n-  LoadQueryFunction,\n-  UseLoadableQueryResult,\n-  useLoadableQuery,\n-  UseQueryRefHandlersResult,\n-  useQueryRefHandlers,\n-  UseReadQueryResult,\n-  useReadQuery,\n-  skipToken,\n-  SkipToken,\n-  useApolloClient,\n-  useLazyQuery,\n-  useMutation,\n-  useSubscription,\n-  useReactiveVar,\n-  useFragment,\n-  UseFragmentOptions,\n-  UseFragmentResult,\n-  QueryReference,\n-  QueryRef,\n-  PreloadedQueryRef,\n-  Context,\n   CommonOptions,\n   BaseQueryOptions,\n-  QueryFunctionOptions,\n   ObservableQueryFields,\n-  QueryResult,\n   QueryDataOptions,\n-  QueryHookOptions,\n-  LazyQueryHookOptions,\n-  LazyQueryHookExecOptions,\n-  SuspenseQueryHookFetchPolicy,\n-  SuspenseQueryHookOptions,\n-  BackgroundQueryHookFetchPolicy,\n-  BackgroundQueryHookOptions,\n-  LoadableQueryHookFetchPolicy,\n-  LoadableQueryHookOptions,\n   QueryLazyOptions,\n-  LazyQueryResult,\n-  QueryTuple,\n-  LazyQueryExecFunction,\n-  LazyQueryResultTuple,\n   RefetchQueriesFunction,\n   BaseMutationOptions,\n-  MutationFunctionOptions,\n-  MutationResult,\n-  MutationFunction,\n-  MutationHookOptions,\n   MutationDataOptions,\n-  MutationTuple,\n-  OnDataOptions,\n-  OnSubscriptionDataOptions,\n-  BaseSubscriptionOptions,\n-  SubscriptionResult,\n-  SubscriptionHookOptions,\n-  SubscriptionDataOptions,\n   SubscriptionCurrentObservable,\n-  VariablesOption,\n-  NoInfer\n+  Defer20220824Handler,\n+  Incremental,\n+  FormattedExecutionResult,\n } from \"@apollo/client\";\n-type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\n-type _Test_DefaultOptions = DefaultOptions;\n+\n+import {\n+  ApolloProvider,\n+  createQueryPreloader,\n+  getApolloContext,\n+  skipToken,\n+  useApolloClient,\n+  useBackgroundQuery,\n+  useFragment,\n+  useLazyQuery,\n+  useLoadableQuery,\n+  useMutation,\n+  useQuery,\n+  useQueryRefHandlers,\n+  useReactiveVar,\n+  useReadQuery,\n+  useSubscription,\n+  useSuspenseFragment,\n+  useSuspenseQuery,\n+} from \"@apollo/client/react\";\n+\n+import type {\n+  QueryRef,\n+  ApolloContextValue,\n+  MutationFunction,\n+  PreloadedQueryRef,\n+  PreloadQueryFetchPolicy,\n+  PreloadQueryFunction,\n+  PreloadQueryOptions,\n+  QueryRef,\n+  SkipToken,\n+  SubscriptionDataOptions,\n+} from \"@apollo/client/react\";\n+\n+import type { NoInfer, VariablesOption } from \"@apollo/client/utilities/internal\";\n+type _Test_ApolloClientOptions = ApolloClient.Options<TCacheShape>;\n+type _Test_DefaultOptions = ApolloClient.DefaultOptions;\n class _Test_ApolloClient extends ApolloClient<TCacheShape> {}\n const _test_ApolloClient = new ApolloClient<TCacheShape>(options)\n mergeOptions<TDefaultOptions, TOptions>(defaults, options)\n-type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\n+type _Test_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables>;\n class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\n const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\n-type _Test_QueryOptions = QueryOptions<TVariables, TData>;\n-type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\n-type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\n-type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\n+type _Test_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\n+type _Test_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\n+type _Test_MutationOptions = ApolloClient.MutateOptions<TData, TVariables, TContext, TCache>;\n+type _Test_SubscriptionOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\n type _Test_FetchPolicy = FetchPolicy;\n type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\n type _Test_MutationFetchPolicy = MutationFetchPolicy;\n type _Test_RefetchWritePolicy = RefetchWritePolicy;\n type _Test_ErrorPolicy = ErrorPolicy;\n type _Test_FetchMoreQueryOptions = FetchMoreQueryOptions<TVariables, TData>;\n-type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n+type _Test_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\n type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\n type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\n type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n@@  @@\n type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\n type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\n type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\n type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\n-type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\n+type _Test_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\n-type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\n+type _Test_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\n type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\n type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\n type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\n type _Test_PureQueryOptions = PureQueryOptions<TVariables, TData>;\n type _Test_OperationVariables = OperationVariables;\n-type _Test_ApolloQueryResult = ApolloQueryResult<T>;\n+type _Test_ApolloQueryResult = ObservableQuery.Result<T>;\n type _Test_MutationQueryReducer = MutationQueryReducer<T>;\n type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\n type _Test_MutationUpdaterFn = MutationUpdaterFn<T>;\n type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\n@@  @@\n const _Test_execute = execute;\n class _Test_ApolloLink extends ApolloLink {}\n const _test_ApolloLink = new ApolloLink(request)\n type _Test_DocumentNode = DocumentNode;\n-type _Test_Path = Path;\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n+type _Test_Path = Incremental.Path;\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n-type _Test_Operation = Operation;\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n-type _Test_NextLink = NextLink;\n-type _Test_RequestHandler = RequestHandler;\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n+type _Test_Operation = ApolloLink.Operation;\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n type _Test_ServerParseError = ServerParseError;\n parseAndCheckHttpResponse(operations)\n type _Test_ClientParseError = ClientParseError;\n const _Test_serializeFetchParameter = serializeFetchParameter;\n@@  @@\n type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\n type _Test_PreloadQueryFunction = PreloadQueryFunction;\n createQueryPreloader(client)\n useQuery<TData, TVariables>(query, options)\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n useSuspenseQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n useBackgroundQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n useSuspenseFragment<TData, TVariables>(options)\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n useLoadableQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n useQueryRefHandlers<TData, TVariables>(queryRef)\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n useReadQuery<TData>(queryRef)\n const _Test_skipToken = skipToken;\n type _Test_SkipToken = SkipToken;\n useApolloClient(override)\n@@  @@\n useMutation<TData, TVariables, TContext, TCache>(mutation, options)\n useSubscription<TData, TVariables>(subscription, options)\n useReactiveVar<T>(rv)\n useFragment<TData, TVars>(options)\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n type _Test_QueryRef = QueryRef<TData, TVariables>;\n type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\n-type _Test_Context = Context;\n+type _Test_Context = DefaultContext;\n type _Test_CommonOptions = CommonOptions<TOptions>;\n type _Test_BaseQueryOptions = BaseQueryOptions<TVariables, TData>;\n-type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\n+type _Test_QueryFunctionOptions = useQuery.Options<TData, TVariables>;\n type _Test_ObservableQueryFields = ObservableQueryFields<TData, TVariables>;\n-type _Test_QueryResult = QueryResult<TData, TVariables>;\n+type _Test_QueryResult = useQuery.Result<TData, TVariables>;\n type _Test_QueryDataOptions = QueryDataOptions<TData, TVariables>;\n-type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\n-type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\n-type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\n-type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\n-type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\n-type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\n-type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\n-type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\n-type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\n+type _Test_QueryHookOptions = useQuery.Options<TData, TVariables>;\n+type _Test_LazyQueryHookOptions = useLazyQuery.Options<TData, TVariables>;\n+type _Test_LazyQueryHookExecOptions = useLazyQuery.ExecOptions<TData, TVariables>;\n+type _Test_SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n+type _Test_SuspenseQueryHookOptions = useSuspenseQuery.Options<TVariables>;\n+type _Test_BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n+type _Test_BackgroundQueryHookOptions = useBackgroundQuery.Options<TVariables>;\n+type _Test_LoadableQueryHookFetchPolicy = useLoadableQuery.FetchPolicy;\n+type _Test_LoadableQueryHookOptions = useLoadableQuery.Options;\n type _Test_QueryLazyOptions = QueryLazyOptions<TVariables>;\n-type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\n-type _Test_QueryTuple = QueryTuple<TData, TVariables>;\n-type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\n-type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\n+type _Test_LazyQueryResult = useLazyQuery.Result<TData, TVariables>;\n+type _Test_QueryTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n+type _Test_LazyQueryExecFunction = useLazyQuery.ExecFunction<TData, TVariables>;\n+type _Test_LazyQueryResultTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n type _Test_RefetchQueriesFunction = RefetchQueriesFunction;\n type _Test_BaseMutationOptions = BaseMutationOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationResult = MutationResult<TData>;\n+type _Test_MutationFunctionOptions = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n+type _Test_MutationResult = useMutation.Result<TData>;\n type _Test_MutationFunction = MutationFunction<TData, TVariables, TContext, TCache>;\n-type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\n+type _Test_MutationHookOptions = useMutation.Options<TData, TVariables, TCache>;\n type _Test_MutationDataOptions = MutationDataOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\n-type _Test_OnDataOptions = OnDataOptions<TData>;\n-type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\n-type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\n-type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\n-type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\n+type _Test_MutationTuple = useMutation.ResultTuple<TData, TVariables, TCache>;\n+type _Test_OnDataOptions = useSubscription.OnDataOptions<TData>;\n+type _Test_OnSubscriptionDataOptions = useSubscription.OnSubscriptionDataOptions<TData>;\n+type _Test_BaseSubscriptionOptions = useSubscription.Options<TData, TVariables>;\n+type _Test_SubscriptionResult = useSubscription.Result<TData>;\n+type _Test_SubscriptionHookOptions = useSubscription.Options<TData, TVariables>;\n type _Test_SubscriptionDataOptions = SubscriptionDataOptions<TData, TVariables>;\n type _Test_SubscriptionCurrentObservable = SubscriptionCurrentObservable;\n type _Test_VariablesOption = VariablesOption<TVariables>;\n type _Test_NoInfer = NoInfer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/cache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n   Transaction,\n-  WatchFragmentOptions,\n-  WatchFragmentResult,\n   ApolloCache,\n   Cache,\n   DataProxy,\n   MissingTree,\n@@  @@\n   ReadFieldOptions,\n   MissingFieldError,\n   Reference,\n   isReference,\n-  makeReference,\n   canonicalStringify,\n   EntityStore,\n   fieldNameFromStoreName,\n   defaultDataIdFromObject,\n@@  @@\n   ApolloReducerConfig,\n   InMemoryCacheConfig,\n   MergeInfo,\n   MergeTree,\n-  ReadMergeModifyContext\n+  ReadMergeModifyContext,\n } from \"@apollo/client/cache\";\n type _Test_Transaction = Transaction<T>;\n-type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\n-type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\n+type _Test_WatchFragmentOptions = ApolloCache.WatchFragmentOptions<TData, TVars>;\n+type _Test_WatchFragmentResult = ApolloCache.WatchFragmentResult<TData>;\n class _Test_ApolloCache extends ApolloCache<TSerialized> {}\n const _test_ApolloCache = new ApolloCache<TSerialized>()\n const _Test_Cache = Cache;\n const _Test_DataProxy = DataProxy;\n\"\n`;\n\nexports[`all exports > @apollo/client/core 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  ApolloClientOptions,\n-  DefaultOptions,\n   ApolloClient,\n-  mergeOptions,\n-  FetchMoreOptions,\n   ObservableQuery,\n-  QueryOptions,\n-  WatchQueryOptions,\n-  MutationOptions,\n-  SubscriptionOptions,\n   FetchPolicy,\n   WatchQueryFetchPolicy,\n   MutationFetchPolicy,\n   RefetchWritePolicy,\n   ErrorPolicy,\n   FetchMoreQueryOptions,\n-  SubscribeToMoreOptions,\n   SubscribeToMoreFunction,\n   UpdateQueryMapFn,\n   UpdateQueryOptions,\n   SubscribeToMoreUpdateQueryFn,\n@@  @@\n   StoreObject,\n   DocumentTransform,\n   Observable,\n   isReference,\n-  makeReference,\n   setLogVerbosity,\n   gql,\n   resetCaches,\n   disableFragmentWarnings,\n@@  @@\n   RefetchQueryDescriptor,\n   InternalRefetchQueryDescriptor,\n   RefetchQueriesInclude,\n   InternalRefetchQueriesInclude,\n-  RefetchQueriesOptions,\n   RefetchQueriesPromiseResults,\n-  RefetchQueriesResult,\n   InternalRefetchQueriesOptions,\n   InternalRefetchQueriesResult,\n   InternalRefetchQueriesMap,\n   PureQueryOptions,\n   OperationVariables,\n-  ApolloQueryResult,\n   MutationQueryReducer,\n   MutationQueryReducersMap,\n   MutationUpdaterFn,\n   MutationUpdaterFunction,\n@@  @@\n   concat,\n   execute,\n   ApolloLink,\n   DocumentNode,\n-  Path,\n-  ExecutionPatchInitialResult,\n-  IncrementalPayload,\n-  ExecutionPatchIncrementalResult,\n   ApolloPayloadResult,\n-  ExecutionPatchResult,\n-  GraphQLRequest,\n-  Operation,\n-  SingleExecutionResult,\n-  FetchResult,\n-  NextLink,\n-  RequestHandler,\n   ServerParseError,\n   parseAndCheckHttpResponse,\n   ClientParseError,\n   serializeFetchParameter,\n@@  @@\n   createSignalIfSupported,\n   selectURI,\n   createHttpLink,\n   HttpLink,\n-  rewriteURIForGET\n-} from \"@apollo/client/core\";\n-type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\n-type _Test_DefaultOptions = DefaultOptions;\n+  rewriteURIForGET,\n+  Defer20220824Handler,\n+  Incremental,\n+  FormattedExecutionResult,\n+} from \"@apollo/client\";\n+type _Test_ApolloClientOptions = ApolloClient.Options<TCacheShape>;\n+type _Test_DefaultOptions = ApolloClient.DefaultOptions;\n class _Test_ApolloClient extends ApolloClient<TCacheShape> {}\n const _test_ApolloClient = new ApolloClient<TCacheShape>(options)\n mergeOptions<TDefaultOptions, TOptions>(defaults, options)\n-type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\n+type _Test_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables>;\n class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\n const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\n-type _Test_QueryOptions = QueryOptions<TVariables, TData>;\n-type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\n-type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\n-type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\n+type _Test_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\n+type _Test_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\n+type _Test_MutationOptions = ApolloClient.MutateOptions<TData, TVariables, TContext, TCache>;\n+type _Test_SubscriptionOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\n type _Test_FetchPolicy = FetchPolicy;\n type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\n type _Test_MutationFetchPolicy = MutationFetchPolicy;\n type _Test_RefetchWritePolicy = RefetchWritePolicy;\n type _Test_ErrorPolicy = ErrorPolicy;\n type _Test_FetchMoreQueryOptions = FetchMoreQueryOptions<TVariables, TData>;\n-type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n+type _Test_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\n type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\n type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\n type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n@@  @@\n type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\n type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\n type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\n type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\n-type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\n+type _Test_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\n-type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\n+type _Test_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\n type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\n type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\n type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\n type _Test_PureQueryOptions = PureQueryOptions<TVariables, TData>;\n type _Test_OperationVariables = OperationVariables;\n-type _Test_ApolloQueryResult = ApolloQueryResult<T>;\n+type _Test_ApolloQueryResult = ObservableQuery.Result<T>;\n type _Test_MutationQueryReducer = MutationQueryReducer<T>;\n type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\n type _Test_MutationUpdaterFn = MutationUpdaterFn<T>;\n type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\n@@  @@\n const _Test_execute = execute;\n class _Test_ApolloLink extends ApolloLink {}\n const _test_ApolloLink = new ApolloLink(request)\n type _Test_DocumentNode = DocumentNode;\n-type _Test_Path = Path;\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n+type _Test_Path = Incremental.Path;\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n-type _Test_Operation = Operation;\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n-type _Test_NextLink = NextLink;\n-type _Test_RequestHandler = RequestHandler;\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n+type _Test_Operation = ApolloLink.Operation;\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n type _Test_ServerParseError = ServerParseError;\n parseAndCheckHttpResponse(operations)\n type _Test_ClientParseError = ClientParseError;\n const _Test_serializeFetchParameter = serializeFetchParameter;\n\"\n`;\n\nexports[`all exports > @apollo/client/dev 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/errors 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/link/batch 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import {\n-  BatchableRequest,\n-  BatchHandler,\n-  OperationBatcher,\n-  BatchLink\n-} from \"@apollo/client/link/batch\";\n+import { BatchableRequest, OperationBatcher, BatchLink } from \"@apollo/client/link/batch\";\n type _Test_BatchableRequest = BatchableRequest;\n-type _Test_BatchHandler = BatchHandler;\n+type _Test_BatchHandler = BatchLink.BatchHandler;\n class _Test_OperationBatcher extends OperationBatcher {}\n const _test_OperationBatcher = new OperationBatcher(param0)\n class _Test_BatchLink extends BatchLink {}\n const _test_BatchLink = new BatchLink(fetchParams)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/batch-http 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/link/context 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n   setContext,\n-  ContextSetter\n+  SetContextLink\n } from \"@apollo/client/link/context\";\n setContext(setter)\n-type _Test_ContextSetter = ContextSetter;\n\\\\ No newline at end of file\n+type _Test_ContextSetter = SetContextLink.LegacyContextSetter;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/core 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n   concat,\n   execute,\n   ApolloLink,\n   DocumentNode,\n-  Path,\n-  ExecutionPatchInitialResult,\n-  IncrementalPayload,\n-  ExecutionPatchIncrementalResult,\n   ApolloPayloadResult,\n-  ExecutionPatchResult,\n-  GraphQLRequest,\n-  Operation,\n-  SingleExecutionResult,\n-  FetchResult,\n-  NextLink,\n-  RequestHandler\n-} from \"@apollo/client/link/core\";\n+} from \"@apollo/client/link\";\n+\n+import type { FormattedExecutionResult } from \"graphql\";\n+import type { Defer20220824Handler, Incremental } from \"@apollo/client/incremental\";\n const _Test_empty = empty;\n const _Test_from = from;\n const _Test_split = split;\n const _Test_concat = concat;\n const _Test_execute = execute;\n class _Test_ApolloLink extends ApolloLink {}\n const _test_ApolloLink = new ApolloLink(request)\n type _Test_DocumentNode = DocumentNode;\n-type _Test_Path = Path;\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n+type _Test_Path = Incremental.Path;\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n-type _Test_Operation = Operation;\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n-type _Test_NextLink = NextLink;\n-type _Test_RequestHandler = RequestHandler;\n\\\\ No newline at end of file\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n+type _Test_Operation = ApolloLink.Operation;\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/error 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import {\n-  onError,\n-  ErrorResponse,\n-  ErrorLink,\n-  ErrorHandler\n-} from \"@apollo/client/link/error\";\n+import { onError, ErrorLink } from \"@apollo/client/link/error\";\n onError(errorHandler)\n-type _Test_ErrorResponse = ErrorResponse;\n+type _Test_ErrorResponse = ErrorLink.ErrorHandlerOptions;\n class _Test_ErrorLink extends ErrorLink {}\n const _test_ErrorLink = new ErrorLink(errorHandler)\n-type _Test_ErrorHandler = ErrorHandler;\n\\\\ No newline at end of file\n+type _Test_ErrorHandler = ErrorLink.ErrorHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/http 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  ServerParseError,\n   parseAndCheckHttpResponse,\n   ClientParseError,\n   serializeFetchParameter,\n   HttpOptions,\n@@  @@\n   createSignalIfSupported,\n   selectURI,\n   createHttpLink,\n   HttpLink,\n-  rewriteURIForGET\n+  rewriteURIForGET,\n } from \"@apollo/client/link/http\";\n+import type { ServerParseError } from \"@apollo/client/errors\";\n type _Test_ServerParseError = ServerParseError;\n parseAndCheckHttpResponse(operations)\n type _Test_ClientParseError = ClientParseError;\n const _Test_serializeFetchParameter = serializeFetchParameter;\n\"\n`;\n\nexports[`all exports > @apollo/client/link/persisted-queries 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import {\n-  VERSION,\n-  ErrorResponse,\n-  PersistedQueryLink,\n-  createPersistedQueryLink\n-} from \"@apollo/client/link/persisted-queries\";\n+import { VERSION, PersistedQueryLink, createPersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\n const _Test_VERSION = VERSION;\n-type _Test_ErrorResponse = ErrorResponse;\n+type _Test_ErrorResponse = PersistedQueryLink.DisableFunctionOptions;\n const _Test_PersistedQueryLink = PersistedQueryLink;\n const _Test_createPersistedQueryLink = createPersistedQueryLink;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/remove-typename 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  RemoveTypenameFromVariablesOptions,\n   removeTypenameFromVariables,\n-  KEEP\n+  KEEP,\n+  RemoveTypenameFromVariablesLink\n } from \"@apollo/client/link/remove-typename\";\n-type _Test_RemoveTypenameFromVariablesOptions = RemoveTypenameFromVariablesOptions;\n+type _Test_RemoveTypenameFromVariablesOptions = RemoveTypenameFromVariablesLink.Options;\n removeTypenameFromVariables(options)\n const _Test_KEEP = KEEP;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/link/retry 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/link/schema 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/link/subscriptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/link/utils 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n   fromError,\n   toPromise,\n   fromPromise,\n-  ServerError,\n   throwServerError,\n   validateOperation,\n   createOperation,\n   transformOperation,\n-  filterOperationVariables\n+  filterOperationVariables,\n } from \"@apollo/client/link/utils\";\n+import type { ServerError } from \"@apollo/client/errors\";\n fromError<T>(errorValue)\n toPromise<R>(observable)\n fromPromise<T>(promise)\n type _Test_ServerError = ServerError;\n\"\n`;\n\nexports[`all exports > @apollo/client/link/ws 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import {\n-  WebSocketLink,\n-  WebSocketParams\n-} from \"@apollo/client/link/ws\";\n+import { WebSocketLink } from \"@apollo/client/link/ws\";\n class _Test_WebSocketLink extends WebSocketLink {}\n const _test_WebSocketLink = new WebSocketLink(paramsOrClient)\n-type _Test_WebSocketParams = WebSocketParams;\n\\\\ No newline at end of file\n+type _Test_WebSocketParams = WebSocketLink.Configuration;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/masking 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/react 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n   PreloadQueryFetchPolicy,\n   PreloadQueryFunction,\n   createQueryPreloader,\n   useQuery,\n-  UseSuspenseQueryResult,\n   useSuspenseQuery,\n-  UseBackgroundQueryResult,\n   useBackgroundQuery,\n-  UseSuspenseFragmentResult,\n-  UseSuspenseFragmentOptions,\n   useSuspenseFragment,\n-  LoadQueryFunction,\n-  UseLoadableQueryResult,\n   useLoadableQuery,\n-  UseQueryRefHandlersResult,\n   useQueryRefHandlers,\n-  UseReadQueryResult,\n   useReadQuery,\n   skipToken,\n   SkipToken,\n   useApolloClient,\n@@  @@\n   useMutation,\n   useSubscription,\n   useReactiveVar,\n   useFragment,\n-  UseFragmentOptions,\n-  UseFragmentResult,\n-  QueryReference,\n   QueryRef,\n   PreloadedQueryRef,\n-  Context,\n   CommonOptions,\n   BaseQueryOptions,\n-  QueryFunctionOptions,\n   ObservableQueryFields,\n-  QueryResult,\n   QueryDataOptions,\n-  QueryHookOptions,\n-  LazyQueryHookOptions,\n-  LazyQueryHookExecOptions,\n-  SuspenseQueryHookFetchPolicy,\n-  SuspenseQueryHookOptions,\n-  BackgroundQueryHookFetchPolicy,\n-  BackgroundQueryHookOptions,\n-  LoadableQueryHookFetchPolicy,\n-  LoadableQueryHookOptions,\n   QueryLazyOptions,\n-  LazyQueryResult,\n-  QueryTuple,\n-  LazyQueryExecFunction,\n-  LazyQueryResultTuple,\n   RefetchQueriesFunction,\n   BaseMutationOptions,\n-  MutationFunctionOptions,\n-  MutationResult,\n   MutationFunction,\n-  MutationHookOptions,\n   MutationDataOptions,\n-  MutationTuple,\n-  OnDataOptions,\n-  OnSubscriptionDataOptions,\n-  BaseSubscriptionOptions,\n-  SubscriptionResult,\n-  SubscriptionHookOptions,\n   SubscriptionDataOptions,\n   SubscriptionCurrentObservable,\n-  VariablesOption,\n-  NoInfer\n } from \"@apollo/client/react\";\n+import type { DefaultContext } from \"@apollo/client\";\n+import type { NoInfer, VariablesOption } from \"@apollo/client/utilities/internal\";\n type _Test_ApolloContextValue = ApolloContextValue;\n const _Test_ApolloProvider = ApolloProvider;\n const _Test_ApolloConsumer = ApolloConsumer;\n getApolloContext()\n@@  @@\n type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\n type _Test_PreloadQueryFunction = PreloadQueryFunction;\n createQueryPreloader(client)\n useQuery<TData, TVariables>(query, options)\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n useSuspenseQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n useBackgroundQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n useSuspenseFragment<TData, TVariables>(options)\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n useLoadableQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n useQueryRefHandlers<TData, TVariables>(queryRef)\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n useReadQuery<TData>(queryRef)\n const _Test_skipToken = skipToken;\n type _Test_SkipToken = SkipToken;\n useApolloClient(override)\n@@  @@\n useMutation<TData, TVariables, TContext, TCache>(mutation, options)\n useSubscription<TData, TVariables>(subscription, options)\n useReactiveVar<T>(rv)\n useFragment<TData, TVars>(options)\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n type _Test_QueryRef = QueryRef<TData, TVariables>;\n type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\n-type _Test_Context = Context;\n+type _Test_Context = DefaultContext;\n type _Test_CommonOptions = CommonOptions<TOptions>;\n type _Test_BaseQueryOptions = BaseQueryOptions<TVariables, TData>;\n-type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\n+type _Test_QueryFunctionOptions = useQuery.Options<TData, TVariables>;\n type _Test_ObservableQueryFields = ObservableQueryFields<TData, TVariables>;\n-type _Test_QueryResult = QueryResult<TData, TVariables>;\n+type _Test_QueryResult = useQuery.Result<TData, TVariables>;\n type _Test_QueryDataOptions = QueryDataOptions<TData, TVariables>;\n-type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\n-type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\n-type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\n-type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\n-type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\n-type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\n-type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\n-type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\n-type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\n+type _Test_QueryHookOptions = useQuery.Options<TData, TVariables>;\n+type _Test_LazyQueryHookOptions = useLazyQuery.Options<TData, TVariables>;\n+type _Test_LazyQueryHookExecOptions = useLazyQuery.ExecOptions<TData, TVariables>;\n+type _Test_SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n+type _Test_SuspenseQueryHookOptions = useSuspenseQuery.Options<TVariables>;\n+type _Test_BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n+type _Test_BackgroundQueryHookOptions = useBackgroundQuery.Options<TVariables>;\n+type _Test_LoadableQueryHookFetchPolicy = useLoadableQuery.FetchPolicy;\n+type _Test_LoadableQueryHookOptions = useLoadableQuery.Options;\n type _Test_QueryLazyOptions = QueryLazyOptions<TVariables>;\n-type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\n-type _Test_QueryTuple = QueryTuple<TData, TVariables>;\n-type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\n-type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\n+type _Test_LazyQueryResult = useLazyQuery.Result<TData, TVariables>;\n+type _Test_QueryTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n+type _Test_LazyQueryExecFunction = useLazyQuery.ExecFunction<TData, TVariables>;\n+type _Test_LazyQueryResultTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n type _Test_RefetchQueriesFunction = RefetchQueriesFunction;\n type _Test_BaseMutationOptions = BaseMutationOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationResult = MutationResult<TData>;\n+type _Test_MutationFunctionOptions = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n+type _Test_MutationResult = useMutation.Result<TData>;\n type _Test_MutationFunction = MutationFunction<TData, TVariables, TContext, TCache>;\n-type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\n+type _Test_MutationHookOptions = useMutation.Options<TData, TVariables, TCache>;\n type _Test_MutationDataOptions = MutationDataOptions<TData, TVariables, TContext, TCache>;\n-type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\n-type _Test_OnDataOptions = OnDataOptions<TData>;\n-type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\n-type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\n-type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\n-type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\n+type _Test_MutationTuple = useMutation.ResultTuple<TData, TVariables, TCache>;\n+type _Test_OnDataOptions = useSubscription.OnDataOptions<TData>;\n+type _Test_OnSubscriptionDataOptions = useSubscription.OnSubscriptionDataOptions<TData>;\n+type _Test_BaseSubscriptionOptions = useSubscription.Options<TData, TVariables>;\n+type _Test_SubscriptionResult = useSubscription.Result<TData>;\n+type _Test_SubscriptionHookOptions = useSubscription.Options<TData, TVariables>;\n type _Test_SubscriptionDataOptions = SubscriptionDataOptions<TData, TVariables>;\n type _Test_SubscriptionCurrentObservable = SubscriptionCurrentObservable;\n type _Test_VariablesOption = VariablesOption<TVariables>;\n type _Test_NoInfer = NoInfer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/react/components 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/react/context 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n   ApolloConsumer,\n   ApolloContextValue,\n   getApolloContext,\n   resetApolloContext,\n-  ApolloProviderProps,\n-  ApolloProvider\n-} from \"@apollo/client/react/context\";\n+  ApolloProvider,\n+} from \"@apollo/client/react\";\n type _Test_ApolloConsumerProps = ApolloConsumerProps;\n const _Test_ApolloConsumer = ApolloConsumer;\n type _Test_ApolloContextValue = ApolloContextValue;\n getApolloContext()\n const _Test_resetApolloContext = resetApolloContext;\n-type _Test_ApolloProviderProps = ApolloProviderProps<TCache>;\n+type _Test_ApolloProviderProps = ApolloProvider.Props<TCache>;\n const _Test_ApolloProvider = ApolloProvider;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/react/hoc 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/react/hooks 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n   useQuery,\n-  UseSuspenseQueryResult,\n   useSuspenseQuery,\n-  UseBackgroundQueryResult,\n   useBackgroundQuery,\n-  UseSuspenseFragmentResult,\n-  UseSuspenseFragmentOptions,\n   useSuspenseFragment,\n-  LoadQueryFunction,\n-  UseLoadableQueryResult,\n   useLoadableQuery,\n-  UseQueryRefHandlersResult,\n   useQueryRefHandlers,\n-  UseReadQueryResult,\n   useReadQuery,\n   skipToken,\n   SkipToken,\n   useApolloClient,\n@@  @@\n   useMutation,\n   useSubscription,\n   useReactiveVar,\n   useFragment,\n-  UseFragmentOptions,\n-  UseFragmentResult\n-} from \"@apollo/client/react/hooks\";\n+} from \"@apollo/client/react\";\n useQuery<TData, TVariables>(query, options)\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n useSuspenseQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n useBackgroundQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n useSuspenseFragment<TData, TVariables>(options)\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n useLoadableQuery<TData, TVariables, TOptions>(query, options)\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n useQueryRefHandlers<TData, TVariables>(queryRef)\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n useReadQuery<TData>(queryRef)\n const _Test_skipToken = skipToken;\n type _Test_SkipToken = SkipToken;\n useApolloClient(override)\n@@  @@\n useMutation<TData, TVariables, TContext, TCache>(mutation, options)\n useSubscription<TData, TVariables>(subscription, options)\n useReactiveVar<T>(rv)\n useFragment<TData, TVars>(options)\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n\\\\ No newline at end of file\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`all exports > @apollo/client/react/internal 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n   getSuspenseCache,\n   CacheKey,\n   QueryKey,\n-  QueryReference,\n-  QueryRef,\n-  PreloadedQueryRef,\n   InternalQueryReference,\n   getWrappedPromise,\n   unwrapQueryRef,\n   updateWrappedQueryRef,\n   wrapQueryRef,\n   assertWrappedQueryRef,\n   SuspenseCacheOptions,\n-  HookWrappers\n+  HookWrappers,\n } from \"@apollo/client/react/internal\";\n+import type { QueryRef, PreloadedQueryRef, QueryRef } from \"@apollo/client/react\";\n getSuspenseCache(client)\n type _Test_CacheKey = CacheKey;\n type _Test_QueryKey = QueryKey;\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n type _Test_QueryRef = QueryRef<TData, TVariables>;\n type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\n class _Test_InternalQueryReference extends InternalQueryReference<TData> {}\n const _test_InternalQueryReference = new InternalQueryReference<TData>(observable, options)\n\"\n`;\n\nexports[`all exports > @apollo/client/react/parser 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/react/ssr 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/testing 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  MockedProviderProps,\n-  MockedProvider,\n-  MockedResponse,\n-  MockLinkOptions,\n-  ResultFunction,\n   MockLink,\n   mockSingleLink,\n   MockSubscriptionLink,\n   mockObservableLink,\n@@  @@\n   wait,\n   tick,\n   withErrorSpy,\n   withWarningSpy,\n-  withLogSpy\n+  withLogSpy,\n } from \"@apollo/client/testing\";\n+import { MockedProvider, MockedProviderProps } from \"@apollo/client/testing/react\";\n type _Test_MockedProviderProps = MockedProviderProps<TSerializedCache>;\n class _Test_MockedProvider extends MockedProvider {}\n const _test_MockedProvider = new MockedProvider(props)\n-type _Test_MockedResponse = MockedResponse<TData, TVariables>;\n-type _Test_MockLinkOptions = MockLinkOptions;\n-type _Test_ResultFunction = ResultFunction<T, V>;\n+type _Test_MockedResponse = MockLink.MockedResponse<TData, TVariables>;\n+type _Test_MockLinkOptions = MockLink.Options;\n+type _Test_ResultFunction = MockLink.ResultFunction<T, V>;\n class _Test_MockLink extends MockLink {}\n const _test_MockLink = new MockLink(mockedResponses, addTypename, options)\n mockSingleLink(mockedResponses)\n class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\n\"\n`;\n\nexports[`all exports > @apollo/client/testing/core 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  MockedResponse,\n-  MockLinkOptions,\n-  ResultFunction,\n   MockLink,\n   mockSingleLink,\n   MockSubscriptionLink,\n   mockObservableLink,\n@@  @@\n   wait,\n   tick,\n   withErrorSpy,\n   withWarningSpy,\n-  withLogSpy\n-} from \"@apollo/client/testing/core\";\n-type _Test_MockedResponse = MockedResponse<TData, TVariables>;\n-type _Test_MockLinkOptions = MockLinkOptions;\n-type _Test_ResultFunction = ResultFunction<T, V>;\n+  withLogSpy,\n+} from \"@apollo/client/testing\";\n+type _Test_MockedResponse = MockLink.MockedResponse<TData, TVariables>;\n+type _Test_MockLinkOptions = MockLink.Options;\n+type _Test_ResultFunction = MockLink.ResultFunction<T, V>;\n class _Test_MockLink extends MockLink {}\n const _test_MockLink = new MockLink(mockedResponses, addTypename, options)\n mockSingleLink(mockedResponses)\n class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\n\"\n`;\n\nexports[`all exports > @apollo/client/testing/experimental 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/utilities 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n import {\n-  DEV,\n-  maybe,\n   DirectiveInfo,\n   InclusionDirectives,\n-  shouldInclude,\n-  hasDirectives,\n   hasAnyDirectives,\n   hasAllDirectives,\n   hasClientExports,\n   getDirectiveNames,\n   getInclusionDirectives,\n   getFragmentMaskMode,\n   DocumentTransformCacheKey,\n   DocumentTransform,\n-  FragmentMap,\n-  FragmentMapFunction,\n-  createFragmentMap,\n-  getFragmentQueryDocument,\n-  getFragmentFromSelection,\n   isFullyUnmaskedOperation,\n-  checkDocument,\n-  getOperationDefinition,\n-  getOperationName,\n-  getFragmentDefinitions,\n-  getQueryDefinition,\n-  getFragmentDefinition,\n   getMainDefinition,\n-  getDefaultValues,\n   print,\n   StoreObject,\n   AsStoreObject,\n   Reference,\n   StoreValue,\n   Directives,\n   VariableValue,\n-  makeReference,\n-  isDocumentNode,\n   isReference,\n-  isField,\n   isInlineFragment,\n   valueToObjectRepresentation,\n-  storeKeyNameFromField,\n-  argumentsObjectFromField,\n-  resultKeyNameFromField,\n-  getStoreKeyName,\n   getTypenameFromResult,\n   RemoveNodeConfig,\n   GetNodeConfig,\n   RemoveDirectiveConfig,\n@@  @@\n   RemoveVariableDefinitionConfig,\n   addTypenameToDocument,\n   addNonReactiveToNamedFragments,\n   buildQueryFromSelectionSet,\n-  removeDirectivesFromDocument,\n   removeConnectionDirectiveFromDocument,\n   removeArgumentsFromDocument,\n   removeFragmentSpreadFromDocument,\n   removeClientSetsFromDocument,\n@@  @@\n   ObservableSubscription,\n   Observable,\n   PromiseWithState,\n   isStatefulPromise,\n-  createFulfilledPromise,\n-  createRejectedPromise,\n   wrapPromiseWithState,\n-  preventUnhandledRejection,\n-  maybeDeepFreeze,\n   canonicalStringify,\n-  omitDeep,\n   stripTypename,\n-  DeepOmit,\n   DeepPartial,\n   OnlyRequiredProperties,\n-  Prettify,\n-  Primitive,\n   UnionToIntersection,\n-  NoInfer,\n-  RemoveIndexSignature,\n-  AutoCleanedStrongCache,\n-  AutoCleanedWeakCache,\n   cacheSizes,\n   defaultCacheSizes,\n   CacheSizes,\n-  mergeDeep,\n-  mergeDeepArray,\n   TupleToIntersection,\n   ReconcilerFunction,\n-  DeepMerger,\n-  cloneDeep,\n   iterateObserversSafely,\n   asyncMap,\n   ConcastSourcesIterable,\n   ConcastSourcesArray,\n   Concast,\n   fixObservableSubclass,\n-  isNonEmptyArray,\n-  isArray,\n-  isNonNullObject,\n-  isPlainObject,\n-  graphQLResultHasError,\n-  getGraphQLErrorsFromResult,\n   canUseWeakMap,\n   canUseWeakSet,\n   canUseSymbol,\n   canUseAsyncIteratorSymbol,\n-  canUseDOM,\n   canUseLayoutEffect,\n-  compact,\n-  makeUniqueId,\n-  stringifyForDisplay,\n-  mergeOptions,\n   isExecutionPatchIncrementalResult,\n   isExecutionPatchInitialResult,\n   isExecutionPatchResult,\n   isApolloPayloadResult,\n   mergeIncrementalData,\n-  IsStrictlyAny\n+  IsStrictlyAny,\n } from \"@apollo/client/utilities\";\n-const _Test_DEV = DEV;\n+\n+import {\n+  argumentsObjectFromField,\n+  AutoCleanedStrongCache,\n+  AutoCleanedWeakCache,\n+  canUseDOM,\n+  checkDocument,\n+  cloneDeep,\n+  compact,\n+  createFragmentMap,\n+  createFulfilledPromise,\n+  createRejectedPromise,\n+  DeepMerger,\n+  getDefaultValues,\n+  getFragmentDefinition,\n+  getFragmentDefinitions,\n+  getFragmentFromSelection,\n+  getFragmentQueryDocument,\n+  getGraphQLErrorsFromResult,\n+  getOperationDefinition,\n+  getOperationName,\n+  getQueryDefinition,\n+  getStoreKeyName,\n+  graphQLResultHasError,\n+  hasDirectives,\n+  isArray,\n+  isDocumentNode,\n+  isField,\n+  isNonEmptyArray,\n+  isNonNullObject,\n+  isPlainObject,\n+  makeReference,\n+  makeUniqueId,\n+  maybeDeepFreeze,\n+  mergeDeep,\n+  mergeDeepArray,\n+  mergeOptions,\n+  omitDeep,\n+  preventUnhandledRejection,\n+  removeDirectivesFromDocument,\n+  resultKeyNameFromField,\n+  shouldInclude,\n+  storeKeyNameFromField,\n+  stringifyForDisplay,\n+  DeepOmit,\n+  FragmentMap,\n+  FragmentMapFunction,\n+  NoInfer,\n+  Prettify,\n+  Primitive,\n+  RemoveIndexSignature,\n+} from \"@apollo/client/utilities/internal\";\n+\n+const _Test_DEV = __DEV__;\n maybe<T>(thunk)\n type _Test_DirectiveInfo = DirectiveInfo;\n type _Test_InclusionDirectives = InclusionDirectives;\n shouldInclude(param0, variables)\n\"\n`;\n\nexports[`all exports > @apollo/client/utilities/globals 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`all exports > @apollo/client/utilities/subscriptions/relay 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloClientOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloClientOptions } from \"@apollo/client\";\n-type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_ApolloClientOptions = ApolloClient.Options<TCacheShape>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloConsumer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloContextValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloContextValue } from \"@apollo/client\";\n+import type { ApolloContextValue } from \"@apollo/client/react\";\n type _Test_ApolloContextValue = ApolloContextValue;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloPayloadResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloProvider 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloProvider } from \"@apollo/client\";\n+import { ApolloProvider } from \"@apollo/client/react\";\n const _Test_ApolloProvider = ApolloProvider;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloQueryResult } from \"@apollo/client\";\n-type _Test_ApolloQueryResult = ApolloQueryResult<T>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_ApolloQueryResult = ObservableQuery.Result<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ApolloReducerConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > BackgroundQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BackgroundQueryHookFetchPolicy } from \"@apollo/client\";\n-type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import type { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > BackgroundQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BackgroundQueryHookOptions } from \"@apollo/client\";\n-type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_BackgroundQueryHookOptions = useBackgroundQuery.Options<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > BaseMutationOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > BaseQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > BaseSubscriptionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BaseSubscriptionOptions } from \"@apollo/client\";\n-type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSubscription } from \"@apollo/client/react\";\n+type _Test_BaseSubscriptionOptions = useSubscription.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > Cache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ClientParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > CommonOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Context 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Context } from \"@apollo/client\";\n-type _Test_Context = Context;\n\\\\ No newline at end of file\n+import type { DefaultContext } from \"@apollo/client\";\n+type _Test_Context = DefaultContext;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > DataMasking 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DataProxy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DefaultContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DefaultOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DefaultOptions } from \"@apollo/client\";\n-type _Test_DefaultOptions = DefaultOptions;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_DefaultOptions = ApolloClient.DefaultOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > DiffQueryAgainstStoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DocumentTransform 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DocumentTransformCacheKey 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > DocumentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ErrorPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ExecutionPatchIncrementalResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchIncrementalResult } from \"@apollo/client\";\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ExecutionPatchInitialResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchInitialResult } from \"@apollo/client\";\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ExecutionPatchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchResult } from \"@apollo/client\";\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > FetchMoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchMoreOptions } from \"@apollo/client\";\n-type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > FetchMoreQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FetchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchResult } from \"@apollo/client\";\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > FieldFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FieldMergeFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FieldPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FieldReadFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FragmentMatcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > FragmentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > GraphQLRequest 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { GraphQLRequest } from \"@apollo/client\";\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > HttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > HttpOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > IDocumentDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > IdGetter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > IdGetterObj 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InMemoryCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InMemoryCacheConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > IncrementalPayload 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { IncrementalPayload } from \"@apollo/client\";\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > InternalRefetchQueriesInclude 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InternalRefetchQueriesMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InternalRefetchQueriesOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InternalRefetchQueriesResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > InternalRefetchQueryDescriptor 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > LazyQueryExecFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryExecFunction } from \"@apollo/client\";\n-type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryExecFunction = useLazyQuery.ExecFunction<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LazyQueryHookExecOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryHookExecOptions } from \"@apollo/client\";\n-type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryHookExecOptions = useLazyQuery.ExecOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LazyQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryHookOptions } from \"@apollo/client\";\n-type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryHookOptions = useLazyQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LazyQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryResult } from \"@apollo/client\";\n-type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryResult = useLazyQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LazyQueryResultTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryResultTuple } from \"@apollo/client\";\n-type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryResultTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LoadQueryFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadQueryFunction } from \"@apollo/client\";\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n+import type { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LoadableQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadableQueryHookFetchPolicy } from \"@apollo/client\";\n-type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import type { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadableQueryHookFetchPolicy = useLoadableQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > LoadableQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadableQueryHookOptions } from \"@apollo/client\";\n-type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\n\\\\ No newline at end of file\n+import type { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadableQueryHookOptions = useLoadableQuery.Options;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > Masked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MaskedDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MaybeMasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MergeInfo 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MergeTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MethodKeys 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MissingFieldError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationFunction } from \"@apollo/client\";\n+import type { MutationFunction } from \"@apollo/client/react\";\n type _Test_MutationFunction = MutationFunction<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationFunctionOptions } from \"@apollo/client\";\n-type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import type { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationFunctionOptions = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationHookOptions } from \"@apollo/client\";\n-type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import type { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationHookOptions = useMutation.Options<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationOptions } from \"@apollo/client\";\n-type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_MutationOptions = ApolloClient.MutateOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationQueryReducer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationQueryReducersMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationResult } from \"@apollo/client\";\n-type _Test_MutationResult = MutationResult<TData>;\n\\\\ No newline at end of file\n+import type { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationResult = useMutation.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationTuple } from \"@apollo/client\";\n-type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import type { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationTuple = useMutation.ResultTuple<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationUpdaterFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > MutationUpdaterFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > NetworkStatus 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > NextLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NextLink } from \"@apollo/client\";\n-type _Test_NextLink = NextLink;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > NoInfer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NoInfer } from \"@apollo/client\";\n+import type { NoInfer } from \"@apollo/client/utilities/internal\";\n type _Test_NoInfer = NoInfer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > NormalizedCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > NormalizedCacheObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Observable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ObservableQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ObservableQueryFields 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ObservableSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Observer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > OnDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OnDataOptions } from \"@apollo/client\";\n-type _Test_OnDataOptions = OnDataOptions<TData>;\n\\\\ No newline at end of file\n+import type { useSubscription } from \"@apollo/client/react\";\n+type _Test_OnDataOptions = useSubscription.OnDataOptions<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > OnQueryUpdated 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > OnSubscriptionDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OnSubscriptionDataOptions } from \"@apollo/client\";\n-type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\n\\\\ No newline at end of file\n+import type { useSubscription } from \"@apollo/client/react\";\n+type _Test_OnSubscriptionDataOptions = useSubscription.OnSubscriptionDataOptions<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > Operation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Operation } from \"@apollo/client\";\n-type _Test_Operation = Operation;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_Operation = ApolloLink.Operation;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > OperationVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > OptimisticStoreItem 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Path 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Path } from \"@apollo/client\";\n-type _Test_Path = Path;\n\\\\ No newline at end of file\n+import { Incremental } from \"@apollo/client\";\n+type _Test_Path = Incremental.Path;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > PossibleTypesMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > PreloadQueryFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PreloadQueryFetchPolicy } from \"@apollo/client\";\n+import type { PreloadQueryFetchPolicy } from \"@apollo/client/react\";\n type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > PreloadQueryFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PreloadQueryFunction } from \"@apollo/client\";\n+import type { PreloadQueryFunction } from \"@apollo/client/react\";\n type _Test_PreloadQueryFunction = PreloadQueryFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > PreloadQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PreloadQueryOptions } from \"@apollo/client\";\n+import type { PreloadQueryOptions } from \"@apollo/client/react\";\n type _Test_PreloadQueryOptions = PreloadQueryOptions<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > PreloadedQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PreloadedQueryRef } from \"@apollo/client\";\n+import type { PreloadedQueryRef } from \"@apollo/client/react\";\n type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > PureQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryFunctionOptions } from \"@apollo/client\";\n-type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryFunctionOptions = useQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryHookOptions } from \"@apollo/client\";\n-type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryHookOptions = useQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryLazyOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryOptions } from \"@apollo/client\";\n-type _Test_QueryOptions = QueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryRef } from \"@apollo/client\";\n+import type { QueryRef } from \"@apollo/client/react\";\n type _Test_QueryRef = QueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryReference } from \"@apollo/client\";\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { QueryRef } from \"@apollo/client/react\";\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryResult } from \"@apollo/client\";\n-type _Test_QueryResult = QueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryResult = useQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > QueryTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryTuple } from \"@apollo/client\";\n-type _Test_QueryTuple = QueryTuple<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_QueryTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > ReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ReadMergeModifyContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ReadQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Reference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueriesFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueriesInclude 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueriesOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesOptions } from \"@apollo/client\";\n-type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueriesPromiseResults 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueriesResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesResult } from \"@apollo/client\";\n-type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchQueryDescriptor 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RefetchWritePolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > RequestHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RequestHandler } from \"@apollo/client\";\n-type _Test_RequestHandler = RequestHandler;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > Resolver 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Resolvers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > ServerParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > SingleExecutionResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SingleExecutionResult } from \"@apollo/client\";\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import { FormattedExecutionResult } from \"@apollo/client\";\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SkipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SkipToken } from \"@apollo/client\";\n+import type { SkipToken } from \"@apollo/client/react\";\n type _Test_SkipToken = SkipToken;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > StoreObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > StoreValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscribeToMoreFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscribeToMoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscribeToMoreOptions } from \"@apollo/client\";\n-type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscribeToMoreUpdateQueryFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscriptionCurrentObservable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscriptionDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionDataOptions } from \"@apollo/client\";\n+import type { SubscriptionDataOptions } from \"@apollo/client/react\";\n type _Test_SubscriptionDataOptions = SubscriptionDataOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscriptionHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionHookOptions } from \"@apollo/client\";\n-type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSubscription } from \"@apollo/client/react\";\n+type _Test_SubscriptionHookOptions = useSubscription.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscriptionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionOptions } from \"@apollo/client\";\n-type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_SubscriptionOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SubscriptionResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionResult } from \"@apollo/client\";\n-type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSubscription } from \"@apollo/client/react\";\n+type _Test_SubscriptionResult = useSubscription.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SuspenseQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SuspenseQueryHookFetchPolicy } from \"@apollo/client\";\n-type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import type { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > SuspenseQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SuspenseQueryHookOptions } from \"@apollo/client\";\n-type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_SuspenseQueryHookOptions = useSuspenseQuery.Options<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > Transaction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > TypePolicies 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > TypePolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > TypedDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > Unmasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > UpdateQueryMapFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > UpdateQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > UriFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseBackgroundQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseBackgroundQueryResult } from \"@apollo/client\";\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentOptions } from \"@apollo/client\";\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n+import type { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentResult } from \"@apollo/client\";\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import type { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseLoadableQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseLoadableQueryResult } from \"@apollo/client\";\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseQueryRefHandlersResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseQueryRefHandlersResult } from \"@apollo/client\";\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useQueryRefHandlers } from \"@apollo/client/react\";\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseReadQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseReadQueryResult } from \"@apollo/client\";\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n\\\\ No newline at end of file\n+import type { useReadQuery } from \"@apollo/client/react\";\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseSuspenseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentOptions } from \"@apollo/client\";\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseSuspenseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentResult } from \"@apollo/client\";\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import type { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > UseSuspenseQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseQueryResult } from \"@apollo/client\";\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > VariablesOption 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { VariablesOption } from \"@apollo/client\";\n+import type { VariablesOption } from \"@apollo/client/utilities/internal\";\n type _Test_VariablesOption = VariablesOption<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > WatchFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > WatchFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > WatchQueryFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > WatchQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchQueryOptions } from \"@apollo/client\";\n-type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > checkFetcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > concat 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > createHttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > createQueryPreloader 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createQueryPreloader } from \"@apollo/client\";\n+import { createQueryPreloader } from \"@apollo/client/react\";\n createQueryPreloader(client)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > createSignalIfSupported 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > defaultDataIdFromObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > defaultPrinter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > disableExperimentalFragmentVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > disableFragmentWarnings 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > empty 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > enableExperimentalFragmentVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > execute 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > fallbackHttpConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > from 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > fromError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > fromPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > getApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getApolloContext } from \"@apollo/client\";\n+import { getApolloContext } from \"@apollo/client/react\";\n getApolloContext()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > gql 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > isApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > isNetworkRequestSettled 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > isReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > makeReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeReference } from \"@apollo/client\";\n makeReference(id)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > makeVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > mergeOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mergeOptions } from \"@apollo/client\";\n mergeOptions<TDefaultOptions, TOptions>(defaults, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > operationName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > parseAndCheckHttpResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > parser 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > resetApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > resetCaches 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > rewriteURIForGET 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > selectHttpOptionsAndBody 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > selectHttpOptionsAndBodyInternal 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > selectURI 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > serializeFetchParameter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > setLogVerbosity 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > skipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { skipToken } from \"@apollo/client\";\n+import { skipToken } from \"@apollo/client/react\";\n const _Test_skipToken = skipToken;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > split 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > throwServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > toPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client > useApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useApolloClient } from \"@apollo/client\";\n+import { useApolloClient } from \"@apollo/client/react\";\n useApolloClient(override)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useBackgroundQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useBackgroundQuery } from \"@apollo/client\";\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n useBackgroundQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useFragment } from \"@apollo/client\";\n+import { useFragment } from \"@apollo/client/react\";\n useFragment<TData, TVars>(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useLazyQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useLazyQuery } from \"@apollo/client\";\n+import { useLazyQuery } from \"@apollo/client/react\";\n useLazyQuery<TData, TVariables>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useLoadableQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useLoadableQuery } from \"@apollo/client\";\n+import { useLoadableQuery } from \"@apollo/client/react\";\n useLoadableQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useMutation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useMutation } from \"@apollo/client\";\n+import { useMutation } from \"@apollo/client/react\";\n useMutation<TData, TVariables, TContext, TCache>(mutation, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useQuery } from \"@apollo/client\";\n+import { useQuery } from \"@apollo/client/react\";\n useQuery<TData, TVariables>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useQueryRefHandlers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useQueryRefHandlers } from \"@apollo/client\";\n+import { useQueryRefHandlers } from \"@apollo/client/react\";\n useQueryRefHandlers<TData, TVariables>(queryRef)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useReactiveVar } from \"@apollo/client\";\n+import { useReactiveVar } from \"@apollo/client/react\";\n useReactiveVar<T>(rv)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useReadQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useReadQuery } from \"@apollo/client\";\n+import { useReadQuery } from \"@apollo/client/react\";\n useReadQuery<TData>(queryRef)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSubscription } from \"@apollo/client\";\n+import { useSubscription } from \"@apollo/client/react\";\n useSubscription<TData, TVariables>(subscription, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useSuspenseFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSuspenseFragment } from \"@apollo/client\";\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n useSuspenseFragment<TData, TVariables>(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client > useSuspenseQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSuspenseQuery } from \"@apollo/client\";\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n useSuspenseQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ApolloCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ApolloReducerConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Cache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > DataProxy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > DiffQueryAgainstStoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > EntityStore 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > FieldFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > FieldMergeFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > FieldPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > FieldReadFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > FragmentRegistryAPI 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > IdGetter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > IdGetterObj 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > InMemoryCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > InMemoryCacheConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > MergeInfo 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > MergeTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > MissingFieldError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > MissingTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Modifier 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ModifierDetails 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Modifiers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > NormalizedCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > NormalizedCacheObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > OptimisticStoreItem 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Policies 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > PossibleTypesMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ReadFieldOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ReadMergeModifyContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > ReadQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Reference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > StoreObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > StoreValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > Transaction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > TypePolicies 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > TypePolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > WatchFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchFragmentOptions } from \"@apollo/client/cache\";\n-type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n+import { ApolloCache } from \"@apollo/client/cache\";\n+type _Test_WatchFragmentOptions = ApolloCache.WatchFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > WatchFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchFragmentResult } from \"@apollo/client/cache\";\n-type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\n\\\\ No newline at end of file\n+import { ApolloCache } from \"@apollo/client/cache\";\n+type _Test_WatchFragmentResult = ApolloCache.WatchFragmentResult<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > cacheSlot 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > canonicalStringify 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > createFragmentRegistry 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > defaultDataIdFromObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > fieldNameFromStoreName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > isReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > makeReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeReference } from \"@apollo/client/cache\";\n makeReference(id)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/cache > makeVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloCache } from \"@apollo/client/core\";\n+import { ApolloCache } from \"@apollo/client\";\n class _Test_ApolloCache extends ApolloCache<TSerialized> {}\n const _test_ApolloCache = new ApolloCache<TSerialized>()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloClient } from \"@apollo/client/core\";\n+import { ApolloClient } from \"@apollo/client\";\n class _Test_ApolloClient extends ApolloClient<TCacheShape> {}\n const _test_ApolloClient = new ApolloClient<TCacheShape>(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloClientOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloClientOptions } from \"@apollo/client/core\";\n-type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_ApolloClientOptions = ApolloClient.Options<TCacheShape>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloError } from \"@apollo/client/core\";\n+import { ApolloError } from \"@apollo/client\";\n class _Test_ApolloError extends ApolloError {}\n const _test_ApolloError = new ApolloError(param0)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloLink } from \"@apollo/client/core\";\n+import { ApolloLink } from \"@apollo/client\";\n class _Test_ApolloLink extends ApolloLink {}\n const _test_ApolloLink = new ApolloLink(request)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloPayloadResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloPayloadResult } from \"@apollo/client/core\";\n+import { ApolloPayloadResult } from \"@apollo/client\";\n type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloQueryResult } from \"@apollo/client/core\";\n-type _Test_ApolloQueryResult = ApolloQueryResult<T>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_ApolloQueryResult = ObservableQuery.Result<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ApolloReducerConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloReducerConfig } from \"@apollo/client/core\";\n+import { ApolloReducerConfig } from \"@apollo/client\";\n type _Test_ApolloReducerConfig = ApolloReducerConfig;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Cache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Cache } from \"@apollo/client/core\";\n+import { Cache } from \"@apollo/client\";\n const _Test_Cache = Cache;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ClientParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ClientParseError } from \"@apollo/client/core\";\n+import { ClientParseError } from \"@apollo/client\";\n type _Test_ClientParseError = ClientParseError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DataMasking 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DataMasking } from \"@apollo/client/core\";\n+import { DataMasking } from \"@apollo/client\";\n type _Test_DataMasking = DataMasking;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DataProxy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DataProxy } from \"@apollo/client/core\";\n+import { DataProxy } from \"@apollo/client\";\n const _Test_DataProxy = DataProxy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DefaultContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DefaultContext } from \"@apollo/client/core\";\n+import { DefaultContext } from \"@apollo/client\";\n type _Test_DefaultContext = DefaultContext;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DefaultOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DefaultOptions } from \"@apollo/client/core\";\n-type _Test_DefaultOptions = DefaultOptions;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_DefaultOptions = ApolloClient.DefaultOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DiffQueryAgainstStoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DiffQueryAgainstStoreOptions } from \"@apollo/client/core\";\n+import { DiffQueryAgainstStoreOptions } from \"@apollo/client\";\n type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DocumentNode } from \"@apollo/client/core\";\n+import { DocumentNode } from \"@apollo/client\";\n type _Test_DocumentNode = DocumentNode;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DocumentTransform 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DocumentTransform } from \"@apollo/client/core\";\n+import { DocumentTransform } from \"@apollo/client\";\n class _Test_DocumentTransform extends DocumentTransform {}\n const _test_DocumentTransform = new DocumentTransform(transform, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > DocumentTransformCacheKey 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DocumentTransformCacheKey } from \"@apollo/client/core\";\n+import { DocumentTransformCacheKey } from \"@apollo/client\";\n type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ErrorPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ErrorPolicy } from \"@apollo/client/core\";\n+import { ErrorPolicy } from \"@apollo/client\";\n type _Test_ErrorPolicy = ErrorPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ExecutionPatchIncrementalResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchIncrementalResult } from \"@apollo/client/core\";\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ExecutionPatchInitialResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchInitialResult } from \"@apollo/client/core\";\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ExecutionPatchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchResult } from \"@apollo/client/core\";\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FetchMoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchMoreOptions } from \"@apollo/client/core\";\n-type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FetchMoreQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchMoreQueryOptions } from \"@apollo/client/core\";\n+import { FetchMoreQueryOptions } from \"@apollo/client\";\n type _Test_FetchMoreQueryOptions = FetchMoreQueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchPolicy } from \"@apollo/client/core\";\n+import { FetchPolicy } from \"@apollo/client\";\n type _Test_FetchPolicy = FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FetchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchResult } from \"@apollo/client/core\";\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FieldFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FieldFunctionOptions } from \"@apollo/client/core\";\n+import { FieldFunctionOptions } from \"@apollo/client\";\n type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FieldMergeFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FieldMergeFunction } from \"@apollo/client/core\";\n+import { FieldMergeFunction } from \"@apollo/client\";\n type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FieldPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FieldPolicy } from \"@apollo/client/core\";\n+import { FieldPolicy } from \"@apollo/client\";\n type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FieldReadFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FieldReadFunction } from \"@apollo/client/core\";\n+import { FieldReadFunction } from \"@apollo/client\";\n type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FragmentMatcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FragmentMatcher } from \"@apollo/client/core\";\n+import { FragmentMatcher } from \"@apollo/client\";\n type _Test_FragmentMatcher = FragmentMatcher;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > FragmentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FragmentType } from \"@apollo/client/core\";\n+import { FragmentType } from \"@apollo/client\";\n type _Test_FragmentType = FragmentType<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > GraphQLRequest 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { GraphQLRequest } from \"@apollo/client/core\";\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > HttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { HttpLink } from \"@apollo/client/core\";\n+import { HttpLink } from \"@apollo/client\";\n class _Test_HttpLink extends HttpLink {}\n const _test_HttpLink = new HttpLink(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > HttpOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { HttpOptions } from \"@apollo/client/core\";\n+import { HttpOptions } from \"@apollo/client\";\n type _Test_HttpOptions = HttpOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > IdGetter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { IdGetter } from \"@apollo/client/core\";\n+import { IdGetter } from \"@apollo/client\";\n type _Test_IdGetter = IdGetter;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > IdGetterObj 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { IdGetterObj } from \"@apollo/client/core\";\n+import { IdGetterObj } from \"@apollo/client\";\n type _Test_IdGetterObj = IdGetterObj;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InMemoryCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InMemoryCache } from \"@apollo/client/core\";\n+import { InMemoryCache } from \"@apollo/client\";\n class _Test_InMemoryCache extends InMemoryCache {}\n const _test_InMemoryCache = new InMemoryCache(config)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InMemoryCacheConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InMemoryCacheConfig } from \"@apollo/client/core\";\n+import { InMemoryCacheConfig } from \"@apollo/client\";\n type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > IncrementalPayload 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { IncrementalPayload } from \"@apollo/client/core\";\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n+import { Defer20220824Handler } from \"@apollo/client\";\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InternalRefetchQueriesInclude 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InternalRefetchQueriesInclude } from \"@apollo/client/core\";\n+import { InternalRefetchQueriesInclude } from \"@apollo/client\";\n type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InternalRefetchQueriesMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InternalRefetchQueriesMap } from \"@apollo/client/core\";\n+import { InternalRefetchQueriesMap } from \"@apollo/client\";\n type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InternalRefetchQueriesOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InternalRefetchQueriesOptions } from \"@apollo/client/core\";\n+import { InternalRefetchQueriesOptions } from \"@apollo/client\";\n type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InternalRefetchQueriesResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InternalRefetchQueriesResult } from \"@apollo/client/core\";\n+import { InternalRefetchQueriesResult } from \"@apollo/client\";\n type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > InternalRefetchQueryDescriptor 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { InternalRefetchQueryDescriptor } from \"@apollo/client/core\";\n+import { InternalRefetchQueryDescriptor } from \"@apollo/client\";\n type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Masked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Masked } from \"@apollo/client/core\";\n+import { Masked } from \"@apollo/client\";\n type _Test_Masked = Masked<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MaskedDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MaskedDocumentNode } from \"@apollo/client/core\";\n+import { MaskedDocumentNode } from \"@apollo/client\";\n type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MaybeMasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MaybeMasked } from \"@apollo/client/core\";\n+import { MaybeMasked } from \"@apollo/client\";\n type _Test_MaybeMasked = MaybeMasked<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MergeInfo 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MergeInfo } from \"@apollo/client/core\";\n+import { MergeInfo } from \"@apollo/client\";\n type _Test_MergeInfo = MergeInfo;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MergeTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MergeTree } from \"@apollo/client/core\";\n+import { MergeTree } from \"@apollo/client\";\n type _Test_MergeTree = MergeTree;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MethodKeys 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MethodKeys } from \"@apollo/client/core\";\n+import { MethodKeys } from \"@apollo/client\";\n type _Test_MethodKeys = MethodKeys<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MissingFieldError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MissingFieldError } from \"@apollo/client/core\";\n+import { MissingFieldError } from \"@apollo/client\";\n class _Test_MissingFieldError extends MissingFieldError {}\n const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationFetchPolicy } from \"@apollo/client/core\";\n+import { MutationFetchPolicy } from \"@apollo/client\";\n type _Test_MutationFetchPolicy = MutationFetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationOptions } from \"@apollo/client/core\";\n-type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_MutationOptions = ApolloClient.MutateOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationQueryReducer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationQueryReducer } from \"@apollo/client/core\";\n+import { MutationQueryReducer } from \"@apollo/client\";\n type _Test_MutationQueryReducer = MutationQueryReducer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationQueryReducersMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationQueryReducersMap } from \"@apollo/client/core\";\n+import { MutationQueryReducersMap } from \"@apollo/client\";\n type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationUpdaterFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationUpdaterFn } from \"@apollo/client/core\";\n+import { MutationUpdaterFn } from \"@apollo/client\";\n type _Test_MutationUpdaterFn = MutationUpdaterFn<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > MutationUpdaterFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationUpdaterFunction } from \"@apollo/client/core\";\n+import { MutationUpdaterFunction } from \"@apollo/client\";\n type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > NetworkStatus 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NetworkStatus } from \"@apollo/client/core\";\n+import { NetworkStatus } from \"@apollo/client\";\n type _Test_NetworkStatus = NetworkStatus;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > NextLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NextLink } from \"@apollo/client/core\";\n-type _Test_NextLink = NextLink;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > NormalizedCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NormalizedCache } from \"@apollo/client/core\";\n+import { NormalizedCache } from \"@apollo/client\";\n type _Test_NormalizedCache = NormalizedCache;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > NormalizedCacheObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NormalizedCacheObject } from \"@apollo/client/core\";\n+import { NormalizedCacheObject } from \"@apollo/client\";\n type _Test_NormalizedCacheObject = NormalizedCacheObject;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Observable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Observable } from \"@apollo/client/core\";\n\\\\ No newline at end of file\n+import { Observable } from \"@apollo/client\";\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ObservableQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ObservableQuery } from \"@apollo/client/core\";\n+import { ObservableQuery } from \"@apollo/client\";\n class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\n const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ObservableSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ObservableSubscription } from \"@apollo/client/core\";\n\\\\ No newline at end of file\n+import { ObservableSubscription } from \"@apollo/client\";\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Observer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Observer } from \"@apollo/client/core\";\n\\\\ No newline at end of file\n+import { Observer } from \"@apollo/client\";\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > OnQueryUpdated 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OnQueryUpdated } from \"@apollo/client/core\";\n+import { OnQueryUpdated } from \"@apollo/client\";\n type _Test_OnQueryUpdated = OnQueryUpdated<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Operation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Operation } from \"@apollo/client/core\";\n-type _Test_Operation = Operation;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_Operation = ApolloLink.Operation;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > OperationVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OperationVariables } from \"@apollo/client/core\";\n+import { OperationVariables } from \"@apollo/client\";\n type _Test_OperationVariables = OperationVariables;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > OptimisticStoreItem 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OptimisticStoreItem } from \"@apollo/client/core\";\n+import { OptimisticStoreItem } from \"@apollo/client\";\n type _Test_OptimisticStoreItem = OptimisticStoreItem;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Path 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Path } from \"@apollo/client/core\";\n-type _Test_Path = Path;\n\\\\ No newline at end of file\n+import { Incremental } from \"@apollo/client\";\n+type _Test_Path = Incremental.Path;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > PossibleTypesMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PossibleTypesMap } from \"@apollo/client/core\";\n+import { PossibleTypesMap } from \"@apollo/client\";\n type _Test_PossibleTypesMap = PossibleTypesMap;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > PureQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PureQueryOptions } from \"@apollo/client/core\";\n+import { PureQueryOptions } from \"@apollo/client\";\n type _Test_PureQueryOptions = PureQueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > QueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryOptions } from \"@apollo/client/core\";\n-type _Test_QueryOptions = QueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ReactiveVar } from \"@apollo/client/core\";\n+import { ReactiveVar } from \"@apollo/client\";\n type _Test_ReactiveVar = ReactiveVar<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ReadMergeModifyContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ReadMergeModifyContext } from \"@apollo/client/core\";\n+import { ReadMergeModifyContext } from \"@apollo/client\";\n type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ReadQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ReadQueryOptions } from \"@apollo/client/core\";\n+import { ReadQueryOptions } from \"@apollo/client\";\n type _Test_ReadQueryOptions = ReadQueryOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Reference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Reference } from \"@apollo/client/core\";\n+import { Reference } from \"@apollo/client\";\n type _Test_Reference = Reference;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchQueriesInclude 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesInclude } from \"@apollo/client/core\";\n+import { RefetchQueriesInclude } from \"@apollo/client\";\n type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchQueriesOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesOptions } from \"@apollo/client/core\";\n-type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchQueriesPromiseResults 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesPromiseResults } from \"@apollo/client/core\";\n+import { RefetchQueriesPromiseResults } from \"@apollo/client\";\n type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchQueriesResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueriesResult } from \"@apollo/client/core\";\n-type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchQueryDescriptor 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchQueryDescriptor } from \"@apollo/client/core\";\n+import { RefetchQueryDescriptor } from \"@apollo/client\";\n type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RefetchWritePolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RefetchWritePolicy } from \"@apollo/client/core\";\n+import { RefetchWritePolicy } from \"@apollo/client\";\n type _Test_RefetchWritePolicy = RefetchWritePolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > RequestHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RequestHandler } from \"@apollo/client/core\";\n-type _Test_RequestHandler = RequestHandler;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client\";\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Resolver 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Resolver } from \"@apollo/client/core\";\n+import { Resolver } from \"@apollo/client\";\n type _Test_Resolver = Resolver;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Resolvers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Resolvers } from \"@apollo/client/core\";\n+import { Resolvers } from \"@apollo/client\";\n type _Test_Resolvers = Resolvers;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ServerError } from \"@apollo/client/core\";\n+import { ServerError } from \"@apollo/client\";\n type _Test_ServerError = ServerError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > ServerParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ServerParseError } from \"@apollo/client/core\";\n+import { ServerParseError } from \"@apollo/client\";\n type _Test_ServerParseError = ServerParseError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > SingleExecutionResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SingleExecutionResult } from \"@apollo/client/core\";\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import { FormattedExecutionResult } from \"@apollo/client\";\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > StoreObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { StoreObject } from \"@apollo/client/core\";\n+import { StoreObject } from \"@apollo/client\";\n type _Test_StoreObject = StoreObject;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > StoreValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { StoreValue } from \"@apollo/client/core\";\n+import { StoreValue } from \"@apollo/client\";\n type _Test_StoreValue = StoreValue;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > SubscribeToMoreFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscribeToMoreFunction } from \"@apollo/client/core\";\n+import { SubscribeToMoreFunction } from \"@apollo/client\";\n type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > SubscribeToMoreOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscribeToMoreOptions } from \"@apollo/client/core\";\n-type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\\\\ No newline at end of file\n+import { ObservableQuery } from \"@apollo/client\";\n+type _Test_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > SubscribeToMoreUpdateQueryFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscribeToMoreUpdateQueryFn } from \"@apollo/client/core\";\n+import { SubscribeToMoreUpdateQueryFn } from \"@apollo/client\";\n type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > SubscriptionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionOptions } from \"@apollo/client/core\";\n-type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_SubscriptionOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Transaction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Transaction } from \"@apollo/client/core\";\n+import { Transaction } from \"@apollo/client\";\n type _Test_Transaction = Transaction<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > TypePolicies 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { TypePolicies } from \"@apollo/client/core\";\n+import { TypePolicies } from \"@apollo/client\";\n type _Test_TypePolicies = TypePolicies;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > TypePolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { TypePolicy } from \"@apollo/client/core\";\n+import { TypePolicy } from \"@apollo/client\";\n type _Test_TypePolicy = TypePolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > TypedDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { TypedDocumentNode } from \"@apollo/client/core\";\n+import { TypedDocumentNode } from \"@apollo/client\";\n type _Test_TypedDocumentNode = TypedDocumentNode<TResult, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > Unmasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Unmasked } from \"@apollo/client/core\";\n+import { Unmasked } from \"@apollo/client\";\n type _Test_Unmasked = Unmasked<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > UpdateQueryMapFn 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UpdateQueryMapFn } from \"@apollo/client/core\";\n+import { UpdateQueryMapFn } from \"@apollo/client\";\n type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > UpdateQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UpdateQueryOptions } from \"@apollo/client/core\";\n+import { UpdateQueryOptions } from \"@apollo/client\";\n type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > UriFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UriFunction } from \"@apollo/client/core\";\n+import { UriFunction } from \"@apollo/client\";\n type _Test_UriFunction = UriFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > WatchFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchFragmentOptions } from \"@apollo/client/core\";\n+import { WatchFragmentOptions } from \"@apollo/client\";\n type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > WatchFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchFragmentResult } from \"@apollo/client/core\";\n+import { WatchFragmentResult } from \"@apollo/client\";\n type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > WatchQueryFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchQueryFetchPolicy } from \"@apollo/client/core\";\n+import { WatchQueryFetchPolicy } from \"@apollo/client\";\n type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > WatchQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WatchQueryOptions } from \"@apollo/client/core\";\n-type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\n\\\\ No newline at end of file\n+import { ApolloClient } from \"@apollo/client\";\n+type _Test_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > checkFetcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { checkFetcher } from \"@apollo/client/core\";\n+import { checkFetcher } from \"@apollo/client\";\n const _Test_checkFetcher = checkFetcher;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > concat 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { concat } from \"@apollo/client/core\";\n+import { concat } from \"@apollo/client\";\n const _Test_concat = concat;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > createHttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createHttpLink } from \"@apollo/client/core\";\n+import { createHttpLink } from \"@apollo/client\";\n const _Test_createHttpLink = createHttpLink;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > createSignalIfSupported 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createSignalIfSupported } from \"@apollo/client/core\";\n+import { createSignalIfSupported } from \"@apollo/client\";\n const _Test_createSignalIfSupported = createSignalIfSupported;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > defaultDataIdFromObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { defaultDataIdFromObject } from \"@apollo/client/core\";\n+import { defaultDataIdFromObject } from \"@apollo/client\";\n defaultDataIdFromObject(param0, context)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > defaultPrinter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { defaultPrinter } from \"@apollo/client/core\";\n+import { defaultPrinter } from \"@apollo/client\";\n const _Test_defaultPrinter = defaultPrinter;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > disableExperimentalFragmentVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { disableExperimentalFragmentVariables } from \"@apollo/client/core\";\n+import { disableExperimentalFragmentVariables } from \"@apollo/client\";\n disableExperimentalFragmentVariables()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > disableFragmentWarnings 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { disableFragmentWarnings } from \"@apollo/client/core\";\n+import { disableFragmentWarnings } from \"@apollo/client\";\n disableFragmentWarnings()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > empty 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { empty } from \"@apollo/client/core\";\n+import { empty } from \"@apollo/client\";\n const _Test_empty = empty;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > enableExperimentalFragmentVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { enableExperimentalFragmentVariables } from \"@apollo/client/core\";\n+import { enableExperimentalFragmentVariables } from \"@apollo/client\";\n enableExperimentalFragmentVariables()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > execute 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { execute } from \"@apollo/client/core\";\n+import { execute } from \"@apollo/client\";\n const _Test_execute = execute;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > fallbackHttpConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { fallbackHttpConfig } from \"@apollo/client/core\";\n+import { fallbackHttpConfig } from \"@apollo/client\";\n const _Test_fallbackHttpConfig = fallbackHttpConfig;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > from 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { from } from \"@apollo/client/core\";\n+import { from } from \"@apollo/client\";\n const _Test_from = from;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > fromError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { fromError } from \"@apollo/client/core\";\n+import { fromError } from \"@apollo/client\";\n fromError<T>(errorValue)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > fromPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { fromPromise } from \"@apollo/client/core\";\n+import { fromPromise } from \"@apollo/client\";\n fromPromise<T>(promise)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > gql 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { gql } from \"@apollo/client/core\";\n+import { gql } from \"@apollo/client\";\n gql(literals, args)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > isApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isApolloError } from \"@apollo/client/core\";\n+import { isApolloError } from \"@apollo/client\";\n isApolloError(err)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > isNetworkRequestSettled 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isNetworkRequestSettled } from \"@apollo/client/core\";\n+import { isNetworkRequestSettled } from \"@apollo/client\";\n isNetworkRequestSettled(networkStatus)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > isReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isReference } from \"@apollo/client/core\";\n+import { isReference } from \"@apollo/client\";\n isReference(obj)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > makeReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeReference } from \"@apollo/client/core\";\n makeReference(id)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > makeVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeVar } from \"@apollo/client/core\";\n+import { makeVar } from \"@apollo/client\";\n makeVar<T>(value)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > mergeOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mergeOptions } from \"@apollo/client/core\";\n mergeOptions<TDefaultOptions, TOptions>(defaults, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > parseAndCheckHttpResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { parseAndCheckHttpResponse } from \"@apollo/client/core\";\n+import { parseAndCheckHttpResponse } from \"@apollo/client\";\n parseAndCheckHttpResponse(operations)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > resetCaches 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { resetCaches } from \"@apollo/client/core\";\n+import { resetCaches } from \"@apollo/client\";\n resetCaches()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > rewriteURIForGET 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { rewriteURIForGET } from \"@apollo/client/core\";\n+import { rewriteURIForGET } from \"@apollo/client\";\n rewriteURIForGET(chosenURI, body)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > selectHttpOptionsAndBody 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { selectHttpOptionsAndBody } from \"@apollo/client/core\";\n+import { selectHttpOptionsAndBody } from \"@apollo/client\";\n selectHttpOptionsAndBody(operation, fallbackConfig, configs)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > selectHttpOptionsAndBodyInternal 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { selectHttpOptionsAndBodyInternal } from \"@apollo/client/core\";\n+import { selectHttpOptionsAndBodyInternal } from \"@apollo/client\";\n selectHttpOptionsAndBodyInternal(operation, printer, configs)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > selectURI 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { selectURI } from \"@apollo/client/core\";\n+import { selectURI } from \"@apollo/client\";\n const _Test_selectURI = selectURI;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > serializeFetchParameter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { serializeFetchParameter } from \"@apollo/client/core\";\n+import { serializeFetchParameter } from \"@apollo/client\";\n const _Test_serializeFetchParameter = serializeFetchParameter;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > setLogVerbosity 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { setLogVerbosity } from \"@apollo/client/core\";\n\\\\ No newline at end of file\n+import { setLogVerbosity } from \"@apollo/client\";\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > split 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { split } from \"@apollo/client/core\";\n+import { split } from \"@apollo/client\";\n const _Test_split = split;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > throwServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { throwServerError } from \"@apollo/client/core\";\n+import { throwServerError } from \"@apollo/client\";\n const _Test_throwServerError = throwServerError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/core > toPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { toPromise } from \"@apollo/client/core\";\n+import { toPromise } from \"@apollo/client\";\n toPromise<R>(observable)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/dev > ErrorMessageHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/dev > loadDevMessages 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/dev > loadErrorMessageHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/dev > loadErrorMessages 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/dev > setErrorMessageHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > ApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > ApolloErrorOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > GraphQLErrors 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > NetworkError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > PROTOCOL_ERRORS_SYMBOL 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > graphQLResultHasProtocolErrors 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/errors > isApolloError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/batch > BatchHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BatchHandler } from \"@apollo/client/link/batch\";\n-type _Test_BatchHandler = BatchHandler;\n\\\\ No newline at end of file\n+import { BatchLink } from \"@apollo/client/link/batch\";\n+type _Test_BatchHandler = BatchLink.BatchHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/batch > BatchLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/batch > BatchableRequest 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/batch > OperationBatcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/batch-http > BatchHttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/context > ContextSetter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ContextSetter } from \"@apollo/client/link/context\";\n-type _Test_ContextSetter = ContextSetter;\n\\\\ No newline at end of file\n+import { SetContextLink } from \"@apollo/client/link/context\";\n+type _Test_ContextSetter = SetContextLink.LegacyContextSetter;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/context > setContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > ApolloLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloLink } from \"@apollo/client/link/core\";\n+import { ApolloLink } from \"@apollo/client/link\";\n class _Test_ApolloLink extends ApolloLink {}\n const _test_ApolloLink = new ApolloLink(request)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > ApolloPayloadResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloPayloadResult } from \"@apollo/client/link/core\";\n+import { ApolloPayloadResult } from \"@apollo/client/link\";\n type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > DocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DocumentNode } from \"@apollo/client/link/core\";\n+import { DocumentNode } from \"@apollo/client/link\";\n type _Test_DocumentNode = DocumentNode;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > ExecutionPatchIncrementalResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchIncrementalResult } from \"@apollo/client/link/core\";\n-type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import type { Defer20220824Handler } from \"@apollo/client/incremental\";\n+type _Test_ExecutionPatchIncrementalResult = Defer20220824Handler.SubsequentResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > ExecutionPatchInitialResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchInitialResult } from \"@apollo/client/link/core\";\n-type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import type { Defer20220824Handler } from \"@apollo/client/incremental\";\n+type _Test_ExecutionPatchInitialResult = Defer20220824Handler.InitialResult<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > ExecutionPatchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ExecutionPatchResult } from \"@apollo/client/link/core\";\n-type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\n\\\\ No newline at end of file\n+import type { Defer20220824Handler } from \"@apollo/client/incremental\";\n+type _Test_ExecutionPatchResult = Defer20220824Handler.Chunk<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > FetchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FetchResult } from \"@apollo/client/link/core\";\n-type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client/link\";\n+type _Test_FetchResult = ApolloLink.Result<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > GraphQLRequest 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { GraphQLRequest } from \"@apollo/client/link/core\";\n-type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client/link\";\n+type _Test_GraphQLRequest = ApolloLink.Request<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > IncrementalPayload 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { IncrementalPayload } from \"@apollo/client/link/core\";\n-type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n+import type { Defer20220824Handler } from \"@apollo/client/incremental\";\n+type _Test_IncrementalPayload = Defer20220824Handler.IncrementalDeferPayload<TData, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > NextLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NextLink } from \"@apollo/client/link/core\";\n-type _Test_NextLink = NextLink;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client/link\";\n+type _Test_NextLink = ApolloLink.ForwardFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > Operation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Operation } from \"@apollo/client/link/core\";\n-type _Test_Operation = Operation;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client/link\";\n+type _Test_Operation = ApolloLink.Operation;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > Path 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Path } from \"@apollo/client/link/core\";\n-type _Test_Path = Path;\n\\\\ No newline at end of file\n+import type { Incremental } from \"@apollo/client/incremental\";\n+type _Test_Path = Incremental.Path;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > RequestHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RequestHandler } from \"@apollo/client/link/core\";\n-type _Test_RequestHandler = RequestHandler;\n\\\\ No newline at end of file\n+import { ApolloLink } from \"@apollo/client/link\";\n+type _Test_RequestHandler = ApolloLink.RequestHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > SingleExecutionResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SingleExecutionResult } from \"@apollo/client/link/core\";\n-type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n+import type { FormattedExecutionResult } from \"graphql\";\n+type _Test_SingleExecutionResult = FormattedExecutionResult<TData, TContext, TExtensions>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > concat 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { concat } from \"@apollo/client/link/core\";\n+import { concat } from \"@apollo/client/link\";\n const _Test_concat = concat;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > empty 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { empty } from \"@apollo/client/link/core\";\n+import { empty } from \"@apollo/client/link\";\n const _Test_empty = empty;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > execute 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { execute } from \"@apollo/client/link/core\";\n+import { execute } from \"@apollo/client/link\";\n const _Test_execute = execute;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > from 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { from } from \"@apollo/client/link/core\";\n+import { from } from \"@apollo/client/link\";\n const _Test_from = from;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/core > split 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { split } from \"@apollo/client/link/core\";\n+import { split } from \"@apollo/client/link\";\n const _Test_split = split;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/error > ErrorHandler 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ErrorHandler } from \"@apollo/client/link/error\";\n-type _Test_ErrorHandler = ErrorHandler;\n\\\\ No newline at end of file\n+import { ErrorLink } from \"@apollo/client/link/error\";\n+type _Test_ErrorHandler = ErrorLink.ErrorHandler;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/error > ErrorLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/error > ErrorResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ErrorResponse } from \"@apollo/client/link/error\";\n-type _Test_ErrorResponse = ErrorResponse;\n\\\\ No newline at end of file\n+import { ErrorLink } from \"@apollo/client/link/error\";\n+type _Test_ErrorResponse = ErrorLink.ErrorHandlerOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/error > onError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > ClientParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > HttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > HttpOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > ServerParseError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ServerParseError } from \"@apollo/client/link/http\";\n+import type { ServerParseError } from \"@apollo/client/errors\";\n type _Test_ServerParseError = ServerParseError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > UriFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > checkFetcher 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > createHttpLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > createSignalIfSupported 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > defaultPrinter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > fallbackHttpConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > parseAndCheckHttpResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > rewriteURIForGET 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > selectHttpOptionsAndBody 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > selectHttpOptionsAndBodyInternal 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > selectURI 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/http > serializeFetchParameter 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/persisted-queries > ErrorResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ErrorResponse } from \"@apollo/client/link/persisted-queries\";\n-type _Test_ErrorResponse = ErrorResponse;\n\\\\ No newline at end of file\n+import { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\n+type _Test_ErrorResponse = PersistedQueryLink.DisableFunctionOptions;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/persisted-queries > PersistedQueryLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/persisted-queries > VERSION 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/persisted-queries > createPersistedQueryLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/remove-typename > KEEP 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/remove-typename > RemoveTypenameFromVariablesOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RemoveTypenameFromVariablesOptions } from \"@apollo/client/link/remove-typename\";\n-type _Test_RemoveTypenameFromVariablesOptions = RemoveTypenameFromVariablesOptions;\n\\\\ No newline at end of file\n+import { RemoveTypenameFromVariablesLink } from \"@apollo/client/link/remove-typename\";\n+type _Test_RemoveTypenameFromVariablesOptions = RemoveTypenameFromVariablesLink.Options;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/remove-typename > removeTypenameFromVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/retry > RetryLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/schema > SchemaLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/subscriptions > GraphQLWsLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > ServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ServerError } from \"@apollo/client/link/utils\";\n+import type { ServerError } from \"@apollo/client/errors\";\n type _Test_ServerError = ServerError;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > createOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > filterOperationVariables 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > fromError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > fromPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > throwServerError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > toPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > transformOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/utils > validateOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/ws > WebSocketLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/link/ws > WebSocketParams 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { WebSocketParams } from \"@apollo/client/link/ws\";\n-type _Test_WebSocketParams = WebSocketParams;\n\\\\ No newline at end of file\n+import { WebSocketLink } from \"@apollo/client/link/ws\";\n+type _Test_WebSocketParams = WebSocketLink.Configuration;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > DataMasking 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > FragmentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > Masked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > MaskedDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > MaybeMasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > Unmasked 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > disableWarningsSlot 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > maskFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/masking > maskOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > ApolloConsumer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > ApolloContextValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > ApolloProvider 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > BackgroundQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BackgroundQueryHookFetchPolicy } from \"@apollo/client/react\";\n-type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > BackgroundQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BackgroundQueryHookOptions } from \"@apollo/client/react\";\n-type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_BackgroundQueryHookOptions = useBackgroundQuery.Options<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > BaseMutationOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > BaseQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > BaseSubscriptionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { BaseSubscriptionOptions } from \"@apollo/client/react\";\n-type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSubscription } from \"@apollo/client/react\";\n+type _Test_BaseSubscriptionOptions = useSubscription.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > CommonOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > Context 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Context } from \"@apollo/client/react\";\n-type _Test_Context = Context;\n\\\\ No newline at end of file\n+import type { DefaultContext } from \"@apollo/client\";\n+type _Test_Context = DefaultContext;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > DocumentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > IDocumentDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LazyQueryExecFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryExecFunction } from \"@apollo/client/react\";\n-type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryExecFunction = useLazyQuery.ExecFunction<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LazyQueryHookExecOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryHookExecOptions } from \"@apollo/client/react\";\n-type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryHookExecOptions = useLazyQuery.ExecOptions<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LazyQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryHookOptions } from \"@apollo/client/react\";\n-type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryHookOptions = useLazyQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LazyQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryResult } from \"@apollo/client/react\";\n-type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryResult = useLazyQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LazyQueryResultTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LazyQueryResultTuple } from \"@apollo/client/react\";\n-type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_LazyQueryResultTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LoadQueryFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadQueryFunction } from \"@apollo/client/react\";\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LoadableQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadableQueryHookFetchPolicy } from \"@apollo/client/react\";\n-type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadableQueryHookFetchPolicy = useLoadableQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > LoadableQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadableQueryHookOptions } from \"@apollo/client/react\";\n-type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadableQueryHookOptions = useLoadableQuery.Options;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationFunctionOptions } from \"@apollo/client/react\";\n-type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationFunctionOptions = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationHookOptions } from \"@apollo/client/react\";\n-type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationHookOptions = useMutation.Options<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationResult } from \"@apollo/client/react\";\n-type _Test_MutationResult = MutationResult<TData>;\n\\\\ No newline at end of file\n+import { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationResult = useMutation.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > MutationTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MutationTuple } from \"@apollo/client/react\";\n-type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\n\\\\ No newline at end of file\n+import { useMutation } from \"@apollo/client/react\";\n+type _Test_MutationTuple = useMutation.ResultTuple<TData, TVariables, TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > NoInfer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NoInfer } from \"@apollo/client/react\";\n+import type { NoInfer } from \"@apollo/client/utilities/internal\";\n type _Test_NoInfer = NoInfer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > ObservableQueryFields 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > OnDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OnDataOptions } from \"@apollo/client/react\";\n-type _Test_OnDataOptions = OnDataOptions<TData>;\n\\\\ No newline at end of file\n+import { useSubscription } from \"@apollo/client/react\";\n+type _Test_OnDataOptions = useSubscription.OnDataOptions<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > OnSubscriptionDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { OnSubscriptionDataOptions } from \"@apollo/client/react\";\n-type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\n\\\\ No newline at end of file\n+import { useSubscription } from \"@apollo/client/react\";\n+type _Test_OnSubscriptionDataOptions = useSubscription.OnSubscriptionDataOptions<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > PreloadQueryFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > PreloadQueryFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > PreloadQueryOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > PreloadedQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryFunctionOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryFunctionOptions } from \"@apollo/client/react\";\n-type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryFunctionOptions = useQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryHookOptions } from \"@apollo/client/react\";\n-type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryHookOptions = useQuery.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryLazyOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryReference } from \"@apollo/client/react\";\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n\\\\ No newline at end of file\n+import { QueryRef } from \"@apollo/client/react\";\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryResult } from \"@apollo/client/react\";\n-type _Test_QueryResult = QueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useQuery } from \"@apollo/client/react\";\n+type _Test_QueryResult = useQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > QueryTuple 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryTuple } from \"@apollo/client/react\";\n-type _Test_QueryTuple = QueryTuple<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLazyQuery } from \"@apollo/client/react\";\n+type _Test_QueryTuple = useLazyQuery.ResultTuple<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > RefetchQueriesFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SkipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SubscriptionCurrentObservable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SubscriptionDataOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SubscriptionHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionHookOptions } from \"@apollo/client/react\";\n-type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSubscription } from \"@apollo/client/react\";\n+type _Test_SubscriptionHookOptions = useSubscription.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SubscriptionResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SubscriptionResult } from \"@apollo/client/react\";\n-type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSubscription } from \"@apollo/client/react\";\n+type _Test_SubscriptionResult = useSubscription.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SuspenseQueryHookFetchPolicy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SuspenseQueryHookFetchPolicy } from \"@apollo/client/react\";\n-type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\n\\\\ No newline at end of file\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > SuspenseQueryHookOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SuspenseQueryHookOptions } from \"@apollo/client/react\";\n-type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_SuspenseQueryHookOptions = useSuspenseQuery.Options<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseBackgroundQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseBackgroundQueryResult } from \"@apollo/client/react\";\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentOptions } from \"@apollo/client/react\";\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n+import { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentResult } from \"@apollo/client/react\";\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseLoadableQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseLoadableQueryResult } from \"@apollo/client/react\";\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseQueryRefHandlersResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseQueryRefHandlersResult } from \"@apollo/client/react\";\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useQueryRefHandlers } from \"@apollo/client/react\";\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseReadQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseReadQueryResult } from \"@apollo/client/react\";\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n\\\\ No newline at end of file\n+import { useReadQuery } from \"@apollo/client/react\";\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseSuspenseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentOptions } from \"@apollo/client/react\";\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseSuspenseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentResult } from \"@apollo/client/react\";\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > UseSuspenseQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseQueryResult } from \"@apollo/client/react\";\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > VariablesOption 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { VariablesOption } from \"@apollo/client/react\";\n+import type { VariablesOption } from \"@apollo/client/utilities/internal\";\n type _Test_VariablesOption = VariablesOption<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > createQueryPreloader 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > getApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > operationName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > parser 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > resetApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > skipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useBackgroundQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useLazyQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useLoadableQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useMutation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useQueryRefHandlers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useReadQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useSuspenseFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react > useSuspenseQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > Mutation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > MutationComponentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > Query 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > QueryComponentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > Subscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/components > SubscriptionComponentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > ApolloConsumer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloConsumer } from \"@apollo/client/react/context\";\n+import { ApolloConsumer } from \"@apollo/client/react\";\n const _Test_ApolloConsumer = ApolloConsumer;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > ApolloConsumerProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloConsumerProps } from \"@apollo/client/react/context\";\n+import { ApolloConsumerProps } from \"@apollo/client/react\";\n type _Test_ApolloConsumerProps = ApolloConsumerProps;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > ApolloContextValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloContextValue } from \"@apollo/client/react/context\";\n+import { ApolloContextValue } from \"@apollo/client/react\";\n type _Test_ApolloContextValue = ApolloContextValue;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > ApolloProvider 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloProvider } from \"@apollo/client/react/context\";\n+import { ApolloProvider } from \"@apollo/client/react\";\n const _Test_ApolloProvider = ApolloProvider;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > ApolloProviderProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ApolloProviderProps } from \"@apollo/client/react/context\";\n-type _Test_ApolloProviderProps = ApolloProviderProps<TCache>;\n\\\\ No newline at end of file\n+import { ApolloProvider } from \"@apollo/client/react\";\n+type _Test_ApolloProviderProps = ApolloProvider.Props<TCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > getApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getApolloContext } from \"@apollo/client/react/context\";\n+import { getApolloContext } from \"@apollo/client/react\";\n getApolloContext()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/context > resetApolloContext 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { resetApolloContext } from \"@apollo/client/react/context\";\n+import { resetApolloContext } from \"@apollo/client/react\";\n const _Test_resetApolloContext = resetApolloContext;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > ChildDataProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > ChildMutateProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > ChildProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > DataProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > DataValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > MutateProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > OperationOption 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > OptionProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > QueryControls 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > WithApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > graphql 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > withApollo 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > withMutation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > withQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hoc > withSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > LoadQueryFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { LoadQueryFunction } from \"@apollo/client/react/hooks\";\n-type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > SkipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { SkipToken } from \"@apollo/client/react/hooks\";\n+import { SkipToken } from \"@apollo/client/react\";\n type _Test_SkipToken = SkipToken;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseBackgroundQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseBackgroundQueryResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n+type _Test_UseBackgroundQueryResult = useBackgroundQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentOptions } from \"@apollo/client/react/hooks\";\n-type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\n\\\\ No newline at end of file\n+import { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentOptions = useFragment.Options<TData, TVars>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseFragmentResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseFragmentResult = UseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import { useFragment } from \"@apollo/client/react\";\n+type _Test_UseFragmentResult = useFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseLoadableQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseLoadableQueryResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useLoadableQuery } from \"@apollo/client/react\";\n+type _Test_UseLoadableQueryResult = useLoadableQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseQueryRefHandlersResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseQueryRefHandlersResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useQueryRefHandlers } from \"@apollo/client/react\";\n+type _Test_UseQueryRefHandlersResult = useQueryRefHandlers.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseReadQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseReadQueryResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\n\\\\ No newline at end of file\n+import { useReadQuery } from \"@apollo/client/react\";\n+type _Test_UseReadQueryResult = useReadQuery.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseSuspenseFragmentOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentOptions } from \"@apollo/client/react/hooks\";\n-type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentOptions = useSuspenseFragment.Options<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseSuspenseFragmentResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseFragmentResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\n\\\\ No newline at end of file\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n+type _Test_UseSuspenseFragmentResult = useSuspenseFragment.Result<TData>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > UseSuspenseQueryResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { UseSuspenseQueryResult } from \"@apollo/client/react/hooks\";\n-type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\n\\\\ No newline at end of file\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n+type _Test_UseSuspenseQueryResult = useSuspenseQuery.Result<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > skipToken 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { skipToken } from \"@apollo/client/react/hooks\";\n+import { skipToken } from \"@apollo/client/react\";\n const _Test_skipToken = skipToken;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useApolloClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useApolloClient } from \"@apollo/client/react/hooks\";\n+import { useApolloClient } from \"@apollo/client/react\";\n useApolloClient(override)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useBackgroundQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useBackgroundQuery } from \"@apollo/client/react/hooks\";\n+import { useBackgroundQuery } from \"@apollo/client/react\";\n useBackgroundQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useFragment } from \"@apollo/client/react/hooks\";\n+import { useFragment } from \"@apollo/client/react\";\n useFragment<TData, TVars>(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useLazyQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useLazyQuery } from \"@apollo/client/react/hooks\";\n+import { useLazyQuery } from \"@apollo/client/react\";\n useLazyQuery<TData, TVariables>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useLoadableQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useLoadableQuery } from \"@apollo/client/react/hooks\";\n+import { useLoadableQuery } from \"@apollo/client/react\";\n useLoadableQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useMutation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useMutation } from \"@apollo/client/react/hooks\";\n+import { useMutation } from \"@apollo/client/react\";\n useMutation<TData, TVariables, TContext, TCache>(mutation, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useQuery } from \"@apollo/client/react/hooks\";\n+import { useQuery } from \"@apollo/client/react\";\n useQuery<TData, TVariables>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useQueryRefHandlers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useQueryRefHandlers } from \"@apollo/client/react/hooks\";\n+import { useQueryRefHandlers } from \"@apollo/client/react\";\n useQueryRefHandlers<TData, TVariables>(queryRef)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useReactiveVar 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useReactiveVar } from \"@apollo/client/react/hooks\";\n+import { useReactiveVar } from \"@apollo/client/react\";\n useReactiveVar<T>(rv)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useReadQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useReadQuery } from \"@apollo/client/react/hooks\";\n+import { useReadQuery } from \"@apollo/client/react\";\n useReadQuery<TData>(queryRef)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSubscription } from \"@apollo/client/react/hooks\";\n+import { useSubscription } from \"@apollo/client/react\";\n useSubscription<TData, TVariables>(subscription, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useSuspenseFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSuspenseFragment } from \"@apollo/client/react/hooks\";\n+import { useSuspenseFragment } from \"@apollo/client/react\";\n useSuspenseFragment<TData, TVariables>(options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/hooks > useSuspenseQuery 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { useSuspenseQuery } from \"@apollo/client/react/hooks\";\n+import { useSuspenseQuery } from \"@apollo/client/react\";\n useSuspenseQuery<TData, TVariables, TOptions>(query, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > CacheKey 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > HookWrappers 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > InternalQueryReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > PreloadedQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { PreloadedQueryRef } from \"@apollo/client/react/internal\";\n+import type { PreloadedQueryRef } from \"@apollo/client/react\";\n type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > QueryKey 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > QueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryRef } from \"@apollo/client/react/internal\";\n+import type { QueryRef } from \"@apollo/client/react\";\n type _Test_QueryRef = QueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > QueryReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { QueryReference } from \"@apollo/client/react/internal\";\n-type _Test_QueryReference = QueryReference<TData, TVariables>;\n\\\\ No newline at end of file\n+import type { QueryRef } from \"@apollo/client/react\";\n+type _Test_QueryReference = QueryRef<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > SuspenseCacheOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > assertWrappedQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > getSuspenseCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > getWrappedPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > unwrapQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > updateWrappedQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/internal > wrapQueryRef 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/parser > DocumentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/parser > IDocumentDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/parser > operationName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/parser > parser 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/parser > verifyDocumentType 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/ssr > RenderPromises 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/ssr > getDataFromTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/ssr > getMarkupFromTree 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/react/ssr > renderToStringWithData 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockLinkOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockLinkOptions } from \"@apollo/client/testing\";\n-type _Test_MockLinkOptions = MockLinkOptions;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_MockLinkOptions = MockLink.Options;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockSubscriptionLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockedProvider 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockedProvider } from \"@apollo/client/testing\";\n+import { MockedProvider } from \"@apollo/client/testing/react\";\n class _Test_MockedProvider extends MockedProvider {}\n const _test_MockedProvider = new MockedProvider(props)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockedProviderProps 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockedProviderProps } from \"@apollo/client/testing\";\n+import type { MockedProviderProps } from \"@apollo/client/testing/react\";\n type _Test_MockedProviderProps = MockedProviderProps<TSerializedCache>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > MockedResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockedResponse } from \"@apollo/client/testing\";\n-type _Test_MockedResponse = MockedResponse<TData, TVariables>;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_MockedResponse = MockLink.MockedResponse<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > ResultFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ResultFunction } from \"@apollo/client/testing\";\n-type _Test_ResultFunction = ResultFunction<T, V>;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_ResultFunction = MockLink.ResultFunction<T, V>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > createMockClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > itAsync 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > mockObservableLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > mockSingleLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > subscribeAndCount 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > tick 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > wait 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > withErrorSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > withLogSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing > withWarningSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > MockLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockLink } from \"@apollo/client/testing/core\";\n+import { MockLink } from \"@apollo/client/testing\";\n class _Test_MockLink extends MockLink {}\n const _test_MockLink = new MockLink(mockedResponses, addTypename, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > MockLinkOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockLinkOptions } from \"@apollo/client/testing/core\";\n-type _Test_MockLinkOptions = MockLinkOptions;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_MockLinkOptions = MockLink.Options;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > MockSubscriptionLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockSubscriptionLink } from \"@apollo/client/testing/core\";\n+import { MockSubscriptionLink } from \"@apollo/client/testing\";\n class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\n const _test_MockSubscriptionLink = new MockSubscriptionLink()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > MockedResponse 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { MockedResponse } from \"@apollo/client/testing/core\";\n-type _Test_MockedResponse = MockedResponse<TData, TVariables>;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_MockedResponse = MockLink.MockedResponse<TData, TVariables>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > ResultFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { ResultFunction } from \"@apollo/client/testing/core\";\n-type _Test_ResultFunction = ResultFunction<T, V>;\n\\\\ No newline at end of file\n+import { MockLink } from \"@apollo/client/testing\";\n+type _Test_ResultFunction = MockLink.ResultFunction<T, V>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > createMockClient 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createMockClient } from \"@apollo/client/testing/core\";\n+import { createMockClient } from \"@apollo/client/testing\";\n createMockClient<TData>(data, query, variables)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > itAsync 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { itAsync } from \"@apollo/client/testing/core\";\n+import { itAsync } from \"@apollo/client/testing\";\n const _Test_itAsync = itAsync;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > mockObservableLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mockObservableLink } from \"@apollo/client/testing/core\";\n+import { mockObservableLink } from \"@apollo/client/testing\";\n mockObservableLink()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > mockSingleLink 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mockSingleLink } from \"@apollo/client/testing/core\";\n+import { mockSingleLink } from \"@apollo/client/testing\";\n mockSingleLink(mockedResponses)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > subscribeAndCount 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { subscribeAndCount } from \"@apollo/client/testing/core\";\n+import { subscribeAndCount } from \"@apollo/client/testing\";\n subscribeAndCount<TResult>(reject, observable, cb)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > tick 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { tick } from \"@apollo/client/testing/core\";\n+import { tick } from \"@apollo/client/testing\";\n tick()\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > wait 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { wait } from \"@apollo/client/testing/core\";\n+import { wait } from \"@apollo/client/testing\";\n wait(ms)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > withErrorSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { withErrorSpy } from \"@apollo/client/testing/core\";\n+import { withErrorSpy } from \"@apollo/client/testing\";\n withErrorSpy<TArgs, TResult>(it, args)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > withLogSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { withLogSpy } from \"@apollo/client/testing/core\";\n+import { withLogSpy } from \"@apollo/client/testing\";\n withLogSpy<TArgs, TResult>(it, args)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/core > withWarningSpy 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { withWarningSpy } from \"@apollo/client/testing/core\";\n+import { withWarningSpy } from \"@apollo/client/testing\";\n withWarningSpy<TArgs, TResult>(it, args)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/experimental > createSchemaFetch 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/testing/experimental > createTestSchema 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > AsStoreObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > AutoCleanedStrongCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { AutoCleanedStrongCache } from \"@apollo/client/utilities\";\n+import { AutoCleanedStrongCache } from \"@apollo/client/utilities/internal\";\n const _Test_AutoCleanedStrongCache = AutoCleanedStrongCache;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > AutoCleanedWeakCache 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { AutoCleanedWeakCache } from \"@apollo/client/utilities\";\n+import { AutoCleanedWeakCache } from \"@apollo/client/utilities/internal\";\n const _Test_AutoCleanedWeakCache = AutoCleanedWeakCache;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > CacheSizes 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Concast 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > ConcastSourcesArray 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > ConcastSourcesIterable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DEV 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DEV } from \"@apollo/client/utilities\";\n-const _Test_DEV = DEV;\n\\\\ No newline at end of file\n+const _Test_DEV = __DEV__;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DeepMerger 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DeepMerger } from \"@apollo/client/utilities\";\n+import { DeepMerger } from \"@apollo/client/utilities/internal\";\n class _Test_DeepMerger extends DeepMerger<TContextArgs> {}\n const _test_DeepMerger = new DeepMerger<TContextArgs>(reconciler)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DeepOmit 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { DeepOmit } from \"@apollo/client/utilities\";\n+import type { DeepOmit } from \"@apollo/client/utilities/internal\";\n type _Test_DeepOmit = DeepOmit<T, K>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DeepPartial 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DirectiveInfo 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Directives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DocumentTransform 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > DocumentTransformCacheKey 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > FragmentMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FragmentMap } from \"@apollo/client/utilities\";\n+import type { FragmentMap } from \"@apollo/client/utilities/internal\";\n type _Test_FragmentMap = FragmentMap;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > FragmentMapFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { FragmentMapFunction } from \"@apollo/client/utilities\";\n+import type { FragmentMapFunction } from \"@apollo/client/utilities/internal\";\n type _Test_FragmentMapFunction = FragmentMapFunction;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > GetDirectiveConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > GetFragmentSpreadConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > GetNodeConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > InclusionDirectives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > IsStrictlyAny 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > NoInfer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { NoInfer } from \"@apollo/client/utilities\";\n+import type { NoInfer } from \"@apollo/client/utilities/internal\";\n type _Test_NoInfer = NoInfer<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Observable 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > ObservableSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Observer 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > OnlyRequiredProperties 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Prettify 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Prettify } from \"@apollo/client/utilities\";\n+import type { Prettify } from \"@apollo/client/utilities/internal\";\n type _Test_Prettify = Prettify<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Primitive 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { Primitive } from \"@apollo/client/utilities\";\n+import type { Primitive } from \"@apollo/client/utilities/internal\";\n type _Test_Primitive = Primitive;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > PromiseWithState 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > ReconcilerFunction 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > Reference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveArgumentsConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveDirectiveConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveFragmentDefinitionConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveFragmentSpreadConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveIndexSignature 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { RemoveIndexSignature } from \"@apollo/client/utilities\";\n+import type { RemoveIndexSignature } from \"@apollo/client/utilities/internal\";\n type _Test_RemoveIndexSignature = RemoveIndexSignature<T>;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveNodeConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > RemoveVariableDefinitionConfig 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > StoreObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > StoreValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > TupleToIntersection 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > UnionToIntersection 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > VariableValue 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > addNonReactiveToNamedFragments 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > addTypenameToDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > argumentsObjectFromField 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { argumentsObjectFromField } from \"@apollo/client/utilities\";\n+import { argumentsObjectFromField } from \"@apollo/client/utilities/internal\";\n argumentsObjectFromField(field, variables)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > asyncMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > buildQueryFromSelectionSet 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > cacheSizes 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseAsyncIteratorSymbol 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseDOM 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { canUseDOM } from \"@apollo/client/utilities\";\n+import { canUseDOM } from \"@apollo/client/utilities/internal\";\n const _Test_canUseDOM = canUseDOM;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseLayoutEffect 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseSymbol 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseWeakMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canUseWeakSet 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > canonicalStringify 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > checkDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { checkDocument } from \"@apollo/client/utilities\";\n+import { checkDocument } from \"@apollo/client/utilities/internal\";\n checkDocument(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > cloneDeep 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { cloneDeep } from \"@apollo/client/utilities\";\n+import { cloneDeep } from \"@apollo/client/utilities/internal\";\n cloneDeep<T>(value)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > compact 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { compact } from \"@apollo/client/utilities\";\n+import { compact } from \"@apollo/client/utilities/internal\";\n compact<TArgs>(objects)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > concatPagination 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > createFragmentMap 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createFragmentMap } from \"@apollo/client/utilities\";\n+import { createFragmentMap } from \"@apollo/client/utilities/internal\";\n createFragmentMap(fragments)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > createFulfilledPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createFulfilledPromise } from \"@apollo/client/utilities\";\n+import { createFulfilledPromise } from \"@apollo/client/utilities/internal\";\n createFulfilledPromise<TValue>(value)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > createRejectedPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { createRejectedPromise } from \"@apollo/client/utilities\";\n+import { createRejectedPromise } from \"@apollo/client/utilities/internal\";\n createRejectedPromise<TValue>(reason)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > defaultCacheSizes 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > fixObservableSubclass 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getDefaultValues 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getDefaultValues } from \"@apollo/client/utilities\";\n+import { getDefaultValues } from \"@apollo/client/utilities/internal\";\n getDefaultValues(definition)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getDirectiveNames 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getFragmentDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getFragmentDefinition } from \"@apollo/client/utilities\";\n+import { getFragmentDefinition } from \"@apollo/client/utilities/internal\";\n getFragmentDefinition(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getFragmentDefinitions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getFragmentDefinitions } from \"@apollo/client/utilities\";\n+import { getFragmentDefinitions } from \"@apollo/client/utilities/internal\";\n getFragmentDefinitions(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getFragmentFromSelection 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getFragmentFromSelection } from \"@apollo/client/utilities\";\n+import { getFragmentFromSelection } from \"@apollo/client/utilities/internal\";\n getFragmentFromSelection(selection, fragmentMap)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getFragmentMaskMode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getFragmentQueryDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getFragmentQueryDocument } from \"@apollo/client/utilities\";\n+import { getFragmentQueryDocument } from \"@apollo/client/utilities/internal\";\n getFragmentQueryDocument(document, fragmentName)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getGraphQLErrorsFromResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getGraphQLErrorsFromResult } from \"@apollo/client/utilities\";\n+import { getGraphQLErrorsFromResult } from \"@apollo/client/utilities/internal\";\n getGraphQLErrorsFromResult<T>(result)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getInclusionDirectives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getMainDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getOperationDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getOperationDefinition } from \"@apollo/client/utilities\";\n+import { getOperationDefinition } from \"@apollo/client/utilities/internal\";\n getOperationDefinition(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getOperationName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getOperationName } from \"@apollo/client/utilities\";\n+import { getOperationName } from \"@apollo/client/utilities/internal\";\n getOperationName(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getQueryDefinition 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getQueryDefinition } from \"@apollo/client/utilities\";\n+import { getQueryDefinition } from \"@apollo/client/utilities/internal\";\n getQueryDefinition(doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getStoreKeyName 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { getStoreKeyName } from \"@apollo/client/utilities\";\n+import { getStoreKeyName } from \"@apollo/client/utilities/internal\";\n const _Test_getStoreKeyName = getStoreKeyName;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > getTypenameFromResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > graphQLResultHasError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { graphQLResultHasError } from \"@apollo/client/utilities\";\n+import { graphQLResultHasError } from \"@apollo/client/utilities/internal\";\n graphQLResultHasError<T>(result)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > hasAllDirectives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > hasAnyDirectives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > hasClientExports 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > hasDirectives 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { hasDirectives } from \"@apollo/client/utilities\";\n+import { hasDirectives } from \"@apollo/client/utilities/internal\";\n hasDirectives(names, root, all)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isApolloPayloadResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isArray 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isArray } from \"@apollo/client/utilities\";\n+import { isArray } from \"@apollo/client/utilities/internal\";\n const _Test_isArray = isArray;\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isDocumentNode 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isDocumentNode } from \"@apollo/client/utilities\";\n+import { isDocumentNode } from \"@apollo/client/utilities/internal\";\n isDocumentNode(value)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isExecutionPatchIncrementalResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isExecutionPatchInitialResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isExecutionPatchResult 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isField 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isField } from \"@apollo/client/utilities\";\n+import { isField } from \"@apollo/client/utilities/internal\";\n isField(selection)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isFullyUnmaskedOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isInlineFragment 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isMutationOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isNonEmptyArray 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isNonEmptyArray } from \"@apollo/client/utilities\";\n+import { isNonEmptyArray } from \"@apollo/client/utilities/internal\";\n isNonEmptyArray<T>(value)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isNonNullObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isNonNullObject } from \"@apollo/client/utilities\";\n+import { isNonNullObject } from \"@apollo/client/utilities/internal\";\n isNonNullObject(obj)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isPlainObject 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { isPlainObject } from \"@apollo/client/utilities\";\n+import { isPlainObject } from \"@apollo/client/utilities/internal\";\n isPlainObject(obj)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isQueryOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isStatefulPromise 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > isSubscriptionOperation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > iterateObserversSafely 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > makeReference 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeReference } from \"@apollo/client/utilities\";\n+import { makeReference } from \"@apollo/client/utilities/internal\";\n makeReference(id)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > makeUniqueId 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { makeUniqueId } from \"@apollo/client/utilities\";\n+import { makeUniqueId } from \"@apollo/client/utilities/internal\";\n makeUniqueId(prefix)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > maybe 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { maybe } from \"@apollo/client/utilities\";\n maybe<T>(thunk)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > maybeDeepFreeze 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { maybeDeepFreeze } from \"@apollo/client/utilities\";\n+import { maybeDeepFreeze } from \"@apollo/client/utilities/internal\";\n maybeDeepFreeze<T>(obj)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > mergeDeep 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mergeDeep } from \"@apollo/client/utilities\";\n+import { mergeDeep } from \"@apollo/client/utilities/internal\";\n mergeDeep<T>(sources)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > mergeDeepArray 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mergeDeepArray } from \"@apollo/client/utilities\";\n+import { mergeDeepArray } from \"@apollo/client/utilities/internal\";\n mergeDeepArray<T>(sources)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > mergeIncrementalData 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > mergeOptions 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { mergeOptions } from \"@apollo/client/utilities\";\n+import { mergeOptions } from \"@apollo/client/utilities/internal\";\n mergeOptions<TDefaultOptions, TOptions>(defaults, options)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > offsetLimitPagination 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > omitDeep 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { omitDeep } from \"@apollo/client/utilities\";\n+import { omitDeep } from \"@apollo/client/utilities/internal\";\n omitDeep<T, K>(value, key)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > preventUnhandledRejection 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { preventUnhandledRejection } from \"@apollo/client/utilities\";\n+import { preventUnhandledRejection } from \"@apollo/client/utilities/internal\";\n preventUnhandledRejection<T>(promise)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > print 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > relayStylePagination 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > removeArgumentsFromDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > removeClientSetsFromDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > removeConnectionDirectiveFromDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > removeDirectivesFromDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { removeDirectivesFromDocument } from \"@apollo/client/utilities\";\n+import { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\n removeDirectivesFromDocument(directives, doc)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > removeFragmentSpreadFromDocument 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > resultKeyNameFromField 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { resultKeyNameFromField } from \"@apollo/client/utilities\";\n+import { resultKeyNameFromField } from \"@apollo/client/utilities/internal\";\n resultKeyNameFromField(field)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > shouldInclude 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { shouldInclude } from \"@apollo/client/utilities\";\n+import { shouldInclude } from \"@apollo/client/utilities/internal\";\n shouldInclude(param0, variables)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > storeKeyNameFromField 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { storeKeyNameFromField } from \"@apollo/client/utilities\";\n+import { storeKeyNameFromField } from \"@apollo/client/utilities/internal\";\n storeKeyNameFromField(field, variables)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > stringifyForDisplay 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n-import { stringifyForDisplay } from \"@apollo/client/utilities\";\n+import { stringifyForDisplay } from \"@apollo/client/utilities/internal\";\n stringifyForDisplay(value, space)\n\\\\ No newline at end of file\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > stripTypename 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > valueToObjectRepresentation 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities > wrapPromiseWithState 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > ___DEV__ 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > DEV 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > InvariantError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > global 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > invariant 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > maybe 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/globals > newInvariantError 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n\nexports[`individual exports > @apollo/client/utilities/subscriptions/relay > createFetchMultipartSubscription 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n\"\n`;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/__snapshots__/removals.test.ts.snap",
    "content": "// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html\n\nexports[`all exports 1`] = `\n\"Index: test.ts\n===================================================================\n--- test.ts\toriginal\n+++ test.ts\ttransformed\n@@  @@\n   WatchFragmentOptions as cache_WatchFragmentOptions,\n   WatchFragmentResult as cache_WatchFragmentResult,\n   ApolloCache as cache_ApolloCache,\n   Cache as cache_Cache,\n-  DataProxy as cache_DataProxy,\n   MissingTree as cache_MissingTree,\n   Modifier as cache_Modifier,\n   Modifiers as cache_Modifiers,\n   ModifierDetails as cache_ModifierDetails,\n@@  @@\n   WatchQueryFetchPolicy as _WatchQueryFetchPolicy,\n   MutationFetchPolicy as _MutationFetchPolicy,\n   RefetchWritePolicy as _RefetchWritePolicy,\n   ErrorPolicy as _ErrorPolicy,\n-  FetchMoreQueryOptions as _FetchMoreQueryOptions,\n   SubscribeToMoreOptions as _SubscribeToMoreOptions,\n   SubscribeToMoreFunction as _SubscribeToMoreFunction,\n   UpdateQueryMapFn as _UpdateQueryMapFn,\n   UpdateQueryOptions as _UpdateQueryOptions,\n   SubscribeToMoreUpdateQueryFn as _SubscribeToMoreUpdateQueryFn,\n   NetworkStatus as _NetworkStatus,\n   isNetworkRequestSettled as _isNetworkRequestSettled,\n-  Resolver as _Resolver,\n-  FragmentMatcher as _FragmentMatcher,\n-  isApolloError as _isApolloError,\n-  ApolloError as _ApolloError,\n   Transaction as _Transaction,\n-  DataProxy as _DataProxy,\n   InMemoryCacheConfig as _InMemoryCacheConfig,\n   ReactiveVar as _ReactiveVar,\n   TypePolicies as _TypePolicies,\n   TypePolicy as _TypePolicy,\n@@  @@\n   MissingFieldError as _MissingFieldError,\n   defaultDataIdFromObject as _defaultDataIdFromObject,\n   makeVar as _makeVar,\n   ServerError as _ServerError,\n-  fromError as _fromError,\n-  toPromise as _toPromise,\n-  fromPromise as _fromPromise,\n-  throwServerError as _throwServerError,\n   DataMasking as _DataMasking,\n   FragmentType as _FragmentType,\n   Masked as _Masked,\n   MaskedDocumentNode as _MaskedDocumentNode,\n   MaybeMasked as _MaybeMasked,\n   Unmasked as _Unmasked,\n   DocumentTransformCacheKey as _DocumentTransformCacheKey,\n-  Observer as _Observer,\n-  ObservableSubscription as _ObservableSubscription,\n   Reference as _Reference,\n   StoreObject as _StoreObject,\n   DocumentTransform as _DocumentTransform,\n   Observable as _Observable,\n@@  @@\n   disableFragmentWarnings as _disableFragmentWarnings,\n   enableExperimentalFragmentVariables as _enableExperimentalFragmentVariables,\n   disableExperimentalFragmentVariables as _disableExperimentalFragmentVariables,\n   TypedDocumentNode as _TypedDocumentNode,\n-  MethodKeys as _MethodKeys,\n   DefaultContext as _DefaultContext,\n   OnQueryUpdated as _OnQueryUpdated,\n   RefetchQueryDescriptor as _RefetchQueryDescriptor,\n   InternalRefetchQueryDescriptor as _InternalRefetchQueryDescriptor,\n@@  @@\n   RefetchQueriesResult as _RefetchQueriesResult,\n   InternalRefetchQueriesOptions as _InternalRefetchQueriesOptions,\n   InternalRefetchQueriesResult as _InternalRefetchQueriesResult,\n   InternalRefetchQueriesMap as _InternalRefetchQueriesMap,\n-  PureQueryOptions as _PureQueryOptions,\n   OperationVariables as _OperationVariables,\n   ApolloQueryResult as _ApolloQueryResult,\n   MutationQueryReducer as _MutationQueryReducer,\n   MutationQueryReducersMap as _MutationQueryReducersMap,\n-  MutationUpdaterFn as _MutationUpdaterFn,\n   MutationUpdaterFunction as _MutationUpdaterFunction,\n-  Resolvers as _Resolvers,\n   StoreValue as _StoreValue,\n   IdGetterObj as _IdGetterObj,\n   IdGetter as _IdGetter,\n   NormalizedCache as _NormalizedCache,\n@@  @@\n   NextLink as _NextLink,\n   RequestHandler as _RequestHandler,\n   ServerParseError as _ServerParseError,\n   parseAndCheckHttpResponse as _parseAndCheckHttpResponse,\n-  ClientParseError as _ClientParseError,\n-  serializeFetchParameter as _serializeFetchParameter,\n   HttpOptions as _HttpOptions,\n   UriFunction as _UriFunction,\n   fallbackHttpConfig as _fallbackHttpConfig,\n   defaultPrinter as _defaultPrinter,\n@@  @@\n   HttpLink as _HttpLink,\n   rewriteURIForGET as _rewriteURIForGET,\n   ApolloContextValue as _ApolloContextValue,\n   ApolloProvider as _ApolloProvider,\n-  ApolloConsumer as _ApolloConsumer,\n   getApolloContext as _getApolloContext,\n-  resetApolloContext as _resetApolloContext,\n-  IDocumentDefinition as _IDocumentDefinition,\n-  DocumentType as _DocumentType,\n-  operationName as _operationName,\n-  parser as _parser,\n   PreloadQueryOptions as _PreloadQueryOptions,\n   PreloadQueryFetchPolicy as _PreloadQueryFetchPolicy,\n   PreloadQueryFunction as _PreloadQueryFunction,\n   createQueryPreloader as _createQueryPreloader,\n@@  @@\n   QueryReference as _QueryReference,\n   QueryRef as _QueryRef,\n   PreloadedQueryRef as _PreloadedQueryRef,\n   Context as _Context,\n-  CommonOptions as _CommonOptions,\n-  BaseQueryOptions as _BaseQueryOptions,\n   QueryFunctionOptions as _QueryFunctionOptions,\n-  ObservableQueryFields as _ObservableQueryFields,\n   QueryResult as _QueryResult,\n-  QueryDataOptions as _QueryDataOptions,\n   QueryHookOptions as _QueryHookOptions,\n   LazyQueryHookOptions as _LazyQueryHookOptions,\n   LazyQueryHookExecOptions as _LazyQueryHookExecOptions,\n   SuspenseQueryHookFetchPolicy as _SuspenseQueryHookFetchPolicy,\n@@  @@\n   BackgroundQueryHookFetchPolicy as _BackgroundQueryHookFetchPolicy,\n   BackgroundQueryHookOptions as _BackgroundQueryHookOptions,\n   LoadableQueryHookFetchPolicy as _LoadableQueryHookFetchPolicy,\n   LoadableQueryHookOptions as _LoadableQueryHookOptions,\n-  QueryLazyOptions as _QueryLazyOptions,\n   LazyQueryResult as _LazyQueryResult,\n   QueryTuple as _QueryTuple,\n   LazyQueryExecFunction as _LazyQueryExecFunction,\n   LazyQueryResultTuple as _LazyQueryResultTuple,\n-  RefetchQueriesFunction as _RefetchQueriesFunction,\n-  BaseMutationOptions as _BaseMutationOptions,\n   MutationFunctionOptions as _MutationFunctionOptions,\n   MutationResult as _MutationResult,\n   MutationFunction as _MutationFunction,\n   MutationHookOptions as _MutationHookOptions,\n-  MutationDataOptions as _MutationDataOptions,\n   MutationTuple as _MutationTuple,\n   OnDataOptions as _OnDataOptions,\n   OnSubscriptionDataOptions as _OnSubscriptionDataOptions,\n   BaseSubscriptionOptions as _BaseSubscriptionOptions,\n   SubscriptionResult as _SubscriptionResult,\n   SubscriptionHookOptions as _SubscriptionHookOptions,\n   SubscriptionDataOptions as _SubscriptionDataOptions,\n-  SubscriptionCurrentObservable as _SubscriptionCurrentObservable,\n   VariablesOption as _VariablesOption,\n   NoInfer as _NoInfer,\n } from \"@apollo/client\";\n \n import {\n+  ApolloError as _ApolloError,\n+  DataProxy as _DataProxy,\n+  fromError as _fromError,\n+  fromPromise as _fromPromise,\n+  isApolloError as _isApolloError,\n+  ObservableSubscription as _ObservableSubscription,\n+  Observer as _Observer,\n+  serializeFetchParameter as _serializeFetchParameter,\n+  throwServerError as _throwServerError,\n+  toPromise as _toPromise,\n+  OperationBatcher as link_batch_OperationBatcher,\n+  transformOperation as link_utils_transformOperation,\n+  validateOperation as link_utils_validateOperation,\n+  ApolloConsumer as react_ApolloConsumer,\n+  DocumentType as react_DocumentType,\n+  operationName as react_operationName,\n+  parser as react_parser,\n+  resetApolloContext as react_resetApolloContext,\n+  Mutation as react_components_Mutation,\n+  Query as react_components_Query,\n+  Subscription as react_components_Subscription,\n+  graphql as react_hoc_graphql,\n+  withApollo as react_hoc_withApollo,\n+  withMutation as react_hoc_withMutation,\n+  withQuery as react_hoc_withQuery,\n+  withSubscription as react_hoc_withSubscription,\n+  verifyDocumentType as react_parser_verifyDocumentType,\n+  RenderPromises as react_ssr_RenderPromises,\n+  createMockClient as testing_createMockClient,\n+  itAsync as testing_itAsync,\n+  mockObservableLink as testing_mockObservableLink,\n+  mockSingleLink as testing_mockSingleLink,\n+  subscribeAndCount as testing_subscribeAndCount,\n+  tick as testing_tick,\n+  wait as testing_wait,\n+  withErrorSpy as testing_withErrorSpy,\n+  withLogSpy as testing_withLogSpy,\n+  withWarningSpy as testing_withWarningSpy,\n+  createSchemaFetch as testing_experimental_createSchemaFetch,\n+  createTestSchema as testing_experimental_createTestSchema,\n+  addNonReactiveToNamedFragments as utilities_addNonReactiveToNamedFragments,\n+  asyncMap as utilities_asyncMap,\n+  buildQueryFromSelectionSet as utilities_buildQueryFromSelectionSet,\n+  canUseAsyncIteratorSymbol as utilities_canUseAsyncIteratorSymbol,\n+  canUseLayoutEffect as utilities_canUseLayoutEffect,\n+  canUseSymbol as utilities_canUseSymbol,\n+  canUseWeakMap as utilities_canUseWeakMap,\n+  canUseWeakSet as utilities_canUseWeakSet,\n+  Concast as utilities_Concast,\n+  defaultCacheSizes as utilities_defaultCacheSizes,\n+  fixObservableSubclass as utilities_fixObservableSubclass,\n+  getDirectiveNames as utilities_getDirectiveNames,\n+  getFragmentMaskMode as utilities_getFragmentMaskMode,\n+  getInclusionDirectives as utilities_getInclusionDirectives,\n+  getTypenameFromResult as utilities_getTypenameFromResult,\n+  hasAllDirectives as utilities_hasAllDirectives,\n+  hasAnyDirectives as utilities_hasAnyDirectives,\n+  hasClientExports as utilities_hasClientExports,\n+  isApolloPayloadResult as utilities_isApolloPayloadResult,\n+  isExecutionPatchIncrementalResult as utilities_isExecutionPatchIncrementalResult,\n+  isExecutionPatchInitialResult as utilities_isExecutionPatchInitialResult,\n+  isExecutionPatchResult as utilities_isExecutionPatchResult,\n+  isFullyUnmaskedOperation as utilities_isFullyUnmaskedOperation,\n+  isInlineFragment as utilities_isInlineFragment,\n+  isStatefulPromise as utilities_isStatefulPromise,\n+  iterateObserversSafely as utilities_iterateObserversSafely,\n+  mergeIncrementalData as utilities_mergeIncrementalData,\n+  removeArgumentsFromDocument as utilities_removeArgumentsFromDocument,\n+  removeClientSetsFromDocument as utilities_removeClientSetsFromDocument,\n+  removeConnectionDirectiveFromDocument as utilities_removeConnectionDirectiveFromDocument,\n+  removeFragmentSpreadFromDocument as utilities_removeFragmentSpreadFromDocument,\n+  valueToObjectRepresentation as utilities_valueToObjectRepresentation,\n+} from \"@apollo/client/v4-migration\";\n+\n+import type {\n+  ClientParseError as _ClientParseError,\n+  ClientParseError as core_ClientParseError,\n+  FetchMoreQueryOptions as _FetchMoreQueryOptions,\n+  FetchMoreQueryOptions as core_FetchMoreQueryOptions,\n+  FragmentMatcher as _FragmentMatcher,\n+  FragmentMatcher as core_FragmentMatcher,\n+  MethodKeys as _MethodKeys,\n+  MethodKeys as core_MethodKeys,\n+  MutationUpdaterFn as _MutationUpdaterFn,\n+  MutationUpdaterFn as core_MutationUpdaterFn,\n+  PureQueryOptions as _PureQueryOptions,\n+  PureQueryOptions as core_PureQueryOptions,\n+  Resolver as _Resolver,\n+  Resolver as core_Resolver,\n+  Resolvers as _Resolvers,\n+  Resolvers as core_Resolvers,\n+  ApolloErrorOptions as errors_ApolloErrorOptions,\n+  GraphQLErrors as errors_GraphQLErrors,\n+  NetworkError as errors_NetworkError,\n+  BatchableRequest as link_batch_BatchableRequest,\n+  ClientParseError as link_http_ClientParseError,\n+  BaseMutationOptions as react_BaseMutationOptions,\n+  BaseMutationOptions as _BaseMutationOptions,\n+  BaseQueryOptions as react_BaseQueryOptions,\n+  BaseQueryOptions as _BaseQueryOptions,\n+  CommonOptions as react_CommonOptions,\n+  CommonOptions as _CommonOptions,\n+  IDocumentDefinition as react_IDocumentDefinition,\n+  IDocumentDefinition as _IDocumentDefinition,\n+  MutationDataOptions as react_MutationDataOptions,\n+  MutationDataOptions as _MutationDataOptions,\n+  ObservableQueryFields as react_ObservableQueryFields,\n+  ObservableQueryFields as _ObservableQueryFields,\n+  QueryDataOptions as react_QueryDataOptions,\n+  QueryDataOptions as _QueryDataOptions,\n+  QueryLazyOptions as react_QueryLazyOptions,\n+  QueryLazyOptions as _QueryLazyOptions,\n+  RefetchQueriesFunction as react_RefetchQueriesFunction,\n+  RefetchQueriesFunction as _RefetchQueriesFunction,\n+  SubscriptionCurrentObservable as react_SubscriptionCurrentObservable,\n+  SubscriptionCurrentObservable as _SubscriptionCurrentObservable,\n+  MutationComponentOptions as react_components_MutationComponentOptions,\n+  QueryComponentOptions as react_components_QueryComponentOptions,\n+  SubscriptionComponentOptions as react_components_SubscriptionComponentOptions,\n+  ApolloConsumerProps as react_context_ApolloConsumerProps,\n+  ChildDataProps as react_hoc_ChildDataProps,\n+  ChildMutateProps as react_hoc_ChildMutateProps,\n+  ChildProps as react_hoc_ChildProps,\n+  DataProps as react_hoc_DataProps,\n+  DataValue as react_hoc_DataValue,\n+  MutateProps as react_hoc_MutateProps,\n+  OperationOption as react_hoc_OperationOption,\n+  OptionProps as react_hoc_OptionProps,\n+  QueryControls as react_hoc_QueryControls,\n+  WithApolloClient as react_hoc_WithApolloClient,\n+  IDocumentDefinition as react_parser_IDocumentDefinition,\n+  ConcastSourcesArray as utilities_ConcastSourcesArray,\n+  ConcastSourcesIterable as utilities_ConcastSourcesIterable,\n+  DirectiveInfo as utilities_DirectiveInfo,\n+  Directives as utilities_Directives,\n+  GetDirectiveConfig as utilities_GetDirectiveConfig,\n+  GetFragmentSpreadConfig as utilities_GetFragmentSpreadConfig,\n+  GetNodeConfig as utilities_GetNodeConfig,\n+  InclusionDirectives as utilities_InclusionDirectives,\n+  IsStrictlyAny as utilities_IsStrictlyAny,\n+  OnlyRequiredProperties as utilities_OnlyRequiredProperties,\n+  PromiseWithState as utilities_PromiseWithState,\n+  ReconcilerFunction as utilities_ReconcilerFunction,\n+  RemoveArgumentsConfig as utilities_RemoveArgumentsConfig,\n+  RemoveDirectiveConfig as utilities_RemoveDirectiveConfig,\n+  RemoveFragmentDefinitionConfig as utilities_RemoveFragmentDefinitionConfig,\n+  RemoveFragmentSpreadConfig as utilities_RemoveFragmentSpreadConfig,\n+  RemoveNodeConfig as utilities_RemoveNodeConfig,\n+  RemoveVariableDefinitionConfig as utilities_RemoveVariableDefinitionConfig,\n+  TupleToIntersection as utilities_TupleToIntersection,\n+  UnionToIntersection as utilities_UnionToIntersection,\n+  VariableValue as utilities_VariableValue,\n+} from \"@apollo/client/v4-migration\";\n+\n+import {\n   ApolloClientOptions as core_ApolloClientOptions,\n   DefaultOptions as core_DefaultOptions,\n   ApolloClient as core_ApolloClient,\n   mergeOptions as core_mergeOptions,\n@@  @@\n   WatchQueryFetchPolicy as core_WatchQueryFetchPolicy,\n   MutationFetchPolicy as core_MutationFetchPolicy,\n   RefetchWritePolicy as core_RefetchWritePolicy,\n   ErrorPolicy as core_ErrorPolicy,\n-  FetchMoreQueryOptions as core_FetchMoreQueryOptions,\n   SubscribeToMoreOptions as core_SubscribeToMoreOptions,\n   SubscribeToMoreFunction as core_SubscribeToMoreFunction,\n   UpdateQueryMapFn as core_UpdateQueryMapFn,\n   UpdateQueryOptions as core_UpdateQueryOptions,\n   SubscribeToMoreUpdateQueryFn as core_SubscribeToMoreUpdateQueryFn,\n   NetworkStatus as core_NetworkStatus,\n   isNetworkRequestSettled as core_isNetworkRequestSettled,\n-  Resolver as core_Resolver,\n-  FragmentMatcher as core_FragmentMatcher,\n-  isApolloError as core_isApolloError,\n-  ApolloError as core_ApolloError,\n   Transaction as core_Transaction,\n-  DataProxy as core_DataProxy,\n   InMemoryCacheConfig as core_InMemoryCacheConfig,\n   ReactiveVar as core_ReactiveVar,\n   TypePolicies as core_TypePolicies,\n   TypePolicy as core_TypePolicy,\n@@  @@\n   MissingFieldError as core_MissingFieldError,\n   defaultDataIdFromObject as core_defaultDataIdFromObject,\n   makeVar as core_makeVar,\n   ServerError as core_ServerError,\n-  fromError as core_fromError,\n-  toPromise as core_toPromise,\n-  fromPromise as core_fromPromise,\n-  throwServerError as core_throwServerError,\n   DataMasking as core_DataMasking,\n   FragmentType as core_FragmentType,\n   Masked as core_Masked,\n   MaskedDocumentNode as core_MaskedDocumentNode,\n   MaybeMasked as core_MaybeMasked,\n   Unmasked as core_Unmasked,\n   DocumentTransformCacheKey as core_DocumentTransformCacheKey,\n-  Observer as core_Observer,\n-  ObservableSubscription as core_ObservableSubscription,\n   Reference as core_Reference,\n   StoreObject as core_StoreObject,\n   DocumentTransform as core_DocumentTransform,\n   Observable as core_Observable,\n@@  @@\n   disableFragmentWarnings as core_disableFragmentWarnings,\n   enableExperimentalFragmentVariables as core_enableExperimentalFragmentVariables,\n   disableExperimentalFragmentVariables as core_disableExperimentalFragmentVariables,\n   TypedDocumentNode as core_TypedDocumentNode,\n-  MethodKeys as core_MethodKeys,\n   DefaultContext as core_DefaultContext,\n   OnQueryUpdated as core_OnQueryUpdated,\n   RefetchQueryDescriptor as core_RefetchQueryDescriptor,\n   InternalRefetchQueryDescriptor as core_InternalRefetchQueryDescriptor,\n@@  @@\n   RefetchQueriesResult as core_RefetchQueriesResult,\n   InternalRefetchQueriesOptions as core_InternalRefetchQueriesOptions,\n   InternalRefetchQueriesResult as core_InternalRefetchQueriesResult,\n   InternalRefetchQueriesMap as core_InternalRefetchQueriesMap,\n-  PureQueryOptions as core_PureQueryOptions,\n   OperationVariables as core_OperationVariables,\n   ApolloQueryResult as core_ApolloQueryResult,\n   MutationQueryReducer as core_MutationQueryReducer,\n   MutationQueryReducersMap as core_MutationQueryReducersMap,\n-  MutationUpdaterFn as core_MutationUpdaterFn,\n   MutationUpdaterFunction as core_MutationUpdaterFunction,\n-  Resolvers as core_Resolvers,\n   StoreValue as core_StoreValue,\n   IdGetterObj as core_IdGetterObj,\n   IdGetter as core_IdGetter,\n   NormalizedCache as core_NormalizedCache,\n@@  @@\n   NextLink as core_NextLink,\n   RequestHandler as core_RequestHandler,\n   ServerParseError as core_ServerParseError,\n   parseAndCheckHttpResponse as core_parseAndCheckHttpResponse,\n-  ClientParseError as core_ClientParseError,\n-  serializeFetchParameter as core_serializeFetchParameter,\n   HttpOptions as core_HttpOptions,\n   UriFunction as core_UriFunction,\n   fallbackHttpConfig as core_fallbackHttpConfig,\n   defaultPrinter as core_defaultPrinter,\n@@  @@\n } from \"@apollo/client/dev\";\n \n import {\n   graphQLResultHasProtocolErrors as errors_graphQLResultHasProtocolErrors,\n-  isApolloError as errors_isApolloError,\n   PROTOCOL_ERRORS_SYMBOL as errors_PROTOCOL_ERRORS_SYMBOL,\n-  ApolloErrorOptions as errors_ApolloErrorOptions,\n-  GraphQLErrors as errors_GraphQLErrors,\n-  NetworkError as errors_NetworkError,\n-  ApolloError as errors_ApolloError,\n } from \"@apollo/client/errors\";\n \n-import {\n-  BatchableRequest as link_batch_BatchableRequest,\n-  BatchHandler as link_batch_BatchHandler,\n-  OperationBatcher as link_batch_OperationBatcher,\n-  BatchLink as link_batch_BatchLink,\n-} from \"@apollo/client/link/batch\";\n+import { BatchHandler as link_batch_BatchHandler, BatchLink as link_batch_BatchLink } from \"@apollo/client/link/batch\";\n \n import {\n   BatchHttpLink as link_batch_http_BatchHttpLink,\n } from \"@apollo/client/link/batch-http\";\n@@  @@\n \n import {\n   ServerParseError as link_http_ServerParseError,\n   parseAndCheckHttpResponse as link_http_parseAndCheckHttpResponse,\n-  ClientParseError as link_http_ClientParseError,\n-  serializeFetchParameter as link_http_serializeFetchParameter,\n   HttpOptions as link_http_HttpOptions,\n   UriFunction as link_http_UriFunction,\n   fallbackHttpConfig as link_http_fallbackHttpConfig,\n   defaultPrinter as link_http_defaultPrinter,\n@@  @@\n   GraphQLWsLink as link_subscriptions_GraphQLWsLink,\n } from \"@apollo/client/link/subscriptions\";\n \n import {\n-  fromError as link_utils_fromError,\n-  toPromise as link_utils_toPromise,\n-  fromPromise as link_utils_fromPromise,\n   ServerError as link_utils_ServerError,\n-  throwServerError as link_utils_throwServerError,\n-  validateOperation as link_utils_validateOperation,\n   createOperation as link_utils_createOperation,\n-  transformOperation as link_utils_transformOperation,\n   filterOperationVariables as link_utils_filterOperationVariables,\n } from \"@apollo/client/link/utils\";\n \n import {\n@@  @@\n \n import {\n   ApolloContextValue as react_ApolloContextValue,\n   ApolloProvider as react_ApolloProvider,\n-  ApolloConsumer as react_ApolloConsumer,\n   getApolloContext as react_getApolloContext,\n-  resetApolloContext as react_resetApolloContext,\n-  IDocumentDefinition as react_IDocumentDefinition,\n-  DocumentType as react_DocumentType,\n-  operationName as react_operationName,\n-  parser as react_parser,\n   PreloadQueryOptions as react_PreloadQueryOptions,\n   PreloadQueryFetchPolicy as react_PreloadQueryFetchPolicy,\n   PreloadQueryFunction as react_PreloadQueryFunction,\n   createQueryPreloader as react_createQueryPreloader,\n@@  @@\n   QueryReference as react_QueryReference,\n   QueryRef as react_QueryRef,\n   PreloadedQueryRef as react_PreloadedQueryRef,\n   Context as react_Context,\n-  CommonOptions as react_CommonOptions,\n-  BaseQueryOptions as react_BaseQueryOptions,\n   QueryFunctionOptions as react_QueryFunctionOptions,\n-  ObservableQueryFields as react_ObservableQueryFields,\n   QueryResult as react_QueryResult,\n-  QueryDataOptions as react_QueryDataOptions,\n   QueryHookOptions as react_QueryHookOptions,\n   LazyQueryHookOptions as react_LazyQueryHookOptions,\n   LazyQueryHookExecOptions as react_LazyQueryHookExecOptions,\n   SuspenseQueryHookFetchPolicy as react_SuspenseQueryHookFetchPolicy,\n@@  @@\n   BackgroundQueryHookFetchPolicy as react_BackgroundQueryHookFetchPolicy,\n   BackgroundQueryHookOptions as react_BackgroundQueryHookOptions,\n   LoadableQueryHookFetchPolicy as react_LoadableQueryHookFetchPolicy,\n   LoadableQueryHookOptions as react_LoadableQueryHookOptions,\n-  QueryLazyOptions as react_QueryLazyOptions,\n   LazyQueryResult as react_LazyQueryResult,\n   QueryTuple as react_QueryTuple,\n   LazyQueryExecFunction as react_LazyQueryExecFunction,\n   LazyQueryResultTuple as react_LazyQueryResultTuple,\n-  RefetchQueriesFunction as react_RefetchQueriesFunction,\n-  BaseMutationOptions as react_BaseMutationOptions,\n   MutationFunctionOptions as react_MutationFunctionOptions,\n   MutationResult as react_MutationResult,\n   MutationFunction as react_MutationFunction,\n   MutationHookOptions as react_MutationHookOptions,\n-  MutationDataOptions as react_MutationDataOptions,\n   MutationTuple as react_MutationTuple,\n   OnDataOptions as react_OnDataOptions,\n   OnSubscriptionDataOptions as react_OnSubscriptionDataOptions,\n   BaseSubscriptionOptions as react_BaseSubscriptionOptions,\n   SubscriptionResult as react_SubscriptionResult,\n   SubscriptionHookOptions as react_SubscriptionHookOptions,\n   SubscriptionDataOptions as react_SubscriptionDataOptions,\n-  SubscriptionCurrentObservable as react_SubscriptionCurrentObservable,\n   VariablesOption as react_VariablesOption,\n   NoInfer as react_NoInfer,\n } from \"@apollo/client/react\";\n \n import {\n-  Query as react_components_Query,\n-  Mutation as react_components_Mutation,\n-  Subscription as react_components_Subscription,\n-  QueryComponentOptions as react_components_QueryComponentOptions,\n-  MutationComponentOptions as react_components_MutationComponentOptions,\n-  SubscriptionComponentOptions as react_components_SubscriptionComponentOptions,\n-} from \"@apollo/client/react/components\";\n-\n-import {\n-  ApolloConsumerProps as react_context_ApolloConsumerProps,\n-  ApolloConsumer as react_context_ApolloConsumer,\n   ApolloContextValue as react_context_ApolloContextValue,\n   getApolloContext as react_context_getApolloContext,\n-  resetApolloContext as react_context_resetApolloContext,\n   ApolloProviderProps as react_context_ApolloProviderProps,\n   ApolloProvider as react_context_ApolloProvider,\n } from \"@apollo/client/react/context\";\n \n import {\n-  graphql as react_hoc_graphql,\n-  withQuery as react_hoc_withQuery,\n-  withMutation as react_hoc_withMutation,\n-  withSubscription as react_hoc_withSubscription,\n-  withApollo as react_hoc_withApollo,\n-  QueryControls as react_hoc_QueryControls,\n-  DataValue as react_hoc_DataValue,\n-  DataProps as react_hoc_DataProps,\n-  MutateProps as react_hoc_MutateProps,\n-  ChildProps as react_hoc_ChildProps,\n-  ChildDataProps as react_hoc_ChildDataProps,\n-  ChildMutateProps as react_hoc_ChildMutateProps,\n-  OptionProps as react_hoc_OptionProps,\n-  OperationOption as react_hoc_OperationOption,\n-  WithApolloClient as react_hoc_WithApolloClient,\n-} from \"@apollo/client/react/hoc\";\n-\n-import {\n   useQuery as react_hooks_useQuery,\n   UseSuspenseQueryResult as react_hooks_UseSuspenseQueryResult,\n   useSuspenseQuery as react_hooks_useSuspenseQuery,\n   UseBackgroundQueryResult as react_hooks_UseBackgroundQueryResult,\n@@  @@\n   HookWrappers as react_internal_HookWrappers,\n } from \"@apollo/client/react/internal\";\n \n import {\n-  operationName as react_parser_operationName,\n-  parser as react_parser_parser,\n-  verifyDocumentType as react_parser_verifyDocumentType,\n-  DocumentType as react_parser_DocumentType,\n-  IDocumentDefinition as react_parser_IDocumentDefinition,\n-} from \"@apollo/client/react/parser\";\n-\n-import {\n   getMarkupFromTree as react_ssr_getMarkupFromTree,\n   getDataFromTree as react_ssr_getDataFromTree,\n   renderToStringWithData as react_ssr_renderToStringWithData,\n-  RenderPromises as react_ssr_RenderPromises,\n } from \"@apollo/client/react/ssr\";\n \n import {\n   MockedProviderProps as testing_MockedProviderProps,\n@@  @@\n   MockedResponse as testing_MockedResponse,\n   MockLinkOptions as testing_MockLinkOptions,\n   ResultFunction as testing_ResultFunction,\n   MockLink as testing_MockLink,\n-  mockSingleLink as testing_mockSingleLink,\n   MockSubscriptionLink as testing_MockSubscriptionLink,\n-  mockObservableLink as testing_mockObservableLink,\n-  createMockClient as testing_createMockClient,\n-  subscribeAndCount as testing_subscribeAndCount,\n-  itAsync as testing_itAsync,\n-  wait as testing_wait,\n-  tick as testing_tick,\n-  withErrorSpy as testing_withErrorSpy,\n-  withWarningSpy as testing_withWarningSpy,\n-  withLogSpy as testing_withLogSpy,\n } from \"@apollo/client/testing\";\n \n import {\n   MockedResponse as testing_core_MockedResponse,\n   MockLinkOptions as testing_core_MockLinkOptions,\n   ResultFunction as testing_core_ResultFunction,\n   MockLink as testing_core_MockLink,\n-  mockSingleLink as testing_core_mockSingleLink,\n   MockSubscriptionLink as testing_core_MockSubscriptionLink,\n-  mockObservableLink as testing_core_mockObservableLink,\n-  createMockClient as testing_core_createMockClient,\n-  subscribeAndCount as testing_core_subscribeAndCount,\n-  itAsync as testing_core_itAsync,\n   wait as testing_core_wait,\n-  tick as testing_core_tick,\n-  withErrorSpy as testing_core_withErrorSpy,\n-  withWarningSpy as testing_core_withWarningSpy,\n-  withLogSpy as testing_core_withLogSpy,\n } from \"@apollo/client/testing/core\";\n \n import {\n-  createTestSchema as testing_experimental_createTestSchema,\n-  createSchemaFetch as testing_experimental_createSchemaFetch,\n-} from \"@apollo/client/testing/experimental\";\n-\n-import {\n   DEV as utilities_DEV,\n   maybe as utilities_maybe,\n-  DirectiveInfo as utilities_DirectiveInfo,\n-  InclusionDirectives as utilities_InclusionDirectives,\n   shouldInclude as utilities_shouldInclude,\n   hasDirectives as utilities_hasDirectives,\n-  hasAnyDirectives as utilities_hasAnyDirectives,\n-  hasAllDirectives as utilities_hasAllDirectives,\n-  hasClientExports as utilities_hasClientExports,\n-  getDirectiveNames as utilities_getDirectiveNames,\n-  getInclusionDirectives as utilities_getInclusionDirectives,\n-  getFragmentMaskMode as utilities_getFragmentMaskMode,\n   DocumentTransformCacheKey as utilities_DocumentTransformCacheKey,\n   DocumentTransform as utilities_DocumentTransform,\n   FragmentMap as utilities_FragmentMap,\n   FragmentMapFunction as utilities_FragmentMapFunction,\n   createFragmentMap as utilities_createFragmentMap,\n   getFragmentQueryDocument as utilities_getFragmentQueryDocument,\n   getFragmentFromSelection as utilities_getFragmentFromSelection,\n-  isFullyUnmaskedOperation as utilities_isFullyUnmaskedOperation,\n   checkDocument as utilities_checkDocument,\n   getOperationDefinition as utilities_getOperationDefinition,\n   getOperationName as utilities_getOperationName,\n   getFragmentDefinitions as utilities_getFragmentDefinitions,\n@@  @@\n   StoreObject as utilities_StoreObject,\n   AsStoreObject as utilities_AsStoreObject,\n   Reference as utilities_Reference,\n   StoreValue as utilities_StoreValue,\n-  Directives as utilities_Directives,\n-  VariableValue as utilities_VariableValue,\n   makeReference as utilities_makeReference,\n   isDocumentNode as utilities_isDocumentNode,\n   isReference as utilities_isReference,\n   isField as utilities_isField,\n-  isInlineFragment as utilities_isInlineFragment,\n-  valueToObjectRepresentation as utilities_valueToObjectRepresentation,\n   storeKeyNameFromField as utilities_storeKeyNameFromField,\n   argumentsObjectFromField as utilities_argumentsObjectFromField,\n   resultKeyNameFromField as utilities_resultKeyNameFromField,\n   getStoreKeyName as utilities_getStoreKeyName,\n-  getTypenameFromResult as utilities_getTypenameFromResult,\n-  RemoveNodeConfig as utilities_RemoveNodeConfig,\n-  GetNodeConfig as utilities_GetNodeConfig,\n-  RemoveDirectiveConfig as utilities_RemoveDirectiveConfig,\n-  GetDirectiveConfig as utilities_GetDirectiveConfig,\n-  RemoveArgumentsConfig as utilities_RemoveArgumentsConfig,\n-  GetFragmentSpreadConfig as utilities_GetFragmentSpreadConfig,\n-  RemoveFragmentSpreadConfig as utilities_RemoveFragmentSpreadConfig,\n-  RemoveFragmentDefinitionConfig as utilities_RemoveFragmentDefinitionConfig,\n-  RemoveVariableDefinitionConfig as utilities_RemoveVariableDefinitionConfig,\n   addTypenameToDocument as utilities_addTypenameToDocument,\n-  addNonReactiveToNamedFragments as utilities_addNonReactiveToNamedFragments,\n-  buildQueryFromSelectionSet as utilities_buildQueryFromSelectionSet,\n   removeDirectivesFromDocument as utilities_removeDirectivesFromDocument,\n-  removeConnectionDirectiveFromDocument as utilities_removeConnectionDirectiveFromDocument,\n-  removeArgumentsFromDocument as utilities_removeArgumentsFromDocument,\n-  removeFragmentSpreadFromDocument as utilities_removeFragmentSpreadFromDocument,\n-  removeClientSetsFromDocument as utilities_removeClientSetsFromDocument,\n   isMutationOperation as utilities_isMutationOperation,\n   isQueryOperation as utilities_isQueryOperation,\n   isSubscriptionOperation as utilities_isSubscriptionOperation,\n   concatPagination as utilities_concatPagination,\n   offsetLimitPagination as utilities_offsetLimitPagination,\n   relayStylePagination as utilities_relayStylePagination,\n-  Observer as utilities_Observer,\n-  ObservableSubscription as utilities_ObservableSubscription,\n   Observable as utilities_Observable,\n-  PromiseWithState as utilities_PromiseWithState,\n-  isStatefulPromise as utilities_isStatefulPromise,\n   createFulfilledPromise as utilities_createFulfilledPromise,\n   createRejectedPromise as utilities_createRejectedPromise,\n   wrapPromiseWithState as utilities_wrapPromiseWithState,\n   preventUnhandledRejection as utilities_preventUnhandledRejection,\n@@  @@\n   omitDeep as utilities_omitDeep,\n   stripTypename as utilities_stripTypename,\n   DeepOmit as utilities_DeepOmit,\n   DeepPartial as utilities_DeepPartial,\n-  OnlyRequiredProperties as utilities_OnlyRequiredProperties,\n   Prettify as utilities_Prettify,\n   Primitive as utilities_Primitive,\n-  UnionToIntersection as utilities_UnionToIntersection,\n   NoInfer as utilities_NoInfer,\n   RemoveIndexSignature as utilities_RemoveIndexSignature,\n   AutoCleanedStrongCache as utilities_AutoCleanedStrongCache,\n   AutoCleanedWeakCache as utilities_AutoCleanedWeakCache,\n   cacheSizes as utilities_cacheSizes,\n-  defaultCacheSizes as utilities_defaultCacheSizes,\n   CacheSizes as utilities_CacheSizes,\n   mergeDeep as utilities_mergeDeep,\n   mergeDeepArray as utilities_mergeDeepArray,\n-  TupleToIntersection as utilities_TupleToIntersection,\n-  ReconcilerFunction as utilities_ReconcilerFunction,\n   DeepMerger as utilities_DeepMerger,\n   cloneDeep as utilities_cloneDeep,\n-  iterateObserversSafely as utilities_iterateObserversSafely,\n-  asyncMap as utilities_asyncMap,\n-  ConcastSourcesIterable as utilities_ConcastSourcesIterable,\n-  ConcastSourcesArray as utilities_ConcastSourcesArray,\n-  Concast as utilities_Concast,\n-  fixObservableSubclass as utilities_fixObservableSubclass,\n   isNonEmptyArray as utilities_isNonEmptyArray,\n   isArray as utilities_isArray,\n   isNonNullObject as utilities_isNonNullObject,\n   isPlainObject as utilities_isPlainObject,\n   graphQLResultHasError as utilities_graphQLResultHasError,\n   getGraphQLErrorsFromResult as utilities_getGraphQLErrorsFromResult,\n-  canUseWeakMap as utilities_canUseWeakMap,\n-  canUseWeakSet as utilities_canUseWeakSet,\n-  canUseSymbol as utilities_canUseSymbol,\n-  canUseAsyncIteratorSymbol as utilities_canUseAsyncIteratorSymbol,\n   canUseDOM as utilities_canUseDOM,\n-  canUseLayoutEffect as utilities_canUseLayoutEffect,\n   compact as utilities_compact,\n   makeUniqueId as utilities_makeUniqueId,\n   stringifyForDisplay as utilities_stringifyForDisplay,\n   mergeOptions as utilities_mergeOptions,\n-  isExecutionPatchIncrementalResult as utilities_isExecutionPatchIncrementalResult,\n-  isExecutionPatchInitialResult as utilities_isExecutionPatchInitialResult,\n-  isExecutionPatchResult as utilities_isExecutionPatchResult,\n-  isApolloPayloadResult as utilities_isApolloPayloadResult,\n-  mergeIncrementalData as utilities_mergeIncrementalData,\n-  IsStrictlyAny as utilities_IsStrictlyAny,\n } from \"@apollo/client/utilities\";\n \n import {\n   maybe as utilities_globals_maybe,\n\"\n`;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/apolloClientInitialization.test.ts",
    "content": "import { applyTransform } from \"jscodeshift/dist/testUtils\";\nimport { describe, expect, test } from \"vitest\";\n\nimport type { Steps } from \"../apolloClientInitialization.js\";\nimport apolloClientInitializationTransform from \"../apolloClientInitialization.js\";\n\nconst transform =\n  (...enabledSteps: Steps[]) =>\n  ([source]: TemplateStringsArray) =>\n    applyTransform(\n      apolloClientInitializationTransform,\n      {\n        apolloClientInitialization:\n          enabledSteps.length > 0 ? enabledSteps : undefined,\n      },\n      { source, path: \"test.ts\" },\n      { parser: \"ts\" }\n    );\n\ndescribe(\"all transforms\", () => {\n  test(\"kitchen sink 1\", () => {\n    expect(transform()`\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nexport const client = new ApolloClient<MyCacheShape>({\n  uri: \"/graphql\",\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n  cache: new InMemoryCache(),\n  ssrForceFetchDelay: 50,\n  ssrMode: true,\n  connectToDevTools: true,\n  queryDeduplication: true,\n  defaultOptions: {},\n  defaultContext: {},\n  assumeImmutableResults: true,\n  resolvers: myResolvers,\n  typeDefs: mySchema,\n  fragmentMatcher: () => true,\n  name: \"my-client\",\n  version: \"1.0.0\",\n  documentTransform: myDocumentTransform,\n  dataMasking: true\n  })\n    `).toMatchInlineSnapshot(`\n      \"import { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\n      import { Defer20220824Handler } from \"@apollo/client/incremental\";\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      export const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        ssrForceFetchDelay: 50,\n        ssrMode: true,\n        queryDeduplication: true,\n        defaultOptions: {},\n        defaultContext: {},\n        assumeImmutableResults: true,\n        documentTransform: myDocumentTransform,\n\n        /*\n        Inserted by Apollo Client 3->4 migration codemod.\n        Keep this comment here if you intend to run the codemod again,\n        to avoid changes from being reapplied.\n        Delete this comment once you are done with the migration.\n        @apollo/client-codemod-migrate-3-to-4 applied\n        */\n        dataMasking: true,\n\n        link: new HttpLink({\n          uri: \"/graphql\",\n          credentials: \"include\",\n\n          headers: {\n            \"x-custom-header\": \"value\",\n          }\n        }),\n\n        clientAwareness: {\n          name: \"my-client\",\n          version: \"1.0.0\"\n        },\n\n        localState: new LocalState({\n          resolvers: myResolvers\n        }),\n\n        devtools: {\n          enabled: true\n        },\n\n        /*\n        Inserted by Apollo Client 3->4 migration codemod.\n        If you are not using the \\`@defer\\` directive in your application,\n        you can safely remove this option.\n        */\n        incrementalHandler: new Defer20220824Handler()\n      })\n\n      /*\n      Start: Inserted by Apollo Client 3->4 migration codemod.\n      Copy the contents of this block into a \\`.d.ts\\` file in your project\n      to enable data masking types.\n      */\n\n\n      import \"@apollo/client\";\n      import { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\n      declare module \"@apollo/client\" {\n        export interface TypeOverrides extends GraphQLCodegenDataMasking.TypeOverrides {}\n      }\n\n      /*\n      End: Inserted by Apollo Client 3->4 migration codemod.\n      */\n\n\n      /*\n      Start: Inserted by Apollo Client 3->4 migration codemod.\n      Copy the contents of this block into a \\`.d.ts\\` file in your project to enable correct response types in your custom links.\n      If you do not use the \\`@defer\\` directive in your application, you can safely remove this block.\n      */\n\n\n      import \"@apollo/client\";\n      import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n      declare module \"@apollo/client\" {\n        export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n      }\n\n      /*\n      End: Inserted by Apollo Client 3->4 migration codemod.\n      */\"\n    `);\n  });\n\n  test(\"Apollo Client renamed\", () => {\n    expect(transform()`\nimport { ApolloClient as RenamedApolloClient, SomethingElse as ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nexport const dontTouchThis: ApolloClient<MyCacheShape> = new ApolloClient<MyCacheShape>({\n  uri: \"/graphql\",\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n  cache: new InMemoryCache(),\n  ssrForceFetchDelay: 50,\n  ssrMode: true,\n  connectToDevTools: true,\n  queryDeduplication: true,\n  defaultOptions: {},\n  defaultContext: {},\n  assumeImmutableResults: true,\n  resolvers: myResolvers,\n  typeDefs: mySchema,\n  fragmentMatcher: () => true,\n  name: \"my-client\",\n  version: \"1.0.0\",\n  documentTransform: myDocumentTransform,\n  dataMasking: true\n  })\n\n  export const transformThis: RenamedApolloClient<MyCacheShape> = new RenamedApolloClient<MyCacheShape>({\n  uri: \"/graphql\",\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n  cache: new InMemoryCache(),\n  ssrForceFetchDelay: 50,\n  ssrMode: true,\n  connectToDevTools: true,\n  queryDeduplication: true,\n  defaultOptions: {},\n  defaultContext: {},\n  assumeImmutableResults: true,\n  resolvers: myResolvers,\n  typeDefs: mySchema,\n  fragmentMatcher: () => true,\n  name: \"my-client\",\n  version: \"1.0.0\",\n  documentTransform: myDocumentTransform,\n  dataMasking: true\n  })\n    `).toMatchInlineSnapshot(`\n      \"import {\n        ApolloClient as RenamedApolloClient,\n        SomethingElse as ApolloClient,\n        InMemoryCache,\n        HttpLink,\n      } from \"@apollo/client\";\n\n      import { Defer20220824Handler } from \"@apollo/client/incremental\";\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      export const dontTouchThis: ApolloClient<MyCacheShape> = new ApolloClient<MyCacheShape>({\n        uri: \"/graphql\",\n        credentials: \"include\",\n        headers: {\n          \"x-custom-header\": \"value\",\n        },\n        cache: new InMemoryCache(),\n        ssrForceFetchDelay: 50,\n        ssrMode: true,\n        connectToDevTools: true,\n        queryDeduplication: true,\n        defaultOptions: {},\n        defaultContext: {},\n        assumeImmutableResults: true,\n        resolvers: myResolvers,\n        typeDefs: mySchema,\n        fragmentMatcher: () => true,\n        name: \"my-client\",\n        version: \"1.0.0\",\n        documentTransform: myDocumentTransform,\n        dataMasking: true\n        })\n\n      export const transformThis: RenamedApolloClient = new RenamedApolloClient({\n        cache: new InMemoryCache(),\n        ssrForceFetchDelay: 50,\n        ssrMode: true,\n        queryDeduplication: true,\n        defaultOptions: {},\n        defaultContext: {},\n        assumeImmutableResults: true,\n        documentTransform: myDocumentTransform,\n\n        /*\n        Inserted by Apollo Client 3->4 migration codemod.\n        Keep this comment here if you intend to run the codemod again,\n        to avoid changes from being reapplied.\n        Delete this comment once you are done with the migration.\n        @apollo/client-codemod-migrate-3-to-4 applied\n        */\n        dataMasking: true,\n\n        link: new HttpLink({\n          uri: \"/graphql\",\n          credentials: \"include\",\n\n          headers: {\n            \"x-custom-header\": \"value\",\n          }\n        }),\n\n        clientAwareness: {\n          name: \"my-client\",\n          version: \"1.0.0\"\n        },\n\n        localState: new LocalState({\n          resolvers: myResolvers\n        }),\n\n        devtools: {\n          enabled: true\n        },\n\n        /*\n        Inserted by Apollo Client 3->4 migration codemod.\n        If you are not using the \\`@defer\\` directive in your application,\n        you can safely remove this option.\n        */\n        incrementalHandler: new Defer20220824Handler()\n      })\n\n      /*\n      Start: Inserted by Apollo Client 3->4 migration codemod.\n      Copy the contents of this block into a \\`.d.ts\\` file in your project\n      to enable data masking types.\n      */\n\n\n      import \"@apollo/client\";\n      import { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\n      declare module \"@apollo/client\" {\n        export interface TypeOverrides extends GraphQLCodegenDataMasking.TypeOverrides {}\n      }\n\n      /*\n      End: Inserted by Apollo Client 3->4 migration codemod.\n      */\n\n\n      /*\n      Start: Inserted by Apollo Client 3->4 migration codemod.\n      Copy the contents of this block into a \\`.d.ts\\` file in your project to enable correct response types in your custom links.\n      If you do not use the \\`@defer\\` directive in your application, you can safely remove this block.\n      */\n\n\n      import \"@apollo/client\";\n      import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n      declare module \"@apollo/client\" {\n        export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n      }\n\n      /*\n      End: Inserted by Apollo Client 3->4 migration codemod.\n      */\"\n    `);\n  });\n});\n\ndescribe(\"http link initialization\", () => {\n  test(\"all options\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  uri: \"https://example.com/graphql\",\n  cache: new InMemoryCache(),\n  credentials: \"include\",\n  devtools: { enabled: true },\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient, HttpLink } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        devtools: { enabled: true },\n\n        link: new HttpLink({\n          uri: \"https://example.com/graphql\",\n          credentials: \"include\",\n\n          headers: {\n            \"x-custom-header\": \"value\",\n          }\n        })\n      })\"\n    `);\n  });\n\n  test(\"only uri\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  uri: \"https://example.com/graphql\",\n  devtools: { enabled: true },\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        devtools: { enabled: true },\n        link: new HttpLink({\n          uri: \"https://example.com/graphql\"\n        }),\n      })\"\n    `);\n  });\n\n  test(\"HttpLink import already there\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient } from \"@apollo/client\";\nimport { HttpLink } from \"@apollo/client/link/http\";\n\nnew ApolloClient({\n  uri: \"https://example.com/graphql\",\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n      import { HttpLink } from \"@apollo/client/link/http\";\n\n      new ApolloClient({\n        link: new HttpLink({\n          uri: \"https://example.com/graphql\",\n          credentials: \"include\",\n\n          headers: {\n            \"x-custom-header\": \"value\",\n          }\n        })\n      })\"\n    `);\n  });\n\n  test(\"HttpLink entry point already there\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient } from \"@apollo/client\";\nimport { defaultPrinter } from \"@apollo/client/link/http\";\n\nnew ApolloClient({\n  uri: \"https://example.com/graphql\",\n  credentials: \"include\",\n  headers: {\n    \"x-custom-header\": \"value\",\n  },\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n      import { defaultPrinter, HttpLink } from \"@apollo/client/link/http\";\n\n      new ApolloClient({\n        link: new HttpLink({\n          uri: \"https://example.com/graphql\",\n          credentials: \"include\",\n\n          headers: {\n            \"x-custom-header\": \"value\",\n          }\n        })\n      })\"\n    `);\n  });\n\n  test(\"link already present inline\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient } from \"@apollo/client\";\nimport { BatchHttpLink } from \"@apollo/client/link/batch-http\";\n\nnew ApolloClient({\n  link: new BatchHttpLink({\n    uri: \"http://localhost:4000/graphql\",\n    batchMax: 5,\n    batchInterval: 20\n  })\n})\n`\n    ).toMatchInlineSnapshot(`\"\"`);\n  });\n\n  test(\"link already present shorthand\", () => {\n    expect(\n      transform(\"explicitLinkConstruction\")`\nimport { ApolloClient } from \"@apollo/client\";\nimport { BatchHttpLink } from \"@apollo/client/link/batch-http\";\n\nconst link = new BatchHttpLink({\n  uri: \"http://localhost:4000/graphql\",\n  batchMax: 5,\n  batchInterval: 20\n});\n\nnew ApolloClient({\n  link\n})\n`\n    ).toMatchInlineSnapshot(`\"\"`);\n  });\n});\n\ndescribe(\"client awareness\", () => {\n  test(\"name and version\", () => {\n    expect(\n      transform(\"clientAwareness\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  name: \"my-client\",\n  version: \"1.0.0\",\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n\n        clientAwareness: {\n          name: \"my-client\",\n          version: \"1.0.0\"\n        }\n      })\"\n    `);\n  });\n  test(\"name only\", () => {\n    expect(\n      transform(\"clientAwareness\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  name: \"my-client\",\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        clientAwareness: {\n          name: \"my-client\"\n        },\n      })\"\n    `);\n  });\n  test(\"version only\", () => {\n    expect(\n      transform(\"clientAwareness\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  version: \"1.0.0\",\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        clientAwareness: {\n          version: \"1.0.0\"\n        },\n      })\"\n    `);\n  });\n});\n\ndescribe(\"local state\", () => {\n  test(\"with resolvers inline\", () => {\n    expect(\n      transform(\"localState\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  resolvers: {\n    foo: () => \"bar\",\n  }\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        localState: new LocalState({\n          resolvers: {\n            foo: () => \"bar\",\n          }\n        })\n      })\"\n    `);\n  });\n  test(\"with resolvers variable\", () => {\n    expect(\n      transform(\"localState\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst myResolvers = {}\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  resolvers: myResolvers\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      const myResolvers = {}\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        localState: new LocalState({\n          resolvers: myResolvers\n        })\n      })\"\n    `);\n  });\n  test(\"with resolvers variable (shorthand)\", () => {\n    expect(\n      transform(\"localState\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst resolvers = {}\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  resolvers\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      const resolvers = {}\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        localState: new LocalState({\n          resolvers\n        })\n      })\"\n    `);\n  });\n  test(\"without resolvers\", () => {\n    expect(\n      transform(\"localState\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      import { LocalState } from \"@apollo/client/local-state\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n\n        /*\n        Inserted by Apollo Client 3->4 migration codemod.\n        If you are not using the \\`@client\\` directive in your application,\n        you can safely remove this option.\n        */\n        localState: new LocalState({})\n      })\"\n    `);\n  });\n});\n\ndescribe(\"devtools option\", () => {\n  test(\"`true`\", () => {\n    expect(\n      transform(\"devtoolsOption\")`\nimport { ApolloClient } from \"@apollo/client\";\n\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  connectToDevTools: true\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        devtools: {\n          enabled: true\n        }\n      })\"\n    `);\n  });\n  test(\"`false`\", () => {\n    expect(\n      transform(\"devtoolsOption\")`\nimport { ApolloClient } from \"@apollo/client\";\n\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  connectToDevTools: false\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        devtools: {\n          enabled: false\n        }\n      })\"\n    `);\n  });\n  test(\"variable\", () => {\n    expect(\n      transform(\"devtoolsOption\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst shouldConnectToDevTools = process.env.NODE_ENV === 'development';\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  // see if this comment moves around too\n  connectToDevTools: shouldConnectToDevTools\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      const shouldConnectToDevTools = process.env.NODE_ENV === 'development';\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        devtools: {\n          // see if this comment moves around too\n          enabled: shouldConnectToDevTools\n        }\n      })\"\n    `);\n  });\n  test(\"process.env.NODE_ENV === 'development'\", () => {\n    expect(\n      transform(\"devtoolsOption\")`\nimport { ApolloClient } from \"@apollo/client\";\n\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  connectToDevTools: process.env.NODE_ENV === 'development'\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        devtools: {\n          enabled: process.env.NODE_ENV === 'development'\n        }\n      })\"\n    `);\n  });\n  test(\"shorthand\", () => {\n    expect(\n      transform(\"devtoolsOption\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst connectToDevTools = process.env.NODE_ENV === 'development';\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  connectToDevTools\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      const connectToDevTools = process.env.NODE_ENV === 'development';\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        devtools: {\n          enabled: connectToDevTools\n        }\n      })\"\n    `);\n  });\n});\n\ndescribe(\"disableNetworkFetches option\", () => {\n  test(\"`true`\", () => {\n    expect(\n      transform(\"prioritizeCacheValues\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  disableNetworkFetches: true\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        prioritizeCacheValues: true\n      })\"\n    `);\n  });\n  test(\"`false`\", () => {\n    expect(\n      transform(\"prioritizeCacheValues\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  disableNetworkFetches: false\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        prioritizeCacheValues: false\n      })\"\n    `);\n  });\n  test(\"variable\", () => {\n    expect(\n      transform(\"prioritizeCacheValues\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst onServer = typeof window === \"undefined\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  disableNetworkFetches: onServer\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      const onServer = typeof window === \"undefined\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        prioritizeCacheValues: onServer\n      })\"\n    `);\n  });\n  test(\"shorthand\", () => {\n    expect(\n      transform(\"prioritizeCacheValues\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nconst disableNetworkFetches = typeof window === \"undefined\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  disableNetworkFetches\n})\n`\n    ).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      const disableNetworkFetches = typeof window === \"undefined\";\n\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: someLink,\n        prioritizeCacheValues: disableNetworkFetches\n      })\"\n    `);\n  });\n});\ndescribe(\"dataMasking types\", () => {\n  test(\"applied if `dataMasking` is set\", () => {\n    expect(transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  dataMasking: true,\n})\n      `).toMatchInlineSnapshot(`\n        \"import { ApolloClient } from \"@apollo/client\";\n\n        new ApolloClient({\n          cache: new InMemoryCache(),\n          link: someLink,\n          /*\n          Inserted by Apollo Client 3->4 migration codemod.\n          Keep this comment here if you intend to run the codemod again,\n          to avoid changes from being reapplied.\n          Delete this comment once you are done with the migration.\n          @apollo/client-codemod-migrate-3-to-4 applied\n          */\n          dataMasking: true,\n        })\n\n        /*\n        Start: Inserted by Apollo Client 3->4 migration codemod.\n        Copy the contents of this block into a \\`.d.ts\\` file in your project\n        to enable data masking types.\n        */\n\n\n        import \"@apollo/client\";\n        import { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\n\n        declare module \"@apollo/client\" {\n          export interface TypeOverrides extends GraphQLCodegenDataMasking.TypeOverrides {}\n        }\n\n        /*\n        End: Inserted by Apollo Client 3->4 migration codemod.\n        */\"\n      `);\n  });\n\n  test(\"not applied if `dataMasking` is not set`\", () => {\n    expect(transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n})\n      `).toMatchInlineSnapshot(`\"\"`);\n  });\n\n  test(\"not applied if `dataMasking` is set to `false`\", () => {\n    expect(transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  dataMasking: false,\n})\n      `).toMatchInlineSnapshot(`\"\"`);\n  });\n\n  test(\"does not reapply on a second run (full comment in place)\", () => {\n    const once = transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  dataMasking: true,\n})\n      `;\n    const twice = transform(\"dataMasking\")([once] as any);\n    expect(twice).toEqual(\"\" /* empty string -> no transformation */);\n  });\n\n  test(\"does not reapply on a second run (full comment in place, added code moved out)\", () => {\n    expect(transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  /*\n  Inserted by Apollo Client 3->4 migration codemod.\n  Keep this comment here if you intend to run the codemod again,\n  to avoid changes from being reapplied.\n  Delete this comment once you are done with the migration.\n  @apollo/client-codemod-migrate-3-to-4 applied\n  */\n  dataMasking: true,\n})\n      `).toMatchInlineSnapshot(`\"\"`);\n  });\n\n  test(\"does not reapply on a second run (only marker left in place, added code moved out)\", () => {\n    expect(transform(\"dataMasking\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  /* @apollo/client-codemod-migrate-3-to-4 applied */\n  dataMasking: true,\n})\n      `).toMatchInlineSnapshot(`\"\"`);\n  });\n});\n\ndescribe(\"incrementalHandler\", () => {\n  test(\"added to ApolloClient constructor options\", () => {\n    expect(transform(\"incrementalHandler\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n})\n      `).toMatchInlineSnapshot(`\n        \"import { ApolloClient } from \"@apollo/client\";\n\n        import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n        new ApolloClient({\n          cache: new InMemoryCache(),\n          link: someLink,\n\n          /*\n          Inserted by Apollo Client 3->4 migration codemod.\n          If you are not using the \\`@defer\\` directive in your application,\n          you can safely remove this option.\n          */\n          incrementalHandler: new Defer20220824Handler()\n        })\n\n        /*\n        Start: Inserted by Apollo Client 3->4 migration codemod.\n        Copy the contents of this block into a \\`.d.ts\\` file in your project to enable correct response types in your custom links.\n        If you do not use the \\`@defer\\` directive in your application, you can safely remove this block.\n        */\n\n\n        import \"@apollo/client\";\n        import { Defer20220824Handler } from \"@apollo/client/incremental\";\n\n        declare module \"@apollo/client\" {\n          export interface TypeOverrides extends Defer20220824Handler.TypeOverrides {}\n        }\n\n        /*\n        End: Inserted by Apollo Client 3->4 migration codemod.\n        */\"\n      `);\n  });\n\n  test(\"not added to ApolloClient constructor options if an `incrementalHandler` option is already present\", () => {\n    expect(transform(\"incrementalHandler\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient({\n  cache: new InMemoryCache(),\n  link: someLink,\n  incrementalHandler: undefined\n})\n      `).toMatchInlineSnapshot(`\"\"`);\n  });\n});\n\ndescribe(\"removeTypeArguments\", () => {\n  test(\"remove constructor type argument\", () => {\n    expect(transform(\"removeTypeArguments\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nnew ApolloClient<CacheShape>({\n  cache: new InMemoryCache(),\n  link: someLink,\n})\n      `).toMatchInlineSnapshot(`\n        \"import { ApolloClient } from \"@apollo/client\";\n\n        new ApolloClient({\n          cache: new InMemoryCache(),\n          link: someLink,\n        })\"\n      `);\n  });\n\n  test(\"removes type arguments for usages of `ApolloClient` as a type\", () => {\n    expect(transform(\"removeTypeArguments\")`\nimport { ApolloClient } from \"@apollo/client\";\n\nfunction test(client: ApolloClient<unknown>): ApolloClient<any> {\n  return client;\n}\n    `).toMatchInlineSnapshot(`\n      \"import { ApolloClient } from \"@apollo/client\";\n\n      function test(client: ApolloClient): ApolloClient {\n        return client;\n      }\"\n    `);\n  });\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/diffTransform.ts",
    "content": "import { createPatch } from \"diff\";\nimport type { Transform } from \"jscodeshift\";\nimport { applyTransform } from \"jscodeshift/dist/testUtils.js\";\n\nexport const createDiff = (transform: Transform) => (source: string) => {\n  const transformed = applyTransform(\n    transform,\n    {},\n    { source },\n    { parser: \"ts\" }\n  );\n  const patch = createPatch(\n    \"test.ts\",\n    source,\n    transformed || source,\n    \"original\",\n    \"transformed\"\n  );\n  return patch.replace(/@@ -\\d+,\\d+ \\+\\d+,\\d+ @@/g, \"@@  @@\");\n};\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/exports.json",
    "content": "{\n  \"@apollo/client/cache\": [\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction<T>;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloCache extends ApolloCache<TSerialized> {}\",\n        \"const _test_ApolloCache = new ApolloCache<TSerialized>()\"\n      ]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"ValueModule\",\n      \"usageExamples\": [\"const _Test_Cache = Cache;\"]\n    },\n    {\n      \"name\": \"DataProxy\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"usageExamples\": [\"const _Test_DataProxy = DataProxy;\"]\n    },\n    {\n      \"name\": \"MissingTree\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MissingTree = MissingTree;\"]\n    },\n    {\n      \"name\": \"Modifier\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Modifier = Modifier<T>;\"]\n    },\n    {\n      \"name\": \"Modifiers\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Modifiers = Modifiers<T>;\"]\n    },\n    {\n      \"name\": \"ModifierDetails\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ModifierDetails = ModifierDetails;\"]\n    },\n    {\n      \"name\": \"ReadFieldOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReadFieldOptions = ReadFieldOptions;\"]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"makeReference\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeReference(id)\"]\n    },\n    {\n      \"name\": \"canonicalStringify\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canonicalStringify = canonicalStringify;\"]\n    },\n    {\n      \"name\": \"EntityStore\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"usageExamples\": [\n        \"class _Test_EntityStore extends EntityStore {}\",\n        \"const _test_EntityStore = new EntityStore(policies, group)\"\n      ]\n    },\n    {\n      \"name\": \"fieldNameFromStoreName\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fieldNameFromStoreName(storeFieldName)\"]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"cacheSlot\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_cacheSlot = cacheSlot;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"Policies\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Policies extends Policies {}\",\n        \"const _test_Policies = new Policies(config)\"\n      ]\n    },\n    {\n      \"name\": \"FragmentRegistryAPI\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_FragmentRegistryAPI = FragmentRegistryAPI;\"]\n    },\n    {\n      \"name\": \"createFragmentRegistry\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFragmentRegistry(fragments)\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    }\n  ],\n  \"@apollo/client\": [\n    {\n      \"name\": \"ApolloClientOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\"type _Test_DefaultOptions = DefaultOptions;\"]\n    },\n    {\n      \"name\": \"ApolloClient\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloClient extends ApolloClient<TCacheShape> {}\",\n        \"const _test_ApolloClient = new ApolloClient<TCacheShape>(options)\"\n      ]\n    },\n    {\n      \"name\": \"mergeOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"mergeOptions<TDefaultOptions, TOptions>(defaults, options)\"\n      ]\n    },\n    {\n      \"name\": \"FetchMoreOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\",\n        \"const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\"\n      ]\n    },\n    {\n      \"name\": \"QueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryOptions = QueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"FetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FetchPolicy = FetchPolicy;\"]\n    },\n    {\n      \"name\": \"WatchQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"MutationFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationFetchPolicy = MutationFetchPolicy;\"]\n    },\n    {\n      \"name\": \"RefetchWritePolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RefetchWritePolicy = RefetchWritePolicy;\"]\n    },\n    {\n      \"name\": \"ErrorPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorPolicy = ErrorPolicy;\"]\n    },\n    {\n      \"name\": \"FetchMoreQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FetchMoreQueryOptions = FetchMoreQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryMapFn\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreUpdateQueryFn\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\"\n      ]\n    },\n    {\n      \"name\": \"NetworkStatus\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_NetworkStatus = NetworkStatus;\"]\n    },\n    {\n      \"name\": \"isNetworkRequestSettled\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNetworkRequestSettled(networkStatus)\"]\n    },\n    {\n      \"name\": \"Resolver\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Resolver = Resolver;\"]\n    },\n    {\n      \"name\": \"FragmentMatcher\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentMatcher = FragmentMatcher;\"]\n    },\n    {\n      \"name\": \"isApolloError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isApolloError(err)\"]\n    },\n    {\n      \"name\": \"ApolloError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloError extends ApolloError {}\",\n        \"const _test_ApolloError = new ApolloError(param0)\"\n      ]\n    },\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction<T>;\"]\n    },\n    {\n      \"name\": \"DataProxy\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\"const _Test_DataProxy = DataProxy;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"ValueModule\",\n      \"usageExamples\": [\"const _Test_Cache = Cache;\"]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloCache extends ApolloCache<TSerialized> {}\",\n        \"const _test_ApolloCache = new ApolloCache<TSerialized>()\"\n      ]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerError = ServerError;\"]\n    },\n    {\n      \"name\": \"fromError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromError<T>(errorValue)\"]\n    },\n    {\n      \"name\": \"toPromise\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"toPromise<R>(observable)\"]\n    },\n    {\n      \"name\": \"fromPromise\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromPromise<T>(promise)\"]\n    },\n    {\n      \"name\": \"throwServerError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_throwServerError = throwServerError;\"]\n    },\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"Observer\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"ObservableSubscription\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"makeReference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeReference(id)\"]\n    },\n    {\n      \"name\": \"setLogVerbosity\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"gql\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\"gql(literals, args)\"]\n    },\n    {\n      \"name\": \"resetCaches\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"resetCaches()\"]\n    },\n    {\n      \"name\": \"disableFragmentWarnings\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableFragmentWarnings()\"]\n    },\n    {\n      \"name\": \"enableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"enableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"disableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"TypedDocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_TypedDocumentNode = TypedDocumentNode<TResult, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MethodKeys\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MethodKeys = MethodKeys<T>;\"]\n    },\n    {\n      \"name\": \"DefaultContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DefaultContext = DefaultContext;\"]\n    },\n    {\n      \"name\": \"OnQueryUpdated\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OnQueryUpdated = OnQueryUpdated<TResult>;\"]\n    },\n    {\n      \"name\": \"RefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesPromiseResults\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"PureQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PureQueryOptions = PureQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"OperationVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OperationVariables = OperationVariables;\"]\n    },\n    {\n      \"name\": \"ApolloQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloQueryResult = ApolloQueryResult<T>;\"]\n    },\n    {\n      \"name\": \"MutationQueryReducer\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducer = MutationQueryReducer<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducersMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationUpdaterFn\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationUpdaterFn = MutationUpdaterFn<T>;\"]\n    },\n    {\n      \"name\": \"MutationUpdaterFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"Resolvers\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Resolvers = Resolvers;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    },\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"Path\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Path = Path;\"]\n    },\n    {\n      \"name\": \"ExecutionPatchInitialResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"IncrementalPayload\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchIncrementalResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"SingleExecutionResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"NextLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NextLink = NextLink;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    },\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerParseError = ServerParseError;\"]\n    },\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"ClientParseError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ClientParseError = ClientParseError;\"]\n    },\n    {\n      \"name\": \"serializeFetchParameter\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_serializeFetchParameter = serializeFetchParameter;\"\n      ]\n    },\n    {\n      \"name\": \"HttpOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_HttpOptions = HttpOptions;\"]\n    },\n    {\n      \"name\": \"UriFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_UriFunction = UriFunction;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    },\n    {\n      \"name\": \"ApolloContextValue\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloContextValue = ApolloContextValue;\"]\n    },\n    {\n      \"name\": \"ApolloProvider\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloProvider = ApolloProvider;\"]\n    },\n    {\n      \"name\": \"ApolloConsumer\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloConsumer = ApolloConsumer;\"]\n    },\n    {\n      \"name\": \"getApolloContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getApolloContext()\"]\n    },\n    {\n      \"name\": \"resetApolloContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_resetApolloContext = resetApolloContext;\"]\n    },\n    {\n      \"name\": \"IDocumentDefinition\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IDocumentDefinition = IDocumentDefinition;\"]\n    },\n    {\n      \"name\": \"DocumentType\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_DocumentType = DocumentType;\"]\n    },\n    {\n      \"name\": \"operationName\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"operationName(type)\"]\n    },\n    {\n      \"name\": \"parser\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\"parser(document)\"]\n    },\n    {\n      \"name\": \"PreloadQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryOptions = PreloadQueryOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFunction = PreloadQueryFunction;\"\n      ]\n    },\n    {\n      \"name\": \"createQueryPreloader\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createQueryPreloader(client)\"]\n    },\n    {\n      \"name\": \"useQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"UseSuspenseQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSuspenseQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseBackgroundQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useBackgroundQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useBackgroundQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseFragment\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useSuspenseFragment<TData, TVariables>(options)\"]\n    },\n    {\n      \"name\": \"LoadQueryFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseLoadableQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useLoadableQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useLoadableQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseQueryRefHandlersResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useQueryRefHandlers\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQueryRefHandlers<TData, TVariables>(queryRef)\"]\n    },\n    {\n      \"name\": \"UseReadQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useReadQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReadQuery<TData>(queryRef)\"]\n    },\n    {\n      \"name\": \"skipToken\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_skipToken = skipToken;\"]\n    },\n    {\n      \"name\": \"SkipToken\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_SkipToken = SkipToken;\"]\n    },\n    {\n      \"name\": \"useApolloClient\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useApolloClient(override)\"]\n    },\n    {\n      \"name\": \"useLazyQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useLazyQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"useMutation\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useMutation<TData, TVariables, TContext, TCache>(mutation, options)\"\n      ]\n    },\n    {\n      \"name\": \"useSubscription\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSubscription<TData, TVariables>(subscription, options)\"\n      ]\n    },\n    {\n      \"name\": \"useReactiveVar\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReactiveVar<T>(rv)\"]\n    },\n    {\n      \"name\": \"useFragment\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useFragment<TData, TVars>(options)\"]\n    },\n    {\n      \"name\": \"UseFragmentOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"UseFragmentResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentResult = UseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryReference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryReference = QueryReference<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryRef\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_QueryRef = QueryRef<TData, TVariables>;\"]\n    },\n    {\n      \"name\": \"PreloadedQueryRef\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"Context\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Context = Context;\"]\n    },\n    {\n      \"name\": \"CommonOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_CommonOptions = CommonOptions<TOptions>;\"]\n    },\n    {\n      \"name\": \"BaseQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseQueryOptions = BaseQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryFunctionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQueryFields\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ObservableQueryFields = ObservableQueryFields<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryResult = QueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryDataOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryDataOptions = QueryDataOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookExecOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\"\n      ]\n    },\n    {\n      \"name\": \"QueryLazyOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryLazyOptions = QueryLazyOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryTuple\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryTuple = QueryTuple<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryExecFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResultTuple\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesFunction = RefetchQueriesFunction;\"\n      ]\n    },\n    {\n      \"name\": \"BaseMutationOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseMutationOptions = BaseMutationOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationFunctionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MutationResult = MutationResult<TData>;\"]\n    },\n    {\n      \"name\": \"MutationFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationFunction = MutationFunction<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationDataOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationDataOptions = MutationDataOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationTuple\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"OnDataOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_OnDataOptions = OnDataOptions<TData>;\"]\n    },\n    {\n      \"name\": \"OnSubscriptionDataOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"BaseSubscriptionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionHookOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionDataOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionDataOptions = SubscriptionDataOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionCurrentObservable\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionCurrentObservable = SubscriptionCurrentObservable;\"\n      ]\n    },\n    {\n      \"name\": \"VariablesOption\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_VariablesOption = VariablesOption<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"NoInfer\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NoInfer = NoInfer<T>;\"]\n    }\n  ],\n  \"@apollo/client/core\": [\n    {\n      \"name\": \"ApolloClientOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloClientOptions = ApolloClientOptions<TCacheShape>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\"type _Test_DefaultOptions = DefaultOptions;\"]\n    },\n    {\n      \"name\": \"ApolloClient\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloClient extends ApolloClient<TCacheShape> {}\",\n        \"const _test_ApolloClient = new ApolloClient<TCacheShape>(options)\"\n      ]\n    },\n    {\n      \"name\": \"mergeOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"mergeOptions<TDefaultOptions, TOptions>(defaults, options)\"\n      ]\n    },\n    {\n      \"name\": \"FetchMoreOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FetchMoreOptions = FetchMoreOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQuery\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\",\n        \"const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\"\n      ]\n    },\n    {\n      \"name\": \"QueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryOptions = QueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationOptions = MutationOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"FetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FetchPolicy = FetchPolicy;\"]\n    },\n    {\n      \"name\": \"WatchQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"MutationFetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationFetchPolicy = MutationFetchPolicy;\"]\n    },\n    {\n      \"name\": \"RefetchWritePolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RefetchWritePolicy = RefetchWritePolicy;\"]\n    },\n    {\n      \"name\": \"ErrorPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorPolicy = ErrorPolicy;\"]\n    },\n    {\n      \"name\": \"FetchMoreQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FetchMoreQueryOptions = FetchMoreQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryMapFn\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreUpdateQueryFn\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\"\n      ]\n    },\n    {\n      \"name\": \"NetworkStatus\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_NetworkStatus = NetworkStatus;\"]\n    },\n    {\n      \"name\": \"isNetworkRequestSettled\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNetworkRequestSettled(networkStatus)\"]\n    },\n    {\n      \"name\": \"Resolver\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Resolver = Resolver;\"]\n    },\n    {\n      \"name\": \"FragmentMatcher\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentMatcher = FragmentMatcher;\"]\n    },\n    {\n      \"name\": \"isApolloError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isApolloError(err)\"]\n    },\n    {\n      \"name\": \"ApolloError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloError extends ApolloError {}\",\n        \"const _test_ApolloError = new ApolloError(param0)\"\n      ]\n    },\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction<T>;\"]\n    },\n    {\n      \"name\": \"DataProxy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\"const _Test_DataProxy = DataProxy;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"ValueModule\",\n      \"usageExamples\": [\"const _Test_Cache = Cache;\"]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloCache extends ApolloCache<TSerialized> {}\",\n        \"const _test_ApolloCache = new ApolloCache<TSerialized>()\"\n      ]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerError = ServerError;\"]\n    },\n    {\n      \"name\": \"fromError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromError<T>(errorValue)\"]\n    },\n    {\n      \"name\": \"toPromise\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"toPromise<R>(observable)\"]\n    },\n    {\n      \"name\": \"fromPromise\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromPromise<T>(promise)\"]\n    },\n    {\n      \"name\": \"throwServerError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_throwServerError = throwServerError;\"]\n    },\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"Observer\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"ObservableSubscription\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"makeReference\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeReference(id)\"]\n    },\n    {\n      \"name\": \"setLogVerbosity\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"gql\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\"gql(literals, args)\"]\n    },\n    {\n      \"name\": \"resetCaches\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"resetCaches()\"]\n    },\n    {\n      \"name\": \"disableFragmentWarnings\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableFragmentWarnings()\"]\n    },\n    {\n      \"name\": \"enableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"enableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"disableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"TypedDocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_TypedDocumentNode = TypedDocumentNode<TResult, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MethodKeys\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MethodKeys = MethodKeys<T>;\"]\n    },\n    {\n      \"name\": \"DefaultContext\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DefaultContext = DefaultContext;\"]\n    },\n    {\n      \"name\": \"OnQueryUpdated\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OnQueryUpdated = OnQueryUpdated<TResult>;\"]\n    },\n    {\n      \"name\": \"RefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesPromiseResults\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"PureQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PureQueryOptions = PureQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"OperationVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OperationVariables = OperationVariables;\"]\n    },\n    {\n      \"name\": \"ApolloQueryResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloQueryResult = ApolloQueryResult<T>;\"]\n    },\n    {\n      \"name\": \"MutationQueryReducer\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducer = MutationQueryReducer<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducersMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationUpdaterFn\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationUpdaterFn = MutationUpdaterFn<T>;\"]\n    },\n    {\n      \"name\": \"MutationUpdaterFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"Resolvers\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Resolvers = Resolvers;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    },\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"Path\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Path = Path;\"]\n    },\n    {\n      \"name\": \"ExecutionPatchInitialResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"IncrementalPayload\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchIncrementalResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"SingleExecutionResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"NextLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NextLink = NextLink;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    },\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerParseError = ServerParseError;\"]\n    },\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"ClientParseError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ClientParseError = ClientParseError;\"]\n    },\n    {\n      \"name\": \"serializeFetchParameter\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_serializeFetchParameter = serializeFetchParameter;\"\n      ]\n    },\n    {\n      \"name\": \"HttpOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_HttpOptions = HttpOptions;\"]\n    },\n    {\n      \"name\": \"UriFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_UriFunction = UriFunction;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    }\n  ],\n  \"@apollo/client/dev\": [\n    {\n      \"name\": \"loadDevMessages\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadDevMessages()\"]\n    },\n    {\n      \"name\": \"loadErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadErrorMessageHandler(errorCodes)\"]\n    },\n    {\n      \"name\": \"loadErrorMessages\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadErrorMessages()\"]\n    },\n    {\n      \"name\": \"setErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setErrorMessageHandler(handler)\"]\n    },\n    {\n      \"name\": \"ErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorMessageHandler = ErrorMessageHandler;\"]\n    }\n  ],\n  \"@apollo/client/errors\": [\n    {\n      \"name\": \"graphQLResultHasProtocolErrors\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"graphQLResultHasProtocolErrors<T>(result)\"]\n    },\n    {\n      \"name\": \"isApolloError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isApolloError(err)\"]\n    },\n    {\n      \"name\": \"PROTOCOL_ERRORS_SYMBOL\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_PROTOCOL_ERRORS_SYMBOL = PROTOCOL_ERRORS_SYMBOL;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloErrorOptions\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloErrorOptions = ApolloErrorOptions;\"]\n    },\n    {\n      \"name\": \"GraphQLErrors\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GraphQLErrors = GraphQLErrors;\"]\n    },\n    {\n      \"name\": \"NetworkError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NetworkError = NetworkError;\"]\n    },\n    {\n      \"name\": \"ApolloError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloError extends ApolloError {}\",\n        \"const _test_ApolloError = new ApolloError(param0)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/batch\": [\n    {\n      \"name\": \"BatchableRequest\",\n      \"moduleName\": \"@apollo/client/link/batch\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_BatchableRequest = BatchableRequest;\"]\n    },\n    {\n      \"name\": \"BatchHandler\",\n      \"moduleName\": \"@apollo/client/link/batch\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_BatchHandler = BatchHandler;\"]\n    },\n    {\n      \"name\": \"OperationBatcher\",\n      \"moduleName\": \"@apollo/client/link/batch\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_OperationBatcher extends OperationBatcher {}\",\n        \"const _test_OperationBatcher = new OperationBatcher(param0)\"\n      ]\n    },\n    {\n      \"name\": \"BatchLink\",\n      \"moduleName\": \"@apollo/client/link/batch\",\n      \"usageExamples\": [\n        \"class _Test_BatchLink extends BatchLink {}\",\n        \"const _test_BatchLink = new BatchLink(fetchParams)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/batch-http\": [\n    {\n      \"name\": \"BatchHttpLink\",\n      \"moduleName\": \"@apollo/client/link/batch-http\",\n      \"usageExamples\": [\n        \"class _Test_BatchHttpLink extends BatchHttpLink {}\",\n        \"const _test_BatchHttpLink = new BatchHttpLink(fetchParams)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/context\": [\n    {\n      \"name\": \"setContext\",\n      \"moduleName\": \"@apollo/client/link/context\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setContext(setter)\"]\n    },\n    {\n      \"name\": \"ContextSetter\",\n      \"moduleName\": \"@apollo/client/link/context\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ContextSetter = ContextSetter;\"]\n    }\n  ],\n  \"@apollo/client/link/core\": [\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"Path\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Path = Path;\"]\n    },\n    {\n      \"name\": \"ExecutionPatchInitialResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchInitialResult = ExecutionPatchInitialResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"IncrementalPayload\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_IncrementalPayload = IncrementalPayload<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchIncrementalResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchIncrementalResult = ExecutionPatchIncrementalResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ExecutionPatchResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ExecutionPatchResult = ExecutionPatchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_GraphQLRequest = GraphQLRequest<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"SingleExecutionResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SingleExecutionResult = SingleExecutionResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TContext, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"NextLink\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NextLink = NextLink;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    }\n  ],\n  \"@apollo/client/link/error\": [\n    {\n      \"name\": \"onError\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"onError(errorHandler)\"]\n    },\n    {\n      \"name\": \"ErrorResponse\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ErrorResponse = ErrorResponse;\"]\n    },\n    {\n      \"name\": \"ErrorLink\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"usageExamples\": [\n        \"class _Test_ErrorLink extends ErrorLink {}\",\n        \"const _test_ErrorLink = new ErrorLink(errorHandler)\"\n      ]\n    },\n    {\n      \"name\": \"ErrorHandler\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ErrorHandler = ErrorHandler;\"]\n    }\n  ],\n  \"@apollo/client/link/http\": [\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerParseError = ServerParseError;\"]\n    },\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"ClientParseError\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ClientParseError = ClientParseError;\"]\n    },\n    {\n      \"name\": \"serializeFetchParameter\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_serializeFetchParameter = serializeFetchParameter;\"\n      ]\n    },\n    {\n      \"name\": \"HttpOptions\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_HttpOptions = HttpOptions;\"]\n    },\n    {\n      \"name\": \"UriFunction\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_UriFunction = UriFunction;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    }\n  ],\n  \"@apollo/client/link/persisted-queries\": [\n    {\n      \"name\": \"VERSION\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_VERSION = VERSION;\"]\n    },\n    {\n      \"name\": \"ErrorResponse\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ErrorResponse = ErrorResponse;\"]\n    },\n    {\n      \"name\": \"PersistedQueryLink\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\"const _Test_PersistedQueryLink = PersistedQueryLink;\"]\n    },\n    {\n      \"name\": \"createPersistedQueryLink\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createPersistedQueryLink = createPersistedQueryLink;\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/retry\": [\n    {\n      \"name\": \"RetryLink\",\n      \"moduleName\": \"@apollo/client/link/retry\",\n      \"usageExamples\": [\n        \"class _Test_RetryLink extends RetryLink {}\",\n        \"const _test_RetryLink = new RetryLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/remove-typename\": [\n    {\n      \"name\": \"RemoveTypenameFromVariablesOptions\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_RemoveTypenameFromVariablesOptions = RemoveTypenameFromVariablesOptions;\"\n      ]\n    },\n    {\n      \"name\": \"removeTypenameFromVariables\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeTypenameFromVariables(options)\"]\n    },\n    {\n      \"name\": \"KEEP\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_KEEP = KEEP;\"]\n    }\n  ],\n  \"@apollo/client/link/schema\": [\n    {\n      \"name\": \"SchemaLink\",\n      \"moduleName\": \"@apollo/client/link/schema\",\n      \"usageExamples\": [\n        \"class _Test_SchemaLink extends SchemaLink {}\",\n        \"const _test_SchemaLink = new SchemaLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/subscriptions\": [\n    {\n      \"name\": \"GraphQLWsLink\",\n      \"moduleName\": \"@apollo/client/link/subscriptions\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_GraphQLWsLink extends GraphQLWsLink {}\",\n        \"const _test_GraphQLWsLink = new GraphQLWsLink(client)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/utils\": [\n    {\n      \"name\": \"fromError\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromError<T>(errorValue)\"]\n    },\n    {\n      \"name\": \"toPromise\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"toPromise<R>(observable)\"]\n    },\n    {\n      \"name\": \"fromPromise\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fromPromise<T>(promise)\"]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ServerError = ServerError;\"]\n    },\n    {\n      \"name\": \"throwServerError\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_throwServerError = throwServerError;\"]\n    },\n    {\n      \"name\": \"validateOperation\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"validateOperation(operation)\"]\n    },\n    {\n      \"name\": \"createOperation\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createOperation(starting, operation)\"]\n    },\n    {\n      \"name\": \"transformOperation\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"transformOperation(operation)\"]\n    },\n    {\n      \"name\": \"filterOperationVariables\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"filterOperationVariables(variables, query)\"]\n    }\n  ],\n  \"@apollo/client/link/ws\": [\n    {\n      \"name\": \"WebSocketLink\",\n      \"moduleName\": \"@apollo/client/link/ws\",\n      \"usageExamples\": [\n        \"class _Test_WebSocketLink extends WebSocketLink {}\",\n        \"const _test_WebSocketLink = new WebSocketLink(paramsOrClient)\"\n      ]\n    },\n    {\n      \"name\": \"WebSocketParams\",\n      \"moduleName\": \"@apollo/client/link/ws\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_WebSocketParams = WebSocketParams;\"]\n    }\n  ],\n  \"@apollo/client/masking\": [\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"disableWarningsSlot\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_disableWarningsSlot = disableWarningsSlot;\"\n      ]\n    },\n    {\n      \"name\": \"maskFragment\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"maskFragment<TData>(data, document, cache, fragmentName)\"\n      ]\n    },\n    {\n      \"name\": \"maskOperation\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"maskOperation<TData>(data, document, cache)\"]\n    }\n  ],\n  \"@apollo/client/react\": [\n    {\n      \"name\": \"ApolloContextValue\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloContextValue = ApolloContextValue;\"]\n    },\n    {\n      \"name\": \"ApolloProvider\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloProvider = ApolloProvider;\"]\n    },\n    {\n      \"name\": \"ApolloConsumer\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloConsumer = ApolloConsumer;\"]\n    },\n    {\n      \"name\": \"getApolloContext\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getApolloContext()\"]\n    },\n    {\n      \"name\": \"resetApolloContext\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_resetApolloContext = resetApolloContext;\"]\n    },\n    {\n      \"name\": \"IDocumentDefinition\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IDocumentDefinition = IDocumentDefinition;\"]\n    },\n    {\n      \"name\": \"DocumentType\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_DocumentType = DocumentType;\"]\n    },\n    {\n      \"name\": \"operationName\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"operationName(type)\"]\n    },\n    {\n      \"name\": \"parser\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\"parser(document)\"]\n    },\n    {\n      \"name\": \"PreloadQueryOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryOptions = PreloadQueryOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFunction = PreloadQueryFunction;\"\n      ]\n    },\n    {\n      \"name\": \"createQueryPreloader\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createQueryPreloader(client)\"]\n    },\n    {\n      \"name\": \"useQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"UseSuspenseQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSuspenseQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseBackgroundQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useBackgroundQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useBackgroundQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseFragment\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useSuspenseFragment<TData, TVariables>(options)\"]\n    },\n    {\n      \"name\": \"LoadQueryFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseLoadableQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useLoadableQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useLoadableQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseQueryRefHandlersResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useQueryRefHandlers\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQueryRefHandlers<TData, TVariables>(queryRef)\"]\n    },\n    {\n      \"name\": \"UseReadQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useReadQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReadQuery<TData>(queryRef)\"]\n    },\n    {\n      \"name\": \"skipToken\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_skipToken = skipToken;\"]\n    },\n    {\n      \"name\": \"SkipToken\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_SkipToken = SkipToken;\"]\n    },\n    {\n      \"name\": \"useApolloClient\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useApolloClient(override)\"]\n    },\n    {\n      \"name\": \"useLazyQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useLazyQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"useMutation\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useMutation<TData, TVariables, TContext, TCache>(mutation, options)\"\n      ]\n    },\n    {\n      \"name\": \"useSubscription\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSubscription<TData, TVariables>(subscription, options)\"\n      ]\n    },\n    {\n      \"name\": \"useReactiveVar\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReactiveVar<T>(rv)\"]\n    },\n    {\n      \"name\": \"useFragment\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useFragment<TData, TVars>(options)\"]\n    },\n    {\n      \"name\": \"UseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"UseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentResult = UseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryReference\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryReference = QueryReference<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryRef\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_QueryRef = QueryRef<TData, TVariables>;\"]\n    },\n    {\n      \"name\": \"PreloadedQueryRef\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"Context\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Context = Context;\"]\n    },\n    {\n      \"name\": \"CommonOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_CommonOptions = CommonOptions<TOptions>;\"]\n    },\n    {\n      \"name\": \"BaseQueryOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseQueryOptions = BaseQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryFunctionOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryFunctionOptions = QueryFunctionOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQueryFields\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ObservableQueryFields = ObservableQueryFields<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryResult = QueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryDataOptions = QueryDataOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookExecOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryHookFetchPolicy = LoadableQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\"\n      ]\n    },\n    {\n      \"name\": \"QueryLazyOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryLazyOptions = QueryLazyOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryTuple\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryTuple = QueryTuple<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryExecFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResultTuple\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesFunction = RefetchQueriesFunction;\"\n      ]\n    },\n    {\n      \"name\": \"BaseMutationOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseMutationOptions = BaseMutationOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationFunctionOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MutationResult = MutationResult<TData>;\"]\n    },\n    {\n      \"name\": \"MutationFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationFunction = MutationFunction<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationDataOptions = MutationDataOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationTuple\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationTuple = MutationTuple<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"OnDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_OnDataOptions = OnDataOptions<TData>;\"]\n    },\n    {\n      \"name\": \"OnSubscriptionDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"BaseSubscriptionOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_BaseSubscriptionOptions = BaseSubscriptionOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionDataOptions = SubscriptionDataOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionCurrentObservable\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionCurrentObservable = SubscriptionCurrentObservable;\"\n      ]\n    },\n    {\n      \"name\": \"VariablesOption\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_VariablesOption = VariablesOption<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"NoInfer\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NoInfer = NoInfer<T>;\"]\n    }\n  ],\n  \"@apollo/client/react/components\": [\n    {\n      \"name\": \"Query\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"usageExamples\": [\"Query<TData, TVariables>(props)\"]\n    },\n    {\n      \"name\": \"Mutation\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"usageExamples\": [\"Mutation<TData, TVariables>(props)\"]\n    },\n    {\n      \"name\": \"Subscription\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"usageExamples\": [\"Subscription<TData, TVariables>(props)\"]\n    },\n    {\n      \"name\": \"QueryComponentOptions\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryComponentOptions = QueryComponentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationComponentOptions\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutationComponentOptions = MutationComponentOptions<TData, TVariables, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionComponentOptions\",\n      \"moduleName\": \"@apollo/client/react/components\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionComponentOptions = SubscriptionComponentOptions<TData, TVariables>;\"\n      ]\n    }\n  ],\n  \"@apollo/client/react/context\": [\n    {\n      \"name\": \"ApolloConsumerProps\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloConsumerProps = ApolloConsumerProps;\"]\n    },\n    {\n      \"name\": \"ApolloConsumer\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloConsumer = ApolloConsumer;\"]\n    },\n    {\n      \"name\": \"ApolloContextValue\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloContextValue = ApolloContextValue;\"]\n    },\n    {\n      \"name\": \"getApolloContext\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getApolloContext()\"]\n    },\n    {\n      \"name\": \"resetApolloContext\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_resetApolloContext = resetApolloContext;\"]\n    },\n    {\n      \"name\": \"ApolloProviderProps\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloProviderProps = ApolloProviderProps<TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloProvider\",\n      \"moduleName\": \"@apollo/client/react/context\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_ApolloProvider = ApolloProvider;\"]\n    }\n  ],\n  \"@apollo/client/react/hoc\": [\n    {\n      \"name\": \"graphql\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"graphql<TProps, TData, TGraphQLVariables, TChildProps>(document, operationOptions)\"\n      ]\n    },\n    {\n      \"name\": \"withQuery\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"withQuery<TProps, TData, TGraphQLVariables, TChildProps>(document, operationOptions)\"\n      ]\n    },\n    {\n      \"name\": \"withMutation\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"withMutation<TProps, TData, TGraphQLVariables, TChildProps, TContext, TCache>(document, operationOptions)\"\n      ]\n    },\n    {\n      \"name\": \"withSubscription\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"withSubscription<TProps, TData, TGraphQLVariables, TChildProps>(document, operationOptions)\"\n      ]\n    },\n    {\n      \"name\": \"withApollo\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"withApollo<TProps, TResult>(WrappedComponent, operationOptions)\"\n      ]\n    },\n    {\n      \"name\": \"QueryControls\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryControls = QueryControls<TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"DataValue\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DataValue = DataValue<TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"DataProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_DataProps = DataProps<TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MutateProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MutateProps = MutateProps<TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ChildProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ChildProps = ChildProps<TProps, TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ChildDataProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ChildDataProps = ChildDataProps<TProps, TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"ChildMutateProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ChildMutateProps = ChildMutateProps<TProps, TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"OptionProps\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_OptionProps = OptionProps<TProps, TData, TGraphQLVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"OperationOption\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_OperationOption = OperationOption<TProps, TData, TGraphQLVariables, TChildProps, TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"WithApolloClient\",\n      \"moduleName\": \"@apollo/client/react/hoc\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_WithApolloClient = WithApolloClient<P>;\"]\n    }\n  ],\n  \"@apollo/client/react/hooks\": [\n    {\n      \"name\": \"useQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"UseSuspenseQueryResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSuspenseQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseBackgroundQueryResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useBackgroundQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useBackgroundQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseFragment\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useSuspenseFragment<TData, TVariables>(options)\"]\n    },\n    {\n      \"name\": \"LoadQueryFunction\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseLoadableQueryResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useLoadableQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useLoadableQuery<TData, TVariables, TOptions>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"UseQueryRefHandlersResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useQueryRefHandlers\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useQueryRefHandlers<TData, TVariables>(queryRef)\"]\n    },\n    {\n      \"name\": \"UseReadQueryResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useReadQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReadQuery<TData>(queryRef)\"]\n    },\n    {\n      \"name\": \"skipToken\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_skipToken = skipToken;\"]\n    },\n    {\n      \"name\": \"SkipToken\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_SkipToken = SkipToken;\"]\n    },\n    {\n      \"name\": \"useApolloClient\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useApolloClient(override)\"]\n    },\n    {\n      \"name\": \"useLazyQuery\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useLazyQuery<TData, TVariables>(query, options)\"]\n    },\n    {\n      \"name\": \"useMutation\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useMutation<TData, TVariables, TContext, TCache>(mutation, options)\"\n      ]\n    },\n    {\n      \"name\": \"useSubscription\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"useSubscription<TData, TVariables>(subscription, options)\"\n      ]\n    },\n    {\n      \"name\": \"useReactiveVar\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReactiveVar<T>(rv)\"]\n    },\n    {\n      \"name\": \"useFragment\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useFragment<TData, TVars>(options)\"]\n    },\n    {\n      \"name\": \"UseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVars>;\"\n      ]\n    },\n    {\n      \"name\": \"UseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react/hooks\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentResult = UseFragmentResult<TData>;\"\n      ]\n    }\n  ],\n  \"@apollo/client/react/internal\": [\n    {\n      \"name\": \"getSuspenseCache\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getSuspenseCache(client)\"]\n    },\n    {\n      \"name\": \"CacheKey\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_CacheKey = CacheKey;\"]\n    },\n    {\n      \"name\": \"QueryKey\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_QueryKey = QueryKey;\"]\n    },\n    {\n      \"name\": \"QueryReference\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryReference = QueryReference<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_QueryRef = QueryRef<TData, TVariables>;\"]\n    },\n    {\n      \"name\": \"PreloadedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalQueryReference\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InternalQueryReference extends InternalQueryReference<TData> {}\",\n        \"const _test_InternalQueryReference = new InternalQueryReference<TData>(observable, options)\"\n      ]\n    },\n    {\n      \"name\": \"getWrappedPromise\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getWrappedPromise<TData>(queryRef)\"]\n    },\n    {\n      \"name\": \"unwrapQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"unwrapQueryRef<TData>(queryRef)\"]\n    },\n    {\n      \"name\": \"updateWrappedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"updateWrappedQueryRef<TData>(queryRef, promise)\"]\n    },\n    {\n      \"name\": \"wrapQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"wrapQueryRef<TData, TVariables>(internalQueryRef)\"]\n    },\n    {\n      \"name\": \"assertWrappedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"assertWrappedQueryRef<TData, TVariables>(queryRef)\"]\n    },\n    {\n      \"name\": \"SuspenseCacheOptions\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseCacheOptions = SuspenseCacheOptions;\"\n      ]\n    },\n    {\n      \"name\": \"HookWrappers\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_HookWrappers = HookWrappers;\"]\n    }\n  ],\n  \"@apollo/client/react/parser\": [\n    {\n      \"name\": \"operationName\",\n      \"moduleName\": \"@apollo/client/react/parser\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"operationName(type)\"]\n    },\n    {\n      \"name\": \"parser\",\n      \"moduleName\": \"@apollo/client/react/parser\",\n      \"usageExamples\": [\"parser(document)\"]\n    },\n    {\n      \"name\": \"verifyDocumentType\",\n      \"moduleName\": \"@apollo/client/react/parser\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"verifyDocumentType(document, type)\"]\n    },\n    {\n      \"name\": \"DocumentType\",\n      \"moduleName\": \"@apollo/client/react/parser\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_DocumentType = DocumentType;\"]\n    },\n    {\n      \"name\": \"IDocumentDefinition\",\n      \"moduleName\": \"@apollo/client/react/parser\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IDocumentDefinition = IDocumentDefinition;\"]\n    }\n  ],\n  \"@apollo/client/react/ssr\": [\n    {\n      \"name\": \"getMarkupFromTree\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getMarkupFromTree(param0)\"]\n    },\n    {\n      \"name\": \"getDataFromTree\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getDataFromTree(tree, context)\"]\n    },\n    {\n      \"name\": \"renderToStringWithData\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"renderToStringWithData(component)\"]\n    },\n    {\n      \"name\": \"RenderPromises\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_RenderPromises extends RenderPromises {}\",\n        \"const _test_RenderPromises = new RenderPromises()\"\n      ]\n    }\n  ],\n  \"@apollo/client/testing\": [\n    {\n      \"name\": \"MockedProviderProps\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MockedProviderProps = MockedProviderProps<TSerializedCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MockedProvider\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MockedProvider extends MockedProvider {}\",\n        \"const _test_MockedProvider = new MockedProvider(props)\"\n      ]\n    },\n    {\n      \"name\": \"MockedResponse\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MockedResponse = MockedResponse<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MockLinkOptions\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MockLinkOptions = MockLinkOptions;\"]\n    },\n    {\n      \"name\": \"ResultFunction\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ResultFunction = ResultFunction<T, V>;\"]\n    },\n    {\n      \"name\": \"MockLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MockLink extends MockLink {}\",\n        \"const _test_MockLink = new MockLink(mockedResponses, addTypename, options)\"\n      ]\n    },\n    {\n      \"name\": \"mockSingleLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mockSingleLink(mockedResponses)\"]\n    },\n    {\n      \"name\": \"MockSubscriptionLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\",\n        \"const _test_MockSubscriptionLink = new MockSubscriptionLink()\"\n      ]\n    },\n    {\n      \"name\": \"mockObservableLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mockObservableLink()\"]\n    },\n    {\n      \"name\": \"createMockClient\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createMockClient<TData>(data, query, variables)\"]\n    },\n    {\n      \"name\": \"subscribeAndCount\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"subscribeAndCount<TResult>(reject, observable, cb)\"]\n    },\n    {\n      \"name\": \"itAsync\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_itAsync = itAsync;\"]\n    },\n    {\n      \"name\": \"wait\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"wait(ms)\"]\n    },\n    {\n      \"name\": \"tick\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"tick()\"]\n    },\n    {\n      \"name\": \"withErrorSpy\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withErrorSpy<TArgs, TResult>(it, args)\"]\n    },\n    {\n      \"name\": \"withWarningSpy\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withWarningSpy<TArgs, TResult>(it, args)\"]\n    },\n    {\n      \"name\": \"withLogSpy\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withLogSpy<TArgs, TResult>(it, args)\"]\n    }\n  ],\n  \"@apollo/client/testing/core\": [\n    {\n      \"name\": \"MockedResponse\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_MockedResponse = MockedResponse<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MockLinkOptions\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MockLinkOptions = MockLinkOptions;\"]\n    },\n    {\n      \"name\": \"ResultFunction\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ResultFunction = ResultFunction<T, V>;\"]\n    },\n    {\n      \"name\": \"MockLink\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MockLink extends MockLink {}\",\n        \"const _test_MockLink = new MockLink(mockedResponses, addTypename, options)\"\n      ]\n    },\n    {\n      \"name\": \"mockSingleLink\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mockSingleLink(mockedResponses)\"]\n    },\n    {\n      \"name\": \"MockSubscriptionLink\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\",\n        \"const _test_MockSubscriptionLink = new MockSubscriptionLink()\"\n      ]\n    },\n    {\n      \"name\": \"mockObservableLink\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mockObservableLink()\"]\n    },\n    {\n      \"name\": \"createMockClient\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createMockClient<TData>(data, query, variables)\"]\n    },\n    {\n      \"name\": \"subscribeAndCount\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"subscribeAndCount<TResult>(reject, observable, cb)\"]\n    },\n    {\n      \"name\": \"itAsync\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_itAsync = itAsync;\"]\n    },\n    {\n      \"name\": \"wait\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"wait(ms)\"]\n    },\n    {\n      \"name\": \"tick\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"tick()\"]\n    },\n    {\n      \"name\": \"withErrorSpy\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withErrorSpy<TArgs, TResult>(it, args)\"]\n    },\n    {\n      \"name\": \"withWarningSpy\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withWarningSpy<TArgs, TResult>(it, args)\"]\n    },\n    {\n      \"name\": \"withLogSpy\",\n      \"moduleName\": \"@apollo/client/testing/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"withLogSpy<TArgs, TResult>(it, args)\"]\n    }\n  ],\n  \"@apollo/client/testing/experimental\": [\n    {\n      \"name\": \"createTestSchema\",\n      \"moduleName\": \"@apollo/client/testing/experimental\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createTestSchema = createTestSchema;\"]\n    },\n    {\n      \"name\": \"createSchemaFetch\",\n      \"moduleName\": \"@apollo/client/testing/experimental\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createSchemaFetch = createSchemaFetch;\"]\n    }\n  ],\n  \"@apollo/client/utilities\": [\n    {\n      \"name\": \"DEV\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_DEV = DEV;\"]\n    },\n    {\n      \"name\": \"maybe\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"maybe<T>(thunk)\"]\n    },\n    {\n      \"name\": \"DirectiveInfo\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DirectiveInfo = DirectiveInfo;\"]\n    },\n    {\n      \"name\": \"InclusionDirectives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_InclusionDirectives = InclusionDirectives;\"]\n    },\n    {\n      \"name\": \"shouldInclude\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"shouldInclude(param0, variables)\"]\n    },\n    {\n      \"name\": \"hasDirectives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"hasDirectives(names, root, all)\"]\n    },\n    {\n      \"name\": \"hasAnyDirectives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_hasAnyDirectives = hasAnyDirectives;\"]\n    },\n    {\n      \"name\": \"hasAllDirectives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_hasAllDirectives = hasAllDirectives;\"]\n    },\n    {\n      \"name\": \"hasClientExports\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"hasClientExports(document)\"]\n    },\n    {\n      \"name\": \"getDirectiveNames\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getDirectiveNames(root)\"]\n    },\n    {\n      \"name\": \"getInclusionDirectives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getInclusionDirectives(directives)\"]\n    },\n    {\n      \"name\": \"getFragmentMaskMode\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getFragmentMaskMode(fragment)\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"FragmentMap\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_FragmentMap = FragmentMap;\"]\n    },\n    {\n      \"name\": \"FragmentMapFunction\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentMapFunction = FragmentMapFunction;\"]\n    },\n    {\n      \"name\": \"createFragmentMap\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFragmentMap(fragments)\"]\n    },\n    {\n      \"name\": \"getFragmentQueryDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getFragmentQueryDocument(document, fragmentName)\"]\n    },\n    {\n      \"name\": \"getFragmentFromSelection\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getFragmentFromSelection(selection, fragmentMap)\"]\n    },\n    {\n      \"name\": \"isFullyUnmaskedOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isFullyUnmaskedOperation(document)\"]\n    },\n    {\n      \"name\": \"checkDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"checkDocument(doc)\"]\n    },\n    {\n      \"name\": \"getOperationDefinition\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getOperationDefinition(doc)\"]\n    },\n    {\n      \"name\": \"getOperationName\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getOperationName(doc)\"]\n    },\n    {\n      \"name\": \"getFragmentDefinitions\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getFragmentDefinitions(doc)\"]\n    },\n    {\n      \"name\": \"getQueryDefinition\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getQueryDefinition(doc)\"]\n    },\n    {\n      \"name\": \"getFragmentDefinition\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getFragmentDefinition(doc)\"]\n    },\n    {\n      \"name\": \"getMainDefinition\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getMainDefinition(queryDoc)\"]\n    },\n    {\n      \"name\": \"getDefaultValues\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getDefaultValues(definition)\"]\n    },\n    {\n      \"name\": \"print\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_print = print;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"AsStoreObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_AsStoreObject = AsStoreObject<T>;\"]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"Directives\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Directives = Directives;\"]\n    },\n    {\n      \"name\": \"VariableValue\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_VariableValue = VariableValue;\"]\n    },\n    {\n      \"name\": \"makeReference\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeReference(id)\"]\n    },\n    {\n      \"name\": \"isDocumentNode\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isDocumentNode(value)\"]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"isField\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isField(selection)\"]\n    },\n    {\n      \"name\": \"isInlineFragment\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isInlineFragment(selection)\"]\n    },\n    {\n      \"name\": \"valueToObjectRepresentation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"valueToObjectRepresentation(argObj, name, value, variables)\"\n      ]\n    },\n    {\n      \"name\": \"storeKeyNameFromField\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"storeKeyNameFromField(field, variables)\"]\n    },\n    {\n      \"name\": \"argumentsObjectFromField\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"argumentsObjectFromField(field, variables)\"]\n    },\n    {\n      \"name\": \"resultKeyNameFromField\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"resultKeyNameFromField(field)\"]\n    },\n    {\n      \"name\": \"getStoreKeyName\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_getStoreKeyName = getStoreKeyName;\"]\n    },\n    {\n      \"name\": \"getTypenameFromResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"getTypenameFromResult(result, selectionSet, fragmentMap)\"\n      ]\n    },\n    {\n      \"name\": \"RemoveNodeConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RemoveNodeConfig = RemoveNodeConfig<N>;\"]\n    },\n    {\n      \"name\": \"GetNodeConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GetNodeConfig = GetNodeConfig<N>;\"]\n    },\n    {\n      \"name\": \"RemoveDirectiveConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveDirectiveConfig = RemoveDirectiveConfig;\"\n      ]\n    },\n    {\n      \"name\": \"GetDirectiveConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GetDirectiveConfig = GetDirectiveConfig;\"]\n    },\n    {\n      \"name\": \"RemoveArgumentsConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveArgumentsConfig = RemoveArgumentsConfig;\"\n      ]\n    },\n    {\n      \"name\": \"GetFragmentSpreadConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_GetFragmentSpreadConfig = GetFragmentSpreadConfig;\"\n      ]\n    },\n    {\n      \"name\": \"RemoveFragmentSpreadConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveFragmentSpreadConfig = RemoveFragmentSpreadConfig;\"\n      ]\n    },\n    {\n      \"name\": \"RemoveFragmentDefinitionConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveFragmentDefinitionConfig = RemoveFragmentDefinitionConfig;\"\n      ]\n    },\n    {\n      \"name\": \"RemoveVariableDefinitionConfig\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveVariableDefinitionConfig = RemoveVariableDefinitionConfig;\"\n      ]\n    },\n    {\n      \"name\": \"addTypenameToDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_addTypenameToDocument = addTypenameToDocument;\"\n      ]\n    },\n    {\n      \"name\": \"addNonReactiveToNamedFragments\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"addNonReactiveToNamedFragments(document)\"]\n    },\n    {\n      \"name\": \"buildQueryFromSelectionSet\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"buildQueryFromSelectionSet(document)\"]\n    },\n    {\n      \"name\": \"removeDirectivesFromDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeDirectivesFromDocument(directives, doc)\"]\n    },\n    {\n      \"name\": \"removeConnectionDirectiveFromDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeConnectionDirectiveFromDocument(doc)\"]\n    },\n    {\n      \"name\": \"removeArgumentsFromDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeArgumentsFromDocument(config, doc)\"]\n    },\n    {\n      \"name\": \"removeFragmentSpreadFromDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeFragmentSpreadFromDocument(config, doc)\"]\n    },\n    {\n      \"name\": \"removeClientSetsFromDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeClientSetsFromDocument(document)\"]\n    },\n    {\n      \"name\": \"isMutationOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isMutationOperation(document)\"]\n    },\n    {\n      \"name\": \"isQueryOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isQueryOperation(document)\"]\n    },\n    {\n      \"name\": \"isSubscriptionOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isSubscriptionOperation(document)\"]\n    },\n    {\n      \"name\": \"concatPagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"concatPagination<T>(keyArgs)\"]\n    },\n    {\n      \"name\": \"offsetLimitPagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"offsetLimitPagination<T>(keyArgs)\"]\n    },\n    {\n      \"name\": \"relayStylePagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"relayStylePagination<TNode>(keyArgs)\"]\n    },\n    {\n      \"name\": \"Observer\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"ObservableSubscription\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"PromiseWithState\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PromiseWithState = PromiseWithState<TValue>;\"\n      ]\n    },\n    {\n      \"name\": \"isStatefulPromise\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isStatefulPromise<TValue>(promise)\"]\n    },\n    {\n      \"name\": \"createFulfilledPromise\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFulfilledPromise<TValue>(value)\"]\n    },\n    {\n      \"name\": \"createRejectedPromise\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createRejectedPromise<TValue>(reason)\"]\n    },\n    {\n      \"name\": \"wrapPromiseWithState\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"wrapPromiseWithState<TValue>(promise)\"]\n    },\n    {\n      \"name\": \"preventUnhandledRejection\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"preventUnhandledRejection<T>(promise)\"]\n    },\n    {\n      \"name\": \"maybeDeepFreeze\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"maybeDeepFreeze<T>(obj)\"]\n    },\n    {\n      \"name\": \"canonicalStringify\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canonicalStringify = canonicalStringify;\"]\n    },\n    {\n      \"name\": \"omitDeep\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"omitDeep<T, K>(value, key)\"]\n    },\n    {\n      \"name\": \"stripTypename\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"stripTypename<T>(value)\"]\n    },\n    {\n      \"name\": \"DeepOmit\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DeepOmit = DeepOmit<T, K>;\"]\n    },\n    {\n      \"name\": \"DeepPartial\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DeepPartial = DeepPartial<T>;\"]\n    },\n    {\n      \"name\": \"OnlyRequiredProperties\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_OnlyRequiredProperties = OnlyRequiredProperties<T>;\"\n      ]\n    },\n    {\n      \"name\": \"Prettify\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Prettify = Prettify<T>;\"]\n    },\n    {\n      \"name\": \"Primitive\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Primitive = Primitive;\"]\n    },\n    {\n      \"name\": \"UnionToIntersection\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UnionToIntersection = UnionToIntersection<U>;\"\n      ]\n    },\n    {\n      \"name\": \"NoInfer\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_NoInfer = NoInfer<T>;\"]\n    },\n    {\n      \"name\": \"RemoveIndexSignature\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RemoveIndexSignature = RemoveIndexSignature<T>;\"\n      ]\n    },\n    {\n      \"name\": \"AutoCleanedStrongCache\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"usageExamples\": [\n        \"const _Test_AutoCleanedStrongCache = AutoCleanedStrongCache;\"\n      ]\n    },\n    {\n      \"name\": \"AutoCleanedWeakCache\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"usageExamples\": [\n        \"const _Test_AutoCleanedWeakCache = AutoCleanedWeakCache;\"\n      ]\n    },\n    {\n      \"name\": \"cacheSizes\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_cacheSizes = cacheSizes;\"]\n    },\n    {\n      \"name\": \"defaultCacheSizes\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"ConstEnum\",\n      \"usageExamples\": [\"type _Test_defaultCacheSizes = defaultCacheSizes;\"]\n    },\n    {\n      \"name\": \"CacheSizes\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_CacheSizes = CacheSizes;\"]\n    },\n    {\n      \"name\": \"mergeDeep\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mergeDeep<T>(sources)\"]\n    },\n    {\n      \"name\": \"mergeDeepArray\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mergeDeepArray<T>(sources)\"]\n    },\n    {\n      \"name\": \"TupleToIntersection\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_TupleToIntersection = TupleToIntersection<T>;\"\n      ]\n    },\n    {\n      \"name\": \"ReconcilerFunction\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ReconcilerFunction = ReconcilerFunction<TContextArgs>;\"\n      ]\n    },\n    {\n      \"name\": \"DeepMerger\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DeepMerger extends DeepMerger<TContextArgs> {}\",\n        \"const _test_DeepMerger = new DeepMerger<TContextArgs>(reconciler)\"\n      ]\n    },\n    {\n      \"name\": \"cloneDeep\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"cloneDeep<T>(value)\"]\n    },\n    {\n      \"name\": \"iterateObserversSafely\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"iterateObserversSafely<E, A>(observers, method, argument)\"\n      ]\n    },\n    {\n      \"name\": \"asyncMap\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"asyncMap<V, R>(observable, mapFn, catchFn)\"]\n    },\n    {\n      \"name\": \"ConcastSourcesIterable\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ConcastSourcesIterable = ConcastSourcesIterable<T>;\"\n      ]\n    },\n    {\n      \"name\": \"ConcastSourcesArray\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ConcastSourcesArray = ConcastSourcesArray<T>;\"\n      ]\n    },\n    {\n      \"name\": \"Concast\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Concast extends Concast<T> {}\",\n        \"const _test_Concast = new Concast<T>(sources)\"\n      ]\n    },\n    {\n      \"name\": \"fixObservableSubclass\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fixObservableSubclass<S>(subclass)\"]\n    },\n    {\n      \"name\": \"isNonEmptyArray\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNonEmptyArray<T>(value)\"]\n    },\n    {\n      \"name\": \"isArray\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_isArray = isArray;\"]\n    },\n    {\n      \"name\": \"isNonNullObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNonNullObject(obj)\"]\n    },\n    {\n      \"name\": \"isPlainObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isPlainObject(obj)\"]\n    },\n    {\n      \"name\": \"graphQLResultHasError\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"graphQLResultHasError<T>(result)\"]\n    },\n    {\n      \"name\": \"getGraphQLErrorsFromResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getGraphQLErrorsFromResult<T>(result)\"]\n    },\n    {\n      \"name\": \"canUseWeakMap\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canUseWeakMap = canUseWeakMap;\"]\n    },\n    {\n      \"name\": \"canUseWeakSet\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canUseWeakSet = canUseWeakSet;\"]\n    },\n    {\n      \"name\": \"canUseSymbol\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canUseSymbol = canUseSymbol;\"]\n    },\n    {\n      \"name\": \"canUseAsyncIteratorSymbol\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_canUseAsyncIteratorSymbol = canUseAsyncIteratorSymbol;\"\n      ]\n    },\n    {\n      \"name\": \"canUseDOM\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canUseDOM = canUseDOM;\"]\n    },\n    {\n      \"name\": \"canUseLayoutEffect\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canUseLayoutEffect = canUseLayoutEffect;\"]\n    },\n    {\n      \"name\": \"compact\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"compact<TArgs>(objects)\"]\n    },\n    {\n      \"name\": \"makeUniqueId\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeUniqueId(prefix)\"]\n    },\n    {\n      \"name\": \"stringifyForDisplay\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"stringifyForDisplay(value, space)\"]\n    },\n    {\n      \"name\": \"mergeOptions\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"mergeOptions<TDefaultOptions, TOptions>(defaults, options)\"\n      ]\n    },\n    {\n      \"name\": \"isExecutionPatchIncrementalResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isExecutionPatchIncrementalResult<T>(value)\"]\n    },\n    {\n      \"name\": \"isExecutionPatchInitialResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isExecutionPatchInitialResult<T>(value)\"]\n    },\n    {\n      \"name\": \"isExecutionPatchResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isExecutionPatchResult<T>(value)\"]\n    },\n    {\n      \"name\": \"isApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isApolloPayloadResult(value)\"]\n    },\n    {\n      \"name\": \"mergeIncrementalData\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"mergeIncrementalData<TData>(prevResult, result)\"]\n    },\n    {\n      \"name\": \"IsStrictlyAny\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IsStrictlyAny = IsStrictlyAny<T>;\"]\n    }\n  ],\n  \"@apollo/client/utilities/globals\": [\n    {\n      \"name\": \"maybe\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"maybe<T>(thunk)\"]\n    },\n    {\n      \"name\": \"global\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"Property\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"invariant\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_invariant = invariant;\"]\n    },\n    {\n      \"name\": \"newInvariantError\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"newInvariantError(message, optionalParams)\"]\n    },\n    {\n      \"name\": \"InvariantError\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"usageExamples\": []\n    },\n    {\n      \"name\": \"DEV\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_DEV = DEV;\"]\n    },\n    {\n      \"name\": \"___DEV__\",\n      \"moduleName\": \"@apollo/client/utilities/globals\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test____DEV__ = ___DEV__;\"]\n    }\n  ],\n  \"@apollo/client/utilities/subscriptions/relay\": [\n    {\n      \"name\": \"createFetchMultipartSubscription\",\n      \"moduleName\": \"@apollo/client/utilities/subscriptions/relay\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFetchMultipartSubscription(uri, param1)\"]\n    }\n  ]\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/exports.new.json",
    "content": "{\n  \"@apollo/client/cache\": [\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"usageExamples\": [\n        \"const _Test_ApolloCache = ApolloCache;\",\n        \"type _Test_ApolloCache_WatchFragmentOptions = ApolloCache.WatchFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloCache_WatchFragmentResult = ApolloCache.WatchFragmentResult<TData>;\",\n        \"class _Test_ApolloCache extends ApolloCache {}\",\n        \"const _test_ApolloCache = new ApolloCache()\"\n      ]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_Cache = Cache;\",\n        \"type _Test_Cache_WatchCallback = Cache.WatchCallback<TData>;\",\n        \"type _Test_Cache_ReadOptions = Cache.ReadOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteOptions = Cache.WriteOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffOptions = Cache.DiffOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WatchOptions = Cache.WatchOptions<TData, TVariables>;\",\n        \"type _Test_Cache_EvictOptions = Cache.EvictOptions;\",\n        \"type _Test_Cache_ResetOptions = Cache.ResetOptions;\",\n        \"type _Test_Cache_ModifyOptions = Cache.ModifyOptions<Entity>;\",\n        \"type _Test_Cache_BatchOptions = Cache.BatchOptions<TCache, TUpdateResult>;\",\n        \"type _Test_Cache_ReadQueryOptions = Cache.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_ReadFragmentOptions = Cache.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteQueryOptions = Cache.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteFragmentOptions = Cache.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateQueryOptions = Cache.UpdateQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateFragmentOptions = Cache.UpdateFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffResult = Cache.DiffResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"IgnoreModifier\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IgnoreModifier = IgnoreModifier;\"]\n    },\n    {\n      \"name\": \"MissingTree\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MissingTree = MissingTree;\"]\n    },\n    {\n      \"name\": \"Modifier\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Modifier = Modifier<T>;\"]\n    },\n    {\n      \"name\": \"ModifierDetails\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ModifierDetails = ModifierDetails;\"]\n    },\n    {\n      \"name\": \"Modifiers\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Modifiers = Modifiers<T>;\"]\n    },\n    {\n      \"name\": \"ReadFieldOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReadFieldOptions = ReadFieldOptions;\"]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"canonicalStringify\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canonicalStringify = canonicalStringify;\"]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"EntityStore\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_EntityStore extends EntityStore {}\",\n        \"const _test_EntityStore = new EntityStore(policies, group)\"\n      ]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"fieldNameFromStoreName\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"fieldNameFromStoreName(storeFieldName)\"]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"cacheSlot\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_cacheSlot = cacheSlot;\"]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"Policies\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Policies extends Policies {}\",\n        \"const _test_Policies = new Policies(config)\"\n      ]\n    },\n    {\n      \"name\": \"FragmentRegistryAPI\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_FragmentRegistryAPI = FragmentRegistryAPI;\"]\n    },\n    {\n      \"name\": \"createFragmentRegistry\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFragmentRegistry(fragments)\"]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/cache\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    }\n  ],\n  \"@apollo/client\": [\n    {\n      \"name\": \"ApolloClientOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloClientOptions = ApolloClientOptions;\"]\n    },\n    {\n      \"name\": \"ApolloQueryResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ApolloQueryResult = ApolloQueryResult<TData, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DefaultOptions = DefaultOptions;\"]\n    },\n    {\n      \"name\": \"DevtoolsOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DevtoolsOptions = DevtoolsOptions;\"]\n    },\n    {\n      \"name\": \"MutateResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutateResult = MutateResult<TData>;\"]\n    },\n    {\n      \"name\": \"MutationOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationOptions = MutationOptions<TData, TVariables, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryOptions = QueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloClient\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ApolloClient = ApolloClient;\",\n        \"type _Test_ApolloClient_DefaultOptions = ApolloClient.DefaultOptions;\",\n        \"type _Test_ApolloClient_Options = ApolloClient.Options;\",\n        \"type _Test_ApolloClient_DevtoolsOptions = ApolloClient.DevtoolsOptions;\",\n        \"type _Test_ApolloClient_MutateOptions = ApolloClient.MutateOptions<TData, TVariables, TCache>;\",\n        \"type _Test_ApolloClient_MutateResult = ApolloClient.MutateResult<TData>;\",\n        \"type _Test_ApolloClient_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_QueryResult = ApolloClient.QueryResult<TData>;\",\n        \"type _Test_ApolloClient_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\",\n        \"type _Test_ApolloClient_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\",\n        \"const _Test_ApolloClient_RefetchQueriesResult = ApolloClient.RefetchQueriesResult;\",\n        \"type _Test_ApolloClient_RefetchQueriesResult_AdditionalProperties = ApolloClient.RefetchQueriesResult.AdditionalProperties<TResult>;\",\n        \"type _Test_ApolloClient_SubscribeOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_SubscribeResult = ApolloClient.SubscribeResult<TData>;\",\n        \"type _Test_ApolloClient_WatchFragmentOptions = ApolloClient.WatchFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WatchFragmentResult = ApolloClient.WatchFragmentResult<TData>;\",\n        \"type _Test_ApolloClient_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_ReadQueryOptions = ApolloClient.ReadQueryOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_ReadFragmentOptions = ApolloClient.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WriteQueryOptions = ApolloClient.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WriteFragmentOptions = ApolloClient.WriteFragmentOptions<TData, TVariables>;\",\n        \"class _Test_ApolloClient extends ApolloClient {}\",\n        \"const _test_ApolloClient = new ApolloClient(options)\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQuery\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ObservableQuery = ObservableQuery;\",\n        \"type _Test_ObservableQuery_Options = ObservableQuery.Options<TData, TVariables>;\",\n        \"type _Test_ObservableQuery_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>;\",\n        \"type _Test_ObservableQuery_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\",\n        \"type _Test_ObservableQuery_CacheWatchOptions = ObservableQuery.CacheWatchOptions<TData, TVariables>;\",\n        \"type _Test_ObservableQuery_Result = ObservableQuery.Result<TData, TStates>;\",\n        \"type _Test_ObservableQuery_ResultPromise = ObservableQuery.ResultPromise<T>;\",\n        \"const _Test_ObservableQuery_DocumentationTypes = ObservableQuery.DocumentationTypes;\",\n        \"type _Test_ObservableQuery_DocumentationTypes_OperatorFunctionChain = ObservableQuery.DocumentationTypes.OperatorFunctionChain<From, To>;\",\n        \"type _Test_ObservableQuery_DocumentationTypes_ObservableMethods = ObservableQuery.DocumentationTypes.ObservableMethods<TData, OperatorResult>;\",\n        \"class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\",\n        \"const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\"\n      ]\n    },\n    {\n      \"name\": \"ErrorPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorPolicy = ErrorPolicy;\"]\n    },\n    {\n      \"name\": \"FetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FetchPolicy = FetchPolicy;\"]\n    },\n    {\n      \"name\": \"MutationFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationFetchPolicy = MutationFetchPolicy;\"]\n    },\n    {\n      \"name\": \"RefetchWritePolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RefetchWritePolicy = RefetchWritePolicy;\"]\n    },\n    {\n      \"name\": \"SubscribeToMoreFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreUpdateQueryFn\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryMapFn\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"isNetworkRequestSettled\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNetworkRequestSettled(networkStatus)\"]\n    },\n    {\n      \"name\": \"NetworkStatus\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_NetworkStatus = NetworkStatus;\"]\n    },\n    {\n      \"name\": \"DataState\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DataState = DataState<TData>;\"]\n    },\n    {\n      \"name\": \"DataValue\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_DataValue = DataValue;\",\n        \"type _Test_DataValue_Complete = DataValue.Complete<TData>;\",\n        \"type _Test_DataValue_Streaming = DataValue.Streaming<TData>;\",\n        \"type _Test_DataValue_Partial = DataValue.Partial<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DefaultContext = DefaultContext;\"]\n    },\n    {\n      \"name\": \"ErrorLike\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ErrorLike = ErrorLike;\"]\n    },\n    {\n      \"name\": \"GetDataState\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_GetDataState = GetDataState<TData, TState>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducer\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducer = MutationQueryReducer<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducersMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationUpdaterFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"NormalizedExecutionResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedExecutionResult = NormalizedExecutionResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"OnQueryUpdated\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OnQueryUpdated = OnQueryUpdated<TResult>;\"]\n    },\n    {\n      \"name\": \"OperationVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OperationVariables = OperationVariables;\"]\n    },\n    {\n      \"name\": \"RefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesPromiseResults\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionObservable\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionObservable = SubscriptionObservable<T>;\"\n      ]\n    },\n    {\n      \"name\": \"TypedDocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_TypedDocumentNode = TypedDocumentNode<TResult, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"TypeOverrides\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_TypeOverrides = TypeOverrides;\"]\n    },\n    {\n      \"name\": \"CombinedGraphQLErrors\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_CombinedGraphQLErrors = CombinedGraphQLErrors;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatterOptions = CombinedGraphQLErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatter = CombinedGraphQLErrors.MessageFormatter;\",\n        \"const _Test_CombinedGraphQLErrors_DocumentationTypes = CombinedGraphQLErrors.DocumentationTypes;\",\n        \"CombinedGraphQLErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"CombinedGraphQLErrors.DocumentationTypes.is(error)\",\n        \"type _Test_CombinedGraphQLErrors_DocumentationTypes_InstanceProperties = CombinedGraphQLErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedGraphQLErrors.is(error)\",\n        \"const _Test_CombinedGraphQLErrors_formatMessage = CombinedGraphQLErrors.formatMessage;\",\n        \"class _Test_CombinedGraphQLErrors extends CombinedGraphQLErrors {}\",\n        \"const _test_CombinedGraphQLErrors = new CombinedGraphQLErrors(result)\"\n      ]\n    },\n    {\n      \"name\": \"CombinedProtocolErrors\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_CombinedProtocolErrors = CombinedProtocolErrors;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatterOptions = CombinedProtocolErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatter = CombinedProtocolErrors.MessageFormatter;\",\n        \"const _Test_CombinedProtocolErrors_DocumentationTypes = CombinedProtocolErrors.DocumentationTypes;\",\n        \"CombinedProtocolErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"type _Test_CombinedProtocolErrors_DocumentationTypes_InstanceProperties = CombinedProtocolErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedProtocolErrors.is(error)\",\n        \"const _Test_CombinedProtocolErrors_formatMessage = CombinedProtocolErrors.formatMessage;\",\n        \"class _Test_CombinedProtocolErrors extends CombinedProtocolErrors {}\",\n        \"const _test_CombinedProtocolErrors = new CombinedProtocolErrors(protocolErrors)\"\n      ]\n    },\n    {\n      \"name\": \"LinkError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_LinkError = LinkError;\"]\n    },\n    {\n      \"name\": \"LocalStateError\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_LocalStateError = LocalStateError;\",\n        \"type _Test_LocalStateError_Options = LocalStateError.Options;\",\n        \"const _Test_LocalStateError_DocumentationTypes = LocalStateError.DocumentationTypes;\",\n        \"type _Test_LocalStateError_DocumentationTypes_InstanceProperties = LocalStateError.DocumentationTypes.InstanceProperties;\",\n        \"LocalStateError.is(error)\",\n        \"class _Test_LocalStateError extends LocalStateError {}\",\n        \"const _test_LocalStateError = new LocalStateError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ServerError = ServerError;\",\n        \"type _Test_ServerError_Options = ServerError.Options;\",\n        \"const _Test_ServerError_DocumentationTypes = ServerError.DocumentationTypes;\",\n        \"type _Test_ServerError_DocumentationTypes_InstanceProperties = ServerError.DocumentationTypes.InstanceProperties;\",\n        \"ServerError.is(error)\",\n        \"class _Test_ServerError extends ServerError {}\",\n        \"const _test_ServerError = new ServerError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ServerParseError = ServerParseError;\",\n        \"type _Test_ServerParseError_Options = ServerParseError.Options;\",\n        \"const _Test_ServerParseError_DocumentationTypes = ServerParseError.DocumentationTypes;\",\n        \"type _Test_ServerParseError_DocumentationTypes_InstanceProperties = ServerParseError.DocumentationTypes.InstanceProperties;\",\n        \"ServerParseError.is(error)\",\n        \"class _Test_ServerParseError extends ServerParseError {}\",\n        \"const _test_ServerParseError = new ServerParseError(originalParseError, options)\"\n      ]\n    },\n    {\n      \"name\": \"UnconventionalError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_UnconventionalError extends UnconventionalError {}\",\n        \"const _test_UnconventionalError = new UnconventionalError(errorType)\"\n      ]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_Cache = Cache;\",\n        \"type _Test_Cache_WatchCallback = Cache.WatchCallback<TData>;\",\n        \"type _Test_Cache_ReadOptions = Cache.ReadOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteOptions = Cache.WriteOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffOptions = Cache.DiffOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WatchOptions = Cache.WatchOptions<TData, TVariables>;\",\n        \"type _Test_Cache_EvictOptions = Cache.EvictOptions;\",\n        \"type _Test_Cache_ResetOptions = Cache.ResetOptions;\",\n        \"type _Test_Cache_ModifyOptions = Cache.ModifyOptions<Entity>;\",\n        \"type _Test_Cache_BatchOptions = Cache.BatchOptions<TCache, TUpdateResult>;\",\n        \"type _Test_Cache_ReadQueryOptions = Cache.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_ReadFragmentOptions = Cache.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteQueryOptions = Cache.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteFragmentOptions = Cache.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateQueryOptions = Cache.UpdateQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateFragmentOptions = Cache.UpdateFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffResult = Cache.DiffResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ApolloCache = ApolloCache;\",\n        \"type _Test_ApolloCache_WatchFragmentOptions = ApolloCache.WatchFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloCache_WatchFragmentResult = ApolloCache.WatchFragmentResult<TData>;\",\n        \"class _Test_ApolloCache extends ApolloCache {}\",\n        \"const _test_ApolloCache = new ApolloCache()\"\n      ]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_ApolloLink = ApolloLink;\",\n        \"type _Test_ApolloLink_ExecuteContext = ApolloLink.ExecuteContext;\",\n        \"type _Test_ApolloLink_ForwardFunction = ApolloLink.ForwardFunction;\",\n        \"type _Test_ApolloLink_Request = ApolloLink.Request;\",\n        \"type _Test_ApolloLink_RequestHandler = ApolloLink.RequestHandler;\",\n        \"type _Test_ApolloLink_Result = ApolloLink.Result<TData, TExtensions>;\",\n        \"type _Test_ApolloLink_Operation = ApolloLink.Operation;\",\n        \"type _Test_ApolloLink_OperationContext = ApolloLink.OperationContext;\",\n        \"const _Test_ApolloLink_DocumentationTypes = ApolloLink.DocumentationTypes;\",\n        \"ApolloLink.DocumentationTypes.RequestHandler(operation, forward)\",\n        \"ApolloLink.DocumentationTypes.ForwardFunction(operation)\",\n        \"ApolloLink.empty()\",\n        \"ApolloLink.from(links)\",\n        \"ApolloLink.split(test, left, right)\",\n        \"ApolloLink.execute(link, request, context)\",\n        \"ApolloLink.concat(links)\",\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GraphQLRequest = GraphQLRequest;\"]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"const _Test_HttpLink = HttpLink;\",\n        \"type _Test_HttpLink_ContextOptions = HttpLink.ContextOptions;\",\n        \"type _Test_HttpLink_Options = HttpLink.Options;\",\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Observable extends Observable<T> {}\",\n        \"const _test_Observable = new Observable<T>(subscribe)\"\n      ]\n    },\n    {\n      \"name\": \"setLogVerbosity\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setLogVerbosity(level)\"]\n    },\n    {\n      \"name\": \"disableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"disableFragmentWarnings\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableFragmentWarnings()\"]\n    },\n    {\n      \"name\": \"enableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"enableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"gql\",\n      \"moduleName\": \"@apollo/client\",\n      \"usageExamples\": [\n        \"gql(literals, args)\",\n        \"const _Test_gql = gql;\",\n        \"const _Test_gql_default = gql.default;\",\n        \"const _Test_gql_gql = gql.gql;\",\n        \"const _Test_gql_resetCaches = gql.resetCaches;\",\n        \"const _Test_gql_disableFragmentWarnings = gql.disableFragmentWarnings;\",\n        \"const _Test_gql_enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables;\",\n        \"const _Test_gql_disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;\",\n        \"const _Test_gql = gql;\",\n        \"const _Test_gql_default = gql.default;\",\n        \"const _Test_gql_gql = gql.gql;\",\n        \"const _Test_gql_resetCaches = gql.resetCaches;\",\n        \"const _Test_gql_disableFragmentWarnings = gql.disableFragmentWarnings;\",\n        \"const _Test_gql_enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables;\",\n        \"const _Test_gql_disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;\"\n      ]\n    },\n    {\n      \"name\": \"resetCaches\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"resetCaches()\"]\n    },\n    {\n      \"name\": \"build\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_build = build;\"]\n    },\n    {\n      \"name\": \"version\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_version = version;\"]\n    },\n    {\n      \"name\": \"InternalTypes\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"ValueModule\",\n      \"usageExamples\": [\n        \"const _Test_InternalTypes = InternalTypes;\",\n        \"type _Test_InternalTypes_NextFetchPolicyContext = InternalTypes.NextFetchPolicyContext<TData, TVariables>;\",\n        \"class _Test_InternalTypes_QueryManager extends InternalTypes.QueryManager {}\",\n        \"const _test_InternalTypes_QueryManager = new InternalTypes.QueryManager(options)\"\n      ]\n    },\n    {\n      \"name\": \"CustomHKT\",\n      \"moduleName\": \"@apollo/client\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_CustomHKT = CustomHKT;\"]\n    }\n  ],\n  \"@apollo/client/core\": [\n    {\n      \"name\": \"ApolloClientOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloClientOptions = ApolloClientOptions;\"]\n    },\n    {\n      \"name\": \"ApolloQueryResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_ApolloQueryResult = ApolloQueryResult<TData, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DefaultOptions = DefaultOptions;\"]\n    },\n    {\n      \"name\": \"DevtoolsOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DevtoolsOptions = DevtoolsOptions;\"]\n    },\n    {\n      \"name\": \"MutateResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutateResult = MutateResult<TData>;\"]\n    },\n    {\n      \"name\": \"MutationOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationOptions = MutationOptions<TData, TVariables, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryOptions = QueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesOptions = RefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesResult = RefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreOptions = SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionOptions = SubscriptionOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryOptions = WatchQueryOptions<TVariables, TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloClient\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ApolloClient = ApolloClient;\",\n        \"type _Test_ApolloClient_DefaultOptions = ApolloClient.DefaultOptions;\",\n        \"type _Test_ApolloClient_Options = ApolloClient.Options;\",\n        \"type _Test_ApolloClient_DevtoolsOptions = ApolloClient.DevtoolsOptions;\",\n        \"type _Test_ApolloClient_MutateOptions = ApolloClient.MutateOptions<TData, TVariables, TCache>;\",\n        \"type _Test_ApolloClient_MutateResult = ApolloClient.MutateResult<TData>;\",\n        \"type _Test_ApolloClient_QueryOptions = ApolloClient.QueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_QueryResult = ApolloClient.QueryResult<TData>;\",\n        \"type _Test_ApolloClient_RefetchQueriesOptions = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\",\n        \"type _Test_ApolloClient_RefetchQueriesResult = ApolloClient.RefetchQueriesResult<TResult>;\",\n        \"const _Test_ApolloClient_RefetchQueriesResult = ApolloClient.RefetchQueriesResult;\",\n        \"type _Test_ApolloClient_RefetchQueriesResult_AdditionalProperties = ApolloClient.RefetchQueriesResult.AdditionalProperties<TResult>;\",\n        \"type _Test_ApolloClient_SubscribeOptions = ApolloClient.SubscribeOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_SubscribeResult = ApolloClient.SubscribeResult<TData>;\",\n        \"type _Test_ApolloClient_WatchFragmentOptions = ApolloClient.WatchFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WatchFragmentResult = ApolloClient.WatchFragmentResult<TData>;\",\n        \"type _Test_ApolloClient_WatchQueryOptions = ApolloClient.WatchQueryOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_Base = ApolloClient.Base;\",\n        \"type _Test_ApolloClient_Base_ReadQueryOptions = ApolloClient.Base.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_ReadFragmentOptions = ApolloClient.Base.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteQueryOptions = ApolloClient.Base.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_Base_WriteFragmentOptions = ApolloClient.Base.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_ReadQueryOptions = ApolloClient.ReadQueryOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"const _Test_ApolloClient_DocumentationTypes = ApolloClient.DocumentationTypes;\",\n        \"type _Test_ApolloClient_DocumentationTypes_ReadQueryOptions = ApolloClient.DocumentationTypes.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteQueryOptions = ApolloClient.DocumentationTypes.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_DocumentationTypes_WriteFragmentOptions = ApolloClient.DocumentationTypes.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_ReadFragmentOptions = ApolloClient.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WriteQueryOptions = ApolloClient.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_ApolloClient_WriteFragmentOptions = ApolloClient.WriteFragmentOptions<TData, TVariables>;\",\n        \"class _Test_ApolloClient extends ApolloClient {}\",\n        \"const _test_ApolloClient = new ApolloClient(options)\"\n      ]\n    },\n    {\n      \"name\": \"ObservableQuery\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ObservableQuery = ObservableQuery;\",\n        \"type _Test_ObservableQuery_Options = ObservableQuery.Options<TData, TVariables>;\",\n        \"type _Test_ObservableQuery_FetchMoreOptions = ObservableQuery.FetchMoreOptions<TData, TVariables, TFetchData, TFetchVars>;\",\n        \"type _Test_ObservableQuery_SubscribeToMoreOptions = ObservableQuery.SubscribeToMoreOptions<TData, TSubscriptionVariables, TSubscriptionData, TVariables>;\",\n        \"type _Test_ObservableQuery_CacheWatchOptions = ObservableQuery.CacheWatchOptions<TData, TVariables>;\",\n        \"type _Test_ObservableQuery_Result = ObservableQuery.Result<TData, TStates>;\",\n        \"type _Test_ObservableQuery_ResultPromise = ObservableQuery.ResultPromise<T>;\",\n        \"const _Test_ObservableQuery_DocumentationTypes = ObservableQuery.DocumentationTypes;\",\n        \"type _Test_ObservableQuery_DocumentationTypes_OperatorFunctionChain = ObservableQuery.DocumentationTypes.OperatorFunctionChain<From, To>;\",\n        \"type _Test_ObservableQuery_DocumentationTypes_ObservableMethods = ObservableQuery.DocumentationTypes.ObservableMethods<TData, OperatorResult>;\",\n        \"class _Test_ObservableQuery extends ObservableQuery<TData, TVariables> {}\",\n        \"const _test_ObservableQuery = new ObservableQuery<TData, TVariables>(param0)\"\n      ]\n    },\n    {\n      \"name\": \"ErrorPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorPolicy = ErrorPolicy;\"]\n    },\n    {\n      \"name\": \"FetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FetchPolicy = FetchPolicy;\"]\n    },\n    {\n      \"name\": \"MutationFetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationFetchPolicy = MutationFetchPolicy;\"]\n    },\n    {\n      \"name\": \"RefetchWritePolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RefetchWritePolicy = RefetchWritePolicy;\"]\n    },\n    {\n      \"name\": \"SubscribeToMoreFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreFunction = SubscribeToMoreFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscribeToMoreUpdateQueryFn\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscribeToMoreUpdateQueryFn = SubscribeToMoreUpdateQueryFn<TData, TVariables, TSubscriptionData>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryMapFn\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryMapFn = UpdateQueryMapFn<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UpdateQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UpdateQueryOptions = UpdateQueryOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchQueryFetchPolicy = WatchQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"isNetworkRequestSettled\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isNetworkRequestSettled(networkStatus)\"]\n    },\n    {\n      \"name\": \"NetworkStatus\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"RegularEnum\",\n      \"usageExamples\": [\"type _Test_NetworkStatus = NetworkStatus;\"]\n    },\n    {\n      \"name\": \"DataState\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DataState = DataState<TData>;\"]\n    },\n    {\n      \"name\": \"DataValue\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_DataValue = DataValue;\",\n        \"type _Test_DataValue_Complete = DataValue.Complete<TData>;\",\n        \"type _Test_DataValue_Streaming = DataValue.Streaming<TData>;\",\n        \"type _Test_DataValue_Partial = DataValue.Partial<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"DefaultContext\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DefaultContext = DefaultContext;\"]\n    },\n    {\n      \"name\": \"ErrorLike\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ErrorLike = ErrorLike;\"]\n    },\n    {\n      \"name\": \"GetDataState\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_GetDataState = GetDataState<TData, TState>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesInclude = InternalRefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesMap = InternalRefetchQueriesMap<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesOptions = InternalRefetchQueriesOptions<TCache, TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueriesResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueriesResult = InternalRefetchQueriesResult<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"InternalRefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_InternalRefetchQueryDescriptor = InternalRefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducer\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducer = MutationQueryReducer<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationQueryReducersMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationQueryReducersMap = MutationQueryReducersMap<T>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationUpdaterFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationUpdaterFunction = MutationUpdaterFunction<TData, TVariables, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"NormalizedExecutionResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedExecutionResult = NormalizedExecutionResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"OnQueryUpdated\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OnQueryUpdated = OnQueryUpdated<TResult>;\"]\n    },\n    {\n      \"name\": \"OperationVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OperationVariables = OperationVariables;\"]\n    },\n    {\n      \"name\": \"RefetchQueriesInclude\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesInclude = RefetchQueriesInclude;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueriesPromiseResults\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueriesPromiseResults = RefetchQueriesPromiseResults<TResult>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchQueryDescriptor\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchQueryDescriptor = RefetchQueryDescriptor;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionObservable\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionObservable = SubscriptionObservable<T>;\"\n      ]\n    },\n    {\n      \"name\": \"TypedDocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_TypedDocumentNode = TypedDocumentNode<TResult, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"TypeOverrides\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_TypeOverrides = TypeOverrides;\"]\n    },\n    {\n      \"name\": \"CombinedGraphQLErrors\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_CombinedGraphQLErrors = CombinedGraphQLErrors;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatterOptions = CombinedGraphQLErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatter = CombinedGraphQLErrors.MessageFormatter;\",\n        \"const _Test_CombinedGraphQLErrors_DocumentationTypes = CombinedGraphQLErrors.DocumentationTypes;\",\n        \"CombinedGraphQLErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"CombinedGraphQLErrors.DocumentationTypes.is(error)\",\n        \"type _Test_CombinedGraphQLErrors_DocumentationTypes_InstanceProperties = CombinedGraphQLErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedGraphQLErrors.is(error)\",\n        \"const _Test_CombinedGraphQLErrors_formatMessage = CombinedGraphQLErrors.formatMessage;\",\n        \"class _Test_CombinedGraphQLErrors extends CombinedGraphQLErrors {}\",\n        \"const _test_CombinedGraphQLErrors = new CombinedGraphQLErrors(result)\"\n      ]\n    },\n    {\n      \"name\": \"CombinedProtocolErrors\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_CombinedProtocolErrors = CombinedProtocolErrors;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatterOptions = CombinedProtocolErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatter = CombinedProtocolErrors.MessageFormatter;\",\n        \"const _Test_CombinedProtocolErrors_DocumentationTypes = CombinedProtocolErrors.DocumentationTypes;\",\n        \"CombinedProtocolErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"type _Test_CombinedProtocolErrors_DocumentationTypes_InstanceProperties = CombinedProtocolErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedProtocolErrors.is(error)\",\n        \"const _Test_CombinedProtocolErrors_formatMessage = CombinedProtocolErrors.formatMessage;\",\n        \"class _Test_CombinedProtocolErrors extends CombinedProtocolErrors {}\",\n        \"const _test_CombinedProtocolErrors = new CombinedProtocolErrors(protocolErrors)\"\n      ]\n    },\n    {\n      \"name\": \"LinkError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_LinkError = LinkError;\"]\n    },\n    {\n      \"name\": \"LocalStateError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_LocalStateError = LocalStateError;\",\n        \"type _Test_LocalStateError_Options = LocalStateError.Options;\",\n        \"const _Test_LocalStateError_DocumentationTypes = LocalStateError.DocumentationTypes;\",\n        \"type _Test_LocalStateError_DocumentationTypes_InstanceProperties = LocalStateError.DocumentationTypes.InstanceProperties;\",\n        \"LocalStateError.is(error)\",\n        \"class _Test_LocalStateError extends LocalStateError {}\",\n        \"const _test_LocalStateError = new LocalStateError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ServerError = ServerError;\",\n        \"type _Test_ServerError_Options = ServerError.Options;\",\n        \"const _Test_ServerError_DocumentationTypes = ServerError.DocumentationTypes;\",\n        \"type _Test_ServerError_DocumentationTypes_InstanceProperties = ServerError.DocumentationTypes.InstanceProperties;\",\n        \"ServerError.is(error)\",\n        \"class _Test_ServerError extends ServerError {}\",\n        \"const _test_ServerError = new ServerError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ServerParseError = ServerParseError;\",\n        \"type _Test_ServerParseError_Options = ServerParseError.Options;\",\n        \"const _Test_ServerParseError_DocumentationTypes = ServerParseError.DocumentationTypes;\",\n        \"type _Test_ServerParseError_DocumentationTypes_InstanceProperties = ServerParseError.DocumentationTypes.InstanceProperties;\",\n        \"ServerParseError.is(error)\",\n        \"class _Test_ServerParseError extends ServerParseError {}\",\n        \"const _test_ServerParseError = new ServerParseError(originalParseError, options)\"\n      ]\n    },\n    {\n      \"name\": \"UnconventionalError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_UnconventionalError extends UnconventionalError {}\",\n        \"const _test_UnconventionalError = new UnconventionalError(errorType)\"\n      ]\n    },\n    {\n      \"name\": \"ApolloReducerConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ApolloReducerConfig = ApolloReducerConfig;\"]\n    },\n    {\n      \"name\": \"Cache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_Cache = Cache;\",\n        \"type _Test_Cache_WatchCallback = Cache.WatchCallback<TData>;\",\n        \"type _Test_Cache_ReadOptions = Cache.ReadOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteOptions = Cache.WriteOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffOptions = Cache.DiffOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WatchOptions = Cache.WatchOptions<TData, TVariables>;\",\n        \"type _Test_Cache_EvictOptions = Cache.EvictOptions;\",\n        \"type _Test_Cache_ResetOptions = Cache.ResetOptions;\",\n        \"type _Test_Cache_ModifyOptions = Cache.ModifyOptions<Entity>;\",\n        \"type _Test_Cache_BatchOptions = Cache.BatchOptions<TCache, TUpdateResult>;\",\n        \"type _Test_Cache_ReadQueryOptions = Cache.ReadQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_ReadFragmentOptions = Cache.ReadFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteQueryOptions = Cache.WriteQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_WriteFragmentOptions = Cache.WriteFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateQueryOptions = Cache.UpdateQueryOptions<TData, TVariables>;\",\n        \"type _Test_Cache_UpdateFragmentOptions = Cache.UpdateFragmentOptions<TData, TVariables>;\",\n        \"type _Test_Cache_DiffResult = Cache.DiffResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"DiffQueryAgainstStoreOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DiffQueryAgainstStoreOptions = DiffQueryAgainstStoreOptions;\"\n      ]\n    },\n    {\n      \"name\": \"FieldFunctionOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_FieldFunctionOptions = FieldFunctionOptions<TArgs, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldMergeFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldMergeFunction = FieldMergeFunction<TExisting, TIncoming, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldPolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldPolicy = FieldPolicy<TExisting, TIncoming, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"FieldReadFunction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FieldReadFunction = FieldReadFunction<TExisting, TReadResult, TOptions>;\"\n      ]\n    },\n    {\n      \"name\": \"IdGetter\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_IdGetter = IdGetter;\"]\n    },\n    {\n      \"name\": \"IdGetterObj\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_IdGetterObj = IdGetterObj;\"]\n    },\n    {\n      \"name\": \"InMemoryCacheConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_InMemoryCacheConfig = InMemoryCacheConfig;\"]\n    },\n    {\n      \"name\": \"MergeInfo\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeInfo = MergeInfo;\"]\n    },\n    {\n      \"name\": \"MergeTree\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_MergeTree = MergeTree;\"]\n    },\n    {\n      \"name\": \"NormalizedCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_NormalizedCache = NormalizedCache;\"]\n    },\n    {\n      \"name\": \"NormalizedCacheObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_NormalizedCacheObject = NormalizedCacheObject;\"\n      ]\n    },\n    {\n      \"name\": \"OptimisticStoreItem\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OptimisticStoreItem = OptimisticStoreItem;\"]\n    },\n    {\n      \"name\": \"PossibleTypesMap\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_PossibleTypesMap = PossibleTypesMap;\"]\n    },\n    {\n      \"name\": \"ReactiveVar\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ReactiveVar = ReactiveVar<T>;\"]\n    },\n    {\n      \"name\": \"ReadMergeModifyContext\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ReadMergeModifyContext = ReadMergeModifyContext;\"\n      ]\n    },\n    {\n      \"name\": \"ReadQueryOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ReadQueryOptions = ReadQueryOptions;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"Transaction\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Transaction = Transaction;\"]\n    },\n    {\n      \"name\": \"TypePolicies\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicies = TypePolicies;\"]\n    },\n    {\n      \"name\": \"TypePolicy\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_TypePolicy = TypePolicy;\"]\n    },\n    {\n      \"name\": \"WatchFragmentOptions\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentOptions = WatchFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"WatchFragmentResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_WatchFragmentResult = WatchFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ApolloCache = ApolloCache;\",\n        \"type _Test_ApolloCache_WatchFragmentOptions = ApolloCache.WatchFragmentOptions<TData, TVariables>;\",\n        \"type _Test_ApolloCache_WatchFragmentResult = ApolloCache.WatchFragmentResult<TData>;\",\n        \"class _Test_ApolloCache extends ApolloCache {}\",\n        \"const _test_ApolloCache = new ApolloCache()\"\n      ]\n    },\n    {\n      \"name\": \"defaultDataIdFromObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"defaultDataIdFromObject(param0, context)\"]\n    },\n    {\n      \"name\": \"InMemoryCache\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InMemoryCache extends InMemoryCache {}\",\n        \"const _test_InMemoryCache = new InMemoryCache(config)\"\n      ]\n    },\n    {\n      \"name\": \"makeVar\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"makeVar<T>(value)\"]\n    },\n    {\n      \"name\": \"MissingFieldError\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_MissingFieldError extends MissingFieldError {}\",\n        \"const _test_MissingFieldError = new MissingFieldError(message, path, query, variables)\"\n      ]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_ApolloLink = ApolloLink;\",\n        \"type _Test_ApolloLink_ExecuteContext = ApolloLink.ExecuteContext;\",\n        \"type _Test_ApolloLink_ForwardFunction = ApolloLink.ForwardFunction;\",\n        \"type _Test_ApolloLink_Request = ApolloLink.Request;\",\n        \"type _Test_ApolloLink_RequestHandler = ApolloLink.RequestHandler;\",\n        \"type _Test_ApolloLink_Result = ApolloLink.Result<TData, TExtensions>;\",\n        \"type _Test_ApolloLink_Operation = ApolloLink.Operation;\",\n        \"type _Test_ApolloLink_OperationContext = ApolloLink.OperationContext;\",\n        \"const _Test_ApolloLink_DocumentationTypes = ApolloLink.DocumentationTypes;\",\n        \"ApolloLink.DocumentationTypes.RequestHandler(operation, forward)\",\n        \"ApolloLink.DocumentationTypes.ForwardFunction(operation)\",\n        \"ApolloLink.empty()\",\n        \"ApolloLink.from(links)\",\n        \"ApolloLink.split(test, left, right)\",\n        \"ApolloLink.execute(link, request, context)\",\n        \"ApolloLink.concat(links)\",\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GraphQLRequest = GraphQLRequest;\"]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"const _Test_HttpLink = HttpLink;\",\n        \"type _Test_HttpLink_ContextOptions = HttpLink.ContextOptions;\",\n        \"type _Test_HttpLink_Options = HttpLink.Options;\",\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Observable extends Observable<T> {}\",\n        \"const _test_Observable = new Observable<T>(subscribe)\"\n      ]\n    },\n    {\n      \"name\": \"setLogVerbosity\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setLogVerbosity(level)\"]\n    },\n    {\n      \"name\": \"disableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"disableFragmentWarnings\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"disableFragmentWarnings()\"]\n    },\n    {\n      \"name\": \"enableExperimentalFragmentVariables\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"enableExperimentalFragmentVariables()\"]\n    },\n    {\n      \"name\": \"gql\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"usageExamples\": [\n        \"gql(literals, args)\",\n        \"const _Test_gql = gql;\",\n        \"const _Test_gql_default = gql.default;\",\n        \"const _Test_gql_gql = gql.gql;\",\n        \"const _Test_gql_resetCaches = gql.resetCaches;\",\n        \"const _Test_gql_disableFragmentWarnings = gql.disableFragmentWarnings;\",\n        \"const _Test_gql_enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables;\",\n        \"const _Test_gql_disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;\",\n        \"const _Test_gql = gql;\",\n        \"const _Test_gql_default = gql.default;\",\n        \"const _Test_gql_gql = gql.gql;\",\n        \"const _Test_gql_resetCaches = gql.resetCaches;\",\n        \"const _Test_gql_disableFragmentWarnings = gql.disableFragmentWarnings;\",\n        \"const _Test_gql_enableExperimentalFragmentVariables = gql.enableExperimentalFragmentVariables;\",\n        \"const _Test_gql_disableExperimentalFragmentVariables = gql.disableExperimentalFragmentVariables;\"\n      ]\n    },\n    {\n      \"name\": \"resetCaches\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"resetCaches()\"]\n    },\n    {\n      \"name\": \"build\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_build = build;\"]\n    },\n    {\n      \"name\": \"version\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_version = version;\"]\n    },\n    {\n      \"name\": \"InternalTypes\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"ValueModule\",\n      \"usageExamples\": [\n        \"const _Test_InternalTypes = InternalTypes;\",\n        \"type _Test_InternalTypes_NextFetchPolicyContext = InternalTypes.NextFetchPolicyContext<TData, TVariables>;\",\n        \"class _Test_InternalTypes_QueryManager extends InternalTypes.QueryManager {}\",\n        \"const _test_InternalTypes_QueryManager = new InternalTypes.QueryManager(options)\"\n      ]\n    },\n    {\n      \"name\": \"CustomHKT\",\n      \"moduleName\": \"@apollo/client/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_CustomHKT = CustomHKT;\"]\n    }\n  ],\n  \"@apollo/client/dev\": [\n    {\n      \"name\": \"loadDevMessages\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadDevMessages()\"]\n    },\n    {\n      \"name\": \"loadErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadErrorMessageHandler(errorCodes)\"]\n    },\n    {\n      \"name\": \"loadErrorMessages\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"loadErrorMessages()\"]\n    },\n    {\n      \"name\": \"setErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setErrorMessageHandler(handler)\"]\n    },\n    {\n      \"name\": \"ErrorMessageHandler\",\n      \"moduleName\": \"@apollo/client/dev\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ErrorMessageHandler = ErrorMessageHandler;\"]\n    }\n  ],\n  \"@apollo/client/errors\": [\n    {\n      \"name\": \"graphQLResultHasProtocolErrors\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"graphQLResultHasProtocolErrors<T>(result)\"]\n    },\n    {\n      \"name\": \"toErrorLike\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"toErrorLike(error)\"]\n    },\n    {\n      \"name\": \"PROTOCOL_ERRORS_SYMBOL\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_PROTOCOL_ERRORS_SYMBOL = PROTOCOL_ERRORS_SYMBOL;\"\n      ]\n    },\n    {\n      \"name\": \"CombinedGraphQLErrors\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"usageExamples\": [\n        \"const _Test_CombinedGraphQLErrors = CombinedGraphQLErrors;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatterOptions = CombinedGraphQLErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedGraphQLErrors_MessageFormatter = CombinedGraphQLErrors.MessageFormatter;\",\n        \"const _Test_CombinedGraphQLErrors_DocumentationTypes = CombinedGraphQLErrors.DocumentationTypes;\",\n        \"CombinedGraphQLErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"CombinedGraphQLErrors.DocumentationTypes.is(error)\",\n        \"type _Test_CombinedGraphQLErrors_DocumentationTypes_InstanceProperties = CombinedGraphQLErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedGraphQLErrors.is(error)\",\n        \"const _Test_CombinedGraphQLErrors_formatMessage = CombinedGraphQLErrors.formatMessage;\",\n        \"class _Test_CombinedGraphQLErrors extends CombinedGraphQLErrors {}\",\n        \"const _test_CombinedGraphQLErrors = new CombinedGraphQLErrors(result)\"\n      ]\n    },\n    {\n      \"name\": \"CombinedProtocolErrors\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"usageExamples\": [\n        \"const _Test_CombinedProtocolErrors = CombinedProtocolErrors;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatterOptions = CombinedProtocolErrors.MessageFormatterOptions;\",\n        \"type _Test_CombinedProtocolErrors_MessageFormatter = CombinedProtocolErrors.MessageFormatter;\",\n        \"const _Test_CombinedProtocolErrors_DocumentationTypes = CombinedProtocolErrors.DocumentationTypes;\",\n        \"CombinedProtocolErrors.DocumentationTypes.formatMessage(errors, options)\",\n        \"type _Test_CombinedProtocolErrors_DocumentationTypes_InstanceProperties = CombinedProtocolErrors.DocumentationTypes.InstanceProperties;\",\n        \"CombinedProtocolErrors.is(error)\",\n        \"const _Test_CombinedProtocolErrors_formatMessage = CombinedProtocolErrors.formatMessage;\",\n        \"class _Test_CombinedProtocolErrors extends CombinedProtocolErrors {}\",\n        \"const _test_CombinedProtocolErrors = new CombinedProtocolErrors(protocolErrors)\"\n      ]\n    },\n    {\n      \"name\": \"isErrorLike\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isErrorLike(error)\"]\n    },\n    {\n      \"name\": \"LinkError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_LinkError = LinkError;\"]\n    },\n    {\n      \"name\": \"registerLinkError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"registerLinkError(error)\"]\n    },\n    {\n      \"name\": \"LocalStateError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"usageExamples\": [\n        \"const _Test_LocalStateError = LocalStateError;\",\n        \"type _Test_LocalStateError_Options = LocalStateError.Options;\",\n        \"const _Test_LocalStateError_DocumentationTypes = LocalStateError.DocumentationTypes;\",\n        \"type _Test_LocalStateError_DocumentationTypes_InstanceProperties = LocalStateError.DocumentationTypes.InstanceProperties;\",\n        \"LocalStateError.is(error)\",\n        \"class _Test_LocalStateError extends LocalStateError {}\",\n        \"const _test_LocalStateError = new LocalStateError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"usageExamples\": [\n        \"const _Test_ServerError = ServerError;\",\n        \"type _Test_ServerError_Options = ServerError.Options;\",\n        \"const _Test_ServerError_DocumentationTypes = ServerError.DocumentationTypes;\",\n        \"type _Test_ServerError_DocumentationTypes_InstanceProperties = ServerError.DocumentationTypes.InstanceProperties;\",\n        \"ServerError.is(error)\",\n        \"class _Test_ServerError extends ServerError {}\",\n        \"const _test_ServerError = new ServerError(message, options)\"\n      ]\n    },\n    {\n      \"name\": \"ServerParseError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"usageExamples\": [\n        \"const _Test_ServerParseError = ServerParseError;\",\n        \"type _Test_ServerParseError_Options = ServerParseError.Options;\",\n        \"const _Test_ServerParseError_DocumentationTypes = ServerParseError.DocumentationTypes;\",\n        \"type _Test_ServerParseError_DocumentationTypes_InstanceProperties = ServerParseError.DocumentationTypes.InstanceProperties;\",\n        \"ServerParseError.is(error)\",\n        \"class _Test_ServerParseError extends ServerParseError {}\",\n        \"const _test_ServerParseError = new ServerParseError(originalParseError, options)\"\n      ]\n    },\n    {\n      \"name\": \"UnconventionalError\",\n      \"moduleName\": \"@apollo/client/errors\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_UnconventionalError extends UnconventionalError {}\",\n        \"const _test_UnconventionalError = new UnconventionalError(errorType)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/batch\": [\n    {\n      \"name\": \"BatchLink\",\n      \"moduleName\": \"@apollo/client/link/batch\",\n      \"usageExamples\": [\n        \"const _Test_BatchLink = BatchLink;\",\n        \"const _Test_BatchLink_Shared = BatchLink.Shared;\",\n        \"type _Test_BatchLink_Shared_Options = BatchLink.Shared.Options;\",\n        \"type _Test_BatchLink_BatchHandler = BatchLink.BatchHandler;\",\n        \"type _Test_BatchLink_Options = BatchLink.Options;\",\n        \"class _Test_BatchLink extends BatchLink {}\",\n        \"const _test_BatchLink = new BatchLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/batch-http\": [\n    {\n      \"name\": \"BaseBatchHttpLink\",\n      \"moduleName\": \"@apollo/client/link/batch-http\",\n      \"usageExamples\": [\n        \"const _Test_BaseBatchHttpLink = BaseBatchHttpLink;\",\n        \"type _Test_BaseBatchHttpLink_ContextOptions = BaseBatchHttpLink.ContextOptions;\",\n        \"type _Test_BaseBatchHttpLink_Options = BaseBatchHttpLink.Options;\",\n        \"class _Test_BaseBatchHttpLink extends BaseBatchHttpLink {}\",\n        \"const _test_BaseBatchHttpLink = new BaseBatchHttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"BatchHttpLink\",\n      \"moduleName\": \"@apollo/client/link/batch-http\",\n      \"usageExamples\": [\n        \"const _Test_BatchHttpLink = BatchHttpLink;\",\n        \"type _Test_BatchHttpLink_Options = BatchHttpLink.Options;\",\n        \"type _Test_BatchHttpLink_ContextOptions = BatchHttpLink.ContextOptions;\",\n        \"class _Test_BatchHttpLink extends BatchHttpLink {}\",\n        \"const _test_BatchHttpLink = new BatchHttpLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/context\": [\n    {\n      \"name\": \"setContext\",\n      \"moduleName\": \"@apollo/client/link/context\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"setContext(setter)\"]\n    },\n    {\n      \"name\": \"SetContextLink\",\n      \"moduleName\": \"@apollo/client/link/context\",\n      \"usageExamples\": [\n        \"const _Test_SetContextLink = SetContextLink;\",\n        \"const _Test_SetContextLink_SetContextLinkDocumentationTypes = SetContextLink.SetContextLinkDocumentationTypes;\",\n        \"SetContextLink.SetContextLinkDocumentationTypes.ContextSetter(prevContext, operation)\",\n        \"type _Test_SetContextLink_ContextSetter = SetContextLink.ContextSetter;\",\n        \"type _Test_SetContextLink_LegacyContextSetter = SetContextLink.LegacyContextSetter;\",\n        \"type _Test_SetContextLink_SetContextOperation = SetContextLink.SetContextOperation;\",\n        \"class _Test_SetContextLink extends SetContextLink {}\",\n        \"const _test_SetContextLink = new SetContextLink(setter)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/core\": [\n    {\n      \"name\": \"empty\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_empty = empty;\"]\n    },\n    {\n      \"name\": \"from\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_from = from;\"]\n    },\n    {\n      \"name\": \"split\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_split = split;\"]\n    },\n    {\n      \"name\": \"concat\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_concat = concat;\"]\n    },\n    {\n      \"name\": \"execute\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_execute = execute;\"]\n    },\n    {\n      \"name\": \"ApolloLink\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"usageExamples\": [\n        \"const _Test_ApolloLink = ApolloLink;\",\n        \"type _Test_ApolloLink_ExecuteContext = ApolloLink.ExecuteContext;\",\n        \"type _Test_ApolloLink_ForwardFunction = ApolloLink.ForwardFunction;\",\n        \"type _Test_ApolloLink_Request = ApolloLink.Request;\",\n        \"type _Test_ApolloLink_RequestHandler = ApolloLink.RequestHandler;\",\n        \"type _Test_ApolloLink_Result = ApolloLink.Result<TData, TExtensions>;\",\n        \"type _Test_ApolloLink_Operation = ApolloLink.Operation;\",\n        \"type _Test_ApolloLink_OperationContext = ApolloLink.OperationContext;\",\n        \"const _Test_ApolloLink_DocumentationTypes = ApolloLink.DocumentationTypes;\",\n        \"ApolloLink.DocumentationTypes.RequestHandler(operation, forward)\",\n        \"ApolloLink.DocumentationTypes.ForwardFunction(operation)\",\n        \"ApolloLink.empty()\",\n        \"ApolloLink.from(links)\",\n        \"ApolloLink.split(test, left, right)\",\n        \"ApolloLink.execute(link, request, context)\",\n        \"ApolloLink.concat(links)\",\n        \"class _Test_ApolloLink extends ApolloLink {}\",\n        \"const _test_ApolloLink = new ApolloLink(request)\"\n      ]\n    },\n    {\n      \"name\": \"AdditionalApolloLinkResultTypes\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_AdditionalApolloLinkResultTypes = AdditionalApolloLinkResultTypes<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"ApolloPayloadResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_ApolloPayloadResult = ApolloPayloadResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"DocumentNode\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DocumentNode = DocumentNode;\"]\n    },\n    {\n      \"name\": \"FetchResult\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchResult = FetchResult<TData, TExtensions>;\"\n      ]\n    },\n    {\n      \"name\": \"GraphQLRequest\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_GraphQLRequest = GraphQLRequest;\"]\n    },\n    {\n      \"name\": \"Operation\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Operation = Operation;\"]\n    },\n    {\n      \"name\": \"RequestHandler\",\n      \"moduleName\": \"@apollo/client/link/core\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_RequestHandler = RequestHandler;\"]\n    }\n  ],\n  \"@apollo/client/link/error\": [\n    {\n      \"name\": \"onError\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"onError(errorHandler)\"]\n    },\n    {\n      \"name\": \"ErrorLink\",\n      \"moduleName\": \"@apollo/client/link/error\",\n      \"usageExamples\": [\n        \"const _Test_ErrorLink = ErrorLink;\",\n        \"const _Test_ErrorLink_ErrorLinkDocumentationTypes = ErrorLink.ErrorLinkDocumentationTypes;\",\n        \"ErrorLink.ErrorLinkDocumentationTypes.ErrorHandler(options)\",\n        \"type _Test_ErrorLink_ErrorHandler = ErrorLink.ErrorHandler;\",\n        \"type _Test_ErrorLink_ErrorHandlerOptions = ErrorLink.ErrorHandlerOptions;\",\n        \"class _Test_ErrorLink extends ErrorLink {}\",\n        \"const _test_ErrorLink = new ErrorLink(errorHandler)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/http\": [\n    {\n      \"name\": \"parseAndCheckHttpResponse\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"parseAndCheckHttpResponse(operations)\"]\n    },\n    {\n      \"name\": \"defaultPrinter\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_defaultPrinter = defaultPrinter;\"]\n    },\n    {\n      \"name\": \"fallbackHttpConfig\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_fallbackHttpConfig = fallbackHttpConfig;\"]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBody\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBody(operation, fallbackConfig, configs)\"\n      ]\n    },\n    {\n      \"name\": \"selectHttpOptionsAndBodyInternal\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"selectHttpOptionsAndBodyInternal(operation, printer, configs)\"\n      ]\n    },\n    {\n      \"name\": \"checkFetcher\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_checkFetcher = checkFetcher;\"]\n    },\n    {\n      \"name\": \"createSignalIfSupported\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createSignalIfSupported = createSignalIfSupported;\"\n      ]\n    },\n    {\n      \"name\": \"selectURI\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_selectURI = selectURI;\"]\n    },\n    {\n      \"name\": \"BaseHttpLink\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"usageExamples\": [\n        \"const _Test_BaseHttpLink = BaseHttpLink;\",\n        \"type _Test_BaseHttpLink_ContextOptions = BaseHttpLink.ContextOptions;\",\n        \"type _Test_BaseHttpLink_HttpOptions = BaseHttpLink.HttpOptions;\",\n        \"const _Test_BaseHttpLink_Shared = BaseHttpLink.Shared;\",\n        \"type _Test_BaseHttpLink_Shared_Options = BaseHttpLink.Shared.Options;\",\n        \"type _Test_BaseHttpLink_Options = BaseHttpLink.Options;\",\n        \"type _Test_BaseHttpLink_Body = BaseHttpLink.Body;\",\n        \"type _Test_BaseHttpLink_Printer = BaseHttpLink.Printer;\",\n        \"type _Test_BaseHttpLink_UriFunction = BaseHttpLink.UriFunction;\",\n        \"class _Test_BaseHttpLink extends BaseHttpLink {}\",\n        \"const _test_BaseHttpLink = new BaseHttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"createHttpLink\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_createHttpLink = createHttpLink;\"]\n    },\n    {\n      \"name\": \"HttpLink\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"usageExamples\": [\n        \"const _Test_HttpLink = HttpLink;\",\n        \"type _Test_HttpLink_ContextOptions = HttpLink.ContextOptions;\",\n        \"type _Test_HttpLink_Options = HttpLink.Options;\",\n        \"class _Test_HttpLink extends HttpLink {}\",\n        \"const _test_HttpLink = new HttpLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"rewriteURIForGET\",\n      \"moduleName\": \"@apollo/client/link/http\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"rewriteURIForGET(chosenURI, body)\"]\n    }\n  ],\n  \"@apollo/client/link/persisted-queries\": [\n    {\n      \"name\": \"VERSION\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_VERSION = VERSION;\"]\n    },\n    {\n      \"name\": \"PersistedQueryLink\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"usageExamples\": [\n        \"const _Test_PersistedQueryLink = PersistedQueryLink;\",\n        \"const _Test_PersistedQueryLink_PersistedQueryLinkDocumentationTypes = PersistedQueryLink.PersistedQueryLinkDocumentationTypes;\",\n        \"PersistedQueryLink.PersistedQueryLinkDocumentationTypes.SHA256Function(queryString)\",\n        \"PersistedQueryLink.PersistedQueryLinkDocumentationTypes.GenerateHashFunction(document)\",\n        \"const _Test_PersistedQueryLink_Base = PersistedQueryLink.Base;\",\n        \"type _Test_PersistedQueryLink_Base_Options = PersistedQueryLink.Base.Options;\",\n        \"type _Test_PersistedQueryLink_ErrorMeta = PersistedQueryLink.ErrorMeta;\",\n        \"type _Test_PersistedQueryLink_GenerateHashFunction = PersistedQueryLink.GenerateHashFunction;\",\n        \"type _Test_PersistedQueryLink_SHA256Function = PersistedQueryLink.SHA256Function;\",\n        \"type _Test_PersistedQueryLink_SHA256Options = PersistedQueryLink.SHA256Options;\",\n        \"type _Test_PersistedQueryLink_GenerateHashOptions = PersistedQueryLink.GenerateHashOptions;\",\n        \"type _Test_PersistedQueryLink_Options = PersistedQueryLink.Options;\",\n        \"type _Test_PersistedQueryLink_RetryFunctionOptions = PersistedQueryLink.RetryFunctionOptions;\",\n        \"type _Test_PersistedQueryLink_DisableFunctionOptions = PersistedQueryLink.DisableFunctionOptions;\",\n        \"class _Test_PersistedQueryLink extends PersistedQueryLink {}\",\n        \"const _test_PersistedQueryLink = new PersistedQueryLink(options)\"\n      ]\n    },\n    {\n      \"name\": \"createPersistedQueryLink\",\n      \"moduleName\": \"@apollo/client/link/persisted-queries\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_createPersistedQueryLink = createPersistedQueryLink;\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/retry\": [\n    {\n      \"name\": \"RetryLink\",\n      \"moduleName\": \"@apollo/client/link/retry\",\n      \"usageExamples\": [\n        \"const _Test_RetryLink = RetryLink;\",\n        \"const _Test_RetryLink_RetryLinkDocumentationTypes = RetryLink.RetryLinkDocumentationTypes;\",\n        \"RetryLink.RetryLinkDocumentationTypes.AttemptsFunction(attempt, operation, error)\",\n        \"RetryLink.RetryLinkDocumentationTypes.DelayFunction(attempt, operation, error)\",\n        \"type _Test_RetryLink_DelayFunction = RetryLink.DelayFunction;\",\n        \"type _Test_RetryLink_DelayOptions = RetryLink.DelayOptions;\",\n        \"type _Test_RetryLink_AttemptsFunction = RetryLink.AttemptsFunction;\",\n        \"type _Test_RetryLink_AttemptsOptions = RetryLink.AttemptsOptions;\",\n        \"type _Test_RetryLink_Options = RetryLink.Options;\",\n        \"class _Test_RetryLink extends RetryLink {}\",\n        \"const _test_RetryLink = new RetryLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/remove-typename\": [\n    {\n      \"name\": \"KEEP\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_KEEP = KEEP;\"]\n    },\n    {\n      \"name\": \"removeTypenameFromVariables\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"removeTypenameFromVariables(options)\"]\n    },\n    {\n      \"name\": \"RemoveTypenameFromVariablesLink\",\n      \"moduleName\": \"@apollo/client/link/remove-typename\",\n      \"usageExamples\": [\n        \"const _Test_RemoveTypenameFromVariablesLink = RemoveTypenameFromVariablesLink;\",\n        \"type _Test_RemoveTypenameFromVariablesLink_KeepTypenameConfig = RemoveTypenameFromVariablesLink.KeepTypenameConfig;\",\n        \"type _Test_RemoveTypenameFromVariablesLink_Options = RemoveTypenameFromVariablesLink.Options;\",\n        \"class _Test_RemoveTypenameFromVariablesLink extends RemoveTypenameFromVariablesLink {}\",\n        \"const _test_RemoveTypenameFromVariablesLink = new RemoveTypenameFromVariablesLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/schema\": [\n    {\n      \"name\": \"SchemaLink\",\n      \"moduleName\": \"@apollo/client/link/schema\",\n      \"usageExamples\": [\n        \"const _Test_SchemaLink = SchemaLink;\",\n        \"const _Test_SchemaLink_SchemaLinkDocumentationTypes = SchemaLink.SchemaLinkDocumentationTypes;\",\n        \"SchemaLink.SchemaLinkDocumentationTypes.ResolverContextFunction(operation)\",\n        \"type _Test_SchemaLink_ResolverContext = SchemaLink.ResolverContext;\",\n        \"type _Test_SchemaLink_ResolverContextFunction = SchemaLink.ResolverContextFunction;\",\n        \"type _Test_SchemaLink_Options = SchemaLink.Options;\",\n        \"class _Test_SchemaLink extends SchemaLink {}\",\n        \"const _test_SchemaLink = new SchemaLink(options)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/subscriptions\": [\n    {\n      \"name\": \"GraphQLWsLink\",\n      \"moduleName\": \"@apollo/client/link/subscriptions\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_GraphQLWsLink extends GraphQLWsLink {}\",\n        \"const _test_GraphQLWsLink = new GraphQLWsLink(client)\"\n      ]\n    }\n  ],\n  \"@apollo/client/link/utils\": [\n    {\n      \"name\": \"createOperation\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createOperation(request, param1)\"]\n    },\n    {\n      \"name\": \"filterOperationVariables\",\n      \"moduleName\": \"@apollo/client/link/utils\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"filterOperationVariables(variables, query)\"]\n    }\n  ],\n  \"@apollo/client/link/ws\": [\n    {\n      \"name\": \"WebSocketLink\",\n      \"moduleName\": \"@apollo/client/link/ws\",\n      \"usageExamples\": [\n        \"const _Test_WebSocketLink = WebSocketLink;\",\n        \"type _Test_WebSocketLink_Configuration = WebSocketLink.Configuration;\",\n        \"class _Test_WebSocketLink extends WebSocketLink {}\",\n        \"const _test_WebSocketLink = new WebSocketLink(paramsOrClient)\"\n      ]\n    }\n  ],\n  \"@apollo/client/masking\": [\n    {\n      \"name\": \"DataMasking\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_DataMasking = DataMasking;\"]\n    },\n    {\n      \"name\": \"FragmentType\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_FragmentType = FragmentType<TData>;\"]\n    },\n    {\n      \"name\": \"Masked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Masked = Masked<TData>;\"]\n    },\n    {\n      \"name\": \"MaskedDocumentNode\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MaskedDocumentNode = MaskedDocumentNode<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MaybeMasked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MaybeMasked = MaybeMasked<TData>;\"]\n    },\n    {\n      \"name\": \"Unmasked\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_Unmasked = Unmasked<TData>;\"]\n    },\n    {\n      \"name\": \"GraphQLCodegenDataMasking\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"NamespaceModule\",\n      \"usageExamples\": [\n        \"const _Test_GraphQLCodegenDataMasking = GraphQLCodegenDataMasking;\",\n        \"type _Test_GraphQLCodegenDataMasking_Implementation = GraphQLCodegenDataMasking.Implementation;\",\n        \"const _Test_GraphQLCodegenDataMasking_HKTImplementation = GraphQLCodegenDataMasking.HKTImplementation;\",\n        \"type _Test_GraphQLCodegenDataMasking_HKTImplementation_Masked = GraphQLCodegenDataMasking.HKTImplementation.Masked;\",\n        \"type _Test_GraphQLCodegenDataMasking_HKTImplementation_MaskedDocumentNode = GraphQLCodegenDataMasking.HKTImplementation.MaskedDocumentNode;\",\n        \"type _Test_GraphQLCodegenDataMasking_HKTImplementation_FragmentType = GraphQLCodegenDataMasking.HKTImplementation.FragmentType;\",\n        \"type _Test_GraphQLCodegenDataMasking_HKTImplementation_MaybeMasked = GraphQLCodegenDataMasking.HKTImplementation.MaybeMasked;\",\n        \"type _Test_GraphQLCodegenDataMasking_HKTImplementation_Unmasked = GraphQLCodegenDataMasking.HKTImplementation.Unmasked;\",\n        \"type _Test_GraphQLCodegenDataMasking_Masked = GraphQLCodegenDataMasking.Masked<TData>;\",\n        \"type _Test_GraphQLCodegenDataMasking_MaskedDocumentNode = GraphQLCodegenDataMasking.MaskedDocumentNode<TData, TVariables>;\",\n        \"type _Test_GraphQLCodegenDataMasking_FragmentType = GraphQLCodegenDataMasking.FragmentType<TData>;\",\n        \"type _Test_GraphQLCodegenDataMasking_MaybeMasked = GraphQLCodegenDataMasking.MaybeMasked<TData>;\",\n        \"type _Test_GraphQLCodegenDataMasking_Unmasked = GraphQLCodegenDataMasking.Unmasked<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"disableWarningsSlot\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_disableWarningsSlot = disableWarningsSlot;\"\n      ]\n    },\n    {\n      \"name\": \"maskFragment\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"maskFragment<TData>(data, document, cache, fragmentName)\"\n      ]\n    },\n    {\n      \"name\": \"maskOperation\",\n      \"moduleName\": \"@apollo/client/masking\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"maskOperation<TData>(data, document, cache)\"]\n    }\n  ],\n  \"@apollo/client/react\": [\n    {\n      \"name\": \"ApolloContextValue\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_ApolloContextValue = ApolloContextValue;\"]\n    },\n    {\n      \"name\": \"getApolloContext\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getApolloContext()\"]\n    },\n    {\n      \"name\": \"ApolloProvider\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"const _Test_ApolloProvider = ApolloProvider;\",\n        \"type _Test_ApolloProvider_Props = ApolloProvider.Props;\",\n        \"const _Test_ApolloProvider = ApolloProvider;\"\n      ]\n    },\n    {\n      \"name\": \"useApolloClient\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useApolloClient(override)\"]\n    },\n    {\n      \"name\": \"useLazyQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useLazyQuery<TData, TVariables>(query, options)\",\n        \"useLazyQuery<TData, TVariables>(query, options)\",\n        \"useLazyQuery<TData, TVariables>(query, options)\",\n        \"useLazyQuery<TData, TVariables, TStates>(query, options)\",\n        \"const _Test_useLazyQuery = useLazyQuery;\",\n        \"type _Test_useLazyQuery_Options = useLazyQuery.Options<TData, TVariables>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes = useLazyQuery.DocumentationTypes;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"useLazyQuery.DocumentationTypes.useLazyQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLazyQuery_DocumentationTypes = useLazyQuery.DocumentationTypes;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"useLazyQuery.DocumentationTypes.useLazyQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLazyQuery_DocumentationTypes = useLazyQuery.DocumentationTypes;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"useLazyQuery.DocumentationTypes.useLazyQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLazyQuery_DocumentationTypes = useLazyQuery.DocumentationTypes;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"useLazyQuery.DocumentationTypes.useLazyQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLazyQuery_DocumentationTypes = useLazyQuery.DocumentationTypes;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"const _Test_useLazyQuery_DocumentationTypes_useLazyQuery = useLazyQuery.DocumentationTypes.useLazyQuery;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Options = useLazyQuery.DocumentationTypes.useLazyQuery.Options<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_Result = useLazyQuery.DocumentationTypes.useLazyQuery.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ExecOptions = useLazyQuery.DocumentationTypes.useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_DocumentationTypes_useLazyQuery_ResultTuple = useLazyQuery.DocumentationTypes.useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"useLazyQuery.DocumentationTypes.useLazyQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLazyQuery_Base = useLazyQuery.Base;\",\n        \"type _Test_useLazyQuery_Base_Result = useLazyQuery.Base.Result<TData, TVariables>;\",\n        \"type _Test_useLazyQuery_Result = useLazyQuery.Result<TData, TVariables, TStates>;\",\n        \"type _Test_useLazyQuery_ExecOptions = useLazyQuery.ExecOptions<TVariables>;\",\n        \"type _Test_useLazyQuery_ResultTuple = useLazyQuery.ResultTuple<TData, TVariables, TStates>;\",\n        \"type _Test_useLazyQuery_ExecFunction = useLazyQuery.ExecFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useMutation\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useMutation<TData, TVariables, TCache, TConfiguredVariables>(mutation, options)\",\n        \"const _Test_useMutation = useMutation;\",\n        \"type _Test_useMutation_Options = useMutation.Options<TData, TVariables, TCache, TConfiguredVariables>;\",\n        \"type _Test_useMutation_Result = useMutation.Result<TData>;\",\n        \"type _Test_useMutation_ResultTuple = useMutation.ResultTuple<TData, TVariables, TCache>;\",\n        \"type _Test_useMutation_MutationFunction = useMutation.MutationFunction<TData, TVariables, TCache>;\",\n        \"type _Test_useMutation_MutationFunctionOptions = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\",\n        \"const _Test_useMutation_DocumentationTypes = useMutation.DocumentationTypes;\",\n        \"useMutation.DocumentationTypes.useMutation<TData, TVariables>(mutation, options)\"\n      ]\n    },\n    {\n      \"name\": \"useQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useQuery<TData, TVariables>(query, options)\",\n        \"useQuery<TData, TVariables>(query, options)\",\n        \"useQuery<TData, TVariables>(query, param1)\",\n        \"useQuery<TData, TVariables>(query, param1)\",\n        \"const _Test_useQuery = useQuery;\",\n        \"const _Test_useQuery_Base = useQuery.Base;\",\n        \"type _Test_useQuery_Base_Options = useQuery.Base.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_Base_Result = useQuery.Base.Result<TData, TVariables>;\",\n        \"const _Test_useQuery_Base = useQuery.Base;\",\n        \"type _Test_useQuery_Base_Options = useQuery.Base.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_Base_Result = useQuery.Base.Result<TData, TVariables>;\",\n        \"type _Test_useQuery_Options = useQuery.Options<TData, TVariables>;\",\n        \"const _Test_useQuery_DocumentationTypes = useQuery.DocumentationTypes;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"useQuery.DocumentationTypes.useQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useQuery_DocumentationTypes = useQuery.DocumentationTypes;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"useQuery.DocumentationTypes.useQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useQuery_DocumentationTypes = useQuery.DocumentationTypes;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"const _Test_useQuery_DocumentationTypes_useQuery = useQuery.DocumentationTypes.useQuery;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Options = useQuery.DocumentationTypes.useQuery.Options<TData, TVariables>;\",\n        \"type _Test_useQuery_DocumentationTypes_useQuery_Result = useQuery.DocumentationTypes.useQuery.Result<TData, TVariables>;\",\n        \"useQuery.DocumentationTypes.useQuery<TData, TVariables>(query, options)\",\n        \"type _Test_useQuery_Result = useQuery.Result<TData, TVariables, TStates>;\",\n        \"const _Test_useQuery_ssrDisabledResult = useQuery.ssrDisabledResult;\"\n      ]\n    },\n    {\n      \"name\": \"useSubscription\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useSubscription<TData, TVariables>(subscription, param1)\",\n        \"const _Test_useSubscription = useSubscription;\",\n        \"const _Test_useSubscription_Base = useSubscription.Base;\",\n        \"type _Test_useSubscription_Base_Options = useSubscription.Base.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_Options = useSubscription.Options<TData, TVariables>;\",\n        \"const _Test_useSubscription_DocumentationTypes = useSubscription.DocumentationTypes;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"useSubscription.DocumentationTypes.useSubscription<TData, TVariables>(options)\",\n        \"const _Test_useSubscription_DocumentationTypes = useSubscription.DocumentationTypes;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"useSubscription.DocumentationTypes.useSubscription<TData, TVariables>(options)\",\n        \"const _Test_useSubscription_DocumentationTypes = useSubscription.DocumentationTypes;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"const _Test_useSubscription_DocumentationTypes_useSubscription = useSubscription.DocumentationTypes.useSubscription;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Options = useSubscription.DocumentationTypes.useSubscription.Options<TData, TVariables>;\",\n        \"type _Test_useSubscription_DocumentationTypes_useSubscription_Result = useSubscription.DocumentationTypes.useSubscription.Result<TData>;\",\n        \"useSubscription.DocumentationTypes.useSubscription<TData, TVariables>(options)\",\n        \"type _Test_useSubscription_Result = useSubscription.Result<TData>;\",\n        \"type _Test_useSubscription_OnDataResult = useSubscription.OnDataResult<TData>;\",\n        \"type _Test_useSubscription_OnDataOptions = useSubscription.OnDataOptions<TData>;\",\n        \"type _Test_useSubscription_OnSubscriptionDataOptions = useSubscription.OnSubscriptionDataOptions<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useReactiveVar\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"useReactiveVar<T>(rv)\"]\n    },\n    {\n      \"name\": \"useFragment\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useFragment<TData, TVariables>(options)\",\n        \"const _Test_useFragment = useFragment;\",\n        \"type _Test_useFragment_Options = useFragment.Options<TData, TVariables>;\",\n        \"const _Test_useFragment_DocumentationTypes = useFragment.DocumentationTypes;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"useFragment.DocumentationTypes.useFragment<TData, TVariables>(param0)\",\n        \"const _Test_useFragment_DocumentationTypes = useFragment.DocumentationTypes;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"useFragment.DocumentationTypes.useFragment<TData, TVariables>(param0)\",\n        \"const _Test_useFragment_DocumentationTypes = useFragment.DocumentationTypes;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"const _Test_useFragment_DocumentationTypes_useFragment = useFragment.DocumentationTypes.useFragment;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Options = useFragment.DocumentationTypes.useFragment.Options<TData, TVariables>;\",\n        \"type _Test_useFragment_DocumentationTypes_useFragment_Result = useFragment.DocumentationTypes.useFragment.Result<TData>;\",\n        \"useFragment.DocumentationTypes.useFragment<TData, TVariables>(param0)\",\n        \"type _Test_useFragment_Result = useFragment.Result<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, param1)\",\n        \"useSuspenseQuery<TData, TVariables>(query, param1)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useSuspenseQuery = useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_FetchPolicy = useSuspenseQuery.FetchPolicy;\",\n        \"const _Test_useSuspenseQuery_Base = useSuspenseQuery.Base;\",\n        \"type _Test_useSuspenseQuery_Base_Options = useSuspenseQuery.Base.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_Base_Result = useSuspenseQuery.Base.Result<TData, TVariables>;\",\n        \"const _Test_useSuspenseQuery_Base = useSuspenseQuery.Base;\",\n        \"type _Test_useSuspenseQuery_Base_Options = useSuspenseQuery.Base.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_Base_Result = useSuspenseQuery.Base.Result<TData, TVariables>;\",\n        \"type _Test_useSuspenseQuery_Options = useSuspenseQuery.Options<TVariables>;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes = useSuspenseQuery.DocumentationTypes;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"useSuspenseQuery.DocumentationTypes.useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes = useSuspenseQuery.DocumentationTypes;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"useSuspenseQuery.DocumentationTypes.useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes = useSuspenseQuery.DocumentationTypes;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"const _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery = useSuspenseQuery.DocumentationTypes.useSuspenseQuery;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Options = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Options<TVariables>;\",\n        \"type _Test_useSuspenseQuery_DocumentationTypes_useSuspenseQuery_Result = useSuspenseQuery.DocumentationTypes.useSuspenseQuery.Result<TData, TVariables>;\",\n        \"useSuspenseQuery.DocumentationTypes.useSuspenseQuery<TData, TVariables>(query, options)\",\n        \"type _Test_useSuspenseQuery_Result = useSuspenseQuery.Result<TData, TVariables, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"useBackgroundQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, param1)\",\n        \"useBackgroundQuery<TData, TVariables>(query, param1)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useBackgroundQuery = useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_FetchPolicy = useBackgroundQuery.FetchPolicy;\",\n        \"const _Test_useBackgroundQuery_Base = useBackgroundQuery.Base;\",\n        \"type _Test_useBackgroundQuery_Base_Options = useBackgroundQuery.Base.Options;\",\n        \"type _Test_useBackgroundQuery_Options = useBackgroundQuery.Options<TVariables>;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes = useBackgroundQuery.DocumentationTypes;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"useBackgroundQuery.DocumentationTypes.useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes = useBackgroundQuery.DocumentationTypes;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"useBackgroundQuery.DocumentationTypes.useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes = useBackgroundQuery.DocumentationTypes;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"const _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery = useBackgroundQuery.DocumentationTypes.useBackgroundQuery;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Options = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Options<TVariables>;\",\n        \"type _Test_useBackgroundQuery_DocumentationTypes_useBackgroundQuery_Result = useBackgroundQuery.DocumentationTypes.useBackgroundQuery.Result<TData, TVariables>;\",\n        \"useBackgroundQuery.DocumentationTypes.useBackgroundQuery<TData, TVariables>(query, options)\",\n        \"type _Test_useBackgroundQuery_Result = useBackgroundQuery.Result<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"useSuspenseFragment\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useSuspenseFragment<TData, TVariables>(options)\",\n        \"useSuspenseFragment<TData, TVariables>(options)\",\n        \"useSuspenseFragment<TData, TVariables>(options)\",\n        \"useSuspenseFragment<TData, TVariables>(options)\",\n        \"useSuspenseFragment<TData, TVariables>(options)\",\n        \"const _Test_useSuspenseFragment = useSuspenseFragment;\",\n        \"const _Test_useSuspenseFragment_Base = useSuspenseFragment.Base;\",\n        \"type _Test_useSuspenseFragment_Base_Options = useSuspenseFragment.Base.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_Options = useSuspenseFragment.Options<TData, TVariables>;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes = useSuspenseFragment.DocumentationTypes;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"useSuspenseFragment.DocumentationTypes.useSuspenseFragment<TData, TVariables>(options)\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes = useSuspenseFragment.DocumentationTypes;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"useSuspenseFragment.DocumentationTypes.useSuspenseFragment<TData, TVariables>(options)\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes = useSuspenseFragment.DocumentationTypes;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"const _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment = useSuspenseFragment.DocumentationTypes.useSuspenseFragment;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Options = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Options<TData, TVariables>;\",\n        \"type _Test_useSuspenseFragment_DocumentationTypes_useSuspenseFragment_Result = useSuspenseFragment.DocumentationTypes.useSuspenseFragment.Result<TData>;\",\n        \"useSuspenseFragment.DocumentationTypes.useSuspenseFragment<TData, TVariables>(options)\",\n        \"type _Test_useSuspenseFragment_Result = useSuspenseFragment.Result<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"useLoadableQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useLoadableQuery<TData, TVariables>(query, options)\",\n        \"useLoadableQuery<TData, TVariables>(query, options)\",\n        \"useLoadableQuery<TData, TVariables>(query, options)\",\n        \"useLoadableQuery<TData, TVariables>(query, options)\",\n        \"useLoadableQuery<TData, TVariables>(query, options)\",\n        \"const _Test_useLoadableQuery = useLoadableQuery;\",\n        \"type _Test_useLoadableQuery_LoadQueryFunction = useLoadableQuery.LoadQueryFunction<TVariables>;\",\n        \"type _Test_useLoadableQuery_Result = useLoadableQuery.Result<TData, TVariables, TStates>;\",\n        \"type _Test_useLoadableQuery_Handlers = useLoadableQuery.Handlers<TData, TVariables>;\",\n        \"type _Test_useLoadableQuery_FetchPolicy = useLoadableQuery.FetchPolicy;\",\n        \"type _Test_useLoadableQuery_Options = useLoadableQuery.Options;\",\n        \"const _Test_useLoadableQuery_DocumentationTypes = useLoadableQuery.DocumentationTypes;\",\n        \"useLoadableQuery.DocumentationTypes.useLoadableQuery<TData, TVariables>(query, options)\"\n      ]\n    },\n    {\n      \"name\": \"useQueryRefHandlers\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useQueryRefHandlers<TData, TVariables>(queryRef)\",\n        \"const _Test_useQueryRefHandlers = useQueryRefHandlers;\",\n        \"type _Test_useQueryRefHandlers_Result = useQueryRefHandlers.Result<TData, TVariables>;\",\n        \"const _Test_useQueryRefHandlers_DocumentationTypes = useQueryRefHandlers.DocumentationTypes;\",\n        \"useQueryRefHandlers.DocumentationTypes.useQueryRefHandlers<TData, TVariables>(queryRef)\"\n      ]\n    },\n    {\n      \"name\": \"useReadQuery\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"usageExamples\": [\n        \"useReadQuery<TData, TStates>(queryRef)\",\n        \"const _Test_useReadQuery = useReadQuery;\",\n        \"const _Test_useReadQuery_Base = useReadQuery.Base;\",\n        \"type _Test_useReadQuery_Base_Result = useReadQuery.Base.Result<TData>;\",\n        \"type _Test_useReadQuery_Result = useReadQuery.Result<TData, TStates>;\",\n        \"const _Test_useReadQuery_DocumentationTypes = useReadQuery.DocumentationTypes;\",\n        \"useReadQuery.DocumentationTypes.useReadQuery<TData>(queryRef)\",\n        \"const _Test_useReadQuery_DocumentationTypes_useReadQuery = useReadQuery.DocumentationTypes.useReadQuery;\",\n        \"type _Test_useReadQuery_DocumentationTypes_useReadQuery_Result = useReadQuery.DocumentationTypes.useReadQuery.Result<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"skipToken\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_skipToken = skipToken;\"]\n    },\n    {\n      \"name\": \"SkipToken\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_SkipToken = SkipToken;\"]\n    },\n    {\n      \"name\": \"PreloadQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFetchPolicy = PreloadQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryFunction = PreloadQueryFunction;\"\n      ]\n    },\n    {\n      \"name\": \"PreloadQueryOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_PreloadQueryOptions = PreloadQueryOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"createQueryPreloader\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createQueryPreloader(client)\"]\n    },\n    {\n      \"name\": \"PreloadedQueryRef\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryRef\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryRef = QueryRef<TData, TVariables, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookFetchPolicy = BackgroundQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"BackgroundQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_BackgroundQueryHookOptions = BackgroundQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryExecFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryExecFunction = LazyQueryExecFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookExecOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookExecOptions = LazyQueryHookExecOptions<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryHookOptions = LazyQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResult = LazyQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LazyQueryResultTuple\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LazyQueryResultTuple = LazyQueryResultTuple<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryFetchPolicy = LoadableQueryFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"LoadableQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadableQueryHookOptions = LoadableQueryHookOptions;\"\n      ]\n    },\n    {\n      \"name\": \"LoadQueryFunction\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_LoadQueryFunction = LoadQueryFunction<TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationFunctionOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationFunctionOptions = MutationFunctionOptions<TData, TVariables, _TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationHookOptions = MutationHookOptions<TData, TVariables, _TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"MutationResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MutationResult = MutationResult<TData>;\"]\n    },\n    {\n      \"name\": \"MutationTuple\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MutationTuple = MutationTuple<TData, TVariables, _TContext, TCache>;\"\n      ]\n    },\n    {\n      \"name\": \"OnDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_OnDataOptions = OnDataOptions<TData>;\"]\n    },\n    {\n      \"name\": \"OnSubscriptionDataOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_OnSubscriptionDataOptions = OnSubscriptionDataOptions<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryHookOptions = QueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_QueryResult = QueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionHookOptions = SubscriptionHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SubscriptionResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SubscriptionResult = SubscriptionResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookFetchPolicy\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookFetchPolicy = SuspenseQueryHookFetchPolicy;\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseQueryHookOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseQueryHookOptions = SuspenseQueryHookOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseBackgroundQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseBackgroundQueryResult = UseBackgroundQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentOptions = UseFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseFragmentResult = UseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseLoadableQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseLoadableQueryResult = UseLoadableQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseQueryRefHandlersResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseQueryRefHandlersResult = UseQueryRefHandlersResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseReadQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseReadQueryResult = UseReadQueryResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentOptions\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentOptions = UseSuspenseFragmentOptions<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseFragmentResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseFragmentResult = UseSuspenseFragmentResult<TData>;\"\n      ]\n    },\n    {\n      \"name\": \"UseSuspenseQueryResult\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_UseSuspenseQueryResult = UseSuspenseQueryResult<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"reactCompilerVersion\",\n      \"moduleName\": \"@apollo/client/react\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_reactCompilerVersion = reactCompilerVersion;\"\n      ]\n    }\n  ],\n  \"@apollo/client/react/components\": [],\n  \"@apollo/client/react/context\": [],\n  \"@apollo/client/react/hoc\": [],\n  \"@apollo/client/react/hooks\": [],\n  \"@apollo/client/react/internal\": [\n    {\n      \"name\": \"getSuspenseCache\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getSuspenseCache(client)\"]\n    },\n    {\n      \"name\": \"CacheKey\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_CacheKey = CacheKey;\"]\n    },\n    {\n      \"name\": \"FragmentKey\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_FragmentKey = FragmentKey;\"]\n    },\n    {\n      \"name\": \"QueryKey\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_QueryKey = QueryKey;\"]\n    },\n    {\n      \"name\": \"PreloadedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_PreloadedQueryRef = PreloadedQueryRef<TData, TVariables, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"QueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_QueryRef = QueryRef<TData, TVariables, TStates>;\"\n      ]\n    },\n    {\n      \"name\": \"assertWrappedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"assertWrappedQueryRef<TData, TVariables, TStates>(queryRef)\",\n        \"assertWrappedQueryRef<TData, TVariables, TStates>(queryRef)\",\n        \"assertWrappedQueryRef<TData, TVariables, TStates>(queryRef)\"\n      ]\n    },\n    {\n      \"name\": \"getWrappedPromise\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getWrappedPromise<TData, TStates>(queryRef)\"]\n    },\n    {\n      \"name\": \"InternalQueryReference\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_InternalQueryReference extends InternalQueryReference<TData, TStates> {}\",\n        \"const _test_InternalQueryReference = new InternalQueryReference<TData, TStates>(observable, options)\"\n      ]\n    },\n    {\n      \"name\": \"unwrapQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"unwrapQueryRef<TData, TStates>(queryRef)\",\n        \"unwrapQueryRef<TData, TStates>(queryRef)\",\n        \"unwrapQueryRef<TData, TStates>(queryRef)\"\n      ]\n    },\n    {\n      \"name\": \"updateWrappedQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"updateWrappedQueryRef<TData, TStates>(queryRef, promise)\"\n      ]\n    },\n    {\n      \"name\": \"wrapQueryRef\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\n        \"wrapQueryRef<TData, TVariables, TStates>(internalQueryRef)\"\n      ]\n    },\n    {\n      \"name\": \"SuspenseCacheOptions\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\n        \"type _Test_SuspenseCacheOptions = SuspenseCacheOptions;\"\n      ]\n    },\n    {\n      \"name\": \"HookWrappers\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_HookWrappers = HookWrappers;\"]\n    },\n    {\n      \"name\": \"wrapperSymbol\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_wrapperSymbol = wrapperSymbol;\"]\n    },\n    {\n      \"name\": \"FetchMoreFunction\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_FetchMoreFunction = FetchMoreFunction<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"RefetchFunction\",\n      \"moduleName\": \"@apollo/client/react/internal\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_RefetchFunction = RefetchFunction<TData, TVariables>;\"\n      ]\n    }\n  ],\n  \"@apollo/client/react/parser\": [],\n  \"@apollo/client/react/ssr\": [\n    {\n      \"name\": \"getDataFromTree\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getDataFromTree(tree, context)\"]\n    },\n    {\n      \"name\": \"getMarkupFromTree\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getMarkupFromTree(param0)\"]\n    },\n    {\n      \"name\": \"prerenderStatic\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"usageExamples\": [\n        \"prerenderStatic(param0)\",\n        \"const _Test_prerenderStatic = prerenderStatic;\",\n        \"type _Test_prerenderStatic_Options = prerenderStatic.Options;\",\n        \"type _Test_prerenderStatic_Result = prerenderStatic.Result;\",\n        \"type _Test_prerenderStatic_Diagnostics = prerenderStatic.Diagnostics;\",\n        \"type _Test_prerenderStatic_RenderToString = prerenderStatic.RenderToString;\",\n        \"type _Test_prerenderStatic_RenderToStringPromise = prerenderStatic.RenderToStringPromise;\",\n        \"type _Test_prerenderStatic_PrerenderToWebStream = prerenderStatic.PrerenderToWebStream;\",\n        \"type _Test_prerenderStatic_PrerenderToNodeStream = prerenderStatic.PrerenderToNodeStream;\"\n      ]\n    },\n    {\n      \"name\": \"renderToStringWithData\",\n      \"moduleName\": \"@apollo/client/react/ssr\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"renderToStringWithData(component)\"]\n    }\n  ],\n  \"@apollo/client/testing\": [\n    {\n      \"name\": \"MockedRequest\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MockedRequest = MockedRequest<TVariables>;\"]\n    },\n    {\n      \"name\": \"MockedResponse\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_MockedResponse = MockedResponse<TData, TVariables>;\"\n      ]\n    },\n    {\n      \"name\": \"MockLinkOptions\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_MockLinkOptions = MockLinkOptions;\"]\n    },\n    {\n      \"name\": \"ResultFunction\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_ResultFunction = ResultFunction<T, V>;\"]\n    },\n    {\n      \"name\": \"MockLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"usageExamples\": [\n        \"const _Test_MockLink = MockLink;\",\n        \"type _Test_MockLink_DelayFunction = MockLink.DelayFunction;\",\n        \"type _Test_MockLink_Delay = MockLink.Delay;\",\n        \"type _Test_MockLink_DefaultOptions = MockLink.DefaultOptions;\",\n        \"type _Test_MockLink_MockedRequest = MockLink.MockedRequest<TVariables>;\",\n        \"type _Test_MockLink_MockedResponse = MockLink.MockedResponse<TData, TVariables>;\",\n        \"type _Test_MockLink_ResultFunction = MockLink.ResultFunction<T, V>;\",\n        \"type _Test_MockLink_Options = MockLink.Options;\",\n        \"const _Test_MockLink_defaultOptions = MockLink.defaultOptions;\",\n        \"class _Test_MockLink extends MockLink {}\",\n        \"const _test_MockLink = new MockLink(mockedResponses, options)\"\n      ]\n    },\n    {\n      \"name\": \"realisticDelay\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"realisticDelay(param0)\"]\n    },\n    {\n      \"name\": \"MockSubscriptionLink\",\n      \"moduleName\": \"@apollo/client/testing\",\n      \"usageExamples\": [\n        \"const _Test_MockSubscriptionLink = MockSubscriptionLink;\",\n        \"type _Test_MockSubscriptionLink_Result = MockSubscriptionLink.Result;\",\n        \"class _Test_MockSubscriptionLink extends MockSubscriptionLink {}\",\n        \"const _test_MockSubscriptionLink = new MockSubscriptionLink()\"\n      ]\n    }\n  ],\n  \"@apollo/client/testing/core\": [],\n  \"@apollo/client/testing/experimental\": [],\n  \"@apollo/client/utilities\": [\n    {\n      \"name\": \"Observable\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_Observable extends Observable<T> {}\",\n        \"const _test_Observable = new Observable<T>(subscribe)\"\n      ]\n    },\n    {\n      \"name\": \"DeepPartial\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_DeepPartial = DeepPartial<T>;\"]\n    },\n    {\n      \"name\": \"DocumentTransformCacheKey\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\n        \"type _Test_DocumentTransformCacheKey = DocumentTransformCacheKey;\"\n      ]\n    },\n    {\n      \"name\": \"DocumentTransform\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Class\",\n      \"usageExamples\": [\n        \"class _Test_DocumentTransform extends DocumentTransform {}\",\n        \"const _test_DocumentTransform = new DocumentTransform(transform, options)\"\n      ]\n    },\n    {\n      \"name\": \"print\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_print = print;\"]\n    },\n    {\n      \"name\": \"isFormattedExecutionResult\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isFormattedExecutionResult(result)\"]\n    },\n    {\n      \"name\": \"AsStoreObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_AsStoreObject = AsStoreObject<T>;\"]\n    },\n    {\n      \"name\": \"Reference\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_Reference = Reference;\"]\n    },\n    {\n      \"name\": \"StoreObject\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_StoreObject = StoreObject;\"]\n    },\n    {\n      \"name\": \"StoreValue\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"TypeAlias\",\n      \"usageExamples\": [\"type _Test_StoreValue = StoreValue;\"]\n    },\n    {\n      \"name\": \"isReference\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isReference(obj)\"]\n    },\n    {\n      \"name\": \"addTypenameToDocument\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\n        \"const _Test_addTypenameToDocument = addTypenameToDocument;\"\n      ]\n    },\n    {\n      \"name\": \"isMutationOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isMutationOperation(document)\"]\n    },\n    {\n      \"name\": \"isQueryOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isQueryOperation(document)\"]\n    },\n    {\n      \"name\": \"isSubscriptionOperation\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"isSubscriptionOperation(document)\"]\n    },\n    {\n      \"name\": \"canonicalStringify\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_canonicalStringify = canonicalStringify;\"]\n    },\n    {\n      \"name\": \"getMainDefinition\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"getMainDefinition(queryDoc)\"]\n    },\n    {\n      \"name\": \"concatPagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"concatPagination<T>(keyArgs)\"]\n    },\n    {\n      \"name\": \"offsetLimitPagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"offsetLimitPagination<T>(keyArgs)\"]\n    },\n    {\n      \"name\": \"relayStylePagination\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"relayStylePagination<TNode>(keyArgs)\"]\n    },\n    {\n      \"name\": \"stripTypename\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"stripTypename<T>(value)\"]\n    },\n    {\n      \"name\": \"cacheSizes\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"BlockScopedVariable\",\n      \"usageExamples\": [\"const _Test_cacheSizes = cacheSizes;\"]\n    },\n    {\n      \"name\": \"CacheSizes\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_CacheSizes = CacheSizes;\"]\n    },\n    {\n      \"name\": \"HKT\",\n      \"moduleName\": \"@apollo/client/utilities\",\n      \"kind\": \"Interface\",\n      \"usageExamples\": [\"type _Test_HKT = HKT;\"]\n    }\n  ],\n  \"@apollo/client/utilities/globals\": [],\n  \"@apollo/client/utilities/subscriptions/relay\": [\n    {\n      \"name\": \"createFetchMultipartSubscription\",\n      \"moduleName\": \"@apollo/client/utilities/subscriptions/relay\",\n      \"kind\": \"Function\",\n      \"usageExamples\": [\"createFetchMultipartSubscription(uri, param1)\"]\n    }\n  ]\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/exports.removed.json",
    "content": "{\n  \"@apollo/client/cache\": {\n    \"value\": [\"DataProxy\", \"makeReference\"],\n    \"type\": []\n  },\n  \"@apollo/client\": {\n    \"value\": [\n      \"mergeOptions\",\n      \"isApolloError\",\n      \"ApolloError\",\n      \"DataProxy\",\n      \"fromError\",\n      \"toPromise\",\n      \"fromPromise\",\n      \"throwServerError\",\n      \"Observer\",\n      \"ObservableSubscription\",\n      \"makeReference\",\n      \"serializeFetchParameter\",\n      \"ApolloProvider\",\n      \"ApolloConsumer\",\n      \"getApolloContext\",\n      \"resetApolloContext\",\n      \"DocumentType\",\n      \"operationName\",\n      \"parser\",\n      \"createQueryPreloader\",\n      \"useQuery\",\n      \"useSuspenseQuery\",\n      \"useBackgroundQuery\",\n      \"useSuspenseFragment\",\n      \"useLoadableQuery\",\n      \"useQueryRefHandlers\",\n      \"useReadQuery\",\n      \"skipToken\",\n      \"useApolloClient\",\n      \"useLazyQuery\",\n      \"useMutation\",\n      \"useSubscription\",\n      \"useReactiveVar\",\n      \"useFragment\"\n    ],\n    \"type\": [\n      \"FetchMoreOptions\",\n      \"FetchMoreQueryOptions\",\n      \"Resolver\",\n      \"FragmentMatcher\",\n      \"MethodKeys\",\n      \"PureQueryOptions\",\n      \"MutationUpdaterFn\",\n      \"Resolvers\",\n      \"Path\",\n      \"ExecutionPatchInitialResult\",\n      \"IncrementalPayload\",\n      \"ExecutionPatchIncrementalResult\",\n      \"ExecutionPatchResult\",\n      \"SingleExecutionResult\",\n      \"NextLink\",\n      \"ClientParseError\",\n      \"HttpOptions\",\n      \"UriFunction\",\n      \"ApolloContextValue\",\n      \"IDocumentDefinition\",\n      \"PreloadQueryOptions\",\n      \"PreloadQueryFetchPolicy\",\n      \"PreloadQueryFunction\",\n      \"UseSuspenseQueryResult\",\n      \"UseBackgroundQueryResult\",\n      \"UseSuspenseFragmentResult\",\n      \"UseSuspenseFragmentOptions\",\n      \"LoadQueryFunction\",\n      \"UseLoadableQueryResult\",\n      \"UseQueryRefHandlersResult\",\n      \"UseReadQueryResult\",\n      \"SkipToken\",\n      \"UseFragmentOptions\",\n      \"UseFragmentResult\",\n      \"QueryReference\",\n      \"QueryRef\",\n      \"PreloadedQueryRef\",\n      \"Context\",\n      \"CommonOptions\",\n      \"BaseQueryOptions\",\n      \"QueryFunctionOptions\",\n      \"ObservableQueryFields\",\n      \"QueryResult\",\n      \"QueryDataOptions\",\n      \"QueryHookOptions\",\n      \"LazyQueryHookOptions\",\n      \"LazyQueryHookExecOptions\",\n      \"SuspenseQueryHookFetchPolicy\",\n      \"SuspenseQueryHookOptions\",\n      \"BackgroundQueryHookFetchPolicy\",\n      \"BackgroundQueryHookOptions\",\n      \"LoadableQueryHookFetchPolicy\",\n      \"LoadableQueryHookOptions\",\n      \"QueryLazyOptions\",\n      \"LazyQueryResult\",\n      \"QueryTuple\",\n      \"LazyQueryExecFunction\",\n      \"LazyQueryResultTuple\",\n      \"RefetchQueriesFunction\",\n      \"BaseMutationOptions\",\n      \"MutationFunctionOptions\",\n      \"MutationResult\",\n      \"MutationFunction\",\n      \"MutationHookOptions\",\n      \"MutationDataOptions\",\n      \"MutationTuple\",\n      \"OnDataOptions\",\n      \"OnSubscriptionDataOptions\",\n      \"BaseSubscriptionOptions\",\n      \"SubscriptionResult\",\n      \"SubscriptionHookOptions\",\n      \"SubscriptionDataOptions\",\n      \"SubscriptionCurrentObservable\",\n      \"VariablesOption\",\n      \"NoInfer\"\n    ]\n  },\n  \"@apollo/client/core\": {\n    \"value\": [\n      \"mergeOptions\",\n      \"isApolloError\",\n      \"ApolloError\",\n      \"DataProxy\",\n      \"fromError\",\n      \"toPromise\",\n      \"fromPromise\",\n      \"throwServerError\",\n      \"Observer\",\n      \"ObservableSubscription\",\n      \"makeReference\",\n      \"serializeFetchParameter\"\n    ],\n    \"type\": [\n      \"FetchMoreOptions\",\n      \"FetchMoreQueryOptions\",\n      \"Resolver\",\n      \"FragmentMatcher\",\n      \"MethodKeys\",\n      \"PureQueryOptions\",\n      \"MutationUpdaterFn\",\n      \"Resolvers\",\n      \"Path\",\n      \"ExecutionPatchInitialResult\",\n      \"IncrementalPayload\",\n      \"ExecutionPatchIncrementalResult\",\n      \"ExecutionPatchResult\",\n      \"SingleExecutionResult\",\n      \"NextLink\",\n      \"ClientParseError\",\n      \"HttpOptions\",\n      \"UriFunction\"\n    ]\n  },\n  \"@apollo/client/dev\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/errors\": {\n    \"value\": [\"isApolloError\", \"ApolloError\"],\n    \"type\": [\"ApolloErrorOptions\", \"GraphQLErrors\", \"NetworkError\"]\n  },\n  \"@apollo/client/link/batch\": {\n    \"value\": [\"OperationBatcher\"],\n    \"type\": [\"BatchableRequest\", \"BatchHandler\"]\n  },\n  \"@apollo/client/link/batch-http\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/context\": {\n    \"value\": [],\n    \"type\": [\"ContextSetter\"]\n  },\n  \"@apollo/client/link/core\": {\n    \"value\": [],\n    \"type\": [\n      \"Path\",\n      \"ExecutionPatchInitialResult\",\n      \"IncrementalPayload\",\n      \"ExecutionPatchIncrementalResult\",\n      \"ExecutionPatchResult\",\n      \"SingleExecutionResult\",\n      \"NextLink\"\n    ]\n  },\n  \"@apollo/client/link/error\": {\n    \"value\": [],\n    \"type\": [\"ErrorResponse\", \"ErrorHandler\"]\n  },\n  \"@apollo/client/link/http\": {\n    \"value\": [\"serializeFetchParameter\"],\n    \"type\": [\n      \"ServerParseError\",\n      \"ClientParseError\",\n      \"HttpOptions\",\n      \"UriFunction\"\n    ]\n  },\n  \"@apollo/client/link/persisted-queries\": {\n    \"value\": [],\n    \"type\": [\"ErrorResponse\"]\n  },\n  \"@apollo/client/link/retry\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/remove-typename\": {\n    \"value\": [],\n    \"type\": [\"RemoveTypenameFromVariablesOptions\"]\n  },\n  \"@apollo/client/link/schema\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/subscriptions\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/utils\": {\n    \"value\": [\n      \"fromError\",\n      \"toPromise\",\n      \"fromPromise\",\n      \"throwServerError\",\n      \"validateOperation\",\n      \"transformOperation\"\n    ],\n    \"type\": [\"ServerError\"]\n  },\n  \"@apollo/client/link/ws\": {\n    \"value\": [],\n    \"type\": [\"WebSocketParams\"]\n  },\n  \"@apollo/client/masking\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/react\": {\n    \"value\": [\n      \"ApolloConsumer\",\n      \"resetApolloContext\",\n      \"DocumentType\",\n      \"operationName\",\n      \"parser\"\n    ],\n    \"type\": [\n      \"IDocumentDefinition\",\n      \"QueryReference\",\n      \"Context\",\n      \"CommonOptions\",\n      \"BaseQueryOptions\",\n      \"QueryFunctionOptions\",\n      \"ObservableQueryFields\",\n      \"QueryDataOptions\",\n      \"LoadableQueryHookFetchPolicy\",\n      \"QueryLazyOptions\",\n      \"QueryTuple\",\n      \"RefetchQueriesFunction\",\n      \"BaseMutationOptions\",\n      \"MutationFunction\",\n      \"MutationDataOptions\",\n      \"BaseSubscriptionOptions\",\n      \"SubscriptionDataOptions\",\n      \"SubscriptionCurrentObservable\",\n      \"VariablesOption\",\n      \"NoInfer\"\n    ]\n  },\n  \"@apollo/client/react/components\": {\n    \"value\": [\"Query\", \"Mutation\", \"Subscription\"],\n    \"type\": [\n      \"QueryComponentOptions\",\n      \"MutationComponentOptions\",\n      \"SubscriptionComponentOptions\"\n    ]\n  },\n  \"@apollo/client/react/context\": {\n    \"value\": [\n      \"ApolloConsumer\",\n      \"getApolloContext\",\n      \"resetApolloContext\",\n      \"ApolloProvider\"\n    ],\n    \"type\": [\"ApolloConsumerProps\", \"ApolloContextValue\", \"ApolloProviderProps\"]\n  },\n  \"@apollo/client/react/hoc\": {\n    \"value\": [\n      \"graphql\",\n      \"withQuery\",\n      \"withMutation\",\n      \"withSubscription\",\n      \"withApollo\"\n    ],\n    \"type\": [\n      \"QueryControls\",\n      \"DataValue\",\n      \"DataProps\",\n      \"MutateProps\",\n      \"ChildProps\",\n      \"ChildDataProps\",\n      \"ChildMutateProps\",\n      \"OptionProps\",\n      \"OperationOption\",\n      \"WithApolloClient\"\n    ]\n  },\n  \"@apollo/client/react/hooks\": {\n    \"value\": [\n      \"useQuery\",\n      \"useSuspenseQuery\",\n      \"useBackgroundQuery\",\n      \"useSuspenseFragment\",\n      \"useLoadableQuery\",\n      \"useQueryRefHandlers\",\n      \"useReadQuery\",\n      \"skipToken\",\n      \"useApolloClient\",\n      \"useLazyQuery\",\n      \"useMutation\",\n      \"useSubscription\",\n      \"useReactiveVar\",\n      \"useFragment\"\n    ],\n    \"type\": [\n      \"UseSuspenseQueryResult\",\n      \"UseBackgroundQueryResult\",\n      \"UseSuspenseFragmentResult\",\n      \"UseSuspenseFragmentOptions\",\n      \"LoadQueryFunction\",\n      \"UseLoadableQueryResult\",\n      \"UseQueryRefHandlersResult\",\n      \"UseReadQueryResult\",\n      \"SkipToken\",\n      \"UseFragmentOptions\",\n      \"UseFragmentResult\"\n    ]\n  },\n  \"@apollo/client/react/internal\": {\n    \"value\": [],\n    \"type\": [\"QueryReference\"]\n  },\n  \"@apollo/client/react/parser\": {\n    \"value\": [\"operationName\", \"parser\", \"verifyDocumentType\", \"DocumentType\"],\n    \"type\": [\"IDocumentDefinition\"]\n  },\n  \"@apollo/client/react/ssr\": {\n    \"value\": [\"RenderPromises\"],\n    \"type\": []\n  },\n  \"@apollo/client/testing\": {\n    \"value\": [\n      \"MockedProvider\",\n      \"mockSingleLink\",\n      \"mockObservableLink\",\n      \"createMockClient\",\n      \"subscribeAndCount\",\n      \"itAsync\",\n      \"wait\",\n      \"tick\",\n      \"withErrorSpy\",\n      \"withWarningSpy\",\n      \"withLogSpy\"\n    ],\n    \"type\": [\"MockedProviderProps\"]\n  },\n  \"@apollo/client/testing/core\": {\n    \"value\": [\n      \"MockLink\",\n      \"mockSingleLink\",\n      \"MockSubscriptionLink\",\n      \"mockObservableLink\",\n      \"createMockClient\",\n      \"subscribeAndCount\",\n      \"itAsync\",\n      \"wait\",\n      \"tick\",\n      \"withErrorSpy\",\n      \"withWarningSpy\",\n      \"withLogSpy\"\n    ],\n    \"type\": [\"MockedResponse\", \"MockLinkOptions\", \"ResultFunction\"]\n  },\n  \"@apollo/client/testing/experimental\": {\n    \"value\": [\"createTestSchema\", \"createSchemaFetch\"],\n    \"type\": []\n  },\n  \"@apollo/client/utilities\": {\n    \"value\": [\n      \"DEV\",\n      \"maybe\",\n      \"shouldInclude\",\n      \"hasDirectives\",\n      \"hasAnyDirectives\",\n      \"hasAllDirectives\",\n      \"hasClientExports\",\n      \"getDirectiveNames\",\n      \"getInclusionDirectives\",\n      \"getFragmentMaskMode\",\n      \"createFragmentMap\",\n      \"getFragmentQueryDocument\",\n      \"getFragmentFromSelection\",\n      \"isFullyUnmaskedOperation\",\n      \"checkDocument\",\n      \"getOperationDefinition\",\n      \"getOperationName\",\n      \"getFragmentDefinitions\",\n      \"getQueryDefinition\",\n      \"getFragmentDefinition\",\n      \"getDefaultValues\",\n      \"makeReference\",\n      \"isDocumentNode\",\n      \"isField\",\n      \"isInlineFragment\",\n      \"valueToObjectRepresentation\",\n      \"storeKeyNameFromField\",\n      \"argumentsObjectFromField\",\n      \"resultKeyNameFromField\",\n      \"getStoreKeyName\",\n      \"getTypenameFromResult\",\n      \"addNonReactiveToNamedFragments\",\n      \"buildQueryFromSelectionSet\",\n      \"removeDirectivesFromDocument\",\n      \"removeConnectionDirectiveFromDocument\",\n      \"removeArgumentsFromDocument\",\n      \"removeFragmentSpreadFromDocument\",\n      \"removeClientSetsFromDocument\",\n      \"Observer\",\n      \"ObservableSubscription\",\n      \"isStatefulPromise\",\n      \"createFulfilledPromise\",\n      \"createRejectedPromise\",\n      \"wrapPromiseWithState\",\n      \"preventUnhandledRejection\",\n      \"maybeDeepFreeze\",\n      \"omitDeep\",\n      \"AutoCleanedStrongCache\",\n      \"AutoCleanedWeakCache\",\n      \"defaultCacheSizes\",\n      \"mergeDeep\",\n      \"mergeDeepArray\",\n      \"DeepMerger\",\n      \"cloneDeep\",\n      \"iterateObserversSafely\",\n      \"asyncMap\",\n      \"Concast\",\n      \"fixObservableSubclass\",\n      \"isNonEmptyArray\",\n      \"isArray\",\n      \"isNonNullObject\",\n      \"isPlainObject\",\n      \"graphQLResultHasError\",\n      \"getGraphQLErrorsFromResult\",\n      \"canUseWeakMap\",\n      \"canUseWeakSet\",\n      \"canUseSymbol\",\n      \"canUseAsyncIteratorSymbol\",\n      \"canUseDOM\",\n      \"canUseLayoutEffect\",\n      \"compact\",\n      \"makeUniqueId\",\n      \"stringifyForDisplay\",\n      \"mergeOptions\",\n      \"isExecutionPatchIncrementalResult\",\n      \"isExecutionPatchInitialResult\",\n      \"isExecutionPatchResult\",\n      \"isApolloPayloadResult\",\n      \"mergeIncrementalData\"\n    ],\n    \"type\": [\n      \"DirectiveInfo\",\n      \"InclusionDirectives\",\n      \"FragmentMap\",\n      \"FragmentMapFunction\",\n      \"Directives\",\n      \"VariableValue\",\n      \"RemoveNodeConfig\",\n      \"GetNodeConfig\",\n      \"RemoveDirectiveConfig\",\n      \"GetDirectiveConfig\",\n      \"RemoveArgumentsConfig\",\n      \"GetFragmentSpreadConfig\",\n      \"RemoveFragmentSpreadConfig\",\n      \"RemoveFragmentDefinitionConfig\",\n      \"RemoveVariableDefinitionConfig\",\n      \"PromiseWithState\",\n      \"DeepOmit\",\n      \"OnlyRequiredProperties\",\n      \"Prettify\",\n      \"Primitive\",\n      \"UnionToIntersection\",\n      \"NoInfer\",\n      \"RemoveIndexSignature\",\n      \"TupleToIntersection\",\n      \"ReconcilerFunction\",\n      \"ConcastSourcesIterable\",\n      \"ConcastSourcesArray\",\n      \"IsStrictlyAny\"\n    ]\n  },\n  \"@apollo/client/utilities/globals\": {\n    \"value\": [\n      \"maybe\",\n      \"global\",\n      \"invariant\",\n      \"newInvariantError\",\n      \"InvariantError\",\n      \"DEV\",\n      \"___DEV__\"\n    ],\n    \"type\": []\n  },\n  \"@apollo/client/utilities/subscriptions/relay\": {\n    \"value\": [],\n    \"type\": []\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/exports.removed.local.json",
    "content": "{\n  \"@apollo/client/cache\": {\n    \"value\": [{ \"from\": \"DataProxy\" }],\n    \"type\": []\n  },\n  \"@apollo/client\": {\n    \"value\": [\n      { \"from\": \"isApolloError\" },\n      { \"from\": \"ApolloError\" },\n      { \"from\": \"DataProxy\" },\n      { \"from\": \"fromError\" },\n      { \"from\": \"toPromise\" },\n      { \"from\": \"fromPromise\" },\n      { \"from\": \"throwServerError\" },\n      { \"from\": \"Observer\" },\n      { \"from\": \"ObservableSubscription\" },\n      { \"from\": \"serializeFetchParameter\" }\n    ],\n    \"type\": [\n      { \"from\": \"FetchMoreQueryOptions\" },\n      { \"from\": \"Resolver\" },\n      { \"from\": \"FragmentMatcher\" },\n      { \"from\": \"MethodKeys\" },\n      { \"from\": \"PureQueryOptions\" },\n      { \"from\": \"MutationUpdaterFn\" },\n      { \"from\": \"Resolvers\" },\n      { \"from\": \"ClientParseError\" }\n    ]\n  },\n  \"@apollo/client/dev\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/errors\": {\n    \"value\": [{ \"from\": \"isApolloError\" }, { \"from\": \"ApolloError\" }],\n    \"type\": [\n      { \"from\": \"ApolloErrorOptions\" },\n      { \"from\": \"GraphQLErrors\" },\n      { \"from\": \"NetworkError\" }\n    ]\n  },\n  \"@apollo/client/link/batch\": {\n    \"value\": [{ \"from\": \"OperationBatcher\" }],\n    \"type\": [{ \"from\": \"BatchableRequest\" }]\n  },\n  \"@apollo/client/link/batch-http\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/link/context\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/core\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/error\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/http\": {\n    \"value\": [{ \"from\": \"serializeFetchParameter\" }],\n    \"type\": [{ \"from\": \"ClientParseError\" }]\n  },\n  \"@apollo/client/link/persisted-queries\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/retry\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/link/remove-typename\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/link/schema\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/link/subscriptions\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/link/utils\": {\n    \"value\": [\n      { \"from\": \"fromError\" },\n      { \"from\": \"toPromise\" },\n      { \"from\": \"fromPromise\" },\n      { \"from\": \"throwServerError\" },\n      { \"from\": \"validateOperation\" },\n      { \"from\": \"transformOperation\" }\n    ],\n    \"type\": []\n  },\n  \"@apollo/client/link/ws\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/masking\": { \"value\": [], \"type\": [] },\n  \"@apollo/client/react\": {\n    \"value\": [\n      { \"from\": \"ApolloConsumer\" },\n      { \"from\": \"resetApolloContext\" },\n      { \"from\": \"DocumentType\" },\n      { \"from\": \"operationName\" },\n      { \"from\": \"parser\" }\n    ],\n    \"type\": [\n      { \"from\": \"IDocumentDefinition\" },\n      { \"from\": \"CommonOptions\" },\n      { \"from\": \"BaseQueryOptions\" },\n      { \"from\": \"ObservableQueryFields\" },\n      { \"from\": \"QueryDataOptions\" },\n      { \"from\": \"QueryLazyOptions\" },\n      { \"from\": \"RefetchQueriesFunction\" },\n      { \"from\": \"BaseMutationOptions\" },\n      { \"from\": \"MutationDataOptions\" },\n      { \"from\": \"SubscriptionCurrentObservable\" }\n    ]\n  },\n  \"@apollo/client/react/components\": {\n    \"value\": [\n      { \"from\": \"Query\" },\n      { \"from\": \"Mutation\" },\n      { \"from\": \"Subscription\" }\n    ],\n    \"type\": [\n      { \"from\": \"QueryComponentOptions\" },\n      { \"from\": \"MutationComponentOptions\" },\n      { \"from\": \"SubscriptionComponentOptions\" }\n    ]\n  },\n  \"@apollo/client/react/context\": {\n    \"value\": [{ \"from\": \"ApolloConsumer\" }, { \"from\": \"resetApolloContext\" }],\n    \"type\": [{ \"from\": \"ApolloConsumerProps\" }]\n  },\n  \"@apollo/client/react/hoc\": {\n    \"value\": [\n      { \"from\": \"graphql\" },\n      { \"from\": \"withQuery\" },\n      { \"from\": \"withMutation\" },\n      { \"from\": \"withSubscription\" },\n      { \"from\": \"withApollo\" }\n    ],\n    \"type\": [\n      { \"from\": \"QueryControls\" },\n      { \"from\": \"DataValue\" },\n      { \"from\": \"DataProps\" },\n      { \"from\": \"MutateProps\" },\n      { \"from\": \"ChildProps\" },\n      { \"from\": \"ChildDataProps\" },\n      { \"from\": \"ChildMutateProps\" },\n      { \"from\": \"OptionProps\" },\n      { \"from\": \"OperationOption\" },\n      { \"from\": \"WithApolloClient\" }\n    ]\n  },\n  \"@apollo/client/react/hooks\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/react/internal\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/react/parser\": {\n    \"value\": [\n      { \"from\": \"operationName\" },\n      { \"from\": \"parser\" },\n      { \"from\": \"verifyDocumentType\" },\n      { \"from\": \"DocumentType\" }\n    ],\n    \"type\": [{ \"from\": \"IDocumentDefinition\" }]\n  },\n  \"@apollo/client/react/ssr\": {\n    \"value\": [{ \"from\": \"RenderPromises\" }],\n    \"type\": []\n  },\n  \"@apollo/client/testing\": {\n    \"value\": [\n      { \"from\": \"mockSingleLink\" },\n      { \"from\": \"mockObservableLink\" },\n      { \"from\": \"createMockClient\" },\n      { \"from\": \"subscribeAndCount\" },\n      { \"from\": \"itAsync\" },\n      { \"from\": \"tick\" },\n      { \"from\": \"withErrorSpy\" },\n      { \"from\": \"withWarningSpy\" },\n      { \"from\": \"withLogSpy\" },\n      { \"from\": \"wait\" }\n    ],\n    \"type\": []\n  },\n  \"@apollo/client/testing/core\": {\n    \"value\": [\n      { \"from\": \"mockSingleLink\" },\n      { \"from\": \"mockObservableLink\" },\n      { \"from\": \"createMockClient\" },\n      { \"from\": \"subscribeAndCount\" },\n      { \"from\": \"itAsync\" },\n      { \"from\": \"tick\" },\n      { \"from\": \"withErrorSpy\" },\n      { \"from\": \"withWarningSpy\" },\n      { \"from\": \"withLogSpy\" }\n    ],\n    \"type\": []\n  },\n  \"@apollo/client/testing/experimental\": {\n    \"value\": [{ \"from\": \"createTestSchema\" }, { \"from\": \"createSchemaFetch\" }],\n    \"type\": []\n  },\n  \"@apollo/client/utilities\": {\n    \"value\": [\n      { \"from\": \"hasAnyDirectives\" },\n      { \"from\": \"hasAllDirectives\" },\n      { \"from\": \"hasClientExports\" },\n      { \"from\": \"getDirectiveNames\" },\n      { \"from\": \"getInclusionDirectives\" },\n      { \"from\": \"getFragmentMaskMode\" },\n      { \"from\": \"isFullyUnmaskedOperation\" },\n      { \"from\": \"isInlineFragment\" },\n      { \"from\": \"valueToObjectRepresentation\" },\n      { \"from\": \"getTypenameFromResult\" },\n      { \"from\": \"addNonReactiveToNamedFragments\" },\n      { \"from\": \"buildQueryFromSelectionSet\" },\n      { \"from\": \"removeConnectionDirectiveFromDocument\" },\n      { \"from\": \"removeArgumentsFromDocument\" },\n      { \"from\": \"removeFragmentSpreadFromDocument\" },\n      { \"from\": \"removeClientSetsFromDocument\" },\n      { \"from\": \"Observer\" },\n      { \"from\": \"ObservableSubscription\" },\n      { \"from\": \"isStatefulPromise\" },\n      { \"from\": \"defaultCacheSizes\" },\n      { \"from\": \"iterateObserversSafely\" },\n      { \"from\": \"asyncMap\" },\n      { \"from\": \"Concast\" },\n      { \"from\": \"fixObservableSubclass\" },\n      { \"from\": \"canUseWeakMap\" },\n      { \"from\": \"canUseWeakSet\" },\n      { \"from\": \"canUseSymbol\" },\n      { \"from\": \"canUseAsyncIteratorSymbol\" },\n      { \"from\": \"canUseLayoutEffect\" },\n      { \"from\": \"isExecutionPatchIncrementalResult\" },\n      { \"from\": \"isExecutionPatchInitialResult\" },\n      { \"from\": \"isExecutionPatchResult\" },\n      { \"from\": \"isApolloPayloadResult\" },\n      { \"from\": \"mergeIncrementalData\" }\n    ],\n    \"type\": [\n      { \"from\": \"DirectiveInfo\" },\n      { \"from\": \"InclusionDirectives\" },\n      { \"from\": \"Directives\" },\n      { \"from\": \"VariableValue\" },\n      { \"from\": \"RemoveNodeConfig\" },\n      { \"from\": \"GetNodeConfig\" },\n      { \"from\": \"RemoveDirectiveConfig\" },\n      { \"from\": \"GetDirectiveConfig\" },\n      { \"from\": \"RemoveArgumentsConfig\" },\n      { \"from\": \"GetFragmentSpreadConfig\" },\n      { \"from\": \"RemoveFragmentSpreadConfig\" },\n      { \"from\": \"RemoveFragmentDefinitionConfig\" },\n      { \"from\": \"RemoveVariableDefinitionConfig\" },\n      { \"from\": \"PromiseWithState\" },\n      { \"from\": \"OnlyRequiredProperties\" },\n      { \"from\": \"UnionToIntersection\" },\n      { \"from\": \"TupleToIntersection\" },\n      { \"from\": \"ReconcilerFunction\" },\n      { \"from\": \"ConcastSourcesIterable\" },\n      { \"from\": \"ConcastSourcesArray\" },\n      { \"from\": \"IsStrictlyAny\" }\n    ]\n  },\n  \"@apollo/client/utilities/globals\": {\n    \"value\": [],\n    \"type\": []\n  },\n  \"@apollo/client/utilities/subscriptions/relay\": { \"value\": [], \"type\": [] }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/exports.test.ts",
    "content": "import { describe, expect, test } from \"vitest\";\n\nimport imports from \"../imports.js\";\n\nimport { createDiff } from \"./diffTransform.js\";\nimport allExports from \"./exports.json\" with { type: \"json\" };\nconst diff = createDiff(imports);\n\ndescribe(\"individual exports\", () => {\n  for (const [entryPoint, exports] of Object.entries(allExports)) {\n    describe(entryPoint, () => {\n      for (const info of exports) {\n        test(info.name, () => {\n          expect(\n            diff(\n              `\nimport { ${info.name} } from \"${info.moduleName}\";\n${info.usageExamples.join(\"\\n\")}\n            `.trim()\n            )\n          ).toMatchSnapshot();\n        });\n      }\n    });\n  }\n});\n\ndescribe(\"all exports\", () => {\n  for (const [entryPoint, exports] of Object.entries(allExports)) {\n    test(entryPoint, () => {\n      expect(\n        diff(\n          `\nimport {\n  ${exports.map((info) => info.name).join(\",\\n  \")}\n} from \"${entryPoint}\";\n${exports.map((info) => info.usageExamples.join(\"\\n\")).join(\"\\n\")}\n            `.trim()\n        )\n      ).toMatchSnapshot();\n    });\n  }\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/fixtures.test.ts",
    "content": "import { defineTest } from \"jscodeshift/dist/testUtils\";\n\ndefineTest(__dirname, \"imports.ts\", null, \"imports\", { parser: \"ts\" });\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/handleIdentifierRename.test.ts",
    "content": "import type { Options } from \"jscodeshift\";\nimport { applyTransform } from \"jscodeshift/dist/testUtils\";\nimport { describe, expect, test } from \"vitest\";\n\nimport type { IdentifierRename } from \"../renames.js\";\nimport { handleIdentiferRename } from \"../util/handleIdentiferRename.js\";\n\ndeclare module \"jscodeshift/dist/testUtils\" {\n  export function applyTransform(\n    module: import(\"jscodeshift\").Transform,\n    options: Options,\n    input: { source: string; path?: string },\n    testOptions?: Record<string, unknown>\n  ): string;\n}\n\nconst transform = (\n  source: string,\n  options: IdentifierRename | IdentifierRename[]\n) => {\n  const lines = source.split(\"\\n\");\n  const minIndent = lines.reduce((min, line) => {\n    if (line.match(/^\\s*$/)) return min; // skip empty lines\n    return Math.min(min, line.search(/\\S|$/));\n  }, Infinity);\n  if (minIndent > 0) {\n    source = lines.map((line) => line.slice(minIndent)).join(\"\\n\");\n  }\n\n  return applyTransform(\n    (file, api, options) => {\n      const j = api.jscodeshift;\n      const source = j(file.source);\n      const context = { j, source };\n      let modified = false;\n      if (!Array.isArray(options)) {\n        options = [options];\n      }\n      for (const rename of options as IdentifierRename[]) {\n        handleIdentiferRename({\n          context,\n          rename,\n          onModify() {\n            modified = true;\n          },\n        });\n      }\n      if (modified) return source.toSource();\n    },\n    options,\n    { source },\n    { parser: \"ts\" }\n  );\n};\n\ntest(\"moving identifier from one module to another\", () => {\n  expect(\n    transform(\"import { useQuery } from '@apollo/client'\", {\n      from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n      to: { module: \"@apollo/client/react\" },\n      importType: \"value\",\n    })\n  ).toMatchInlineSnapshot(`\n    \"import { useQuery } from \"@apollo/client/react\";\"\n  `);\n});\n\ntest(\"renaming identifier inside module\", () => {\n  expect(\n    transform(\n      `\n      import { useQuery } from '@apollo/client'\n      useQuery({ query: MY_QUERY });\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: { identifier: \"useRenamedQuery\" },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { useRenamedQuery } from '@apollo/client'\n    useRenamedQuery({ query: MY_QUERY });\"\n  `);\n});\n\ntest(\"moving identifier onto namespace inside module\", () => {\n  expect(\n    transform(\n      `\n      import { useQuery } from '@apollo/client'\n      useQuery({ query: MY_QUERY });\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: { namespace: \"surpriseNamespace\", identifier: \"useRenamedQuery\" },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { surpriseNamespace } from '@apollo/client'\n    surpriseNamespace.useRenamedQuery({ query: MY_QUERY });\"\n  `);\n});\n\ntest(\"renaming identifier to different module\", () => {\n  expect(\n    transform(\n      `\n      import { useQuery } from '@apollo/client'\n      useQuery({ query: MY_QUERY });\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: { module: \"@apollo/client/react\", identifier: \"useRenamedQuery\" },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { useRenamedQuery } from \"@apollo/client/react\";\n    useRenamedQuery({ query: MY_QUERY });\"\n  `);\n});\n\ntest(\"moving identifier into namespace in different module\", () => {\n  expect(\n    transform(\n      `\n      import { useQuery } from '@apollo/client'\n      useQuery({ query: MY_QUERY });\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: {\n          module: \"@apollo/client/react\",\n          identifier: \"useRenamedQuery\",\n          namespace: \"surpriseNamespace\",\n        },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { surpriseNamespace } from \"@apollo/client/react\";\n    surpriseNamespace.useRenamedQuery({ query: MY_QUERY });\"\n  `);\n});\n\ntest(\"type import moves into type import if available (1)\", () => {\n  expect(\n    transform(\n      `\n      import type { QueryOptions } from '@apollo/client'\n      import { unrelated } from '@apollo/client/react'\n      import type { UnrelatedType } from '@apollo/client/react'\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"QueryOptions\" },\n        to: {\n          module: \"@apollo/client/react\",\n        },\n        importType: \"type\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { unrelated } from '@apollo/client/react'\n    import type { UnrelatedType, QueryOptions } from '@apollo/client/react';\"\n  `);\n});\n\ntest(\"type import moves into type import if available (2)\", () => {\n  expect(\n    transform(\n      `\n      import type { QueryOptions } from '@apollo/client'\n      import type { UnrelatedType } from '@apollo/client/react'\n      import { unrelated } from '@apollo/client/react'\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"QueryOptions\" },\n        to: {\n          module: \"@apollo/client/react\",\n        },\n        importType: \"type\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import type { UnrelatedType, QueryOptions } from '@apollo/client/react';\n    import { unrelated } from '@apollo/client/react'\"\n  `);\n});\n\ntest(\"type import moves into value import if no type import available\", () => {\n  expect(\n    transform(\n      `\n      import type { QueryOptions } from '@apollo/client'\n      import { unrelated } from '@apollo/client/react'\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"QueryOptions\" },\n        to: {\n          module: \"@apollo/client/react\",\n        },\n        importType: \"type\",\n      }\n    )\n  ).toMatchInlineSnapshot(\n    `\"import { unrelated, QueryOptions } from '@apollo/client/react';\"`\n  );\n});\n\ntest(\"value import moves into value import if available (1)\", () => {\n  expect(\n    transform(\n      `\n      import type { useQuery } from '@apollo/client'\n      import type { UnrelatedType } from '@apollo/client/react'\n      import { unrelated } from '@apollo/client/react'\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: {\n          module: \"@apollo/client/react\",\n        },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import type { UnrelatedType } from '@apollo/client/react'\n    import { unrelated, useQuery } from '@apollo/client/react';\"\n  `);\n});\n\ntest(\"value import moves into value import if available (2)\", () => {\n  expect(\n    transform(\n      `\n      import type { useQuery } from '@apollo/client'\n      import { unrelated } from '@apollo/client/react'\n      import type { UnrelatedType } from '@apollo/client/react'\n      `,\n      {\n        from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n        to: {\n          module: \"@apollo/client/react\",\n        },\n        importType: \"value\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { unrelated, useQuery } from '@apollo/client/react';\n    import type { UnrelatedType } from '@apollo/client/react'\"\n  `);\n});\n\ndescribe(\"aliased imports\", () => {\n  test(\"moving identifier from one module to another\", () => {\n    expect(\n      transform(\n        `\n        import { useQuery as useAliasedQuery } from '@apollo/client'\n        useAliasedQuery({ query: MY_QUERY });\n        `,\n        {\n          from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n          to: { module: \"@apollo/client/react\" },\n          importType: \"value\",\n        }\n      )\n    ).toMatchInlineSnapshot(\n      `\n      \"import { useQuery as useAliasedQuery } from \"@apollo/client/react\";\n      useAliasedQuery({ query: MY_QUERY });\"\n    `\n    );\n  });\n\n  test(\"renaming identifier inside module\", () => {\n    expect(\n      transform(\n        `\n      import { useQuery as useAliasedQuery } from '@apollo/client'\n      useAliasedQuery({ query: MY_QUERY });\n      `,\n        {\n          from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n          to: { identifier: \"useRenamedQuery\" },\n          importType: \"value\",\n        }\n      )\n    ).toMatchInlineSnapshot(`\n      \"import { useRenamedQuery as useAliasedQuery } from '@apollo/client'\n      useAliasedQuery({ query: MY_QUERY });\"\n    `);\n  });\n\n  test(\"moving identifier onto namespace inside module\", () => {\n    expect(\n      transform(\n        `\n      import { useQuery as useAliasedQuery } from '@apollo/client'\n      useAliasedQuery({ query: MY_QUERY });\n      `,\n        {\n          from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n          to: { namespace: \"surpriseNamespace\", identifier: \"useRenamedQuery\" },\n          importType: \"value\",\n        }\n      )\n    ).toMatchInlineSnapshot(`\n      \"import { surpriseNamespace } from '@apollo/client'\n      surpriseNamespace.useRenamedQuery({ query: MY_QUERY });\"\n    `);\n  });\n\n  test(\"renaming identifier to different module\", () => {\n    expect(\n      transform(\n        `\n      import { useQuery as useAliasedQuery } from '@apollo/client'\n      useAliasedQuery({ query: MY_QUERY });\n      `,\n        {\n          from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n          to: { module: \"@apollo/client/react\", identifier: \"useRenamedQuery\" },\n          importType: \"value\",\n        }\n      )\n    ).toMatchInlineSnapshot(`\n      \"import { useRenamedQuery as useAliasedQuery } from \"@apollo/client/react\";\n      useAliasedQuery({ query: MY_QUERY });\"\n    `);\n  });\n\n  test(\"moving identifier into namespace in different module\", () => {\n    expect(\n      transform(\n        `\n      import { useQuery as useAliasedQuery } from '@apollo/client'\n      useAliasedQuery({ query: MY_QUERY });\n      `,\n        {\n          from: { module: \"@apollo/client\", identifier: \"useQuery\" },\n          to: {\n            module: \"@apollo/client/react\",\n            identifier: \"useRenamedQuery\",\n            namespace: \"surpriseNamespace\",\n          },\n          importType: \"value\",\n        }\n      )\n    ).toMatchInlineSnapshot(`\n      \"import { surpriseNamespace } from \"@apollo/client/react\";\n      surpriseNamespace.useRenamedQuery({ query: MY_QUERY });\"\n    `);\n  });\n\n  test(\"target namespace import already exists\", () => {\n    expect(\n      transform(\n        `\n      import type { ExecutionPatchInitialResult } from \"@apollo/client\";\n      import type { ExecutionPatchIncrementalResult } from \"@apollo/client/link\"\n      type Test = ExecutionPatchInitialResult | ExecutionPatchIncrementalResult;\n      `,\n        [\n          {\n            from: {\n              module: \"@apollo/client/link\",\n              alternativeModules: [\"@apollo/client\"],\n              identifier: \"ExecutionPatchInitialResult\",\n            },\n            to: {\n              module: \"@apollo/client/incremental\",\n              namespace: \"Defer20220824Handler\",\n              identifier: \"InitialResult\",\n            },\n            importType: \"type\",\n          },\n          {\n            from: {\n              module: \"@apollo/client/link\",\n              alternativeModules: [\"@apollo/client\"],\n              identifier: \"ExecutionPatchIncrementalResult\",\n            },\n            to: {\n              module: \"@apollo/client/incremental\",\n              namespace: \"Defer20220824Handler\",\n              identifier: \"SubsequentResult\",\n            },\n            importType: \"type\",\n          },\n        ]\n      )\n    ).toMatchInlineSnapshot(`\n      \"import type { Defer20220824Handler } from \"@apollo/client\";\n      type Test = Defer20220824Handler.InitialResult | Defer20220824Handler.SubsequentResult;\"\n    `);\n  });\n});\n\ntest(\"generic position\", () => {\n  expect(\n    transform(\n      `\n        import { FetchResult } from \"@apollo/client\";\n        fn<FetchResult>();\n      `,\n      {\n        from: {\n          module: \"@apollo/client/link\",\n          alternativeModules: [\"@apollo/client\"],\n          identifier: \"FetchResult\",\n        },\n        to: { namespace: \"ApolloLink\", identifier: \"Result\" },\n        importType: \"type\",\n      }\n    )\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client\";\n    fn<ApolloLink.Result>();\"\n  `);\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/imports.test.ts",
    "content": "import { applyTransform } from \"jscodeshift/dist/testUtils\";\nimport { describe, expect, test } from \"vitest\";\n\nimport imports from \"../imports.js\";\n\nconst transform = ([source]: TemplateStringsArray) =>\n  applyTransform(imports, {}, { source }, { parser: \"ts\" });\n\ndescribe(\"aliases if `legacyEntryPoints` transform was not applied\", () => {\n  test('moves into existing compatible \"legacy\" entry point', () => {\n    expect(\n      transform`\n    import { useQuery } from \"@apollo/client/index.js\";\n    import { somethingElse } from \"@apollo/client/react/react.cjs\";\n    `\n    ).toMatchInlineSnapshot(\n      `\"import { somethingElse, useQuery } from \"@apollo/client/react/react.cjs\";\"`\n    );\n  });\n  test(\"if nonexistent, creates new modern entry points\", () => {\n    expect(\n      transform`\n    import { useQuery } from \"@apollo/client/index.js\";\n    `\n    ).toMatchInlineSnapshot(\n      `\"import { useQuery } from \"@apollo/client/react\";\"`\n    );\n  });\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/legacyEntryPoints.test.ts",
    "content": "import { applyTransform } from \"jscodeshift/dist/testUtils\";\nimport { expect, test } from \"vitest\";\n\nimport legacyEntrypointTransform from \"../legacyEntrypoints.js\";\n\nconst transform = ([source]: TemplateStringsArray) =>\n  applyTransform(legacyEntrypointTransform, {}, { source }, { parser: \"ts\" });\n\ntest(\"renames\", () => {\n  expect(\n    transform`import { something } from \"@apollo/client/apollo-client.cjs\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/apollo-client.min.cjs\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/index.js\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/main.cjs\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/main.cjs.native.js\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/core/index.js\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/link/core/index.js\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client/link\";\"`);\n\n  expect(\n    transform`import { something } from \"@apollo/client/link/core/core.cjs\";`\n  ).toMatchInlineSnapshot(`\"import { something } from \"@apollo/client/link\";\"`);\n});\n\ntest(\"merge into existing import\", () => {\n  expect(\n    transform`\n    import { something } from \"@apollo/client/core/index.js\";\n    import { somethingElse } from \"@apollo/client\";\n    `\n  ).toMatchInlineSnapshot(\n    `\"import { somethingElse, something } from \"@apollo/client\";\"`\n  );\n});\n\ntest(\"avoids merging type/value\", () => {\n  expect(\n    transform`\n    import type { something } from \"@apollo/client/core/index.js\";\n    import { somethingElse } from \"@apollo/client\";\n    `\n  ).toMatchInlineSnapshot(\n    `\n    \"import type { something } from \"@apollo/client\";\n        import { somethingElse } from \"@apollo/client\";\"\n  `\n  );\n\n  expect(\n    transform`\n    import  { something } from \"@apollo/client/core/index.js\";\n    import type { somethingElse } from \"@apollo/client\";\n    `\n  ).toMatchInlineSnapshot(\n    `\n    \"import { something } from \"@apollo/client\";\n        import type { somethingElse } from \"@apollo/client\";\"\n  `\n  );\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/links.test.ts",
    "content": "import { applyTransform } from \"jscodeshift/dist/testUtils\";\nimport { expect, test } from \"vitest\";\n\nimport links from \"../links.js\";\n\nconst transform = ([source]: TemplateStringsArray) =>\n  applyTransform(links, {}, { source }, { parser: \"ts\" });\n\ntest(\"`concat` moves onto `ApolloLink`\", () => {\n  expect(\n    transform`\nimport { concat } from \"@apollo/client\";\n\nconst link = concat(link1, link2);\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client\";\n\n    const link = ApolloLink.concat(link1, link2);\"\n  `);\n});\n\ntest(\"`empty` moves onto `ApolloLink`\", () => {\n  expect(\n    transform`\nimport { empty } from \"@apollo/client\";\n\nconst link = empty();\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client\";\n\n    const link = ApolloLink.empty();\"\n  `);\n});\n\ntest(\"`from` moves onto `ApolloLink`\", () => {\n  expect(\n    transform`\nimport { from } from \"@apollo/client\";\n\nconst link = from(link1, link2);\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client\";\n\n    const link = ApolloLink.from(link1, link2);\"\n  `);\n});\n\ntest(\"`split` moves onto `ApolloLink`\", () => {\n  expect(\n    transform`\nimport { split } from \"@apollo/client\";\n\nconst link = split(op => op.operationType === \"mutation\", link1, link2);\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client\";\n\n    const link = ApolloLink.split(op => op.operationType === \"mutation\", link1, link2);\"\n  `);\n});\n\ntest(\"combined\", () => {\n  expect(\n    transform`\nimport { split, from, concat } from \"@apollo/client\";\nimport { ApolloLink, empty} from \"@apollo/client/link\";\n\nconst logLink = new ApolloLink((op, forward) => {\n    console.log(op);\n    return forward(op);\n})\n\nlet link = split(op => op.operationType === \"mutation\", logLink, empty);\nlink = from([link, concat(logLink, link)]);\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ApolloLink } from \"@apollo/client/link\";\n\n    const logLink = new ApolloLink((op, forward) => {\n        console.log(op);\n        return forward(op);\n    })\n\n    let link = ApolloLink.split(op => op.operationType === \"mutation\", logLink, ApolloLink.empty);\n    link = ApolloLink.from([link, ApolloLink.concat(logLink, link)]);\"\n  `);\n});\n\ntest(\"`onError` renames to `ErrorLink`\", () => {\n  expect(\n    transform`\nimport { onError } from \"@apollo/client/link/error\";\n\nconst link = onError(({ graphQLErrors, networkError }) => {\n  /** foo */\n})\n`\n  ).toMatchInlineSnapshot(`\n    \"import { ErrorLink } from \"@apollo/client/link/error\";\n\n    const link = new ErrorLink(({ graphQLErrors, networkError }) => {\n      /** foo */\n    })\"\n  `);\n});\n\ntest(\"`setContext` stays untouched\", () => {\n  expect(\n    transform`\nimport { setContext } from \"@apollo/client/link/error\";\n\nconst link = setContext((operation, prevContext) => {\n  return {\n    credentials: \"include\",\n  };\n});\n`\n  ).toMatchInlineSnapshot(`\"\"`);\n});\n\ntest(\"`createPersistedQueryLink` renames to `PersistedQueryLink`\", () => {\n  expect(\n    transform`\nimport { createPersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\nimport { sha256 } from \"crypto-hash\";\n\nconst link = new createPersistedQueryLink({\n  sha256: (queryString) => sha256(queryString),\n});\n`\n  ).toMatchInlineSnapshot(`\n    \"import { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\n    import { sha256 } from \"crypto-hash\";\n\n    const link = new PersistedQueryLink({\n      sha256: (queryString) => sha256(queryString),\n    });\"\n  `);\n});\n\ntest(\"`createHttpLink` renames to `HttpLink`\", () => {\n  expect(\n    transform`\nimport { createHttpLink } from \"@apollo/client\";\n\nconst link = createHttpLink({\n  uri: \"http://localhost:4000/graphql\",\n  // Additional options\n});\n`\n  ).toMatchInlineSnapshot(`\n    \"import { HttpLink } from \"@apollo/client\";\n\n    const link = new HttpLink({\n      uri: \"http://localhost:4000/graphql\",\n      // Additional options\n    });\"\n  `);\n});\n\ntest(\"`removeTypenameFromVariables` renames to `RemoveTypenameFromVariablesLink`\", () => {\n  expect(\n    transform`\nimport {\n  removeTypenameFromVariables,\n  KEEP,\n} from \"@apollo/client/link/remove-typename\";\n\nconst link = removeTypenameFromVariables({\n  except: {\n    JSON: KEEP, // Keep __typename for all JSON scalar variables\n    DashboardInput: {\n      config: KEEP, // Keep __typename only for the config field\n    },\n  },\n});\n`\n  ).toMatchInlineSnapshot(`\n    \"import {\n      KEEP,\n      RemoveTypenameFromVariablesLink,\n    } from \"@apollo/client/link/remove-typename\";\n\n    const link = new RemoveTypenameFromVariablesLink({\n      except: {\n        JSON: KEEP, // Keep __typename for all JSON scalar variables\n        DashboardInput: {\n          config: KEEP, // Keep __typename only for the config field\n        },\n      },\n    });\"\n  `);\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/__tests__/removals.test.ts",
    "content": "import { describe, expect, test } from \"vitest\";\n\nimport removals from \"../removals.js\";\n\nimport { createDiff } from \"./diffTransform.js\";\nimport allExports from \"./exports.json\" with { type: \"json\" };\nconst diff = createDiff(removals);\n\ntest(\"all exports\", () => {\n  const source = Object.entries(allExports)\n    .map(([entryPoint, exports]) =>\n      `\nimport {\n  ${exports\n    .map(\n      (info) =>\n        `${info.name} as ${entryPoint\n          .replace(/@apollo\\/client\\/?/, \"\")\n          .replace(/[/-]/g, \"_\")}_${info.name}`\n    )\n    .join(\",\\n  \")},\n} from \"${entryPoint}\";\n            `.trim()\n    )\n    .join(\"\\n\\n\");\n\n  //console.log(source);\n\n  expect(diff(source)).toMatchSnapshot();\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/apolloClientInitialization.ts",
    "content": "import assert from \"node:assert\";\n\nimport type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift\";\n\nimport type { IdentifierRename } from \"./renames.js\";\nimport type { UtilContext } from \"./types.js\";\nimport { findImportSpecifiersFor } from \"./util/findImportSpecifiersFor.js\";\nimport { findOrInsertImport } from \"./util/findOrInsertImport.js\";\nimport { findReferences } from \"./util/findReferences.js\";\nimport { getProperty } from \"./util/getProperty.js\";\nimport { monkeyPatchAstTypes } from \"./util/monkeyPatchAstTypes.js\";\n\nconst steps = {\n  explicitLinkConstruction,\n  clientAwareness,\n  localState,\n  devtoolsOption,\n  prioritizeCacheValues,\n  dataMasking,\n  incrementalHandler,\n} satisfies Record<string, (options: StepOptions) => void>;\n\nexport type Steps = keyof typeof steps | \"removeTypeArguments\";\n\nconst apolloClientInitializationTransform: j.Transform = function transform(\n  file,\n  api,\n  options = {}\n) {\n  const j = api.jscodeshift;\n  const source = j(file.source);\n  const context = { j, source };\n\n  monkeyPatchAstTypes(j);\n\n  let modified = false;\n  function onModified() {\n    modified = true;\n  }\n  const enabledStepNames =\n    Array.isArray(options.apolloClientInitialization) ?\n      options.apolloClientInitialization\n    : Object.keys(steps).concat(\"removeTypeArguments\");\n  const enabledSteps = Object.fromEntries(\n    Object.entries(steps).filter(([name]) => enabledStepNames.includes(name))\n  );\n\n  for (const constructorCall of apolloClientConstructions({ context })) {\n    const options = {\n      context,\n      onModified,\n      constructorCall,\n      prop: (name: string) =>\n        getProperty({\n          context,\n          objectPath: constructorCall.optionsPath,\n          name,\n        }),\n      file,\n    };\n    for (const step of Object.values(enabledSteps)) {\n      step(options);\n    }\n  }\n\n  // removes `TCacheShape` parameter from all `ApolloClient` usages, not just constructor calls\n  if (enabledStepNames.includes(\"removeTypeArguments\")) {\n    for (const specPath of findImportSpecifiersFor({\n      description: apolloClientDescription,\n      context,\n    }).paths()) {\n      for (const refParent of findReferences({\n        context,\n        identifier: (specPath.node.local || specPath.node.imported).name + \"\",\n        scope: specPath.scope,\n      })\n        .map((refPath) => {\n          const parentPath = refPath.parentPath;\n          return j.ImportSpecifier.check(parentPath.node) ? null : parentPath;\n        })\n        .paths()) {\n        const typeParameters = refParent.get(\"typeParameters\");\n        if (typeParameters?.node?.params?.length) {\n          modified = true;\n          typeParameters.prune();\n        }\n      }\n    }\n  }\n\n  return modified ? source.toSource() : undefined;\n};\nexport default apolloClientInitializationTransform;\n\ninterface StepOptions {\n  context: UtilContext;\n  constructorCall: ConstructorCall;\n  onModified: () => void;\n  prop: (name: string) => j.ASTPath<namedTypes.ObjectProperty> | null;\n  file: j.FileInfo;\n}\n\nfunction explicitLinkConstruction({\n  context,\n  context: { j },\n  constructorCall: { optionsPath },\n  onModified,\n  prop,\n}: StepOptions) {\n  if (prop(\"link\")) {\n    return;\n  }\n  onModified();\n\n  const uriPath = prop(\"uri\");\n  const uri = uriPath?.node;\n  uriPath?.replace();\n\n  const credentialsPath = prop(\"credentials\");\n  const credentials = credentialsPath?.node;\n  credentialsPath?.replace();\n\n  const headersPath = prop(\"headers\");\n  const headers = headersPath?.node;\n  headersPath?.replace();\n\n  const linkSpec = findOrInsertImport({\n    context,\n    description: {\n      module: \"@apollo/client/link/http\",\n      identifier: \"HttpLink\",\n      alternativeModules: [\"@apollo/client\"],\n    },\n    compatibleWith: \"value\",\n  });\n\n  optionsPath.node.properties.push(\n    j.objectProperty.from({\n      key: j.identifier(\"link\"),\n      value: j.newExpression.from({\n        callee: linkSpec.local || linkSpec.imported,\n        arguments: [\n          j.objectExpression.from({\n            properties: [uri, credentials, headers].filter((prop) => !!prop),\n          }),\n        ],\n      }),\n    })\n  );\n}\n\nfunction clientAwareness({\n  context: { j },\n  constructorCall: { optionsPath },\n  onModified,\n  prop,\n}: StepOptions) {\n  const namePath = prop(\"name\");\n  const name = namePath?.node;\n  namePath?.replace();\n\n  const versionPath = prop(\"version\");\n  const version = versionPath?.node;\n  versionPath?.replace();\n\n  if (!namePath && !versionPath) {\n    return;\n  }\n  onModified();\n\n  optionsPath.node.properties.push(\n    j.objectProperty.from({\n      key: j.identifier(\"clientAwareness\"),\n      value: j.objectExpression.from({\n        properties: [name, version].filter((prop) => !!prop),\n      }),\n    })\n  );\n}\n\nfunction localState({\n  context,\n  context: { j },\n  constructorCall: { specPath, optionsPath },\n  onModified,\n  prop,\n}: StepOptions) {\n  const resolversPath = prop(\"resolvers\");\n  const resolvers = resolversPath?.node;\n  resolversPath?.replace();\n\n  const typeDefsPath = prop(\"typeDefs\");\n  typeDefsPath?.replace();\n\n  const fragmentMatcherPath = prop(\"fragmentMatcher\");\n  fragmentMatcherPath?.replace();\n\n  if (resolversPath || typeDefsPath || fragmentMatcherPath) {\n    onModified();\n  }\n  if (prop(\"localState\")) {\n    return;\n  }\n  onModified();\n  const localStateSpec = findOrInsertImport({\n    context,\n    description: {\n      module: \"@apollo/client/local-state\",\n      identifier: \"LocalState\",\n    },\n    compatibleWith: \"value\",\n    after: j(specPath).closest(j.ImportDeclaration),\n  });\n\n  optionsPath.node.properties.push(\n    j.objectProperty.from({\n      key: j.identifier(\"localState\"),\n      value: j.newExpression.from({\n        callee: localStateSpec.local || localStateSpec.imported,\n        arguments: [\n          j.objectExpression.from({\n            properties: [resolvers].filter((prop) => !!prop),\n          }),\n        ],\n      }),\n      comments:\n        resolvers ?\n          []\n        : [\n            j.commentBlock.from({\n              leading: true,\n              value: `\nInserted by Apollo Client 3->4 migration codemod.\nIf you are not using the \\`@client\\` directive in your application,\nyou can safely remove this option.\n`,\n            }),\n          ],\n    })\n  );\n}\n\nfunction devtoolsOption({\n  context: { j },\n  constructorCall: { optionsPath },\n  onModified,\n  prop,\n}: StepOptions) {\n  const devtoolsPath = prop(\"connectToDevTools\");\n  const node = devtoolsPath?.node;\n  devtoolsPath?.replace();\n  if (!devtoolsPath) {\n    return;\n  }\n  onModified();\n\n  assert(node);\n\n  if (node.shorthand) {\n    node.value = node.key;\n    node.shorthand = false;\n  }\n  node.key = j.identifier(\"enabled\");\n  optionsPath.node.properties.push(\n    j.objectProperty.from({\n      key: j.identifier(\"devtools\"),\n      value: j.objectExpression.from({\n        properties: [node],\n      }),\n    })\n  );\n}\n\nfunction prioritizeCacheValues({\n  context: { j },\n  onModified,\n  prop,\n}: StepOptions) {\n  const devtoolsPath = prop(\"disableNetworkFetches\");\n  if (!devtoolsPath) {\n    return;\n  }\n  onModified();\n\n  const node = devtoolsPath.node;\n  if (node.shorthand) {\n    node.value = node.key;\n    node.shorthand = false;\n  }\n  node.key = j.identifier(\"prioritizeCacheValues\");\n}\n\ninterface ConstructorCall {\n  specPath: j.ASTPath<namedTypes.ImportSpecifier>;\n  newExprPath: j.ASTPath<namedTypes.NewExpression>;\n  optionsPath: j.ASTPath<namedTypes.ObjectExpression>;\n}\n\nfunction dataMasking({\n  context,\n  context: { j, source },\n  onModified,\n  prop,\n  file,\n}: StepOptions) {\n  if (!file.path.endsWith(\".ts\") && !file.path.endsWith(\".tsx\")) {\n    // avoid inserting data masking types in non-TypeScript files\n    return;\n  }\n\n  const dataMaskingPath = prop(\"dataMasking\");\n  const dataMasking = dataMaskingPath?.node;\n  if (\n    !dataMasking ||\n    (j.BooleanLiteral.check(dataMasking.value) &&\n      dataMasking.value.value === false) ||\n    dataMasking.comments?.some((comment) =>\n      CODEMOD_MARKER_REGEX(\"applied\").test(comment.value)\n    )\n  ) {\n    return;\n  }\n\n  onModified();\n  dataMasking.comments ??= [];\n  dataMasking.comments.push(\n    j.commentBlock.from({\n      leading: true,\n      value: `\nInserted by Apollo Client 3->4 migration codemod.\nKeep this comment here if you intend to run the codemod again,\nto avoid changes from being reapplied.\nDelete this comment once you are done with the migration.\n${CODEMOD_MARKER} applied\n`,\n    })\n  );\n\n  insertTypeOverrideBlock({\n    context,\n    leadingComment: `Copy the contents of this block into a \\`.d.ts\\` file in your project\nto enable data masking types.`,\n    overridingType: {\n      module: \"@apollo/client/masking\",\n      namespace: \"GraphQLCodegenDataMasking\",\n      identifier: \"TypeOverrides\",\n    },\n  });\n}\n\nfunction incrementalHandler({\n  context,\n  context: { j, source },\n  constructorCall: { specPath, optionsPath },\n  onModified,\n  prop,\n  file,\n}: StepOptions) {\n  if (prop(\"incrementalHandler\")) {\n    return;\n  }\n  onModified();\n\n  const deferHandlerSpec = findOrInsertImport({\n    context,\n    description: {\n      module: \"@apollo/client/incremental\",\n      identifier: \"Defer20220824Handler\",\n    },\n    compatibleWith: \"value\",\n    after: j(specPath).closest(j.ImportDeclaration),\n  });\n\n  optionsPath.node.properties.push(\n    j.objectProperty.from({\n      key: j.identifier(\"incrementalHandler\"),\n      value: j.newExpression.from({\n        callee: deferHandlerSpec.local || deferHandlerSpec.imported,\n        arguments: [],\n      }),\n      comments: [\n        j.commentBlock.from({\n          leading: true,\n          value: `\nInserted by Apollo Client 3->4 migration codemod.\nIf you are not using the \\`@defer\\` directive in your application,\nyou can safely remove this option.\n`,\n        }),\n      ],\n    })\n  );\n\n  if (!file.path.endsWith(\".ts\") && !file.path.endsWith(\".tsx\")) {\n    // avoid inserting defer types in non-TypeScript files\n    return;\n  }\n\n  insertTypeOverrideBlock({\n    context,\n    leadingComment: `Copy the contents of this block into a \\`.d.ts\\` file in your project to enable correct response types in your custom links.\nIf you do not use the \\`@defer\\` directive in your application, you can safely remove this block.`,\n    overridingType: {\n      module: \"@apollo/client/incremental\",\n      namespace: \"Defer20220824Handler\",\n      identifier: \"TypeOverrides\",\n    },\n  });\n}\n\nfunction insertTypeOverrideBlock({\n  context: { source, j },\n  leadingComment,\n  overridingType: { identifier, module, namespace },\n}: {\n  context: UtilContext;\n  leadingComment: string;\n  overridingType: Required<\n    Pick<IdentifierRename[\"to\"], \"module\" | \"namespace\" | \"identifier\">\n  >;\n}) {\n  const program = source.find(j.Program).nodes()[0]!;\n  program.body.push(\n    j.emptyStatement.from({\n      comments: [\n        j.commentBlock.from({\n          leading: true,\n          value: `\nStart: Inserted by Apollo Client 3->4 migration codemod.\n${leadingComment}\n`,\n        }),\n      ],\n    }),\n    j.importDeclaration.from({ source: j.literal(\"@apollo/client\") }),\n    j.importDeclaration.from({\n      specifiers: [\n        j.importSpecifier.from({\n          imported: j.identifier(namespace),\n        }),\n      ],\n      source: j.literal(module),\n    }),\n    j.tsModuleDeclaration.from({\n      id: j.stringLiteral(\"@apollo/client\"),\n      declare: true,\n      body: j.tsModuleBlock.from({\n        body: [\n          j.exportNamedDeclaration.from({\n            declaration: j.tsInterfaceDeclaration.from({\n              id: j.identifier(\"TypeOverrides\"),\n              extends: [\n                j.tsExpressionWithTypeArguments.from({\n                  expression: j.tsQualifiedName.from({\n                    left: j.identifier(namespace),\n                    right: j.identifier(identifier),\n                  }),\n                }),\n              ],\n              body: j.tsInterfaceBody.from({ body: [] }),\n            }),\n          }),\n        ],\n      }),\n    }),\n    j.emptyStatement.from({\n      comments: [\n        j.commentBlock.from({\n          leading: true,\n          value: `\nEnd: Inserted by Apollo Client 3->4 migration codemod.\n`,\n        }),\n      ],\n    })\n  );\n}\n\nfunction* apolloClientConstructions({\n  context,\n  context: { j },\n}: {\n  context: UtilContext;\n}): Generator<ConstructorCall> {\n  for (const specPath of findImportSpecifiersFor({\n    description: apolloClientDescription,\n    compatibleWith: \"value\",\n    context,\n  }).paths()) {\n    for (const newExprPath of findReferences({\n      context,\n      identifier: (specPath.node.local || specPath.node.imported).name + \"\",\n      scope: specPath.scope,\n    })\n      .map<namedTypes.NewExpression>((usage) =>\n        j.NewExpression.check(usage.parentPath.node) ? usage.parentPath : null\n      )\n      .paths()) {\n      const optionsPath = newExprPath.get(\"arguments\", 0);\n      if (optionsPath && j.ObjectExpression.check(optionsPath.node)) {\n        yield {\n          specPath,\n          newExprPath,\n          optionsPath: optionsPath as j.ASTPath<namedTypes.ObjectExpression>,\n        };\n      }\n    }\n  }\n}\n\nconst CODEMOD_MARKER = `@apollo/client-codemod-migrate-3-to-4`;\nconst CODEMOD_MARKER_REGEX = (keyword: string) =>\n  new RegExp(`^\\\\s*(?:[*]?\\\\s*)${CODEMOD_MARKER} ${keyword}\\\\s*$`, \"m\");\n\nconst apolloClientDescription = {\n  module: \"@apollo/client\",\n  identifier: \"ApolloClient\",\n  alternativeModules: [\n    \"@apollo/client/core\",\n    \"@apollo/client-react-streaming\",\n    \"@apollo/experimental-nextjs-app-support\",\n    \"@apollo/client-integration-nextjs\",\n    \"@apollo/client-integration-react-router\",\n    \"@apollo/client-integration-tanstack-start\",\n  ],\n};\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/cli.ts",
    "content": "#!/usr/bin/env node\n\nimport { createRequire } from \"node:module\";\nimport { dirname, extname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// @ts-ignore\nconst url = import.meta.url;\nconst fullName = fileURLToPath(url);\n\nprocess.argv.splice(\n  2,\n  0,\n  \"--transform\",\n  join(dirname(fullName), `index${extname(fullName)}`)\n);\nconst require = createRequire(url);\nrequire(\"jscodeshift/bin/jscodeshift.js\");\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/devLoader.js",
    "content": "import { registerHooks } from \"node:module\";\n\nregisterHooks({\n  resolve(specifier, context, nextResolve) {\n    try {\n      return nextResolve(specifier, context);\n    } catch (e) {\n      if (specifier.endsWith(\".js\")) {\n        for (const ext of [\".ts\", \".tsx\"]) {\n          return nextResolve(specifier.slice(0, -3) + ext, context);\n        }\n      }\n      throw e;\n    }\n  },\n});\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/imports.ts",
    "content": "import type { Transform } from \"jscodeshift\";\n\nimport { renames } from \"./renames.js\";\nimport type { ImportKind } from \"./types.js\";\nimport { handleIdentiferRename } from \"./util/handleIdentiferRename.js\";\nimport { handleModuleRename } from \"./util/handleModuleRename.js\";\nimport { monkeyPatchAstTypes } from \"./util/monkeyPatchAstTypes.js\";\n\ndeclare module \"ast-types\" {\n  export namespace namedTypes {\n    interface ImportSpecifier {\n      importKind?: ImportKind;\n    }\n  }\n}\n\nconst importTransform: Transform = function transform(file, api) {\n  const j = api.jscodeshift;\n  const source = j(file.source);\n  const context = { j, source };\n\n  monkeyPatchAstTypes(j);\n\n  let modified = false;\n  for (const rename of renames) {\n    if (!(\"importType\" in rename)) {\n      handleModuleRename({\n        rename,\n        context,\n        onModify() {\n          modified = true;\n        },\n      });\n    } else {\n      handleIdentiferRename({\n        rename,\n        context,\n        onModify() {\n          modified = true;\n        },\n      });\n    }\n  }\n  return modified ? source.toSource() : undefined;\n};\n\nexport default importTransform;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/index.ts",
    "content": "import type { API, FileInfo, Options, Transform } from \"jscodeshift\";\n\nimport clientSetup from \"./apolloClientInitialization.js\";\nimport imports from \"./imports.js\";\nimport legacyEntrypoints from \"./legacyEntrypoints.js\";\nimport links from \"./links.js\";\nimport removals from \"./removals.js\";\nimport { monkeyPatchAstTypes } from \"./util/monkeyPatchAstTypes.js\";\n\nexport const codemods = {\n  legacyEntrypoints,\n  imports,\n  links,\n  removals,\n  clientSetup,\n} satisfies Record<string, Transform>;\n\nexport default async function transform(\n  file: FileInfo,\n  api: API,\n  options: Options\n): Promise<string | undefined> {\n  monkeyPatchAstTypes(api.jscodeshift);\n\n  const run =\n    \"codemod\" in options ?\n      Array.isArray(options.codemod) ?\n        options.codemod\n      : [options.codemod]\n    : Object.keys(codemods);\n\n  let all_skipped = true;\n\n  for (const codemod of run) {\n    if (codemod in codemods) {\n      const ret = await codemods[codemod as keyof typeof codemods](\n        file,\n        api,\n        options\n      );\n\n      if (typeof ret === \"string\" && ret !== file.source) {\n        file.source = ret;\n        all_skipped = false;\n      }\n    } else {\n      console.warn(`Codemod \"${codemod}\" not found, skipping.`);\n      process.exitCode = 1;\n    }\n  }\n\n  return all_skipped ? undefined : file.source;\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/legacyEntrypoints.ts",
    "content": "import type { Transform } from \"jscodeshift\";\n\nimport { entryPointAliases } from \"./util/entryPointAliases.js\";\nimport { handleModuleRename } from \"./util/handleModuleRename.js\";\n\nconst legacyEntrypointTransform: Transform = function transform(file, api) {\n  const j = api.jscodeshift;\n  const source = j(file.source);\n  const context = { j, source };\n\n  let modified = false;\n  for (const [to, legacy] of Object.entries(entryPointAliases)) {\n    for (const from of legacy) {\n      handleModuleRename({\n        rename: { to: { module: to }, from: { module: from } },\n        context,\n        onModify() {\n          modified = true;\n        },\n      });\n    }\n  }\n  return modified ? source.toSource() : undefined;\n};\nexport default legacyEntrypointTransform;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/links.ts",
    "content": "import type { Transform } from \"jscodeshift\";\n\nimport type { IdentifierRename } from \"./renames.js\";\nimport { callExpressionToNewExpression } from \"./util/callExpressionToNewExpression.js\";\nimport { handleIdentiferRename } from \"./util/handleIdentiferRename.js\";\n\nconst linkTransform: Transform = function transform(file, api) {\n  const j = api.jscodeshift;\n  const source = j(file.source);\n  const context = { j, source };\n  const changes = [\n    {\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n        identifier: \"concat\",\n      },\n      to: { namespace: \"ApolloLink\" },\n      importType: \"value\",\n    },\n    {\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n        identifier: \"empty\",\n      },\n      to: { namespace: \"ApolloLink\" },\n      importType: \"value\",\n    },\n    {\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n        identifier: \"from\",\n      },\n      to: { namespace: \"ApolloLink\" },\n      importType: \"value\",\n    },\n    {\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n        identifier: \"split\",\n      },\n      to: { namespace: \"ApolloLink\" },\n      importType: \"value\",\n    },\n    {\n      from: { module: \"@apollo/client/link/error\", identifier: \"onError\" },\n      to: { identifier: \"ErrorLink\" },\n      importType: \"value\",\n      postProcess: callExpressionToNewExpression(),\n    },\n    // {\n    //   from: { module: \"@apollo/client/link/context\", identifier: \"setContext\" },\n    //   to: { identifier: \"SetContextLink\" },\n    //   importType: \"value\",\n    //   // Note: setContext arguments are flipped compared to SetContextLink\n    //   // cannot codemod this reliably, so we leave it to the user\n    //   postProcess: callExpressionToNewExpression(),\n    // },\n    {\n      from: {\n        module: \"@apollo/client/link/persisted-queries\",\n        identifier: \"createPersistedQueryLink\",\n      },\n      to: { identifier: \"PersistedQueryLink\" },\n      importType: \"value\",\n      postProcess: callExpressionToNewExpression(),\n    },\n    {\n      from: {\n        module: \"@apollo/client/link/http\",\n        identifier: \"createHttpLink\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { identifier: \"HttpLink\" },\n      importType: \"value\",\n      postProcess: callExpressionToNewExpression(),\n    },\n    {\n      from: {\n        module: \"@apollo/client/link/remove-typename\",\n        identifier: \"removeTypenameFromVariables\",\n      },\n      to: { identifier: \"RemoveTypenameFromVariablesLink\" },\n      importType: \"value\",\n      postProcess: callExpressionToNewExpression(),\n    },\n  ] satisfies IdentifierRename[];\n\n  let modified = false;\n  for (const rename of changes) {\n    handleIdentiferRename({\n      rename,\n      context,\n      onModify: () => {\n        modified = true;\n      },\n    });\n  }\n  return modified ? source.toSource() : undefined;\n};\nexport default linkTransform;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/removals.ts",
    "content": "import type { Transform } from \"jscodeshift\";\n\nimport type { IdentifierRename } from \"./renames.js\";\nimport { handleIdentiferRename } from \"./util/handleIdentiferRename.js\";\n\n// prettier-ignore\nconst removals = [\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"ClientParseError\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"FetchMoreQueryOptions\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"FragmentMatcher\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"MethodKeys\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"MutationUpdaterFn\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"PureQueryOptions\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"Resolver\" },\n  { importType: \"type\", module: \"@apollo/client\", identifier: \"Resolvers\" },\n  { importType: \"type\", module: \"@apollo/client/errors\", identifier: \"ApolloErrorOptions\" },\n  { importType: \"type\", module: \"@apollo/client/errors\", identifier: \"GraphQLErrors\" },\n  { importType: \"type\", module: \"@apollo/client/errors\", identifier: \"NetworkError\" },\n  { importType: \"type\", module: \"@apollo/client/link/batch\", identifier: \"BatchableRequest\" },\n  { importType: \"type\", module: \"@apollo/client/link/http\", identifier: \"ClientParseError\" },\n  { importType: \"type\", module: \"@apollo/client/masking\", identifier: \"Masked\" },\n  { importType: \"type\", module: \"@apollo/client/masking\", identifier: \"MaskedDocumentNode\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"BaseMutationOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"BaseQueryOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"CommonOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"IDocumentDefinition\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"MutationDataOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"ObservableQueryFields\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"QueryDataOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"QueryLazyOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"RefetchQueriesFunction\" },\n  { importType: \"type\", module: \"@apollo/client/react\", identifier: \"SubscriptionCurrentObservable\" },\n  { importType: \"type\", module: \"@apollo/client/react/components\", identifier: \"MutationComponentOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react/components\", identifier: \"QueryComponentOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react/components\", identifier: \"SubscriptionComponentOptions\" },\n  { importType: \"type\", module: \"@apollo/client/react/context\", identifier: \"ApolloConsumerProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"ChildDataProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"ChildMutateProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"ChildProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"DataProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"DataValue\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"MutateProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"OperationOption\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"OptionProps\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"QueryControls\" },\n  { importType: \"type\", module: \"@apollo/client/react/hoc\", identifier: \"WithApolloClient\" },\n  { importType: \"type\", module: \"@apollo/client/react/parser\", identifier: \"IDocumentDefinition\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"ConcastSourcesArray\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"ConcastSourcesIterable\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"DirectiveInfo\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"Directives\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"GetDirectiveConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"GetFragmentSpreadConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"GetNodeConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"InclusionDirectives\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"IsStrictlyAny\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"OnlyRequiredProperties\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"PromiseWithState\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"ReconcilerFunction\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveArgumentsConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveDirectiveConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveFragmentDefinitionConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveFragmentSpreadConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveNodeConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"RemoveVariableDefinitionConfig\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"TupleToIntersection\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"UnionToIntersection\" },\n  { importType: \"type\", module: \"@apollo/client/utilities\", identifier: \"VariableValue\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"ApolloError\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"DataProxy\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"fromError\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"fromPromise\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"isApolloError\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"ObservableSubscription\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"Observer\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"serializeFetchParameter\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"throwServerError\" },\n  { importType: \"value\", module: \"@apollo/client\", identifier: \"toPromise\" },\n  { importType: \"value\", module: \"@apollo/client/cache\", identifier: \"DataProxy\" },\n  { importType: \"value\", module: \"@apollo/client/errors\", identifier: \"ApolloError\" },\n  { importType: \"value\", module: \"@apollo/client/errors\", identifier: \"isApolloError\" },\n  { importType: \"value\", module: \"@apollo/client/link/batch\", identifier: \"OperationBatcher\" },\n  { importType: \"value\", module: \"@apollo/client/link/http\", identifier: \"serializeFetchParameter\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"fromError\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"fromPromise\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"throwServerError\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"toPromise\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"transformOperation\" },\n  { importType: \"value\", module: \"@apollo/client/link/utils\", identifier: \"validateOperation\" },\n  { importType: \"value\", module: \"@apollo/client/react\", identifier: \"ApolloConsumer\" },\n  { importType: \"value\", module: \"@apollo/client/react\", identifier: \"DocumentType\" },\n  { importType: \"value\", module: \"@apollo/client/react\", identifier: \"operationName\" },\n  { importType: \"value\", module: \"@apollo/client/react\", identifier: \"parser\" },\n  { importType: \"value\", module: \"@apollo/client/react\", identifier: \"resetApolloContext\" },\n  { importType: \"value\", module: \"@apollo/client/react/components\", identifier: \"Mutation\" },\n  { importType: \"value\", module: \"@apollo/client/react/components\", identifier: \"Query\" },\n  { importType: \"value\", module: \"@apollo/client/react/components\", identifier: \"Subscription\" },\n  { importType: \"value\", module: \"@apollo/client/react/context\", identifier: \"ApolloConsumer\" },\n  { importType: \"value\", module: \"@apollo/client/react/context\", identifier: \"resetApolloContext\" },\n  { importType: \"value\", module: \"@apollo/client/react/hoc\", identifier: \"graphql\" },\n  { importType: \"value\", module: \"@apollo/client/react/hoc\", identifier: \"withApollo\" },\n  { importType: \"value\", module: \"@apollo/client/react/hoc\", identifier: \"withMutation\" },\n  { importType: \"value\", module: \"@apollo/client/react/hoc\", identifier: \"withQuery\" },\n  { importType: \"value\", module: \"@apollo/client/react/hoc\", identifier: \"withSubscription\" },\n  { importType: \"value\", module: \"@apollo/client/react/parser\", identifier: \"DocumentType\" },\n  { importType: \"value\", module: \"@apollo/client/react/parser\", identifier: \"operationName\" },\n  { importType: \"value\", module: \"@apollo/client/react/parser\", identifier: \"parser\" },\n  { importType: \"value\", module: \"@apollo/client/react/parser\", identifier: \"verifyDocumentType\" },\n  { importType: \"value\", module: \"@apollo/client/react/ssr\", identifier: \"RenderPromises\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"createMockClient\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"itAsync\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"mockObservableLink\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"mockSingleLink\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"subscribeAndCount\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"tick\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"wait\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"withErrorSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"withLogSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing\", identifier: \"withWarningSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"createMockClient\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"itAsync\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"mockObservableLink\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"mockSingleLink\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"subscribeAndCount\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"tick\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"withErrorSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"withLogSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing/core\", identifier: \"withWarningSpy\" },\n  { importType: \"value\", module: \"@apollo/client/testing/experimental\", identifier: \"createSchemaFetch\" },\n  { importType: \"value\", module: \"@apollo/client/testing/experimental\", identifier: \"createTestSchema\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"addNonReactiveToNamedFragments\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"asyncMap\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"buildQueryFromSelectionSet\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"canUseAsyncIteratorSymbol\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"canUseLayoutEffect\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"canUseSymbol\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"canUseWeakMap\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"canUseWeakSet\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"Concast\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"defaultCacheSizes\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"fixObservableSubclass\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"getDirectiveNames\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"getFragmentMaskMode\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"getInclusionDirectives\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"getTypenameFromResult\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"hasAllDirectives\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"hasAnyDirectives\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"hasClientExports\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isApolloPayloadResult\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isExecutionPatchIncrementalResult\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isExecutionPatchInitialResult\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isExecutionPatchResult\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isFullyUnmaskedOperation\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isInlineFragment\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"isStatefulPromise\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"iterateObserversSafely\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"mergeIncrementalData\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"ObservableSubscription\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"Observer\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"removeArgumentsFromDocument\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"removeClientSetsFromDocument\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"removeConnectionDirectiveFromDocument\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"removeFragmentSpreadFromDocument\" },\n  { importType: \"value\", module: \"@apollo/client/utilities\", identifier: \"valueToObjectRepresentation\" },\n] satisfies Array<{\n  module: string;\n  identifier: string;\n  importType: \"type\" | \"value\";\n}>;\n\nconst removalsTransform: Transform = function transform(file, api) {\n  const j = api.jscodeshift;\n  const source = j(file.source);\n  const context = { j, source };\n\n  let modified = false;\n  for (const removal of removals) {\n    const rename: IdentifierRename = {\n      from: {\n        module: removal.module,\n        identifier: removal.identifier,\n        alternativeModules: [\"@apollo/client\", \"@apollo/client/core\"],\n      },\n      to: { module: \"@apollo/client/v4-migration\", alternativeModules: [] },\n      importType: removal.importType,\n    };\n    handleIdentiferRename({\n      rename,\n      context,\n      onModify: () => {\n        modified = true;\n      },\n    });\n  }\n  return modified ? source.toSource() : undefined;\n};\nexport default removalsTransform;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/renames.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift\";\n\nimport type { UtilContext } from \"./types.js\";\nimport { reorderGenericArguments } from \"./util/reorderGenericArguments.js\";\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/react/components\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/react/hoc\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/react/components\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/react/parser\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/testing/experimental\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/utilities/globals\" },\n// },\n// {\n//   // completely removed in AC4\n//   from: { module: \"@apollo/client/utilities/subscriptions/urql\" },\n// },\n\nexport const renames: Array<IdentifierRename | ModuleRename> = [\n  {\n    from: { module: \"@apollo/client/core\" },\n    to: { module: \"@apollo/client\" },\n  },\n  {\n    from: { module: \"@apollo/client/link/core\" },\n    to: { module: \"@apollo/client/link\" },\n  },\n  {\n    from: { module: \"@apollo/client/react/context\" },\n    to: { module: \"@apollo/client/react\" },\n  },\n  {\n    from: { module: \"@apollo/client/react/hooks\" },\n    to: { module: \"@apollo/client/react\" },\n  },\n  {\n    from: { module: \"@apollo/client/testing/core\" },\n    to: { module: \"@apollo/client/testing\" },\n  },\n  {\n    from: {\n      module: \"@apollo/client/react\",\n      alternativeModules: [\"@apollo/client\", \"@apollo/client/react/internal\"],\n      identifier: \"QueryReference\",\n    },\n    to: {\n      module: \"@apollo/client/react\",\n      alternativeModules: [],\n      identifier: \"QueryRef\",\n    },\n    importType: \"type\",\n  },\n  ...[\n    // were re-exported from the `@apollo/client/react` entry point\n    { from: \"ApolloProvider\" },\n    { from: \"createQueryPreloader\" },\n    { from: \"getApolloContext\" },\n    { from: \"skipToken\" },\n    { from: \"useApolloClient\" },\n    { from: \"useBackgroundQuery\" },\n    { from: \"useFragment\" },\n    { from: \"useLazyQuery\" },\n    { from: \"useLoadableQuery\" },\n    { from: \"useMutation\" },\n    { from: \"useQuery\" },\n    { from: \"useQueryRefHandlers\" },\n    { from: \"useReactiveVar\" },\n    { from: \"useReadQuery\" },\n    { from: \"useSubscription\" },\n    { from: \"useSuspenseFragment\" },\n    { from: \"useSuspenseQuery\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client\" },\n      to: { module: \"@apollo/client/react\" },\n      importType: \"value\",\n    })\n  ),\n  ...[\n    // were re-exported from the `@apollo/client/react` entry point\n    { from: \"ApolloContextValue\" },\n    { from: \"BackgroundQueryHookFetchPolicy\" },\n    { from: \"BackgroundQueryHookOptions\" },\n    { from: \"BaseSubscriptionOptions\" },\n    { from: \"Context\" },\n    { from: \"LazyQueryExecFunction\" },\n    { from: \"LazyQueryHookExecOptions\" },\n    { from: \"LazyQueryHookOptions\" },\n    { from: \"LazyQueryResult\" },\n    { from: \"LazyQueryResultTuple\" },\n    { from: \"LoadableQueryHookFetchPolicy\" },\n    { from: \"LoadableQueryHookOptions\" },\n    { from: \"LoadQueryFunction\" },\n    { from: \"MutationFunction\" },\n    { from: \"MutationFunctionOptions\" },\n    { from: \"MutationHookOptions\" },\n    { from: \"MutationResult\" },\n    { from: \"MutationTuple\" },\n    { from: \"NoInfer\" },\n    { from: \"OnDataOptions\" },\n    { from: \"OnSubscriptionDataOptions\" },\n    { from: \"PreloadedQueryRef\" },\n    { from: \"PreloadQueryFetchPolicy\" },\n    { from: \"PreloadQueryFunction\" },\n    { from: \"PreloadQueryOptions\" },\n    { from: \"QueryFunctionOptions\" },\n    { from: \"QueryHookOptions\" },\n    { from: \"QueryRef\" },\n    { from: \"QueryReference\" },\n    { from: \"QueryResult\" },\n    { from: \"QueryTuple\" },\n    { from: \"SkipToken\" },\n    { from: \"SubscriptionDataOptions\" },\n    { from: \"SubscriptionHookOptions\" },\n    { from: \"SubscriptionResult\" },\n    { from: \"SuspenseQueryHookFetchPolicy\" },\n    { from: \"SuspenseQueryHookOptions\" },\n    { from: \"UseBackgroundQueryResult\" },\n    { from: \"UseFragmentOptions\" },\n    { from: \"UseFragmentResult\" },\n    { from: \"UseLoadableQueryResult\" },\n    { from: \"UseQueryRefHandlersResult\" },\n    { from: \"UseReadQueryResult\" },\n    { from: \"UseSuspenseFragmentOptions\" },\n    { from: \"UseSuspenseFragmentResult\" },\n    { from: \"UseSuspenseQueryResult\" },\n    { from: \"VariablesOption\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client\" },\n      to: { module: \"@apollo/client/react\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    // move to the `@apollo/client/react` entry point\n    { from: \"PreloadedQueryRef\" },\n    { from: \"QueryRef\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/react/internal\" },\n      to: { module: \"@apollo/client/react\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    // move to the `@apollo/client/utilities/internal` entry point\n    { from: \"argumentsObjectFromField\" },\n    { from: \"AutoCleanedStrongCache\" },\n    { from: \"AutoCleanedWeakCache\" },\n    { from: \"canUseDOM\" },\n    { from: \"checkDocument\" },\n    { from: \"cloneDeep\" },\n    { from: \"compact\" },\n    { from: \"createFragmentMap\" },\n    { from: \"createFulfilledPromise\" },\n    { from: \"createRejectedPromise\" },\n    { from: \"dealias\" },\n    { from: \"decoratePromise\" },\n    { from: \"DeepMerger\" },\n    { from: \"filterMap\" },\n    { from: \"getApolloCacheMemoryInternals\" },\n    { from: \"getApolloClientMemoryInternals\" },\n    { from: \"getDefaultValues\" },\n    { from: \"getFragmentDefinition\" },\n    { from: \"getFragmentDefinitions\" },\n    { from: \"getFragmentFromSelection\" },\n    { from: \"getFragmentQueryDocument\" },\n    { from: \"getGraphQLErrorsFromResult\" },\n    { from: \"getInMemoryCacheMemoryInternals\" },\n    { from: \"getOperationDefinition\" },\n    { from: \"getOperationName\" },\n    { from: \"getQueryDefinition\" },\n    { from: \"getStoreKeyName\" },\n    { from: \"graphQLResultHasError\" },\n    { from: \"hasDirectives\" },\n    { from: \"hasForcedResolvers\" },\n    { from: \"isArray\" },\n    { from: \"isDocumentNode\" },\n    { from: \"isField\" },\n    { from: \"isNonEmptyArray\" },\n    { from: \"isNonNullObject\" },\n    { from: \"isPlainObject\" },\n    { from: \"makeReference\" },\n    { from: \"makeUniqueId\" },\n    { from: \"maybeDeepFreeze\" },\n    { from: \"mergeDeep\" },\n    { from: \"mergeDeepArray\" },\n    { from: \"mergeOptions\" },\n    { from: \"omitDeep\" },\n    { from: \"preventUnhandledRejection\" },\n    { from: \"registerGlobalCache\" },\n    { from: \"removeDirectivesFromDocument\" },\n    { from: \"resultKeyNameFromField\" },\n    { from: \"shouldInclude\" },\n    { from: \"storeKeyNameFromField\" },\n    { from: \"stringifyForDisplay\" },\n    { from: \"toQueryResult\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/utilities\",\n        alternativeModules: [\n          // mergeOptions, makeReference\n          \"@apollo/client\",\n          // makeReference\n          \"@apollo/client/cache\",\n        ],\n      },\n      to: { module: \"@apollo/client/utilities/internal\" },\n      importType: \"value\",\n    })\n  ),\n  ...[\n    // move to the `@apollo/client/utilities/internal` entry point\n    { from: \"DecoratedPromise\" },\n    { from: \"DeepOmit\" },\n    { from: \"FragmentMap\" },\n    { from: \"FragmentMapFunction\" },\n    { from: \"FulfilledPromise\" },\n    { from: \"IsAny\" },\n    { from: \"NoInfer\" },\n    { from: \"PendingPromise\" },\n    { from: \"Prettify\" },\n    { from: \"Primitive\" },\n    { from: \"RejectedPromise\" },\n    { from: \"RemoveIndexSignature\" },\n    { from: \"VariablesOption\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/utilities\" },\n      to: { module: \"@apollo/client/utilities/internal\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"NoInfer\" }, { from: \"VariablesOption\" }].map(\n    moveInto({\n      from: { module: \"@apollo/client/react\" },\n      to: { module: \"@apollo/client/utilities/internal\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"DEV\", to: \"__DEV__\" }, { from: \"__DEV__\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/utilities/global\",\n        alternativeModules: [\"@apollo/client/utilities\"],\n      },\n      to: { module: \"@apollo/client/utilities/environment\" },\n      importType: \"value\",\n    })\n  ),\n  ...[{ from: \"global\" }, { from: \"maybe\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/utilities/global\",\n        alternativeModules: [\"@apollo/client/utilities\"],\n      },\n      to: { module: \"@apollo/client/utilities/internal/globals\" },\n      importType: \"value\",\n    })\n  ),\n  ...[\n    { from: \"invariant\" },\n    { from: \"InvariantError\" },\n    { from: \"newInvariantError\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/utilities/global\" },\n      to: { module: \"@apollo/client/utilities/invariant\" },\n      importType: \"value\",\n    })\n  ),\n  ...[\n    // move into `ApolloClient` type namespace\n    { from: \"ApolloClientOptions\", to: \"Options\" },\n    { from: \"DefaultOptions\" },\n    { from: \"DevtoolsOptions\" },\n    { from: \"MutateResult\" },\n    { from: \"MutationOptions\", to: \"MutateOptions\" },\n    { from: \"QueryOptions\", postProcess: reorderGenerics([1, 0]) },\n    { from: \"RefetchQueriesOptions\" },\n    { from: \"RefetchQueriesResult\" },\n    {\n      from: \"SubscriptionOptions\",\n      to: \"SubscribeOptions\",\n      postProcess: reorderGenerics([1, 0]),\n    },\n    { from: \"WatchQueryOptions\", postProcess: reorderGenerics([1, 0]) },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client\" },\n      to: { namespace: \"ApolloClient\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    // move into `ObservableQuery` type namespace\n    { from: \"ApolloQueryResult\", to: \"Result\" },\n    { from: \"FetchMoreOptions\" },\n    { from: \"SubscribeToMoreOptions\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client\" },\n      to: { namespace: \"ObservableQuery\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    // move into `ApolloCache` type namespace\n    { from: \"WatchFragmentOptions\" },\n    { from: \"WatchFragmentResult\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/cache\" },\n      to: { namespace: \"ApolloCache\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"Context\", to: \"DefaultContext\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n      },\n      to: { module: \"@apollo/client\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"ApolloProviderProps\", to: \"Props\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"ApolloProvider\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"BackgroundQueryHookFetchPolicy\", to: \"FetchPolicy\" },\n    {\n      from: \"BackgroundQueryHookOptions\",\n      to: \"Options\",\n      postProcess: reorderGenerics([1]),\n    },\n    { from: \"UseBackgroundQueryResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useBackgroundQuery\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"LazyQueryExecFunction\", to: \"ExecFunction\" },\n    { from: \"LazyQueryHookExecOptions\", to: \"ExecOptions\" },\n    { from: \"LazyQueryHookOptions\", to: \"Options\" },\n    { from: \"LazyQueryResult\", to: \"Result\" },\n    { from: \"LazyQueryResultTuple\", to: \"ResultTuple\" },\n    { from: \"QueryTuple\", to: \"ResultTuple\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useLazyQuery\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"LoadableQueryFetchPolicy\", to: \"FetchPolicy\" },\n    { from: \"LoadableQueryHookFetchPolicy\", to: \"FetchPolicy\" },\n    { from: \"LoadableQueryHookOptions\", to: \"Options\" },\n    { from: \"LoadQueryFunction\" },\n    { from: \"UseLoadableQueryResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useLoadableQuery\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    {\n      from: \"MutationFunctionOptions\",\n      postProcess: reorderGenerics([0, 1, 3]),\n    },\n    {\n      from: \"MutationHookOptions\",\n      to: \"Options\",\n      postProcess: reorderGenerics([0, 1, 3]),\n    },\n    { from: \"MutationResult\", to: \"Result\" },\n    {\n      from: \"MutationTuple\",\n      to: \"ResultTuple\",\n      postProcess: reorderGenerics([0, 1, 3]),\n    },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useMutation\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"BaseSubscriptionOptions\", to: \"Options\" },\n    { from: \"OnDataOptions\" },\n    { from: \"OnSubscriptionDataOptions\" },\n    { from: \"SubscriptionHookOptions\", to: \"Options\" },\n    {\n      from: \"SubscriptionResult\",\n      to: \"Result\",\n      postProcess: reorderGenerics([0]),\n    },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useSubscription\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"QueryFunctionOptions\", to: \"Options\" },\n    { from: \"QueryHookOptions\", to: \"Options\" },\n    { from: \"QueryResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useQuery\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    {\n      from: \"SuspenseQueryHookFetchPolicy\",\n      to: \"FetchPolicy\",\n      alternativeModules: [\"@apollo/client\"],\n    },\n    {\n      from: \"SuspenseQueryHookOptions\",\n      to: \"Options\",\n      alternativeModules: [],\n      postProcess: reorderGenerics([1]),\n    },\n    { from: \"UseSuspenseQueryResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/react\" },\n      to: { namespace: \"useSuspenseQuery\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"UseQueryRefHandlersResult\", to: \"Result\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useQueryRefHandlers\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"UseFragmentOptions\", to: \"Options\" },\n    { from: \"UseFragmentResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useFragment\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"UseReadQueryResult\", to: \"Result\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useReadQuery\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"UseSuspenseFragmentOptions\", to: \"Options\" },\n    { from: \"UseSuspenseFragmentResult\", to: \"Result\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/react\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"useSuspenseFragment\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  {\n    from: {\n      module: \"@apollo/client/testing\",\n      identifier: \"MockedProvider\",\n    },\n    to: {\n      module: \"@apollo/client/testing/react\",\n    },\n    importType: \"value\",\n  },\n  {\n    from: {\n      module: \"@apollo/client/testing\",\n      identifier: \"MockedProviderProps\",\n    },\n    to: {\n      module: \"@apollo/client/testing/react\",\n    },\n    importType: \"type\",\n  },\n  ...[\n    { from: \"MockedRequest\" },\n    { from: \"MockedResponse\" },\n    { from: \"MockLinkOptions\", to: \"Options\" },\n    { from: \"ResultFunction\" },\n  ].map(\n    moveInto({\n      from: { module: \"@apollo/client/testing\" },\n      to: { namespace: \"MockLink\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    // move into `ApolloLink` type namespace\n    {\n      from: \"FetchResult\",\n      to: \"Result\", // FetchResult<TData, TContext, TExtensions> -> ApolloLink.Result<TData, TExtensions>\n      postProcess: reorderGenerics([0, 2]),\n    },\n    { from: \"GraphQLRequest\", to: \"Request\" },\n    { from: \"NextLink\", to: \"ForwardFunction\" },\n    { from: \"Operation\" },\n    { from: \"RequestHandler\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"ApolloLink\" },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"ExecutionPatchIncrementalResult\", to: \"SubsequentResult\" },\n    { from: \"ExecutionPatchInitialResult\", to: \"InitialResult\" },\n    { from: \"ExecutionPatchResult\", to: \"Chunk\" },\n    { from: \"IncrementalPayload\", to: \"IncrementalDeferPayload\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: {\n        module: \"@apollo/client/incremental\",\n        alternativeModules: [],\n        namespace: \"Defer20220824Handler\",\n      },\n      importType: \"type\",\n    })\n  ),\n  {\n    from: {\n      identifier: \"Path\",\n      module: \"@apollo/client/link\",\n      alternativeModules: [\"@apollo/client\"],\n    },\n    to: {\n      module: \"@apollo/client/incremental\",\n      namespace: \"Incremental\",\n    },\n    importType: \"type\",\n  },\n  {\n    from: {\n      identifier: \"SingleExecutionResult\",\n      module: \"@apollo/client/link\",\n      alternativeModules: [\"@apollo/client\"],\n    },\n    to: {\n      identifier: \"FormattedExecutionResult\",\n      module: \"graphql\",\n    },\n    importType: \"type\",\n  },\n  ...[{ from: \"BatchHandler\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/batch\",\n      },\n      to: {\n        namespace: \"BatchLink\",\n      },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"ContextSetter\", to: \"LegacyContextSetter\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/context\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"SetContextLink\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"ErrorHandler\" },\n    { from: \"ErrorResponse\", to: \"ErrorHandlerOptions\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/error\",\n      },\n      to: { namespace: \"ErrorLink\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"ServerParseError\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/http\",\n      },\n      to: {\n        module: \"@apollo/client/errors\",\n      },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"ErrorResponse\", to: \"DisableFunctionOptions\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/persisted-queries\",\n        alternativeModules: [\"@apollo/client\"],\n      },\n      to: { namespace: \"PersistedQueryLink\", alternativeModules: [] },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"RemoveTypenameFromVariablesOptions\", to: \"Options\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/remove-typename\",\n      },\n      to: { namespace: \"RemoveTypenameFromVariablesLink\" },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"ServerError\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/utils\",\n      },\n      to: {\n        module: \"@apollo/client/errors\",\n      },\n      importType: \"type\",\n    })\n  ),\n  ...[{ from: \"WebSocketParams\", to: \"Configuration\" }].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/link/ws\",\n      },\n      to: {\n        namespace: \"WebSocketLink\",\n      },\n      importType: \"type\",\n    })\n  ),\n  ...[\n    { from: \"isNetworkRequestInFlight\" },\n    { from: \"isNetworkRequestSettled\" },\n  ].map(\n    moveInto({\n      from: {\n        module: \"@apollo/client/core/networkStatus\",\n        alternativeModules: [\"@apollo/client/core\", \"@apollo/client\"],\n      },\n      to: {\n        module: \"@apollo/client/utilities\",\n        alternativeModules: [],\n      },\n      importType: \"value\",\n    })\n  ),\n  // no direct 1:1 drop-in replacement\n  // {\n  //   from: { module: \"@apollo/client/react/ssr\", identifier: \"renderToStringWithData\" },\n  //   to: {\n  //     module: \"@apollo/client/react/ssr\",\n  //     identifier: \"prerenderStatic\",\n  //   },\n  //   realm: \"runtime\",\n  // },\n  // {\n  //   from: { module: \"@apollo/client/react/ssr\", identifier: \"getDataFromTree\" },\n  //   to: {\n  //     module: \"@apollo/client/react/ssr\",\n  //     identifier: \"prerenderStatic\",\n  //   },\n  //   realm: \"runtime\",\n  // },\n  // {\n  //   from: { module: \"@apollo/client/react/ssr\", identifier: \"getMarkupFromTree\" },\n  //   to: {\n  //     module: \"@apollo/client/react/ssr\",\n  //     identifier: \"prerenderStatic\",\n  //   },\n  //   realm: \"runtime\",\n  // },\n];\n\nexport interface IdentifierRename {\n  from: {\n    /** A list of source modules to look out for. */\n    module: string;\n    /** Alternative modules that should also be rewritten if encountered */\n    alternativeModules?: string[];\n    /** The identifier to be renamed or moved into another module/namespace. */\n    identifier: string;\n    /** If omitted, the source is not namespaced. */\n    namespace?: string;\n  };\n  to: {\n    /** If omitted, identifier was renamed within the same entry point. */\n    module?: string;\n    /**\n     * A list of alternative valid entry points.\n     * If one of these is already used, but `to.module` is not used in the file yet,\n     * the alternative module will be used instead of adding a new `import` statement.\n     */\n    alternativeModules?: string[];\n    /** If omitted, the identifier did not change. */\n    identifier?: string;\n    /** If omitted, the target is not namespaced. */\n    namespace?: string;\n  };\n  importType: \"type\" | \"value\";\n  postProcess?(args: {\n    context: UtilContext;\n    namespace?: string;\n    identifier: string;\n    renamedSpecifierPath: j.ASTPath<namedTypes.ImportSpecifier>;\n  }): void;\n}\n\ninterface IdentifierRenameCommon extends Omit<IdentifierRename, \"from\"> {\n  from: Omit<IdentifierRename[\"from\"], \"identifier\"> & {\n    identifier?: string;\n  };\n}\n\nexport interface ModuleRename {\n  from: {\n    module: string;\n    identifier?: never;\n    namespace?: never;\n  };\n  to: {\n    module: string;\n    identifier?: never;\n    namespace?: never;\n  };\n}\n\nfunction reorderGenerics(\n  newOrder: number[]\n): (args: {\n  context: UtilContext;\n  namespace?: string;\n  identifier: string;\n  renamedSpecifierPath: j.ASTPath<namedTypes.ImportSpecifier>;\n}) => void {\n  return ({ context, identifier, namespace, renamedSpecifierPath }) => {\n    reorderGenericArguments({\n      context,\n      namespace,\n      identifier,\n      scope: renamedSpecifierPath.scope,\n      newOrder,\n    });\n  };\n}\n\nfunction moveInto(common: IdentifierRenameCommon) {\n  return ({\n    from,\n    to = from,\n    postProcess = common.postProcess,\n  }: {\n    from: string;\n    to?: string;\n    postProcess?: IdentifierRename[\"postProcess\"];\n  }): IdentifierRename => ({\n    ...common,\n    postProcess,\n    from: { ...common.from, identifier: from },\n    to: { ...common.to, identifier: to },\n  });\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/types.ts",
    "content": "import type { Collection, JSCodeshift } from \"jscodeshift\";\n\nexport type ImportKind = \"type\" | \"value\";\n\nexport interface UtilContext {\n  j: JSCodeshift;\n  source: Collection<any>;\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/callExpressionToNewExpression.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift/src/core.js\";\n\nimport type { UtilContext } from \"../types.js\";\n\nimport { findReferences } from \"./findReferences.js\";\nimport { pick } from \"./pick.js\";\n\nexport function callExpressionToNewExpression(): (args: {\n  context: UtilContext;\n  namespace?: string;\n  identifier: string;\n  renamedSpecifierPath: j.ASTPath<namedTypes.ImportSpecifier>;\n}) => void {\n  return ({\n    context,\n    context: { j },\n    identifier,\n    namespace,\n    renamedSpecifierPath,\n  }) =>\n    findReferences({\n      context,\n      namespace,\n      identifier,\n      scope: renamedSpecifierPath.scope,\n    }).forEach((identifierPath) => {\n      if (!j.CallExpression.check(identifierPath.parentPath.node)) {\n        return;\n      }\n      const callPath: j.ASTPath<j.CallExpression> = identifierPath.parentPath;\n      const call = callPath.node;\n\n      callPath.replace(\n        j.newExpression.from(pick(call, \"callee\", \"comments\", \"arguments\"))\n      );\n    });\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/entryPointAliases.ts",
    "content": "/*\n```sh\njq --slurpfile packages <(find . -name package.json | xargs cat) '$packages|map({key:.name, value: [.name+\"/\"+.main,.name+\"/\"+.module]})|from_entries' <(echo '{}')\n```\n*/\nconst fromPackageJson = {\n  \"@apollo/client/core\": [\n    \"@apollo/client/core/core.cjs\",\n    \"@apollo/client/core/index.js\",\n  ],\n  \"@apollo/client/cache\": [\n    \"@apollo/client/cache/cache.cjs\",\n    \"@apollo/client/cache/index.js\",\n  ],\n  \"@apollo/client/utilities/globals\": [\n    \"@apollo/client/utilities/globals/globals.cjs\",\n    \"@apollo/client/utilities/globals/index.js\",\n  ],\n  \"@apollo/client/utilities/subscriptions/urql\": [\n    \"@apollo/client/utilities/subscriptions/urql/urql.cjs\",\n    \"@apollo/client/utilities/subscriptions/urql/index.js\",\n  ],\n  \"@apollo/client/utilities/subscriptions/relay\": [\n    \"@apollo/client/utilities/subscriptions/relay/relay.cjs\",\n    \"@apollo/client/utilities/subscriptions/relay/index.js\",\n  ],\n  \"@apollo/client/utilities\": [\n    \"@apollo/client/utilities/utilities.cjs\",\n    \"@apollo/client/utilities/index.js\",\n  ],\n  \"@apollo/client/testing/experimental\": [\n    \"@apollo/client/testing/experimental/experimental.cjs\",\n    \"@apollo/client/testing/experimental/index.js\",\n  ],\n  \"@apollo/client/testing/core\": [\n    \"@apollo/client/testing/core/core.cjs\",\n    \"@apollo/client/testing/core/index.js\",\n  ],\n  \"@apollo/client/testing\": [\n    \"@apollo/client/testing/testing.cjs\",\n    \"@apollo/client/testing/index.js\",\n  ],\n  \"@apollo/client/link/remove-typename\": [\n    \"@apollo/client/link/remove-typename/remove-typename.cjs\",\n    \"@apollo/client/link/remove-typename/index.js\",\n  ],\n  \"@apollo/client/link/context\": [\n    \"@apollo/client/link/context/context.cjs\",\n    \"@apollo/client/link/context/index.js\",\n  ],\n  \"@apollo/client/link/core\": [\n    \"@apollo/client/link/core/core.cjs\",\n    \"@apollo/client/link/core/index.js\",\n  ],\n  \"@apollo/client/link/retry\": [\n    \"@apollo/client/link/retry/retry.cjs\",\n    \"@apollo/client/link/retry/index.js\",\n  ],\n  \"@apollo/client/link/utils\": [\n    \"@apollo/client/link/utils/utils.cjs\",\n    \"@apollo/client/link/utils/index.js\",\n  ],\n  \"@apollo/client/link/subscriptions\": [\n    \"@apollo/client/link/subscriptions/subscriptions.cjs\",\n    \"@apollo/client/link/subscriptions/index.js\",\n  ],\n  \"@apollo/client/link/schema\": [\n    \"@apollo/client/link/schema/schema.cjs\",\n    \"@apollo/client/link/schema/index.js\",\n  ],\n  \"@apollo/client/link/http\": [\n    \"@apollo/client/link/http/http.cjs\",\n    \"@apollo/client/link/http/index.js\",\n  ],\n  \"@apollo/client/link/batch\": [\n    \"@apollo/client/link/batch/batch.cjs\",\n    \"@apollo/client/link/batch/index.js\",\n  ],\n  \"@apollo/client/link/batch-http\": [\n    \"@apollo/client/link/batch-http/batch-http.cjs\",\n    \"@apollo/client/link/batch-http/index.js\",\n  ],\n  \"@apollo/client/link/error\": [\n    \"@apollo/client/link/error/error.cjs\",\n    \"@apollo/client/link/error/index.js\",\n  ],\n  \"@apollo/client/link/persisted-queries\": [\n    \"@apollo/client/link/persisted-queries/persisted-queries.cjs\",\n    \"@apollo/client/link/persisted-queries/index.js\",\n  ],\n  \"@apollo/client/link/ws\": [\n    \"@apollo/client/link/ws/ws.cjs\",\n    \"@apollo/client/link/ws/index.js\",\n  ],\n  \"@apollo/client\": [\"@apollo/client/./main.cjs\", \"@apollo/client/./index.js\"],\n  \"@apollo/client/dev\": [\n    \"@apollo/client/dev/dev.cjs\",\n    \"@apollo/client/dev/index.js\",\n  ],\n  \"@apollo/client/errors\": [\n    \"@apollo/client/errors/errors.cjs\",\n    \"@apollo/client/errors/index.js\",\n  ],\n  \"@apollo/client/react/context\": [\n    \"@apollo/client/react/context/context.cjs\",\n    \"@apollo/client/react/context/index.js\",\n  ],\n  \"@apollo/client/react/hoc\": [\n    \"@apollo/client/react/hoc/hoc.cjs\",\n    \"@apollo/client/react/hoc/index.js\",\n  ],\n  \"@apollo/client/react/internal\": [\n    \"@apollo/client/react/internal/internal.cjs\",\n    \"@apollo/client/react/internal/index.js\",\n  ],\n  \"@apollo/client/react/parser\": [\n    \"@apollo/client/react/parser/parser.cjs\",\n    \"@apollo/client/react/parser/index.js\",\n  ],\n  \"@apollo/client/react/ssr\": [\n    \"@apollo/client/react/ssr/ssr.cjs\",\n    \"@apollo/client/react/ssr/index.js\",\n  ],\n  \"@apollo/client/react/components\": [\n    \"@apollo/client/react/components/components.cjs\",\n    \"@apollo/client/react/components/index.js\",\n  ],\n  \"@apollo/client/react\": [\n    \"@apollo/client/react/react.cjs\",\n    \"@apollo/client/react/index.js\",\n  ],\n  \"@apollo/client/react/hooks\": [\n    \"@apollo/client/react/hooks/hooks.cjs\",\n    \"@apollo/client/react/hooks/index.js\",\n  ],\n  \"@apollo/client/masking\": [\n    \"@apollo/client/masking/masking.cjs\",\n    \"@apollo/client/masking/index.js\",\n  ],\n} satisfies Record<string, string[]>;\n\nexport const entryPointAliases = {\n  ...fromPackageJson,\n  \"@apollo/client/core\": [] as string[],\n  \"@apollo/client\": [\n    \"@apollo/client/apollo-client.cjs\",\n    \"@apollo/client/apollo-client.min.cjs\",\n    \"@apollo/client/index.js\",\n    \"@apollo/client/main.cjs\",\n    \"@apollo/client/main.cjs.native.js\",\n    ...fromPackageJson[\"@apollo/client/core\"],\n  ],\n  \"@apollo/client/link/core\": [] as string[],\n  \"@apollo/client/link\": fromPackageJson[\"@apollo/client/link/core\"],\n} satisfies Record<string, string[]>;\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/findImportDeclarationFor.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift/src/core.js\";\n\nimport type { IdentifierRename } from \"../renames.js\";\nimport type { ImportKind, UtilContext } from \"../types.js\";\n\nimport { entryPointAliases } from \"./entryPointAliases.js\";\n\nconst typeImportsFirst = (\n  a: j.ASTPath<namedTypes.ImportDeclaration>,\n  b: j.ASTPath<namedTypes.ImportDeclaration>\n) =>\n  a.value.importKind === \"type\" && b.value.importKind !== \"type\" ? -1\n  : a.value.importKind !== \"type\" && b.value.importKind === \"type\" ? 1\n  : 0;\n\nexport function findImportDeclarationFor({\n  description,\n  compatibleWith = \"type\",\n  context: { j, source },\n  exact = false,\n}: {\n  description: Pick<\n    IdentifierRename[\"from\"] & IdentifierRename[\"to\"],\n    \"module\" | \"alternativeModules\"\n  >;\n  compatibleWith?: ImportKind;\n  context: UtilContext;\n  exact?: boolean;\n}): j.Collection<namedTypes.ImportDeclaration> {\n  const test = (node: namedTypes.ImportDeclaration) => {\n    const isValidImportKind =\n      compatibleWith === \"type\" || node.importKind !== \"type\";\n    const hasNamespaceImport =\n      j(node).find(j.ImportNamespaceSpecifier).size() > 0;\n    return isValidImportKind && !hasNamespaceImport;\n  };\n  const perfectMatch = source\n    .find(\n      j.ImportDeclaration,\n      (node) => test(node) && description.module == \"\" + node.source.value\n    )\n    .paths()\n    .sort(typeImportsFirst);\n  const alternativeMatches = source\n    .find(\n      j.ImportDeclaration,\n      (node) =>\n        (test(node) &&\n          description.alternativeModules?.includes(\"\" + node.source.value)) ||\n        false\n    )\n    .paths()\n    .sort(typeImportsFirst);\n  const fallback =\n    entryPointAliases[description.module as keyof typeof entryPointAliases];\n  const fallbackMatches =\n    exact ?\n      []\n    : source\n        .find(\n          j.ImportDeclaration,\n          (node) =>\n            (test(node) && fallback?.includes(\"\" + node.source.value)) || false\n        )\n        .paths()\n        .sort(typeImportsFirst);\n  return j(perfectMatch.concat(...alternativeMatches, ...fallbackMatches));\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/findImportSpecifiersFor.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift\";\n\nimport type { IdentifierRename } from \"../renames.js\";\nimport type { ImportKind, UtilContext } from \"../types.js\";\n\nimport { findImportDeclarationFor } from \"./findImportDeclarationFor.js\";\n\nexport function findImportSpecifiersFor({\n  description,\n  compatibleWith = \"type\",\n  context,\n  context: { j },\n}: {\n  description: IdentifierRename[\"from\"] & IdentifierRename[\"to\"];\n  compatibleWith?: ImportKind;\n  context: UtilContext;\n}) {\n  return findImportDeclarationFor({\n    description,\n    compatibleWith,\n    context,\n  }).find(j.ImportSpecifier, (node) => {\n    return (\n      node.imported.name ===\n        (description.namespace || description.identifier) &&\n      (compatibleWith === \"type\" || node.importKind !== \"type\")\n    );\n  });\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/findOrInsertImport.ts",
    "content": "import type * as j from \"jscodeshift/src/core.js\";\n\nimport type { IdentifierRename } from \"../renames.js\";\nimport type { ImportKind, UtilContext } from \"../types.js\";\n\nimport { findImportDeclarationFor } from \"./findImportDeclarationFor.js\";\nimport { findImportSpecifiersFor } from \"./findImportSpecifiersFor.js\";\n\nexport function findOrInsertImport({\n  context,\n  context: { j, source },\n  description,\n  compatibleWith,\n  after,\n}: {\n  context: UtilContext;\n  description: IdentifierRename[\"from\"];\n  compatibleWith: ImportKind;\n  after?: j.Collection<any>;\n}) {\n  const found = findImportSpecifiersFor({\n    description,\n    context,\n    compatibleWith,\n  }).nodes()[0];\n  if (found) {\n    return found;\n  }\n  let addInto = findImportDeclarationFor({\n    description,\n    context,\n    compatibleWith,\n  }).nodes()[0];\n  if (!addInto) {\n    addInto = j.importDeclaration.from({\n      specifiers: [],\n      source: j.literal(description.module),\n      importKind: compatibleWith,\n    });\n    if (!after) {\n      after = source.find(j.ImportDeclaration);\n    }\n    if (!after || after.size() === 0) {\n      const program = source.find(j.Program).nodes()[0]!;\n      program.body.unshift(addInto);\n    } else {\n      after.at(-1).insertAfter(addInto);\n    }\n  }\n  const spec = j.importSpecifier.from({\n    imported: j.identifier(description.identifier),\n  });\n  (addInto.specifiers ??= []).push(spec);\n  return spec;\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/findReferences.ts",
    "content": "import assert from \"assert\";\n\nimport type { namedTypes } from \"ast-types\";\n\nimport type { UtilContext } from \"../types.js\";\n\nexport function findReferences({\n  context: { j },\n  namespace,\n  identifier,\n  scope: rootScope,\n}: {\n  context: UtilContext;\n  namespace?: string;\n  identifier: string;\n  scope: any;\n}) {\n  assert(rootScope && \"bindings\" in rootScope, \"Expected a scope\");\n  const rootPath = rootScope.path;\n  // code strongly inspired by https://github.com/facebook/jscodeshift/blob/656c20e2b5c9f59585c0485a0ab497ab703ec348/src/collections/VariableDeclarator.js#L76\n  // original licensed MIT for Facebook, Inc. and its affiliates https://github.com/facebook/jscodeshift/blob/814683361502d1b641aeccce9462976a88246a35/LICENSE\n\n  return j(rootPath)\n    .find(j.Identifier, { name: namespace || identifier })\n    .filter(function (path) {\n      // ignore non-variables\n      const parent = path.parent.node;\n\n      if (\n        j.MemberExpression.check(parent) &&\n        parent.property === path.node &&\n        !parent.computed\n      ) {\n        // obj.oldName\n        return false;\n      }\n\n      if (\n        j.Property.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // { oldName: 3 }\n        return false;\n      }\n\n      if (\n        j.ObjectProperty.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // { oldName: 3 }\n        return false;\n      }\n\n      if (\n        j.ObjectMethod.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // { oldName() {} }\n        return false;\n      }\n\n      if (\n        j.MethodDefinition.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // class A { oldName() {} }\n        return false;\n      }\n\n      if (\n        j.ClassMethod.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // class A { oldName() {} }\n        return false;\n      }\n\n      if (\n        j.ClassProperty.check(parent) &&\n        parent.key === path.node &&\n        !parent.computed\n      ) {\n        // class A { oldName = 3 }\n        return false;\n      }\n\n      if (\n        j.JSXAttribute.check(parent) &&\n        // @ts-ignore\n        parent.name === path.node &&\n        // @ts-ignore\n        !parent.computed\n      ) {\n        // <Foo oldName={oldName} />\n        return false;\n      }\n\n      if (\n        (j.JSXOpeningElement.check(parent) ||\n          j.JSXClosingElement.check(parent)) &&\n        // @ts-ignore\n        parent.name === path.node &&\n        // @ts-ignore\n        /^[a-z]/.test(path.node.name)\n      ) {\n        // <oldName></oldName>\n        return false;\n      }\n\n      let scope = path.scope;\n      while (scope && scope !== rootScope) {\n        if (scope.declares(namespace || identifier)) {\n          return false;\n        }\n        scope = scope.parent;\n      }\n\n      return true;\n    })\n    .map<namedTypes.Identifier>((path) => {\n      if (!namespace) return path;\n      const parent = path.parent;\n      if (j.TSQualifiedName.check(parent.node)) {\n        return parent.get(\"right\");\n      }\n      if (j.MemberExpression.check(parent.node)) {\n        return parent.get(\"property\");\n      }\n    })\n    .filter((path) => path.node.name === identifier);\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/getAllExports.ts",
    "content": "import assert from \"assert\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport * as ts from \"typescript\";\nimport { createRequire } from \"module\";\n\nconst __filename = fileURLToPath(import.meta.url);\n\ninterface ExportInfo {\n  name: string;\n  moduleName: string;\n  kind: string;\n  usageExamples: string[];\n}\n\nfunction analyze(\n  entryPoint: string,\n  projectRoot: string,\n  moduleName = projectRoot\n): ExportInfo[] {\n  // Load tsconfig.json from the project root\n  const configPath = path.join(projectRoot, \"tsconfig.json\");\n  if (!fs.existsSync(configPath)) {\n    throw new Error(`tsconfig.json not found at: ${configPath}`);\n  }\n\n  const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n  if (configFile.error) {\n    throw new Error(\n      `Error reading tsconfig.json: ${ts.flattenDiagnosticMessageText(\n        configFile.error.messageText,\n        \"\\n\"\n      )}`\n    );\n  }\n\n  const parsedConfig = ts.parseJsonConfigFileContent(\n    configFile.config,\n    ts.sys,\n    projectRoot\n  );\n\n  if (parsedConfig.errors.length > 0) {\n    console.warn(\"tsconfig.json parsing warnings:\");\n    parsedConfig.errors.forEach((error) => {\n      console.warn(ts.flattenDiagnosticMessageText(error.messageText, \"\\n\"));\n    });\n  }\n\n  // Create program with all files that might be needed for proper resolution\n  // Include the entry point and let TypeScript resolve all dependencies\n  const rootFiles =\n    parsedConfig.fileNames.length > 0 ? parsedConfig.fileNames : [entryPoint];\n  if (!rootFiles.includes(entryPoint)) {\n    rootFiles.push(entryPoint);\n  }\n\n  const program = ts.createProgram(rootFiles, parsedConfig.options);\n  const checker = program.getTypeChecker();\n\n  const sourceFile = program.getSourceFile(entryPoint)!;\n\n  // Run diagnostics to ensure proper type resolution\n  ts.getPreEmitDiagnostics(program);\n\n  return analyzeExports(sourceFile);\n\n  function analyzeExports(sourceFile: ts.SourceFile): ExportInfo[] {\n    const moduleSymbol = checker.getSymbolAtLocation(sourceFile);\n    const info = new Map<string, ExportInfo>();\n    if (moduleSymbol && moduleSymbol.exports) {\n      moduleSymbol.exports.forEach((symbol, name) => {\n        if ((symbol.flags & ts.SymbolFlags.ExportStar) != symbol.flags) {\n          info.set(name.toString(), analyzeExport(symbol, name.toString()));\n        }\n      });\n    }\n    // Look for export statements\n    ts.forEachChild(sourceFile, (node) => {\n      if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n        const moduleSpecifier = (node.moduleSpecifier as ts.StringLiteral).text;\n\n        if (!node.exportClause) {\n          for (const exp of analyzeExports(\n            resolveSourceFile(moduleSpecifier, sourceFile)\n          )) {\n            info.set(exp.name, exp);\n          }\n        } else if (ts.isNamedExports(node.exportClause)) {\n          node.exportClause.elements.forEach((specifier) => {\n            const exportName = specifier.name.text;\n            const originalName = specifier.propertyName?.text || exportName;\n\n            // Try to resolve the actual symbol being re-exported\n            const resolvedSymbol = resolveReExportedSymbol(\n              moduleSpecifier,\n              originalName,\n              sourceFile\n            );\n\n            assert(\n              resolvedSymbol,\n              `Symbol ${originalName} not found in module ${moduleSpecifier}`\n            );\n\n            if (resolvedSymbol) {\n              info.set(exportName, analyzeExport(resolvedSymbol, exportName));\n            }\n          });\n        }\n      }\n    });\n    return [...info.values()];\n  }\n\n  function analyzeExport(symbol: ts.Symbol, name: string): ExportInfo {\n    if ((symbol.flags & ts.SymbolFlags.Alias) === ts.SymbolFlags.Alias) {\n      return analyzeExport(checker.getAliasedSymbol(symbol), name);\n    }\n\n    return {\n      name,\n      moduleName,\n      kind: ts.SymbolFlags[symbol.flags],\n      usageExamples: Array.from(collectUsageExamples(symbol, name)),\n    };\n  }\n\n  function* collectUsageExamples(\n    symbol: ts.Symbol,\n    name: string\n  ): Generator<string, void, unknown> {\n    if ((symbol.flags & ts.SymbolFlags.Alias) === ts.SymbolFlags.Alias) {\n      yield* collectUsageExamples(checker.getAliasedSymbol(symbol), name);\n      return;\n    }\n\n    for (const declaration of symbol.declarations || [\n      symbol.valueDeclaration,\n    ]) {\n      if (!declaration || ts.isExportAssignment(declaration)) {\n        return;\n      }\n\n      let typeParameters = \"\";\n      if (\n        (ts.isInterfaceDeclaration(declaration) ||\n          ts.isTypeAliasDeclaration(declaration) ||\n          ts.isClassDeclaration(declaration) ||\n          ts.isFunctionDeclaration(declaration) ||\n          ts.isMethodDeclaration(declaration) ||\n          ts.isConstructorDeclaration(declaration) ||\n          ts.isFunctionExpression(declaration) ||\n          ts.isArrowFunction(declaration)) &&\n        declaration.typeParameters\n      ) {\n        typeParameters = `<${declaration.typeParameters\n          .map((tp) => tp.name.text)\n          .join(\", \")}>`;\n      }\n\n      const identifierUc = `_Test_${name.replaceAll(\".\", \"_\")}`;\n      const identifierLc = `_test_${name.replaceAll(\".\", \"_\")}`;\n\n      if (\n        ts.isInterfaceDeclaration(declaration) ||\n        ts.isTypeAliasDeclaration(declaration)\n      ) {\n        yield `type ${identifierUc} = ${name}${typeParameters};`;\n      } else if (ts.isClassDeclaration(declaration)) {\n        const constructor = declaration.members.find((member) =>\n          ts.isConstructorDeclaration(member)\n        );\n        const constructorParams =\n          constructor ?\n            (constructor as ts.ConstructorDeclaration).parameters\n              .map((param, id) =>\n                ts.isIdentifier(param.name) ? param.name.text : `param${id}`\n              )\n              .join(\", \")\n          : \"\";\n        yield `class ${identifierUc} extends ${name}${typeParameters} {}`;\n        yield `const ${identifierLc} = new ${name}${typeParameters}(${constructorParams})`;\n      } else if (\n        ts.isFunctionDeclaration(declaration) ||\n        ts.isArrowFunction(declaration) ||\n        ts.isFunctionExpression(declaration) ||\n        ts.isMethodDeclaration(declaration)\n      ) {\n        yield `${name}${typeParameters}(${declaration.parameters\n          .map((param, id) =>\n            ts.isIdentifier(param.name) ? param.name.text : `param${id}`\n          )\n          .join(\", \")})`;\n      } else if (ts.isModuleDeclaration(declaration)) {\n        yield `const ${identifierUc} = ${name};`;\n        for (const [childName, childSymbol] of symbol.exports || []) {\n          yield* collectUsageExamples(\n            childSymbol,\n            `${name}.${childName.toString()}`\n          );\n        }\n      } else if (ts.isEnumDeclaration(declaration)) {\n        yield `type ${identifierUc} = ${name};`;\n      } else if (\n        ts.isVariableDeclaration(declaration) ||\n        ts.isPropertyDeclaration(declaration) ||\n        ts.isPropertyAccessExpression(declaration)\n      ) {\n        yield `const ${identifierUc} = ${name};`;\n      } else if (ts.isIdentifier(declaration)) {\n        /*ignore*/\n      } else {\n        throw new Error(\n          `Unsupported declaration type for symbol ${name}: ${\n            declaration.kind\n          } - ${ts.SyntaxKind[declaration.kind]}`\n        );\n      }\n    }\n  }\n\n  function resolveSourceFile(\n    moduleSpecifier: string,\n    containingFile: ts.SourceFile\n  ): ts.SourceFile {\n    // Use the more advanced module resolution that handles package.json exports\n    const resolvedModule = ts.resolveModuleName(\n      moduleSpecifier,\n      containingFile.fileName,\n      program.getCompilerOptions(),\n      ts.sys\n    );\n    assert(resolvedModule.resolvedModule);\n    const resolvedFileName = resolvedModule.resolvedModule.resolvedFileName;\n    const targetSourceFile = program.getSourceFile(resolvedFileName);\n    assert(targetSourceFile);\n    return targetSourceFile;\n  }\n  function resolveReExportedSymbol(\n    moduleSpecifier: string,\n    symbolName: string,\n    containingFile: ts.SourceFile\n  ): ts.Symbol | undefined {\n    const targetFile = resolveSourceFile(moduleSpecifier, containingFile);\n    const moduleSymbol = checker.getSymbolAtLocation(targetFile);\n    assert(moduleSymbol?.exports);\n    let symbol = moduleSymbol.exports.get(symbolName as ts.__String);\n    if (!symbol) {\n      for (const [name, sym] of moduleSymbol.exports) {\n        const declaration = sym.valueDeclaration || sym.declarations?.[0];\n        if (!declaration || !ts.isExportDeclaration(declaration)) {\n          continue;\n        }\n        symbol = resolveReExportedSymbol(\n          (declaration.moduleSpecifier as ts.StringLiteral).text,\n          symbolName,\n          targetFile\n        );\n        if (symbol) {\n          return symbol;\n        }\n      }\n    }\n    return symbol;\n  }\n}\n\nconst entryPoints = [\n  [\"src/cache/index.ts\", \"@apollo/client/cache\"],\n  [\"src/index.ts\", \"@apollo/client\"],\n  [\"src/core/index.ts\", \"@apollo/client/core\"],\n  [\"src/dev/index.ts\", \"@apollo/client/dev\"],\n  [\"src/errors/index.ts\", \"@apollo/client/errors\"],\n  [\"src/link/batch/index.ts\", \"@apollo/client/link/batch\"],\n  [\"src/link/batch-http/index.ts\", \"@apollo/client/link/batch-http\"],\n  [\"src/link/context/index.ts\", \"@apollo/client/link/context\"],\n  [\"src/link/core/index.ts\", \"@apollo/client/link/core\"],\n  [\"src/link/error/index.ts\", \"@apollo/client/link/error\"],\n  [\"src/link/http/index.ts\", \"@apollo/client/link/http\"],\n  [\n    \"src/link/persisted-queries/index.ts\",\n    \"@apollo/client/link/persisted-queries\",\n  ],\n  [\"src/link/retry/index.ts\", \"@apollo/client/link/retry\"],\n  [\"src/link/remove-typename/index.ts\", \"@apollo/client/link/remove-typename\"],\n  [\"src/link/schema/index.ts\", \"@apollo/client/link/schema\"],\n  [\"src/link/subscriptions/index.ts\", \"@apollo/client/link/subscriptions\"],\n  [\"src/link/utils/index.ts\", \"@apollo/client/link/utils\"],\n  [\"src/link/ws/index.ts\", \"@apollo/client/link/ws\"],\n  [\"src/masking/index.ts\", \"@apollo/client/masking\"],\n  [\"src/react/index.ts\", \"@apollo/client/react\"],\n  [\"src/react/components/index.ts\", \"@apollo/client/react/components\"],\n  [\"src/react/context/index.ts\", \"@apollo/client/react/context\"],\n  [\"src/react/hoc/index.ts\", \"@apollo/client/react/hoc\"],\n  [\"src/react/hooks/index.ts\", \"@apollo/client/react/hooks\"],\n  [\"src/react/internal/index.ts\", \"@apollo/client/react/internal\"],\n  [\"src/react/parser/index.ts\", \"@apollo/client/react/parser\"],\n  [\"src/react/ssr/index.ts\", \"@apollo/client/react/ssr\"],\n  [\"src/testing/index.ts\", \"@apollo/client/testing\"],\n  [\"src/testing/core/index.ts\", \"@apollo/client/testing/core\"],\n  [\"src/testing/experimental/index.ts\", \"@apollo/client/testing/experimental\"],\n  [\"src/utilities/index.ts\", \"@apollo/client/utilities\"],\n  [\"src/utilities/globals/index.ts\", \"@apollo/client/utilities/globals\"],\n  [\n    \"src/utilities/subscriptions/urql/index.ts\",\n    \"@apollo/client/utilities/subscriptions/relay\",\n  ],\n];\n// @ts-ignore\nconst projectRoot = path.join(import.meta.dirname, \"../../../../..\");\nconst require = createRequire(path.join(projectRoot, \"src\", \"index.ts\"));\n\nif (!fs.existsSync(path.join(projectRoot, \"package.json\"))) {\n  const pkg = JSON.parse(\n    fs.readFileSync(path.join(projectRoot, \"package.json\"), \"utf-8\")\n  );\n  if (\"exports\" in pkg) {\n    for (const exp of Object.keys(pkg.exports)) {\n      if (!entryPoints.some(([_, moduleName]) => moduleName === exp)) {\n        entryPoints.push([\"\", exp]);\n      }\n    }\n  }\n}\n\nconst collected: Record<string, ExportInfo[]> = {};\nfor (const [entryPoint, moduleName] of entryPoints) {\n  // Resolve entry point relative to project root if not absolute\n  let resolvedEntryPoint: string | undefined = undefined;\n  try {\n    // for AC4 we can resolve the module directly\n    resolvedEntryPoint = require.resolve(moduleName);\n  } catch {\n    if (moduleName === \"@apollo/client/link/core\") {\n      try {\n        // this has been renamed, for comparison sake handle it the same as before\n        resolvedEntryPoint = require.resolve(\"@apollo/client/link\");\n      } catch {}\n    }\n  }\n  if (!resolvedEntryPoint) {\n    // if that didn't work we are probably dealing with AC3, use the known entry point\n    resolvedEntryPoint =\n      path.isAbsolute(entryPoint) ? entryPoint : (\n        path.resolve(projectRoot, entryPoint)\n      );\n  }\n  console.log(\n    `Analyzing exports for module: ${moduleName} at ${resolvedEntryPoint}`\n  );\n\n  if (!fs.existsSync(resolvedEntryPoint)) {\n    console.log(\n      \"File not found - entry point might have been deleted:\",\n      resolvedEntryPoint\n    );\n    collected[moduleName] = [];\n    continue;\n  }\n  assert(fs.existsSync(projectRoot));\n\n  const exports = analyze(resolvedEntryPoint, projectRoot, moduleName);\n  collected[moduleName] = exports;\n}\n\n// in the end, generated files can be diffed with\n/*\n```sh\njq --slurpfile new src/__tests__/exports.new.json -f <(\ncat <<'EOF'\nwith_entries(\n {\n  key,\n  value: (.key as $key | .value | map(.name as $name | select(($new[0][$key]|map(.name))|index($name)|not)))\n    | map({\n      name,\n      importType: (if .kind == \"Interface\" or .kind == \"TypeAlias\" or .kind == \"NamespaceModule\" then \"type\" else \"value\" end)\n    })\n    | {\n      value: . | map(select(.importType == \"value\")) | map(.name),\n      type: . | map(select(.importType == \"type\")) | map(.name),\n    }\n  }\n)\nEOF\n) < src/__tests__/exports.json >| src/__tests__/exports.removed.json\n```\n */\n\nfs.writeFileSync(\n  // @ts-ignore\n  path.join(import.meta.dirname, \"..\", \"__tests__\", \"exports.json\"),\n  JSON.stringify(collected, null, 2)\n);\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/getProperty.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift/src/core.js\";\n\nimport type { UtilContext } from \"../types.js\";\n\nexport function getProperty({\n  context: { j },\n  objectPath,\n  name,\n}: {\n  objectPath: j.ASTPath<namedTypes.ObjectExpression>;\n  context: UtilContext;\n  name: string;\n}): j.ASTPath<namedTypes.ObjectProperty> | null {\n  return (\n    (objectPath.get(\"properties\") as j.ASTPath).filter(\n      (path: j.ASTPath) =>\n        j.ObjectProperty.check(path.node) &&\n        j.Identifier.check(path.node.key) &&\n        path.node.key.name === name\n    )[0] || null\n  );\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/getUnusedIdentifier.ts",
    "content": "import type { UtilContext } from \"../types.js\";\n\nexport function getUnusedIdentifier({\n  similarTo,\n  context: { j, source },\n}: {\n  similarTo: string;\n  context: UtilContext;\n}) {\n  let identifier = similarTo;\n  let counter = 0;\n  while (source.find(j.Identifier, { name: identifier }).size() > 0) {\n    identifier = `${similarTo}_${++counter}`;\n  }\n  return identifier;\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/handleIdentiferRename.ts",
    "content": "import assert from \"assert\";\n\nimport type * as j from \"jscodeshift\";\n\nimport type { IdentifierRename } from \"../renames.js\";\nimport type { UtilContext } from \"../types.js\";\n\nimport { findImportDeclarationFor } from \"./findImportDeclarationFor.js\";\nimport { findImportSpecifiersFor } from \"./findImportSpecifiersFor.js\";\nimport { getUnusedIdentifier } from \"./getUnusedIdentifier.js\";\nimport { monkeyPatchAstTypes } from \"./monkeyPatchAstTypes.js\";\nimport { moveGlobalIdentifierToNamespaceAccess } from \"./moveGlobalIdentifierToNamespaceAccess.js\";\nimport { pick } from \"./pick.js\";\nimport { renameGlobalIdentifier } from \"./renameGlobalIdentifier.js\";\n\nexport function handleIdentiferRename({\n  rename,\n  context,\n  context: { j, source },\n  onModify,\n}: {\n  rename: IdentifierRename;\n  context: UtilContext;\n  onModify: () => void;\n}) {\n  const { from, to } = rename;\n  const final = { ...from, ...to };\n\n  monkeyPatchAstTypes(context.j);\n\n  findImportSpecifiersFor({ description: from, context }).forEach(\n    (specifierPath) => {\n      assert(\n        !from.namespace,\n        \"This case is not supported yet: \" + JSON.stringify(rename)\n      );\n\n      if (\n        source.find(j.ImportSpecifier, (node) => node === specifierPath.value)\n          .length === 0\n      ) {\n        // if the specifier is not found in the source, it was already removed by a previous iteration\n        return;\n      }\n\n      const specifier = specifierPath.value;\n      const importedName = specifier.imported.name;\n      const localName =\n        specifier.local && specifier.local.name !== importedName ?\n          specifier.local.name\n        : undefined;\n\n      const importDeclarations = j(specifierPath).closest(j.ImportDeclaration);\n      const importDeclarationPath = importDeclarations.paths()[0];\n      const importDeclaration = importDeclarationPath.value;\n      const importedFrom = importDeclaration.source.value;\n      const importType =\n        specifier.importKind ||\n        importDeclaration.importKind ||\n        rename.importType;\n      if (importType === \"typeof\") {\n        return; // typeof imports are not supported, skip\n      }\n      const renameFrom = getLocalName(specifier);\n      const alreadyImported = findImportSpecifiersFor({\n        description: final,\n        compatibleWith: importType,\n        context,\n      });\n      let importAs = final.namespace || final.identifier;\n      if (alreadyImported.size() > 0) {\n        importAs = getLocalName(alreadyImported.nodes()[0]);\n      } else if (getLocalName(specifier) !== importAs) {\n        getUnusedIdentifier({ similarTo: importAs, context });\n      }\n\n      if (\n        from.namespace === final.namespace &&\n        importedName === final.identifier &&\n        importedFrom === final.module\n      ) {\n        return;\n      }\n\n      onModify();\n\n      try {\n        if (\n          from.namespace === final.namespace &&\n          localName &&\n          importedFrom === final.module\n        ) {\n          // simple case - we just need to rename the import, everything else stays the same\n          specifierPath.get(\"imported\").replace(j.identifier(final.identifier));\n\n          return;\n        }\n\n        if (final.namespace) {\n          moveGlobalIdentifierToNamespaceAccess({\n            globalIdentifer:\n              specifierPath.get(\"local\") || specifierPath.get(\"imported\"),\n            namespace: importAs,\n            namespaceProp: final.identifier,\n            context,\n          });\n          specifierPath.get(\"local\").replace();\n        } else if (!localName) {\n          renameGlobalIdentifier({\n            identifierName: renameFrom,\n            newName: importAs,\n            context,\n          });\n        }\n\n        if (alreadyImported.size() > 0) {\n          // if the target import specifier already exists, we can just remove this one\n          specifierPath.replace(\n            // but keep comments in place\n            j.emptyStatement.from(pick(specifier, \"comments\"))\n          );\n        } else {\n          const targetDeclaration = findImportDeclarationFor({\n            description: final,\n            compatibleWith: rename.importType === \"type\" ? \"type\" : importType,\n            context,\n          }).nodes()[0];\n          // specifier should have been removed anyways, so we just reuse it in the existing position\n          // this also moves comments around\n          specifierPath\n            .get(\"imported\")\n            .replace(j.identifier(final.namespace || final.identifier));\n\n          if (targetDeclaration !== specifierPath.parent) {\n            // remove the specifier, we create a new one in a different import declaration\n            specifierPath.replace();\n            if (targetDeclaration) {\n              if (\n                j(targetDeclaration)\n                  .find(j.ImportSpecifier, pick(specifier, \"imported\", \"local\"))\n                  .size() === 0\n              ) {\n                (targetDeclaration.specifiers ??= []).push(specifier);\n              }\n            } else {\n              importDeclarations.insertAfter(\n                j.importDeclaration(\n                  [specifier],\n                  j.literal(to.module || from.module),\n                  rename.importType\n                )\n              );\n            }\n          }\n        }\n        if (importDeclarations.find(j.ImportSpecifier).size() === 0) {\n          importDeclarationPath.replace(\n            // when removing the import declaration, try to keep comments\n            // in place - we don't know if they really were attached\n            // to the import declaration or \"just there\"\n            j.emptyStatement.from(pick(importDeclaration, \"comments\"))\n          );\n        }\n      } finally {\n        rename.postProcess?.({\n          context,\n          namespace: final.namespace ? importAs : undefined,\n          identifier: final.namespace ? final.identifier : importAs,\n          renamedSpecifierPath: source\n            .find(\n              j.ImportSpecifier,\n              (node) => (node.local?.name || node.imported.name) === importAs\n            )\n            .paths()[0],\n        });\n      }\n    }\n  );\n}\n\nfunction getLocalName(spec: j.ImportSpecifier): string {\n  return \"\" + (spec.local?.name || spec.imported.name);\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/handleModuleRename.ts",
    "content": "import type { ModuleRename } from \"../renames.js\";\nimport type { UtilContext } from \"../types.js\";\n\nimport { findImportDeclarationFor } from \"./findImportDeclarationFor.js\";\n\nexport function handleModuleRename({\n  rename,\n  onModify,\n  context,\n  context: { j, source },\n}: {\n  onModify: () => void;\n  rename: ModuleRename;\n  context: UtilContext;\n}) {\n  renameNamespaceOrSideEffectImports();\n  mergeIntoExistingOrRenameImport();\n\n  function renameNamespaceOrSideEffectImports() {\n    source\n      .find(\n        j.ImportDeclaration,\n        (node) =>\n          node.source.value === rename.from.module &&\n          (!node.specifiers ||\n            node.specifiers.some(\n              (specifier) => specifier.type === \"ImportNamespaceSpecifier\"\n            ))\n      )\n      .forEach((sourcePath) => {\n        if (sourcePath.node.source.value == rename.to.module) {\n          return; // No change needed.\n        }\n        onModify();\n        sourcePath.get(\"value\", \"source\").replace(j.literal(rename.to.module));\n      });\n  }\n\n  function mergeIntoExistingOrRenameImport() {\n    findImportDeclarationFor({ description: rename.from, context }).forEach(\n      (sourcePath) => {\n        if (sourcePath.node.source.value == rename.to.module) {\n          return; // No change needed.\n        }\n        onModify();\n        const sourceImport = j(sourcePath);\n        let targetImport = findImportDeclarationFor({\n          description: rename.to,\n          context,\n          exact: true,\n        })\n          .filter(\n            (declaration) =>\n              declaration.value.importKind === sourcePath.value.importKind\n          )\n          .nodes()[0];\n        if (!targetImport) {\n          targetImport = j.importDeclaration(\n            [],\n            j.literal(rename.to.module),\n            sourcePath.value.importKind\n          );\n          sourceImport.insertAfter(targetImport);\n        }\n        sourceImport.find(j.ImportSpecifier).forEach((specifierPath) => {\n          (targetImport.specifiers ??= []).push(specifierPath.value);\n        });\n        sourceImport.remove();\n      }\n    );\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/monkeyPatchAstTypes.ts",
    "content": "import type { JSCodeshift } from \"jscodeshift\";\n\nconst patched = new WeakSet();\n\n// https://github.com/benjamn/ast-types/pull/954\nexport function monkeyPatchAstTypes(j: JSCodeshift) {\n  if (patched.has(j.types.Type)) {\n    return;\n  }\n  patched.add(j.types.Type);\n\n  const ce = j.types.Type.def(\"CallExpression\");\n  ce.finalized = false;\n  ce.bases(\"TSHasOptionalTypeParameterInstantiation\");\n  ce.finalize();\n  const ne = j.types.Type.def(\"NewExpression\");\n  ne.finalized = false;\n  ne.bases(\"TSHasOptionalTypeParameterInstantiation\");\n  ne.finalize();\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/moveGlobalIdentifierToNamespaceAccess.ts",
    "content": "import type { namedTypes } from \"ast-types\";\nimport type * as j from \"jscodeshift/src/core.js\";\n\nimport type { UtilContext } from \"../types.js\";\n\nimport { findReferences } from \"./findReferences.js\";\n\nexport function moveGlobalIdentifierToNamespaceAccess({\n  globalIdentifer,\n  namespace,\n  namespaceProp,\n  context: { j },\n  context,\n}: {\n  globalIdentifer: j.ASTPath<namedTypes.Identifier>;\n  namespace: string;\n  namespaceProp: string;\n  context: UtilContext;\n}) {\n  findReferences({\n    context,\n    identifier: globalIdentifer.node.name,\n    scope: globalIdentifer.scope,\n  })\n    .filter((node) => {\n      return node.parentPath.value.type !== \"ImportSpecifier\";\n    })\n    .forEach((node) => {\n      if (j(node).closest(j.TSTypeReference).size() > 0) {\n        node.replace(\n          j.tsQualifiedName(\n            j.identifier(namespace),\n            j.identifier(namespaceProp)\n          )\n        );\n      } else {\n        node.replace(\n          j.memberExpression(\n            j.identifier(namespace),\n            j.identifier(namespaceProp)\n          )\n        );\n      }\n    });\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/pick.ts",
    "content": "export function pick<T extends Record<string, any>, K extends keyof T>(\n  obj: T,\n  ...keys: K[]\n): Pick<T, K> {\n  return keys.reduce(\n    (acc, key) => {\n      if (key in obj) {\n        acc[key] = obj[key];\n      }\n      return acc;\n    },\n    {} as Pick<T, K>\n  );\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/renameGlobalIdentifier.ts",
    "content": "import type { UtilContext } from \"../types.js\";\n\nexport function renameGlobalIdentifier({\n  identifierName,\n  newName,\n  context: { j, source },\n}: {\n  identifierName: string;\n  newName: string;\n  context: UtilContext;\n}) {\n  // create a temporary const definition with the original \"local name\" of the import\n  const tempDeclaration = j.variableDeclaration(\"const\", [\n    j.variableDeclarator(j.identifier(identifierName)),\n  ]);\n  // insert the temporary declaration in the source\n  source.find(j.Program).nodes()[0].body.unshift(tempDeclaration);\n  // find the inserted variable declaration from the source (required to be able to rename it)\n  const tempVariable = source\n    .find(j.VariableDeclaration, tempDeclaration)\n    .find(j.VariableDeclarator);\n  // rename the temporary variable to a temporary unique identifier\n  tempVariable.renameTo(newName);\n  // and remove it\n  tempVariable.remove();\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/src/util/reorderGenericArguments.ts",
    "content": "import type { TSTypeKind } from \"ast-types/lib/gen/kinds\";\n\nimport type { UtilContext } from \"../types.js\";\n\nimport { findReferences } from \"./findReferences.js\";\n\nexport function reorderGenericArguments({\n  context,\n  namespace,\n  identifier,\n  scope,\n  newOrder,\n  context: { j },\n}: {\n  namespace?: string;\n  identifier: string;\n  scope: any;\n  /**\n   * To reorder `<TData, TVariables>` to `<TVariables, TData>`, pass `[1, 0]`.\n   * `[0, 1, 3]` would drop the third generic argument.\n   */\n  newOrder: number[];\n  context: UtilContext;\n}): void {\n  findReferences({\n    context,\n    namespace,\n    identifier,\n    scope,\n  }).forEach((path) => {\n    j(path).closest(j.TSTypeReference);\n    const parentPath = namespace ? path.parent.parent : path.parent;\n    const parentNode = parentPath.node;\n    if (\n      !j.TSTypeReference.check(parentNode) ||\n      !parentNode.typeParameters?.params\n    ) {\n      return;\n    }\n    let newParams: TSTypeKind[] = [];\n    for (const idx of newOrder) {\n      if (idx >= parentNode.typeParameters.params.length) {\n        break;\n      }\n      newParams.push(parentNode.typeParameters.params[idx]);\n    }\n    parentNode.typeParameters.params = newParams;\n  });\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"noEmit\": false,\n    \"rootDir\": \"./src\",\n    \"outDir\": \"./dist\"\n  },\n  \"include\": [\"src/**/*.ts\"],\n  \"exclude\": [\n    \"node_modules\",\n    \"dist\",\n    \"src/__tests__\",\n    \"src/__testfixtures__\",\n    \"src/@types\"\n  ]\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noEmit\": true,\n    \"target\": \"ESNext\",\n    \"module\": \"nodenext\",\n    \"moduleResolution\": \"nodenext\",\n    \"lib\": [\"ES2022\"],\n    \"paths\": {},\n    \"types\": [\"node\"],\n    \"declaration\": true,\n    \"sourceMap\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"resolveJsonModule\": true\n  },\n  \"include\": [\"src/**/*.ts\"],\n  \"exclude\": [\"node_modules\", \"dist\", \"src/__testfixtures__\"]\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/tsconfig.tests.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"types\": [\"node\", \"./src/@types/jscodeshift.d.ts\"]\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/ac3-to-ac4/vitest.config.ts",
    "content": "import { configDefaults, defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n  test: {\n    include: [...configDefaults.include, \"**/__tests__/*.test.ts\"],\n    globals: true,\n  },\n});\n"
  },
  {
    "path": "scripts/codemods/data-masking/examples/queries-codegen.ts",
    "content": "import { graphql } from \"./gql\";\n\nexport const query = graphql(`\n  query GetCurrentUser {\n    currentUser {\n      id\n      ...CurrentUserFields\n    }\n  }\n`);\n\nexport const currentUserFieldsFragment = graphql(`\n  fragment CurrentUserFields on User {\n    name\n    ...ProfileFields\n  }\n`);\n\nexport const profileFieldsFragment = graphql(`\n  fragment ProfileFields on User {\n    profile {\n      id\n      avatarUrl\n    }\n  }\n`);\n"
  },
  {
    "path": "scripts/codemods/data-masking/examples/queries-react.tsx",
    "content": "import React from \"react\";\nimport { gql, useQuery } from \"@apollo/client\";\n\nconst ProfileFieldsFragment = gql`\n  fragment ProfileFields on User {\n    profile {\n      id\n      avatarUrl\n    }\n  }\n`;\n\nconst fragment = gql`\n  fragment CurrentUserFields on User {\n    name\n    ...ProfileFields\n  }\n\n  ${ProfileFieldsFragment}\n`;\n\nexport function MyComponent() {\n  const { data, loading } = useQuery(gql`\n    query GetCurrentUser {\n      currentUser {\n        id\n        ...CurrentUserFields\n      }\n    }\n\n    ${fragment}\n  `);\n\n  if (loading) {\n    return <div>Loading...</div>;\n  }\n\n  return <div>{JSON.stringify(data)}</div>;\n}\n"
  },
  {
    "path": "scripts/codemods/data-masking/examples/queries.graphql",
    "content": "query GetCurrentUser {\n  currentUser {\n    id\n    ...CurrentUserFields\n  }\n}\n\nfragment CurrentUserFields on User {\n  name\n  ...ProfileFields\n}\n\nfragment ProfileFields on User {\n  profile {\n    id\n    avatarUrl\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/data-masking/examples/queries.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport type { TypedDocumentNode } from \"@apollo/client\";\n\nexport const ProfileFieldsFragment: TypedDocumentNode<{\n  profile: { id: string; avatarUrl: string };\n}> = gql`\n  fragment ProfileFields on User {\n    profile {\n      id\n      avatarUrl\n    }\n  }\n`;\n\nconst CurrentUserFieldsFragment = gql`\n  fragment CurrentUserFields on User {\n    name\n    ...ProfileFields\n  }\n`;\n\nexport const GetCurrentUser = gql`\n  query GetCurrentUser {\n    currentUser {\n      id\n      ...CurrentUserFields\n    }\n  }\n\n  ${CurrentUserFieldsFragment}\n`;\n\nexport const SKIP_TO_NEXT_MUTATION = gql`\n  mutation SkipToNextMutation {\n    skipToNext {\n      playbackState {\n        progressMs\n        item {\n          __typename\n          ... on Track {\n            id\n            name\n            album {\n              id\n              name\n              images {\n                url\n              }\n            }\n            artists {\n              id\n              name\n            }\n          }\n\n          ... on Episode {\n            id\n            name\n            show {\n              id\n              name\n              images {\n                url\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\nexport const SKIP_TO_NEXT_MUTATION_WITH_FRAGMENT = gql`\n  mutation SkipToNextMutation {\n    skipToNext {\n      playbackState {\n        progressMs\n        item {\n          __typename\n          ... on Track {\n            id\n            name\n            album {\n              id\n              name\n              images {\n                url\n              }\n            }\n            artists {\n              id\n              name\n            }\n            ...TrackItem_track\n          }\n\n          ... on Episode {\n            id\n            name\n            show {\n              id\n              name\n              images {\n                url\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n"
  },
  {
    "path": "scripts/codemods/data-masking/package.json",
    "content": "{\n  \"private\": true,\n  \"devDependencies\": {\n    \"jscodeshift\": \"17.1.1\",\n    \"@types/jscodeshift\": \"0.12.0\"\n  }\n}\n"
  },
  {
    "path": "scripts/codemods/data-masking/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noImplicitAny\": true,\n    \"strictNullChecks\": true,\n    \"noUnusedParameters\": false,\n    \"noUnusedLocals\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"node\",\n    \"importHelpers\": true,\n    \"sourceMap\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"target\": \"es5\",\n    \"module\": \"es2015\",\n    \"esModuleInterop\": true,\n    \"lib\": [\"es2015\", \"esnext.asynciterable\"],\n    \"strict\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"./unmask.ts\"]\n}\n"
  },
  {
    "path": "scripts/codemods/data-masking/unmask.ts",
    "content": "import type { Collection, Transform, TemplateLiteral } from \"jscodeshift\";\nimport type { DirectiveNode, DocumentNode } from \"graphql\";\nimport { Kind, parse, visit, print } from \"graphql\";\nimport path from \"node:path\";\n\nconst LEADING_WHITESPACE = /^[\\s\\t]*(?=[\\S\\n])/;\nconst TRAILING_WHITESPACE = /(?<=[\\S\\n])[\\s\\t]*$/;\n\nconst DEFAULT_TAGS = [\"gql\", \"graphql\"];\n\nconst transform: Transform = function transform(file, api, options) {\n  const { tag = DEFAULT_TAGS, mode } = options;\n\n  if (mode && mode !== \"migrate\") {\n    console.warn(\n      `The option --mode '${mode}' is not supported. Please use --mode 'migrate' to enable migrate mode for the @ummask directive.`\n    );\n  }\n\n  const extname = path.extname(file.path);\n\n  if (extname === \".graphql\" || extname === \".gql\") {\n    return transformGraphQLFile(file.source, mode);\n  }\n\n  const j = api.jscodeshift;\n  const source = j(file.source);\n\n  const tagNames = Array.isArray(tag) ? tag : [tag];\n\n  tagNames.forEach((tagName) => {\n    addUnmaskToTaggedTemplate(tagName);\n    addUnmaskToFunctionCall(tagName);\n  });\n\n  return source.toSource();\n\n  function addUnmaskToFunctionCall(name: string) {\n    source\n      .find(j.CallExpression, {\n        callee: { name },\n        arguments: [{ type: \"TemplateLiteral\" }],\n      })\n      .forEach((p) => {\n        addUnmaskToTemplateLiteral(j(p.value.arguments[0]));\n      });\n  }\n\n  function addUnmaskToTaggedTemplate(name: string) {\n    source\n      .find(j.TaggedTemplateExpression, { tag: { name } })\n      .forEach((taggedTemplateExpressionPath) => {\n        addUnmaskToTemplateLiteral(\n          j(taggedTemplateExpressionPath).find(j.TemplateLiteral)\n        );\n      });\n  }\n\n  function addUnmaskToTemplateLiteral(template: Collection<TemplateLiteral>) {\n    template.find(j.TemplateElement).replaceWith((templateElementPath) => {\n      const templateElement = templateElementPath.value;\n      const queryString =\n        templateElement.value.cooked || templateElement.value.raw;\n      const document = parseDocument(queryString);\n\n      if (document === null) {\n        return templateElement;\n      }\n\n      const modifiedDocument = addUnmaskDirective(document, mode);\n\n      if (modifiedDocument === document) {\n        return templateElement;\n      }\n\n      const query = applyIndentationFromOriginalQuery(\n        queryString,\n        modifiedDocument\n      );\n\n      return j.templateElement(\n        {\n          raw: String.raw({ raw: [query] }),\n          cooked: query,\n        },\n        templateElement.tail\n      );\n    });\n  }\n};\n\nfunction parseDocument(source: string) {\n  try {\n    return parse(source);\n  } catch (e) {\n    return null;\n  }\n}\n\nfunction applyIndentationFromOriginalQuery(\n  source: string,\n  document: DocumentNode\n) {\n  const lines = source.split(\"\\n\");\n  const locationOffset = document.loc!.source.locationOffset.line;\n\n  const leadingWhitespace = getMatch(source, /^[\\s]*(?=\\S)/);\n  const trailingWhitespace = getMatch(source, TRAILING_WHITESPACE);\n  const indentation = getMatch(lines[locationOffset], LEADING_WHITESPACE);\n\n  return (\n    leadingWhitespace +\n    print(document)\n      .split(\"\\n\")\n      .map((line, idx) => {\n        // `leadingWhitespace` will contain the whitespace needed for the\n        // first line so we can skip adding it\n        return idx === 0 ? line : indentation + line;\n      })\n      .join(\"\\n\") +\n    trailingWhitespace\n  );\n}\n\nfunction addUnmaskDirective(document: DocumentNode, mode: string | undefined) {\n  return visit(document, {\n    FragmentSpread: (node) => {\n      if (\n        node.directives?.some((directive) => directive.name.value === \"unmask\")\n      ) {\n        return;\n      }\n\n      return {\n        ...node,\n        directives: [\n          ...(node.directives || []),\n          {\n            kind: Kind.DIRECTIVE,\n            name: { kind: Kind.NAME, value: \"unmask\" },\n            arguments:\n              mode === \"migrate\" ?\n                [\n                  {\n                    kind: Kind.ARGUMENT,\n                    name: { kind: Kind.NAME, value: \"mode\" },\n                    value: { kind: Kind.STRING, value: \"migrate\" },\n                  },\n                ]\n              : undefined,\n          } satisfies DirectiveNode,\n        ],\n      };\n    },\n  });\n}\n\nfunction getMatch(str: string, match: RegExp) {\n  return str.match(match)?.at(0) ?? \"\";\n}\n\nfunction transformGraphQLFile(source: string, mode: string) {\n  return print(addUnmaskDirective(parse(source), mode));\n}\n\nexport default transform;\n"
  },
  {
    "path": "scripts/codemods/misc/mockLinkRejection.ts",
    "content": "import * as recast from \"recast\";\nconst n = recast.types.namedTypes;\nconst b = recast.types.builders;\n\nexport default function (fileInfo: any, api: any) {\n  const ast = recast.parse(fileInfo.source, {\n    parser: require(\"recast/parsers/typescript\"),\n  });\n\n  // Transform mockSingleLink(reject, ...) to\n  // mockSingleLink(...).setOnError(reject):\n\n  const transformed = recast.visit(ast, {\n    visitCallExpression(path) {\n      this.traverse(path);\n      const node = path.node;\n      if (\n        n.Identifier.check(node.callee) &&\n        node.callee.name === \"mockSingleLink\"\n      ) {\n        const firstArg = node.arguments[0];\n        if (\n          (n.Identifier.check(firstArg) && firstArg.name === \"reject\") ||\n          n.Function.check(firstArg)\n        ) {\n          path.get(\"arguments\").shift();\n          path.replace(\n            b.callExpression(\n              b.memberExpression(node, b.identifier(\"setOnError\"), false),\n              [firstArg]\n            )\n          );\n        }\n      }\n    },\n  });\n\n  return recast.print(transformed).code;\n}\n"
  },
  {
    "path": "scripts/memory/README.md",
    "content": "# Memory and Garbage Collection tests\n\nThis directory contains a few important memory-related tests that were\ndifficult to run within the usual Jest environment. Instead, these tests\nrun directly in Node.js, importing `@apollo/client` from the `../../dist`\ndirectory, rather than from `../../src`.\n\n## Running the tests\n\nRun `npm install` in this directory, followed by `npm test`. Failure is\nindicated by a non-zero exit code.\n"
  },
  {
    "path": "scripts/memory/package.json",
    "content": "{\n  \"name\": \"apollo-client-memory-tests\",\n  \"private\": true,\n  \"scripts\": {\n    \"test\": \"node --expose-gc --test tests.cts\"\n  },\n  \"dependencies\": {\n    \"@apollo/client\": \"file:../../dist\",\n    \"graphql\": \"^16.0.0\"\n  }\n}\n"
  },
  {
    "path": "scripts/memory/tests.cts",
    "content": "const assert = require(\"node:assert\");\nconst { describe, it } = require(\"node:test\");\n\nconst { ApolloClient, InMemoryCache, gql, makeVar } = require(\"@apollo/client\");\n\nfunction itAsync(message, testFn) {\n  const start = Date.now();\n  let timeout;\n  (function pollGC() {\n    gc(); // enabled by --expose-gc\n    // Passing --exit to mocha should cause the process to exit after\n    // tests pass/fail/timeout, but (in case that fails) we also set a\n    // hard limit of 10 seconds for GC polling.\n    if (Date.now() < start + 10000) {\n      timeout = setTimeout(pollGC, 100);\n    }\n  })();\n  return it(message, () =>\n    new Promise(testFn).finally(() => {\n      clearTimeout(timeout);\n    })\n  );\n}\n\nconst registries = [];\nfunction makeRegistry(callback, reject) {\n  assert.strictEqual(typeof callback, \"function\");\n  assert.strictEqual(typeof reject, \"function\");\n\n  const registry = new FinalizationRegistry((key) => {\n    try {\n      callback(key);\n    } catch (error) {\n      // Exceptions thrown in FinalizationRegistry callbacks can be tricky\n      // for test frameworks to catch, without some help.\n      reject(error);\n    }\n  });\n\n  // If the registry object itself gets garbage collected before the\n  // callback fires, the callback might never be called:\n  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry#notes_on_cleanup_callbacks\n  registries.push(registry);\n\n  return registry;\n}\n\ndescribe(\"garbage collection\", () => {\n  itAsync(\n    \"should collect client.cache after client.stop()\",\n    (resolve, reject) => {\n      const expectedKeys = new Set([\"client.cache\", \"ObservableQuery\"]);\n\n      const registry = makeRegistry((key) => {\n        if (expectedKeys.delete(key) && !expectedKeys.size) {\n          resolve();\n        }\n      }, reject);\n\n      const localVar = makeVar(123);\n\n      (function (client) {\n        registry.register(client.cache, \"client.cache\");\n\n        const obsQuery = client.watchQuery({\n          query: gql`\n            query {\n              local\n            }\n          `,\n        });\n\n        registry.register(obsQuery, \"ObservableQuery\");\n\n        obsQuery.subscribe({\n          next(result) {\n            assert.deepStrictEqual(result.data, {\n              local: 123,\n            });\n\n            client.stop();\n          },\n        });\n      })(\n        new ApolloClient({\n          cache: new InMemoryCache({\n            typePolicies: {\n              Query: {\n                fields: {\n                  local() {\n                    return localVar();\n                  },\n                },\n              },\n            },\n          }),\n        })\n      );\n    }\n  );\n\n  itAsync(\n    \"should release cache.storeReader if requested via cache.gc\",\n    (resolve, reject) => {\n      const expectedKeys = {\n        __proto__: null,\n        StoreReader1: true,\n        StoreReader2: true,\n        StoreReader3: false,\n      };\n\n      const registry = makeRegistry((key) => {\n        // Referring to client here should keep the client itself alive\n        // until after the ObservableQuery is (or should have been)\n        // collected. Collecting the ObservableQuery just because the whole\n        // client instance was collected is not interesting.\n        assert.strictEqual(client instanceof ApolloClient, true);\n        if (key in expectedKeys) {\n          assert.strictEqual(expectedKeys[key], true, key);\n        }\n        delete expectedKeys[key];\n        if (Object.keys(expectedKeys).every((key) => !expectedKeys[key])) {\n          setTimeout(resolve, 100);\n        }\n      }, reject);\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              local() {\n                return \"hello\";\n              },\n            },\n          },\n        },\n      });\n\n      const client = new ApolloClient({ cache });\n\n      (function () {\n        const query = gql`\n          query {\n            local\n          }\n        `;\n        const obsQuery = client.watchQuery({ query });\n\n        function register(suffix) {\n          const reader = cache[\"storeReader\"];\n          registry.register(reader, \"StoreReader\" + suffix);\n        }\n\n        register(1);\n\n        const sub = obsQuery.subscribe({\n          next(result) {\n            assert.deepStrictEqual(result.data, {\n              local: \"hello\",\n            });\n\n            const read = () => cache.readQuery({ query });\n\n            assert.deepStrictEqual(read(), result.data);\n\n            assert.deepStrictEqual(cache.gc(), []);\n\n            // Nothing changes because we merely called cache.gc().\n            assert.deepStrictEqual(read(), result.data);\n\n            assert.deepStrictEqual(\n              cache.gc({\n                // Now reset the result cache but preserve reader.canon, so the\n                // results will be === even though they have to be recomputed.\n                resetResultCache: true,\n              }),\n              []\n            );\n\n            register(2);\n\n            const dataAfterResetWithSameCanon = read();\n            assert.deepStrictEqual(dataAfterResetWithSameCanon, result.data);\n\n            assert.deepStrictEqual(\n              cache.gc({\n                // Finally, do a full reset of the result caching system, including\n                // discarding reader.canon, so === result identity is lost.\n                resetResultCache: true,\n              }),\n              []\n            );\n\n            register(3);\n\n            const dataAfterFullReset = read();\n            assert.notStrictEqual(dataAfterFullReset, result.data);\n            assert.deepStrictEqual(dataAfterFullReset, result.data);\n\n            setTimeout(() => {\n              sub.unsubscribe();\n            });\n          },\n        });\n      })();\n    }\n  );\n\n  itAsync(\n    \"should collect ObservableQuery after tear-down\",\n    (resolve, reject) => {\n      const expectedKeys = new Set([\"ObservableQuery\"]);\n\n      const registry = makeRegistry((key) => {\n        // Referring to client here should keep the client itself alive\n        // until after the ObservableQuery is (or should have been)\n        // collected. Collecting the ObservableQuery just because the whole\n        // client instance was collected is not interesting.\n        assert.strictEqual(client instanceof ApolloClient, true);\n\n        if (expectedKeys.delete(key) && !expectedKeys.size) {\n          resolve();\n        }\n      }, reject);\n\n      const localVar = makeVar(123);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                local() {\n                  return localVar();\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      (function () {\n        const obsQuery = client.watchQuery({\n          query: gql`\n            query {\n              local\n            }\n          `,\n        });\n\n        registry.register(obsQuery, \"ObservableQuery\");\n\n        const sub = obsQuery.subscribe({\n          next(result) {\n            assert.deepStrictEqual(result.data, {\n              local: 123,\n            });\n            setTimeout(() => {\n              sub.unsubscribe();\n            });\n          },\n        });\n      })();\n    }\n  );\n});\n"
  },
  {
    "path": "scripts/memory/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"esnext\",\n    \"module\": \"nodenext\",\n    \"allowJs\": true,\n    \"noEmit\": true,\n    \"allowImportingTsExtensions\": true,\n    \"rewriteRelativeImportExtensions\": true,\n    \"verbatimModuleSyntax\": true,\n    \"resolveJsonModule\": true\n  }\n}\n"
  },
  {
    "path": "src/__tests__/ApolloClient.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { expectTypeOf } from \"expect-type\";\nimport { Kind } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { delay, Observable, of } from \"rxjs\";\n\nimport type {\n  ApolloCache,\n  DataValue,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus, setLogVerbosity } from \"@apollo/client\";\nimport { createFragmentRegistry, InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  withCleanup,\n} from \"@apollo/client/testing/internal\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport { makeReference } from \"@apollo/client/utilities/internal\";\nimport { invariant, InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"ApolloClient\", () => {\n  describe(\"constructor\", () => {\n    let oldFetch: any;\n\n    beforeEach(() => {\n      oldFetch = window.fetch;\n      window.fetch = () => null as any;\n    });\n\n    afterEach(() => {\n      window.fetch = oldFetch;\n    });\n\n    it(\"will throw an error if cache is not passed in\", () => {\n      expect(() => {\n        new ApolloClient({ link: ApolloLink.empty() } as any);\n      }).toThrowErrorMatchingSnapshot();\n    });\n\n    it(\"will throw an error if link is not passed in\", () => {\n      expect(() => {\n        new ApolloClient({ cache: new InMemoryCache() } as any);\n      }).toThrowErrorMatchingSnapshot();\n    });\n  });\n\n  describe(\"readQuery\", () => {\n    it(\"will read some data from the store\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          ROOT_QUERY: {\n            a: 1,\n            b: 2,\n            c: 3,\n          },\n        }),\n      });\n\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n            }\n          `,\n        })\n      ).toEqual({ a: 1 });\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              b\n              c\n            }\n          `,\n        })\n      ).toEqual({ b: 2, c: 3 });\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n              b\n              c\n            }\n          `,\n        })\n      ).toEqual({ a: 1, b: 2, c: 3 });\n    });\n\n    it(\"will read some deeply nested data from the store\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          ROOT_QUERY: {\n            a: 1,\n            b: 2,\n            c: 3,\n            d: makeReference(\"foo\"),\n          },\n          foo: {\n            __typename: \"Foo\",\n            e: 4,\n            f: 5,\n            g: 6,\n            h: makeReference(\"bar\"),\n          },\n          bar: {\n            __typename: \"Bar\",\n            i: 7,\n            j: 8,\n            k: 9,\n          },\n        }),\n      });\n\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n              d {\n                e\n              }\n            }\n          `,\n        })\n      ).toEqual({ a: 1, d: { e: 4, __typename: \"Foo\" } });\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n              d {\n                e\n                h {\n                  i\n                }\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        a: 1,\n        d: { __typename: \"Foo\", e: 4, h: { i: 7, __typename: \"Bar\" } },\n      });\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n              b\n              c\n              d {\n                e\n                f\n                g\n                h {\n                  i\n                  j\n                  k\n                }\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        a: 1,\n        b: 2,\n        c: 3,\n        d: {\n          __typename: \"Foo\",\n          e: 4,\n          f: 5,\n          g: 6,\n          h: { __typename: \"Bar\", i: 7, j: 8, k: 9 },\n        },\n      });\n    });\n\n    it(\"will read some data from the store with variables\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          ROOT_QUERY: {\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        }),\n      });\n\n      expect(\n        client.readQuery({\n          query: gql`\n            query ($literal: Boolean, $value: Int) {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: 42,\n          },\n        })\n      ).toEqual({ a: 1, b: 2 });\n    });\n  });\n\n  it(\"will read some data from the store with default values\", () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache().restore({\n        ROOT_QUERY: {\n          'field({\"literal\":true,\"value\":-1})': 1,\n          'field({\"literal\":false,\"value\":42})': 2,\n        },\n      }),\n    });\n\n    expect(\n      client.readQuery({\n        query: gql`\n          query ($literal: Boolean, $value: Int = -1) {\n            a: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: false,\n          value: 42,\n        },\n      })\n    ).toEqual({ a: 2 });\n\n    expect(\n      client.readQuery({\n        query: gql`\n          query ($literal: Boolean, $value: Int = -1) {\n            a: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: true,\n        },\n      })\n    ).toEqual({ a: 1 });\n  });\n\n  describe(\"readFragment\", () => {\n    it(\"will throw an error when there is no fragment\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      expect(() => {\n        client.readFragment({\n          id: \"x\",\n          fragment: gql`\n            query {\n              a\n              b\n              c\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n      );\n      expect(() => {\n        client.readFragment({\n          id: \"x\",\n          fragment: gql`\n            schema {\n              query: Query\n            }\n          `,\n        });\n      }).toThrow(\n        'Schema type definitions not allowed in queries. Found: \"SchemaDefinition\"'\n      );\n    });\n\n    it(\"will throw an error when there is more than one fragment but no fragment name\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      expect(() => {\n        client.readFragment({\n          id: \"x\",\n          fragment: gql`\n            fragment a on A {\n              a\n            }\n\n            fragment b on B {\n              b\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n      );\n      expect(() => {\n        client.readFragment({\n          id: \"x\",\n          fragment: gql`\n            fragment a on A {\n              a\n            }\n\n            fragment b on B {\n              b\n            }\n\n            fragment c on C {\n              c\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found 3 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n      );\n    });\n\n    it(\"will read some deeply nested data from the store at any id\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          ROOT_QUERY: {\n            __typename: \"Foo\",\n            a: 1,\n            b: 2,\n            c: 3,\n            d: makeReference(\"foo\"),\n          },\n          foo: {\n            __typename: \"Foo\",\n            e: 4,\n            f: 5,\n            g: 6,\n            h: makeReference(\"bar\"),\n          },\n          bar: {\n            __typename: \"Bar\",\n            i: 7,\n            j: 8,\n            k: 9,\n          },\n        }),\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              e\n              h {\n                i\n              }\n            }\n          `,\n        })\n      ).toEqual({ __typename: \"Foo\", e: 4, h: { __typename: \"Bar\", i: 7 } });\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        e: 4,\n        f: 5,\n        g: 6,\n        h: { __typename: \"Bar\", i: 7, j: 8, k: 9 },\n      });\n      expect(\n        client.readFragment({\n          id: \"bar\",\n          fragment: gql`\n            fragment fragmentBar on Bar {\n              i\n            }\n          `,\n        })\n      ).toEqual({ __typename: \"Bar\", i: 7 });\n      expect(\n        client.readFragment({\n          id: \"bar\",\n          fragment: gql`\n            fragment fragmentBar on Bar {\n              i\n              j\n              k\n            }\n          `,\n        })\n      ).toEqual({ __typename: \"Bar\", i: 7, j: 8, k: 9 });\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n\n            fragment fragmentBar on Bar {\n              i\n              j\n              k\n            }\n          `,\n          fragmentName: \"fragmentFoo\",\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        e: 4,\n        f: 5,\n        g: 6,\n        h: { __typename: \"Bar\", i: 7, j: 8, k: 9 },\n      });\n      expect(\n        client.readFragment({\n          id: \"bar\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n\n            fragment fragmentBar on Bar {\n              i\n              j\n              k\n            }\n          `,\n          fragmentName: \"fragmentBar\",\n        })\n      ).toEqual({ __typename: \"Bar\", i: 7, j: 8, k: 9 });\n    });\n\n    it(\"will read some data from the store with variables\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          foo: {\n            __typename: \"Foo\",\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        }),\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment foo on Foo {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: 42,\n          },\n        })\n      ).toEqual({ __typename: \"Foo\", a: 1, b: 2 });\n    });\n\n    it(\"will return null when an id that can’t be found is provided\", () => {\n      const client1 = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n      const client2 = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          bar: { __typename: \"Foo\", a: 1, b: 2, c: 3 },\n        }),\n      });\n      const client3 = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache().restore({\n          foo: { __typename: \"Foo\", a: 1, b: 2, c: 3 },\n        }),\n      });\n\n      expect(\n        client1.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fooFragment on Foo {\n              a\n              b\n              c\n            }\n          `,\n        })\n      ).toBe(null);\n      expect(\n        client2.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fooFragment on Foo {\n              a\n              b\n              c\n            }\n          `,\n        })\n      ).toBe(null);\n      expect(\n        client3.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment fooFragment on Foo {\n              a\n              b\n              c\n            }\n          `,\n        })\n      ).toEqual({ __typename: \"Foo\", a: 1, b: 2, c: 3 });\n    });\n  });\n\n  describe(\"writeQuery\", () => {\n    it(\"will write some data to the store\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        data: { a: 1 },\n        query: gql`\n          {\n            a\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n        },\n      });\n\n      client.writeQuery({\n        data: { b: 2, c: 3 },\n        query: gql`\n          {\n            b\n            c\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          c: 3,\n        },\n      });\n\n      client.writeQuery({\n        data: { a: 4, b: 5, c: 6 },\n        query: gql`\n          {\n            a\n            b\n            c\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 4,\n          b: 5,\n          c: 6,\n        },\n      });\n    });\n\n    it(\"will write some deeply nested data to the store\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                d: {\n                  // Silence \"Cache data may be lost...\"  warnings by\n                  // unconditionally favoring the incoming data.\n                  merge: false,\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      client.writeQuery({\n        data: { a: 1, d: { __typename: \"D\", e: 4 } },\n        query: gql`\n          {\n            a\n            d {\n              e\n            }\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeQuery({\n        data: { a: 1, d: { __typename: \"D\", h: { __typename: \"H\", i: 7 } } },\n        query: gql`\n          {\n            a\n            d {\n              h {\n                i\n              }\n            }\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeQuery({\n        data: {\n          a: 1,\n          b: 2,\n          c: 3,\n          d: {\n            __typename: \"D\",\n            e: 4,\n            f: 5,\n            g: 6,\n            h: {\n              __typename: \"H\",\n              i: 7,\n              j: 8,\n              k: 9,\n            },\n          },\n        },\n        query: gql`\n          {\n            a\n            b\n            c\n            d {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will write some data to the store with variables\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        data: {\n          a: 1,\n          b: 2,\n        },\n        query: gql`\n          query ($literal: Boolean, $value: Int) {\n            a: field(literal: true, value: 42)\n            b: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: false,\n          value: 42,\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'field({\"literal\":true,\"value\":42})': 1,\n          'field({\"literal\":false,\"value\":42})': 2,\n        },\n      });\n    });\n\n    it(\"will write some data to the store with default values for variables\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        data: {\n          a: 2,\n        },\n        query: gql`\n          query ($literal: Boolean, $value: Int = -1) {\n            a: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: true,\n          value: 42,\n        },\n      });\n\n      client.writeQuery({\n        data: {\n          a: 1,\n        },\n        query: gql`\n          query ($literal: Boolean, $value: Int = -1) {\n            a: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: false,\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'field({\"literal\":true,\"value\":42})': 2,\n          'field({\"literal\":false,\"value\":-1})': 1,\n        },\n      });\n    });\n\n    it(\"should warn when the data provided does not match the query shape\", () => {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({\n          // Passing an empty map enables the warning:\n          possibleTypes: {},\n        }),\n      });\n\n      client.writeQuery({\n        data: {\n          todos: [\n            {\n              id: \"1\",\n              name: \"Todo 1\",\n              __typename: \"Todo\",\n            },\n          ],\n        },\n        query: gql`\n          query {\n            todos {\n              id\n              name\n              description\n            }\n          }\n        `,\n      });\n    });\n  });\n\n  describe(\"writeFragment\", () => {\n    it(\"will throw an error when there is no fragment\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      expect(() => {\n        client.writeFragment({\n          data: {},\n          id: \"x\",\n          fragment: gql`\n            query {\n              a\n              b\n              c\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n      );\n      expect(() => {\n        client.writeFragment({\n          data: {},\n          id: \"x\",\n          fragment: gql`\n            schema {\n              query: Query\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found 0 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n      );\n    });\n\n    it(\"will throw an error when there is more than one fragment but no fragment name\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      expect(() => {\n        client.writeFragment({\n          data: {},\n          id: \"x\",\n          fragment: gql`\n            fragment a on A {\n              a\n            }\n\n            fragment b on B {\n              b\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n      );\n      expect(() => {\n        client.writeFragment({\n          data: {},\n          id: \"x\",\n          fragment: gql`\n            fragment a on A {\n              a\n            }\n\n            fragment b on B {\n              b\n            }\n\n            fragment c on C {\n              c\n            }\n          `,\n        });\n      }).toThrow(\n        \"Found 3 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n      );\n    });\n\n    it(\"will write some deeply nested data into the store at any id\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({ dataIdFromObject: (o: any) => o.id }),\n      });\n\n      client.writeFragment({\n        data: {\n          __typename: \"Foo\",\n          e: 4,\n          h: { __typename: \"Bar\", id: \"bar\", i: 7 },\n        },\n        id: \"foo\",\n        fragment: gql`\n          fragment fragmentFoo on Foo {\n            e\n            h {\n              i\n            }\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeFragment({\n        data: {\n          __typename: \"Foo\",\n          f: 5,\n          g: 6,\n          h: { __typename: \"Bar\", id: \"bar\", j: 8, k: 9 },\n        },\n        id: \"foo\",\n        fragment: gql`\n          fragment fragmentFoo on Foo {\n            f\n            g\n            h {\n              j\n              k\n            }\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeFragment({\n        data: { __typename: \"Bar\", i: 10 },\n        id: \"bar\",\n        fragment: gql`\n          fragment fragmentBar on Bar {\n            i\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeFragment({\n        data: { __typename: \"Bar\", j: 11, k: 12 },\n        id: \"bar\",\n        fragment: gql`\n          fragment fragmentBar on Bar {\n            j\n            k\n          }\n        `,\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeFragment({\n        data: {\n          __typename: \"Foo\",\n          e: 4,\n          f: 5,\n          g: 6,\n          h: { __typename: \"Bar\", id: \"bar\", i: 7, j: 8, k: 9 },\n        },\n        id: \"foo\",\n        fragment: gql`\n          fragment fooFragment on Foo {\n            e\n            f\n            g\n            h {\n              i\n              j\n              k\n            }\n          }\n\n          fragment barFragment on Bar {\n            i\n            j\n            k\n          }\n        `,\n        fragmentName: \"fooFragment\",\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n\n      client.writeFragment({\n        data: { __typename: \"Bar\", i: 10, j: 11, k: 12 },\n        id: \"bar\",\n        fragment: gql`\n          fragment fooFragment on Foo {\n            e\n            f\n            g\n            h {\n              i\n              j\n              k\n            }\n          }\n\n          fragment barFragment on Bar {\n            i\n            j\n            k\n          }\n        `,\n        fragmentName: \"barFragment\",\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will write some data to the store with variables\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeFragment({\n        data: {\n          __typename: \"Foo\",\n          a: 1,\n          b: 2,\n        },\n        id: \"foo\",\n        fragment: gql`\n          fragment foo on Foo {\n            a: field(literal: true, value: 42)\n            b: field(literal: $literal, value: $value)\n          }\n        `,\n        variables: {\n          literal: false,\n          value: 42,\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        __META: {\n          extraRootIds: [\"foo\"],\n        },\n        foo: {\n          __typename: \"Foo\",\n          'field({\"literal\":true,\"value\":42})': 1,\n          'field({\"literal\":false,\"value\":42})': 2,\n        },\n      });\n    });\n\n    it(\"should warn when the data provided does not match the fragment shape\", () => {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({\n          // Passing an empty map enables the warning:\n          possibleTypes: {},\n        }),\n      });\n\n      client.writeFragment({\n        data: { __typename: \"Bar\", i: 10 },\n        id: \"bar\",\n        fragment: gql`\n          fragment fragmentBar on Bar {\n            i\n            e\n          }\n        `,\n      });\n    });\n\n    describe(\"change will call observable next\", () => {\n      const query = gql`\n        query nestedData {\n          people {\n            id\n            friends {\n              id\n              type\n            }\n          }\n        }\n      `;\n\n      interface Friend {\n        id: number;\n        type: string;\n        __typename: string;\n      }\n      interface Data {\n        people: {\n          id: number;\n          __typename: string;\n          friends: Friend[];\n        };\n      }\n      const bestFriend = {\n        id: 1,\n        type: \"best\",\n        __typename: \"Friend\",\n      };\n      const badFriend = {\n        id: 2,\n        type: \"bad\",\n        __typename: \"Friend\",\n      };\n      const data = {\n        people: {\n          id: 1,\n          __typename: \"Person\",\n          friends: [bestFriend, badFriend],\n        },\n      };\n      const link = new ApolloLink(() => {\n        return of({ data }).pipe(delay(20));\n      });\n      function newClient() {\n        return new ApolloClient({\n          link,\n          cache: new InMemoryCache({\n            typePolicies: {\n              Person: {\n                fields: {\n                  friends: {\n                    // Deliberately silence \"Cache data may be lost...\"\n                    // warnings by preferring the incoming data, rather\n                    // than (say) concatenating the arrays together.\n                    merge: false,\n                  },\n                },\n              },\n            },\n            dataIdFromObject: (result) => {\n              if (result.id && result.__typename) {\n                return result.__typename + result.id;\n              }\n            },\n          }),\n        });\n      }\n\n      describe(\"using writeQuery\", () => {\n        it(\"with TypedDocumentNode\", async () => {\n          const client = newClient();\n\n          // This is defined manually for the purpose of the test, but\n          // eventually this could be generated with graphql-code-generator\n          const typedQuery: TypedDocumentNode<Data, { testVar: string }> =\n            query;\n\n          // The result and variables are being typed automatically, based on the query object we pass,\n          // and type inference is done based on the TypeDocumentNode object.\n          const result = await client.query({\n            query: typedQuery,\n            variables: { testVar: \"foo\" },\n          });\n\n          // Just try to access it, if something will break, TS will throw an error\n          // during the test\n          result.data?.people.friends[0].id;\n        });\n\n        it(\"with a replacement of nested array (wq)\", async () => {\n          const client = newClient();\n          const observable = client.watchQuery<Data>({ query });\n          const stream = new ObservableStream(observable);\n\n          await expect(stream).toEmitTypedValue({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n          expect(observable.getCurrentResult().data).toEqual(data);\n\n          const readData = client.readQuery<Data>({ query });\n          expect(readData).toEqual(data);\n\n          // modify readData and writeQuery\n          const bestFriends = readData!.people.friends.filter(\n            (x) => x.type === \"best\"\n          );\n          // this should re call next\n          client.writeQuery<Data>({\n            query,\n            data: {\n              people: {\n                id: 1,\n                friends: bestFriends,\n                __typename: \"Person\",\n              },\n            },\n          });\n\n          const expectation = {\n            people: {\n              id: 1,\n              friends: [bestFriend],\n              __typename: \"Person\",\n            },\n          };\n\n          await expect(stream).toEmitTypedValue({\n            data: expectation,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n          expect(client.readQuery<Data>({ query })).toEqual(expectation);\n        });\n\n        it(\"with a value change inside a nested array (wq)\", async () => {\n          const client = newClient();\n          const observable = client.watchQuery<Data>({ query });\n          const stream = new ObservableStream(observable);\n\n          await expect(stream).toEmitTypedValue({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n\n          expect(observable.getCurrentResult().data).toEqual(data);\n\n          const readData = client.readQuery<Data>({ query });\n          expect(readData).toEqual(data);\n\n          // modify readData and writeQuery\n          const friends = readData!.people.friends.slice();\n          friends[0] = { ...friends[0], type: \"okayest\" };\n          friends[1] = { ...friends[1], type: \"okayest\" };\n\n          // this should re call next\n          client.writeQuery<Data>({\n            query,\n            data: {\n              people: {\n                id: 1,\n                friends,\n                __typename: \"Person\",\n              },\n            },\n          });\n\n          const expectation0 = {\n            ...bestFriend,\n            type: \"okayest\",\n          };\n          const expectation1 = {\n            ...badFriend,\n            type: \"okayest\",\n          };\n\n          await expect(stream).toEmitTypedValue({\n            data: {\n              ...data,\n              people: {\n                ...data.people,\n                friends: [expectation0, expectation1],\n              },\n            },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n\n          const readFriends = client.readQuery<Data>({ query })!.people.friends;\n          expect(readFriends[0]).toEqual(expectation0);\n          expect(readFriends[1]).toEqual(expectation1);\n        });\n      });\n\n      describe(\"using writeFragment\", () => {\n        it(\"with a replacement of nested array (wf)\", async () => {\n          const client = newClient();\n          const observable = client.watchQuery<Data>({ query });\n          const stream = new ObservableStream(observable);\n\n          await expect(stream).toEmitTypedValue({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n          expect(observable.getCurrentResult()).toStrictEqualTyped({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n\n          const result = stream.getCurrent();\n          invariant(\n            result?.dataState === \"complete\",\n            \"dataState should be complete\"\n          );\n\n          const bestFriends = result.data.people.friends.filter(\n            (x) => x.type === \"best\"\n          );\n\n          // this should re call next\n          client.writeFragment({\n            id: `Person${result.data!.people.id}`,\n            fragment: gql`\n              fragment bestFriends on Person {\n                friends {\n                  id\n                }\n              }\n            `,\n            data: {\n              friends: bestFriends,\n              __typename: \"Person\",\n            },\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data: {\n              ...data,\n              people: {\n                ...data.people,\n                friends: [bestFriend],\n              },\n            },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n        });\n\n        it(\"with a value change inside a nested array (wf)\", async () => {\n          const client = newClient();\n          const observable = client.watchQuery<Data>({ query });\n          const stream = new ObservableStream(observable);\n\n          await expect(stream).toEmitTypedValue({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n          expect(observable.getCurrentResult()).toStrictEqualTyped({\n            data,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n\n          const result = stream.getCurrent();\n\n          invariant(result?.dataState === \"complete\");\n\n          const friends = result.data.people.friends;\n\n          // this should re call next\n          client.writeFragment({\n            id: `Person${result.data!.people.id}`,\n            fragment: gql`\n              fragment bestFriends on Person {\n                friends {\n                  id\n                  type\n                }\n              }\n            `,\n            data: {\n              friends: [\n                { ...friends[0], type: \"okayest\" },\n                { ...friends[1], type: \"okayest\" },\n              ],\n              __typename: \"Person\",\n            },\n          });\n\n          await expect(stream).toEmitTypedValue({\n            data: {\n              ...data,\n              people: {\n                ...data.people,\n                friends: [\n                  { ...bestFriend, type: \"okayest\" },\n                  { ...badFriend, type: \"okayest\" },\n                ],\n              },\n            },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n        });\n      });\n    });\n  });\n\n  describe(\"write then read\", () => {\n    it(\"will write data locally which will then be read back\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({\n          dataIdFromObject(object) {\n            if (typeof object.__typename === \"string\") {\n              return object.__typename.toLowerCase();\n            }\n          },\n        }).restore({\n          foo: {\n            __typename: \"Foo\",\n            a: 1,\n            b: 2,\n            c: 3,\n            bar: makeReference(\"bar\"),\n          },\n          bar: {\n            __typename: \"Bar\",\n            d: 4,\n            e: 5,\n            f: 6,\n          },\n        }),\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment x on Foo {\n              a\n              b\n              c\n              bar {\n                d\n                e\n                f\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        a: 1,\n        b: 2,\n        c: 3,\n        bar: { d: 4, e: 5, f: 6, __typename: \"Bar\" },\n      });\n\n      client.writeFragment({\n        id: \"foo\",\n        fragment: gql`\n          fragment x on Foo {\n            a\n          }\n        `,\n        data: { __typename: \"Foo\", a: 7 },\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment x on Foo {\n              a\n              b\n              c\n              bar {\n                d\n                e\n                f\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        a: 7,\n        b: 2,\n        c: 3,\n        bar: { __typename: \"Bar\", d: 4, e: 5, f: 6 },\n      });\n\n      client.writeFragment({\n        id: \"foo\",\n        fragment: gql`\n          fragment x on Foo {\n            bar {\n              d\n            }\n          }\n        `,\n        data: { __typename: \"Foo\", bar: { __typename: \"Bar\", d: 8 } },\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment x on Foo {\n              a\n              b\n              c\n              bar {\n                d\n                e\n                f\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        a: 7,\n        b: 2,\n        c: 3,\n        bar: { __typename: \"Bar\", d: 8, e: 5, f: 6 },\n      });\n\n      client.writeFragment({\n        id: \"bar\",\n        fragment: gql`\n          fragment y on Bar {\n            e\n          }\n        `,\n        data: { __typename: \"Bar\", e: 9 },\n      });\n\n      expect(\n        client.readFragment({\n          id: \"foo\",\n          fragment: gql`\n            fragment x on Foo {\n              a\n              b\n              c\n              bar {\n                d\n                e\n                f\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        __typename: \"Foo\",\n        a: 7,\n        b: 2,\n        c: 3,\n        bar: { __typename: \"Bar\", d: 8, e: 9, f: 6 },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will write data to a specific id\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache({\n          dataIdFromObject: (o: any) => o.key,\n        }),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                key\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            __typename: \"foo\",\n            c: 3,\n            d: 4,\n            bar: { key: \"foobar\", __typename: \"bar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      expect(\n        client.readQuery({\n          query: gql`\n            {\n              a\n              b\n              foo {\n                c\n                d\n                bar {\n                  key\n                  e\n                  f\n                }\n              }\n            }\n          `,\n        })\n      ).toEqual({\n        a: 1,\n        b: 2,\n        foo: {\n          __typename: \"foo\",\n          c: 3,\n          d: 4,\n          bar: { __typename: \"bar\", key: \"foobar\", e: 5, f: 6 },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will not use a default id getter if __typename is not present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: { c: 3, d: 4, bar: { id: \"foobar\", e: 5, f: 6 } },\n        },\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            g\n            h\n            bar {\n              i\n              j\n              foo {\n                _id\n                k\n                l\n              }\n            }\n          }\n        `,\n        data: {\n          g: 8,\n          h: 9,\n          bar: { i: 10, j: 11, foo: { _id: \"barfoo\", k: 12, l: 13 } },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          g: 8,\n          h: 9,\n          bar: {\n            i: 10,\n            j: 11,\n            foo: {\n              _id: \"barfoo\",\n              k: 12,\n              l: 13,\n            },\n          },\n          foo: {\n            c: 3,\n            d: 4,\n            bar: {\n              id: \"foobar\",\n              e: 5,\n              f: 6,\n            },\n          },\n        },\n      });\n    });\n\n    it(\"will not use a default id getter if id and _id are not present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            __typename: \"foo\",\n            c: 3,\n            d: 4,\n            bar: { __typename: \"bar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            g\n            h\n            bar {\n              i\n              j\n              foo {\n                k\n                l\n              }\n            }\n          }\n        `,\n        data: {\n          g: 8,\n          h: 9,\n          bar: {\n            __typename: \"bar\",\n            i: 10,\n            j: 11,\n            foo: { __typename: \"foo\", k: 12, l: 13 },\n          },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will use a default id getter if __typename and id are present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            __typename: \"foo\",\n            c: 3,\n            d: 4,\n            bar: { __typename: \"bar\", id: \"foobar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will use a default id getter if __typename and _id are present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                _id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            __typename: \"foo\",\n            c: 3,\n            d: 4,\n            bar: { __typename: \"bar\", _id: \"foobar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will not use a default id getter if id is present and __typename is not present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: { c: 3, d: 4, bar: { id: \"foobar\", e: 5, f: 6 } },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          foo: {\n            c: 3,\n            d: 4,\n            bar: {\n              id: \"foobar\",\n              e: 5,\n              f: 6,\n            },\n          },\n        },\n      });\n    });\n\n    it(\"will not use a default id getter if _id is present but __typename is not present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                _id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: { c: 3, d: 4, bar: { _id: \"foobar\", e: 5, f: 6 } },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          foo: {\n            c: 3,\n            d: 4,\n            bar: {\n              _id: \"foobar\",\n              e: 5,\n              f: 6,\n            },\n          },\n        },\n      });\n    });\n\n    it(\"will not use a default id getter if either _id or id is present when __typename is not also present\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            c: 3,\n            d: 4,\n            bar: { __typename: \"bar\", id: \"foobar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            g\n            h\n            bar {\n              i\n              j\n              foo {\n                _id\n                k\n                l\n              }\n            }\n          }\n        `,\n        data: {\n          g: 8,\n          h: 9,\n          bar: { i: 10, j: 11, foo: { _id: \"barfoo\", k: 12, l: 13 } },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n\n    it(\"will use a default id getter if one is not specified and __typename is present along with either _id or id\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            a\n            b\n            foo {\n              c\n              d\n              bar {\n                id\n                e\n                f\n              }\n            }\n          }\n        `,\n        data: {\n          a: 1,\n          b: 2,\n          foo: {\n            __typename: \"foo\",\n            c: 3,\n            d: 4,\n            bar: { __typename: \"bar\", id: \"foobar\", e: 5, f: 6 },\n          },\n        },\n      });\n\n      client.writeQuery({\n        query: gql`\n          {\n            g\n            h\n            bar {\n              i\n              j\n              foo {\n                _id\n                k\n                l\n              }\n            }\n          }\n        `,\n        data: {\n          g: 8,\n          h: 9,\n          bar: {\n            __typename: \"bar\",\n            i: 10,\n            j: 11,\n            foo: { __typename: \"foo\", _id: \"barfoo\", k: 12, l: 13 },\n          },\n        },\n      });\n\n      expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n    });\n  });\n\n  describe(\"watchQuery & prioritizeCacheValues\", () => {\n    it.each([\n      [true, \"cache-first\"],\n      [true, \"cache-and-network\"],\n      [true, \"network-only\"],\n      [true, \"cache-only\"],\n      [true, \"no-cache\"],\n      [false, \"cache-first\"],\n      [false, \"cache-and-network\"],\n      [false, \"network-only\"],\n      [false, \"cache-only\"],\n      [false, \"no-cache\"],\n    ] as const)(\n      \"should not change the `fetchPolicy` (`prioritizeCacheValues`: %s, `fetchPolicy`: %s)\",\n      async (prioritizeCacheValues, fetchPolicy) => {\n        const client = new ApolloClient({\n          link: ApolloLink.empty(),\n          cache: new InMemoryCache(),\n        });\n        client.prioritizeCacheValues = prioritizeCacheValues;\n\n        const observable = client.watchQuery({\n          query: gql`\n            query {\n              foo\n            }\n          `,\n          fetchPolicy,\n        });\n        expect(observable.options.fetchPolicy).toEqual(fetchPolicy);\n      }\n    );\n\n    it.each([\n      [\"network-only\"],\n      [\"cache-and-network\"],\n      [\"cache-first\"],\n    ] as const)(\n      \"should not make a network request if the cache can fulfill the query (`prioritizeCacheValues`: true, `fetchPolicy`: %s)\",\n      async (fetchPolicy) => {\n        const query = gql`\n          query someData {\n            source\n          }\n        `;\n        const client = new ApolloClient({\n          link: new MockLink([\n            { request: { query }, result: { data: { source: \"network\" } } },\n          ]),\n          cache: new InMemoryCache(),\n        });\n        client.prioritizeCacheValues = true;\n        client.writeQuery({ query, data: { source: \"cache\" } });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy,\n        });\n        const stream = new ObservableStream(observable);\n        await expect(stream).toEmitTypedValue({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n          data: { source: \"cache\" },\n          dataState: \"complete\",\n        });\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n\n    it.each([\n      [\"network-only\"],\n      [\"cache-and-network\"],\n      [\"cache-first\"],\n    ] as const)(\n      \"should make a network request if the cache cannot fulfill the query (`prioritizeCacheValues`: true, `fetchPolicy`: %s)\",\n      async (fetchPolicy) => {\n        const query = gql`\n          query someData {\n            source\n          }\n        `;\n        const client = new ApolloClient({\n          link: new MockLink([\n            { request: { query }, result: { data: { source: \"network\" } } },\n          ]),\n          cache: new InMemoryCache(),\n        });\n        client.prioritizeCacheValues = true;\n\n        const observable = client.watchQuery({ query, fetchPolicy });\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n          data: { source: \"network\" },\n          dataState: \"complete\",\n        });\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n\n    it.each([[\"no-cache\"]] as const)(\n      \"should make a network request (`prioritizeCacheValues`: true, `fetchPolicy`: %s)\",\n      async (fetchPolicy) => {\n        const query = gql`\n          query someData {\n            source\n          }\n        `;\n        const client = new ApolloClient({\n          link: new MockLink([\n            { request: { query }, result: { data: { source: \"network\" } } },\n          ]),\n          cache: new InMemoryCache(),\n        });\n        client.prioritizeCacheValues = true;\n        client.writeQuery({ query, data: { source: \"cache\" } });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy,\n          notifyOnNetworkStatusChange: true,\n        });\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n          data: undefined,\n          dataState: \"empty\",\n        });\n        await expect(stream).toEmitTypedValue({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n          data: { source: \"network\" },\n          dataState: \"complete\",\n        });\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n\n    it.each([[\"standby\"]] as const)(\n      \"should not emit anything (`prioritizeCacheValues`: true, `fetchPolicy`: %s)\",\n      async (fetchPolicy) => {\n        const query = gql`\n          query someData {\n            source\n          }\n        `;\n        const client = new ApolloClient({\n          link: new MockLink([\n            { request: { query }, result: { data: { source: \"network\" } } },\n          ]),\n          cache: new InMemoryCache(),\n        });\n        client.prioritizeCacheValues = true;\n        client.writeQuery({ query, data: { source: \"cache\" } });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy,\n          notifyOnNetworkStatusChange: true,\n        });\n        const stream = new ObservableStream(observable);\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n  });\n\n  describe(\"watchFragment\", () => {\n    it(\"if all data is available, `complete` is `true`\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"cache writes emit a new value\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 (edited)\",\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 (edited)\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"if only partial data is available, `complete` is `false`\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n        }\n      `;\n\n      {\n        // we expect a \"Missing field 'text' while writing result...\" error\n        // when writing item to the cache, so we'll silence the console.error\n        using _consoleSpy = spyOnConsole(\"error\");\n        cache.writeFragment({\n          fragment: ItemFragment,\n          data: {\n            __typename: \"Item\",\n            id: 5,\n          },\n        });\n      }\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n        },\n        dataState: \"partial\",\n        complete: false,\n        missing: {\n          text: \"Can't find field 'text' on Item:5 object\",\n        },\n      });\n    });\n\n    it(\"if no data is written after observable is subscribed to, next is never called\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n        }\n      `;\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {},\n        dataState: \"partial\",\n        complete: false,\n        missing: \"Dangling reference to missing Item:5 object\",\n      });\n\n      await expect(stream).not.toEmitAnything({ timeout: 1000 });\n    });\n\n    it(\"supports the @nonreactive directive\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text @nonreactive\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 (edited)\",\n        },\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"works with `variables`\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text(language: $language)\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        variables: { language: \"Esperanto\" },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n        variables: { language: \"Esperanto\" },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"supports the @includes directive with `variables`\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text @include(if: $withText)\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        variables: { withText: true },\n      });\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n        },\n        variables: { withText: false },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n        variables: { withText: true },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"supports the @includes directive with `variables` - parallel cache modification\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n      const FullFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n        }\n      `;\n\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          ...IncludedFragment @include(if: $withText)\n        }\n\n        fragment IncludedFragment on Item {\n          id\n          text\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: FullFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 5 },\n        variables: { withText: true },\n        fragmentName: \"ItemFragment\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n\n      client.writeFragment({\n        fragment: FullFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"changed Item #5\",\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"changed Item #5\",\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"works with nested fragments\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n\n      const ItemNestedFragment = gql`\n        fragment ItemNestedFragment on Item {\n          complete\n        }\n      `;\n\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n          ...ItemNestedFragment\n        }\n\n        ${ItemNestedFragment}\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        fragmentName: \"ItemFragment\",\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n          complete: true,\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        fragmentName: \"ItemFragment\",\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n          complete: true,\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n\n    it(\"can use the fragment registry for nested fragments\", async () => {\n      const fragments = createFragmentRegistry();\n      const cache = new InMemoryCache({ fragments });\n\n      fragments.register(gql`\n        fragment ItemNestedFragment on Item {\n          complete\n        }\n      `);\n\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n\n      const ItemFragment = gql`\n        fragment ItemFragment on Item {\n          id\n          text\n          ...ItemNestedFragment\n        }\n      `;\n\n      cache.writeFragment({\n        fragment: ItemFragment,\n        fragmentName: \"ItemFragment\",\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n          complete: true,\n        },\n      });\n\n      const observable = client.watchFragment({\n        fragment: ItemFragment,\n        fragmentName: \"ItemFragment\",\n        from: { __typename: \"Item\", id: 5 },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n          complete: true,\n        },\n        dataState: \"complete\",\n        complete: true,\n      });\n    });\n  });\n\n  describe(\"defaultOptions\", () => {\n    it(\n      \"should set `defaultOptions` to an empty object if not provided in \" +\n        \"the constructor\",\n      () => {\n        const client = new ApolloClient({\n          link: ApolloLink.empty(),\n          cache: new InMemoryCache(),\n        });\n        expect(client.defaultOptions).toEqual({});\n      }\n    );\n\n    it(\"should set `defaultOptions` using options passed into the constructor\", () => {\n      const defaultOptions: ApolloClient.DefaultOptions = {\n        query: {\n          fetchPolicy: \"no-cache\",\n        },\n      };\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        defaultOptions,\n      });\n      expect(client.defaultOptions).toEqual(defaultOptions);\n    });\n\n    it(\"should use default options (unless overridden) when querying\", async () => {\n      const defaultOptions: ApolloClient.DefaultOptions = {\n        query: {\n          fetchPolicy: \"no-cache\",\n        },\n      };\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        defaultOptions,\n      });\n\n      let queryOptions: ApolloClient.QueryOptions = {\n        query: gql`\n          {\n            a\n          }\n        `,\n      };\n\n      // @ts-ignore\n      const queryManager = client.queryManager;\n      const _query = queryManager.query;\n      queryManager.query = (options) => {\n        queryOptions = options;\n        return _query(options);\n      };\n\n      try {\n        await client.query({\n          query: gql`\n            {\n              a\n            }\n          `,\n        });\n      } catch (error) {\n        // Swallow errors caused by mocking; not part of this test\n      }\n\n      expect(queryOptions.fetchPolicy).toEqual(\n        defaultOptions.query!.fetchPolicy\n      );\n\n      client.stop();\n    });\n\n    it(\"should be able to set all default query options\", () => {\n      new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          query: {\n            query: { kind: Kind.DOCUMENT, definitions: [] },\n            variables: { foo: \"bar\" },\n            errorPolicy: \"none\",\n            context: undefined,\n            fetchPolicy: \"cache-first\",\n          },\n        },\n      });\n    });\n  });\n\n  describe(\"clearStore\", () => {\n    it(\"should remove all data from the store\", async () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n      interface Data {\n        a: number;\n      }\n      client.writeQuery<Data>({\n        data: { a: 1 },\n        query: gql`\n          {\n            a\n          }\n        `,\n      });\n\n      expect((client.cache as any).data.data).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n        },\n      });\n\n      await client.clearStore();\n      expect((client.cache as any).data.data).toEqual({});\n    });\n  });\n\n  describe(\"setLink\", () => {\n    it(\"should override default link with newly set link\", async () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n      expect(client.link).toBeDefined();\n\n      const newLink = new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          observer.next({\n            data: {\n              widgets: [{ name: \"Widget 1\" }, { name: \"Widget 2\" }],\n            },\n          });\n          observer.complete();\n        });\n      });\n\n      client.setLink(newLink);\n\n      const { data } = await client.query<any>({\n        query: gql`\n          {\n            widgets\n          }\n        `,\n      });\n      expect(data.widgets).toBeDefined();\n      expect(data.widgets.length).toBe(2);\n    });\n  });\n\n  describe(\"refetchQueries\", () => {\n    it(\"should emit error from refetchQueries when not caught explicitly\", async () => {\n      using consoleSpies = spyOnConsole(\"debug\");\n      using _ = withCleanup(\n        { oldVerbosity: setLogVerbosity(\"debug\") },\n        ({ oldVerbosity }) => setLogVerbosity(oldVerbosity)\n      );\n\n      const link = new MockSubscriptionLink();\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const query = gql`\n        query someData {\n          foo {\n            bar\n          }\n        }\n      `;\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"network-only\",\n      });\n\n      const stream = new ObservableStream(observable);\n      link.simulateResult({ result: { data: { foo: { bar: 1 } } } }, true);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { foo: { bar: 1 } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const result = client.refetchQueries({\n        include: \"all\",\n      });\n\n      const stream2 = new ObservableStream(result.queries[0]);\n\n      await expect(stream2).toEmitTypedValue({\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n        data: { foo: { bar: 1 } },\n        dataState: \"complete\",\n      });\n\n      link.simulateResult({ error: new Error(\"refetch failed\") });\n\n      await expect(stream2).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n        data: { foo: { bar: 1 } },\n        dataState: \"complete\",\n        error: new Error(\"refetch failed\"),\n      });\n\n      expect(consoleSpies.debug).toHaveBeenCalledTimes(1);\n      expect(consoleSpies.debug).toHaveBeenCalledWith(\n        \"In client.refetchQueries, Promise.all promise rejected with error %o\",\n        new Error(\"refetch failed\")\n      );\n    });\n  });\n\n  test(\"will error when used with `@defer` in a without specifying an incremental strategy\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const query = gql`\n      query {\n        foo @defer {\n          bar\n        }\n      }\n    `;\n\n    await expect(() => client.query({ query })).rejects.toThrow(\n      new InvariantError(\n        \"`@defer` and `@stream` are not supported without specifying an incremental handler. Please pass a handler as the `incrementalHandler` option to the `ApolloClient` constructor.\"\n      )\n    );\n  });\n\n  test(\"will error when used with `@stream` in a without specifying an incremental strategy\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const query = gql`\n      query {\n        items @stream {\n          bar\n        }\n      }\n    `;\n\n    await expect(() => client.query({ query })).rejects.toThrow(\n      new InvariantError(\n        \"`@defer` and `@stream` are not supported without specifying an incremental handler. Please pass a handler as the `incrementalHandler` option to the `ApolloClient` constructor.\"\n      )\n    );\n  });\n\n  describe.skip(\"type tests\", () => {\n    test(\"client.mutate uses any as masked and unmasked type when using plain DocumentNode\", () => {\n      const mutation = gql`\n        mutation ($id: ID!) {\n          updateUser(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      const promise = client.mutate({\n        mutation,\n        optimisticResponse: { foo: \"foo\" },\n        updateQueries: {\n          TestQuery: (_, { mutationResult }) => {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<any>();\n\n            return {};\n          },\n        },\n        refetchQueries(result) {\n          expectTypeOf(result.data).toMatchTypeOf<any>();\n\n          return \"active\";\n        },\n        update(_, result) {\n          expectTypeOf(result.data).toMatchTypeOf<any>();\n        },\n      });\n\n      expectTypeOf(promise).branded.toEqualTypeOf<\n        Promise<ApolloClient.MutateResult<any>>\n      >();\n    });\n\n    test(\"client.mutate uses TData type when using plain TypedDocumentNode\", () => {\n      interface Mutation {\n        updateUser: {\n          __typename: \"User\";\n          id: string;\n          age: number;\n        };\n      }\n\n      interface Variables {\n        id: string;\n      }\n\n      const mutation: TypedDocumentNode<Mutation, Variables> = gql`\n        mutation ($id: ID!) {\n          updateUser(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      const promise = client.mutate({\n        variables: { id: \"1\" },\n        mutation,\n        optimisticResponse: {\n          updateUser: { __typename: \"User\", id: \"1\", age: 30 },\n        },\n        updateQueries: {\n          TestQuery: (_, { mutationResult }) => {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              DeepPartial<Mutation> | null | undefined\n            >();\n\n            if (mutationResult.dataState === \"streaming\") {\n              expectTypeOf(mutationResult.data).toMatchTypeOf<\n                DeepPartial<Mutation> | null | undefined\n              >();\n            }\n            if (mutationResult.dataState === \"complete\") {\n              expectTypeOf(mutationResult.data).toMatchTypeOf<\n                Mutation | null | undefined\n              >();\n            }\n\n            return {};\n          },\n        },\n        refetchQueries(result) {\n          expectTypeOf(result.data).toMatchTypeOf<\n            Mutation | DeepPartial<Mutation> | null | undefined\n          >();\n          if (result.dataState === \"streaming\") {\n            expectTypeOf(result.data).toMatchTypeOf<\n              DeepPartial<Mutation> | null | undefined\n            >();\n          }\n          if (result.dataState === \"complete\") {\n            expectTypeOf(result.data).toMatchTypeOf<\n              Mutation | null | undefined\n            >();\n          }\n\n          return \"active\";\n        },\n        update(_, result) {\n          expectTypeOf(result.data).toMatchTypeOf<\n            Mutation | null | undefined\n          >();\n        },\n      });\n\n      expectTypeOf(promise).branded.toEqualTypeOf<\n        Promise<ApolloClient.MutateResult<Mutation>>\n      >();\n    });\n\n    test(\"client.mutate proper uses masked/unmasked type\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\": \"UserFieldsFragment\" };\n\n      type Mutation = {\n        updateUser: {\n          __typename: \"User\";\n          id: string;\n        } & { \" $fragmentRefs\": { UserFieldsFragment: UserFieldsFragment } };\n      };\n\n      type UnmaskedMutation = {\n        updateUser: {\n          __typename: \"User\";\n          id: string;\n          age: number;\n        };\n      };\n\n      interface Variables {\n        id: string;\n      }\n\n      const mutation: TypedDocumentNode<Mutation, Variables> = gql`\n        mutation ($id: ID!) {\n          updateUser(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      const result = await client.mutate({\n        variables: { id: \"1\" },\n        mutation,\n        optimisticResponse: {\n          updateUser: { __typename: \"User\", id: \"1\", age: 30 },\n        },\n        updateQueries: {\n          TestQuery: (_, { mutationResult }) => {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              DeepPartial<UnmaskedMutation> | null | undefined\n            >();\n\n            return {};\n          },\n        },\n        refetchQueries(result) {\n          expectTypeOf(result.data).toMatchTypeOf<\n            UnmaskedMutation | DeepPartial<UnmaskedMutation> | null | undefined\n          >();\n          if (result.dataState === \"streaming\") {\n            expectTypeOf(result.data).toMatchTypeOf<\n              DeepPartial<UnmaskedMutation> | null | undefined\n            >();\n          }\n          if (result.dataState === \"complete\") {\n            expectTypeOf(result.data).toMatchTypeOf<\n              UnmaskedMutation | null | undefined\n            >();\n          }\n\n          return \"active\";\n        },\n        update(_, result) {\n          expectTypeOf(result.data).toMatchTypeOf<\n            UnmaskedMutation | null | undefined\n          >();\n        },\n      });\n\n      expectTypeOf(result.data).toEqualTypeOf<Mutation | undefined>();\n    });\n\n    test(\"client.query uses correct masked/unmasked types\", async () => {\n      type UserFieldsFragment = {\n        age: number;\n      } & { \" $fragmentName\": \"UserFieldsFragment\" };\n\n      type Query = {\n        user: {\n          __typename: \"User\";\n          id: string;\n        } & { \" $fragmentRefs\": { UserFieldsFragment: UserFieldsFragment } };\n      };\n\n      interface Variables {\n        id: string;\n      }\n\n      const query: TypedDocumentNode<Query, Variables> = gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const result = await client.query({ variables: { id: \"1\" }, query });\n\n      expectTypeOf(result.data).toMatchTypeOf<Query | null | undefined>();\n    });\n\n    test(\"client.watchQuery uses correct masked/unmasked types\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\": \"UserFieldsFragment\" };\n\n      type Query = {\n        user: {\n          __typename: \"User\";\n          id: string;\n        } & { \" $fragmentRefs\": { UserFieldsFragment: UserFieldsFragment } };\n      };\n\n      type UnmaskedQuery = {\n        user: {\n          __typename: \"User\";\n          id: string;\n          age: number;\n        };\n      };\n\n      type Subscription = {\n        updatedUser: {\n          __typename: \"User\";\n          id: string;\n        } & { \" $fragmentRefs\": { UserFieldsFragment: UserFieldsFragment } };\n      };\n\n      type UnmaskedSubscription = {\n        updatedUser: {\n          __typename: \"User\";\n          id: string;\n          age: number;\n        };\n      };\n\n      interface Variables {\n        id: string;\n      }\n\n      const query: TypedDocumentNode<Query, Variables> = gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const subscription: TypedDocumentNode<Subscription, Variables> = gql`\n        subscription ($id: ID!) {\n          updatedUser(id: $id) {\n            id\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const observableQuery = client.watchQuery({\n        query,\n        variables: { id: \"1\" },\n      });\n\n      expectTypeOf(observableQuery).toMatchTypeOf<\n        ObservableQuery<Query, Variables>\n      >();\n      expectTypeOf(observableQuery).not.toMatchTypeOf<\n        ObservableQuery<UnmaskedQuery, Variables>\n      >();\n\n      observableQuery.subscribe({\n        next: (result) => {\n          if (result.dataState === \"complete\") {\n            expectTypeOf(result.data).toEqualTypeOf<Query>();\n          }\n\n          if (result.dataState === \"partial\") {\n            expectTypeOf(result.data).toEqualTypeOf<DeepPartial<Query>>();\n          }\n\n          if (result.dataState === \"streaming\") {\n            expectTypeOf(result.data).toEqualTypeOf<\n              DataValue.Streaming<Query>\n            >();\n          }\n\n          if (result.dataState === \"empty\") {\n            expectTypeOf(result.data).toEqualTypeOf<undefined>();\n          }\n        },\n      });\n\n      expectTypeOf(observableQuery.getCurrentResult()).toEqualTypeOf<\n        ObservableQuery.Result<Query>\n      >();\n\n      const fetchMoreResult = await observableQuery.fetchMore({\n        updateQuery: (previousData, { fetchMoreResult }) => {\n          expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n\n          expectTypeOf(fetchMoreResult).toEqualTypeOf<UnmaskedQuery>();\n\n          return {} as UnmaskedQuery;\n        },\n      });\n\n      expectTypeOf(fetchMoreResult.data).toEqualTypeOf<Query | undefined>();\n\n      const refetchResult = await observableQuery.refetch();\n\n      expectTypeOf(refetchResult.data).toEqualTypeOf<Query | undefined>();\n\n      const setVariablesResult = await observableQuery.setVariables({\n        id: \"2\",\n      });\n\n      expectTypeOf(setVariablesResult?.data).toEqualTypeOf<Query | undefined>();\n\n      const reobserveResult = await observableQuery.reobserve({\n        variables: { id: \"2\" },\n      });\n\n      expectTypeOf(reobserveResult.data).toEqualTypeOf<Query | undefined>();\n\n      observableQuery.updateQuery(\n        (_previousData, { complete, previousData }) => {\n          expectTypeOf(_previousData).toEqualTypeOf<\n            DeepPartial<UnmaskedQuery>\n          >();\n\n          if (complete) {\n            expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n          } else {\n            expectTypeOf(previousData).toEqualTypeOf<\n              DeepPartial<UnmaskedQuery> | undefined\n            >();\n          }\n        }\n      );\n\n      observableQuery.subscribeToMore({\n        document: subscription,\n        updateQuery(queryData, { subscriptionData, complete, previousData }) {\n          expectTypeOf(queryData).toEqualTypeOf<DeepPartial<UnmaskedQuery>>();\n\n          if (complete) {\n            expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n          } else {\n            expectTypeOf(previousData).toEqualTypeOf<\n              DeepPartial<UnmaskedQuery> | undefined\n            >();\n          }\n\n          expectTypeOf(\n            subscriptionData.data\n          ).toEqualTypeOf<UnmaskedSubscription>();\n        },\n      });\n    });\n    test(\"ApolloClient and ApolloCache methods with the same name should have compatible signatures\", function <TData, TVariables extends\n      OperationVariables>() {\n      // specific set of common methods\n      expectTypeOf<keyof ApolloClient & keyof ApolloCache>().toEqualTypeOf<\n        | \"readQuery\"\n        | \"readFragment\"\n        | \"writeQuery\"\n        | \"writeFragment\"\n        | \"watchFragment\"\n        | \"extract\"\n        | \"restore\"\n        | \"getMemoryInternals\"\n      >();\n      const client: ApolloClient = {} as any;\n      const cache: ApolloCache = {} as any;\n      type NonMaskingData = {\n        foo: string;\n        bar: {\n          baz: number;\n        };\n      };\n\n      // not testing `expectTypeOf...toEqualTypeOf` here, because these functions\n      // are not exactly equal - instead we use to more loose `satisfies` operator\n      // to test for assignability in both directions\n\n      client.readQuery<TData, TVariables> satisfies typeof cache.readQuery<\n        TData,\n        TVariables\n      >;\n      cache.readQuery<TData, TVariables> satisfies typeof client.readQuery<\n        TData,\n        TVariables\n      >;\n\n      client.readFragment<\n        TData,\n        TVariables\n      > satisfies typeof cache.readFragment<TData, TVariables>;\n      cache.readFragment<\n        TData,\n        TVariables\n      > satisfies typeof client.readFragment<TData, TVariables>;\n\n      client.writeQuery<TData, TVariables> satisfies typeof cache.writeQuery<\n        TData,\n        TVariables\n      >;\n      cache.writeQuery<TData, TVariables> satisfies typeof client.writeQuery<\n        TData,\n        TVariables\n      >;\n\n      client.writeFragment<\n        TData,\n        TVariables\n      > satisfies typeof cache.writeFragment<TData, TVariables>;\n      cache.writeFragment<\n        TData,\n        TVariables\n      > satisfies typeof client.writeFragment<TData, TVariables>;\n\n      // `watchFragment` on ApolloClient is masked, and not masked on ApolloCache so instead of the unresolved `TData` we have to use a specific type that won't be masked\n      cache.watchFragment<\n        NonMaskingData,\n        TVariables\n      > satisfies typeof client.watchFragment<NonMaskingData, TVariables>;\n      client.watchFragment<\n        NonMaskingData,\n        TVariables\n      > satisfies typeof cache.watchFragment<NonMaskingData, TVariables>;\n\n      client.extract satisfies typeof cache.extract;\n      cache.extract satisfies typeof client.extract;\n\n      client.restore satisfies typeof cache.restore;\n      cache.restore satisfies typeof client.restore;\n\n      // `getMemoryInternals` is different, that's okay\n    });\n  });\n});\n"
  },
  {
    "path": "src/__tests__/__snapshots__/ApolloClient.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`ApolloClient constructor will throw an error if cache is not passed in 1`] = `\n\"To initialize Apollo Client, you must specify a 'cache' property in the options object. \nFor more information, please visit: https://go.apollo.dev/c/docs\"\n`;\n\nexports[`ApolloClient constructor will throw an error if link is not passed in 1`] = `\n\"To initialize Apollo Client, you must specify a 'link' property in the options object. \nFor more information, please visit: https://go.apollo.dev/c/docs\"\n`;\n\nexports[`ApolloClient write then read will not use a default id getter if either _id or id is present when __typename is not also present 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"bar\": Object {\n      \"foo\": Object {\n        \"_id\": \"barfoo\",\n        \"k\": 12,\n        \"l\": 13,\n      },\n      \"i\": 10,\n      \"j\": 11,\n    },\n    \"foo\": Object {\n      \"bar\": Object {\n        \"__ref\": \"bar:foobar\",\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n    \"g\": 8,\n    \"h\": 9,\n  },\n  \"bar:foobar\": Object {\n    \"__typename\": \"bar\",\n    \"e\": 5,\n    \"f\": 6,\n    \"id\": \"foobar\",\n  },\n}\n`;\n\nexports[`ApolloClient write then read will not use a default id getter if id and _id are not present 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"bar\": Object {\n      \"__typename\": \"bar\",\n      \"foo\": Object {\n        \"__typename\": \"foo\",\n        \"k\": 12,\n        \"l\": 13,\n      },\n      \"i\": 10,\n      \"j\": 11,\n    },\n    \"foo\": Object {\n      \"__typename\": \"foo\",\n      \"bar\": Object {\n        \"__typename\": \"bar\",\n        \"e\": 5,\n        \"f\": 6,\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n    \"g\": 8,\n    \"h\": 9,\n  },\n}\n`;\n\nexports[`ApolloClient write then read will use a default id getter if __typename and _id are present 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"foo\": Object {\n      \"__typename\": \"foo\",\n      \"bar\": Object {\n        \"__ref\": \"bar:foobar\",\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n  },\n  \"bar:foobar\": Object {\n    \"__typename\": \"bar\",\n    \"_id\": \"foobar\",\n    \"e\": 5,\n    \"f\": 6,\n  },\n}\n`;\n\nexports[`ApolloClient write then read will use a default id getter if __typename and id are present 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"foo\": Object {\n      \"__typename\": \"foo\",\n      \"bar\": Object {\n        \"__ref\": \"bar:foobar\",\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n  },\n  \"bar:foobar\": Object {\n    \"__typename\": \"bar\",\n    \"e\": 5,\n    \"f\": 6,\n    \"id\": \"foobar\",\n  },\n}\n`;\n\nexports[`ApolloClient write then read will use a default id getter if one is not specified and __typename is present along with either _id or id 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"bar\": Object {\n      \"__typename\": \"bar\",\n      \"foo\": Object {\n        \"__ref\": \"foo:barfoo\",\n      },\n      \"i\": 10,\n      \"j\": 11,\n    },\n    \"foo\": Object {\n      \"__typename\": \"foo\",\n      \"bar\": Object {\n        \"__ref\": \"bar:foobar\",\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n    \"g\": 8,\n    \"h\": 9,\n  },\n  \"bar:foobar\": Object {\n    \"__typename\": \"bar\",\n    \"e\": 5,\n    \"f\": 6,\n    \"id\": \"foobar\",\n  },\n  \"foo:barfoo\": Object {\n    \"__typename\": \"foo\",\n    \"_id\": \"barfoo\",\n    \"k\": 12,\n    \"l\": 13,\n  },\n}\n`;\n\nexports[`ApolloClient write then read will write data locally which will then be read back 1`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"d\": 8,\n    \"e\": 9,\n    \"f\": 6,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"a\": 7,\n    \"b\": 2,\n    \"bar\": Object {\n      \"__ref\": \"bar\",\n    },\n    \"c\": 3,\n  },\n}\n`;\n\nexports[`ApolloClient write then read will write data to a specific id 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"foo\": Object {\n      \"__typename\": \"foo\",\n      \"bar\": Object {\n        \"__ref\": \"foobar\",\n      },\n      \"c\": 3,\n      \"d\": 4,\n    },\n  },\n  \"foobar\": Object {\n    \"__typename\": \"bar\",\n    \"e\": 5,\n    \"f\": 6,\n    \"key\": \"foobar\",\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment should warn when the data provided does not match the fragment shape 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"e\",\n      Object {\n        \"__typename\": \"Bar\",\n        \"i\": 10,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 1`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 7,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 2`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 3`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 4`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 5`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeFragment will write some deeply nested data into the store at any id 6`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeQuery should warn when the data provided does not match the query shape 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"description\",\n      Object {\n        \"__typename\": \"Todo\",\n        \"id\": \"1\",\n        \"name\": \"Todo 1\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`ApolloClient writeQuery will write some deeply nested data to the store 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"d\": Object {\n      \"__typename\": \"D\",\n      \"e\": 4,\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeQuery will write some deeply nested data to the store 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"d\": Object {\n      \"__typename\": \"D\",\n      \"h\": Object {\n        \"__typename\": \"H\",\n        \"i\": 7,\n      },\n    },\n  },\n}\n`;\n\nexports[`ApolloClient writeQuery will write some deeply nested data to the store 3`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": 1,\n    \"b\": 2,\n    \"c\": 3,\n    \"d\": Object {\n      \"__typename\": \"D\",\n      \"e\": 4,\n      \"f\": 5,\n      \"g\": 6,\n      \"h\": Object {\n        \"__typename\": \"H\",\n        \"i\": 7,\n        \"j\": 8,\n        \"k\": 9,\n      },\n    },\n  },\n}\n`;\n"
  },
  {
    "path": "src/__tests__/__snapshots__/client.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`@connection should run a query with the @connection directive and write the result to the store key defined in the directive 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"books:abc\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"name\": \"abcd\",\n      },\n    ],\n  },\n}\n`;\n\nexports[`@connection should run a query with the connection directive and filter arguments and write the result to the correct store key 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"books:abc({\\\\\"order\\\\\":\\\\\"popularity\\\\\"})\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"name\": \"abcd\",\n      },\n    ],\n  },\n}\n`;\n\nexports[`@connection should support cache field policies that filter key arguments 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"books:{\\\\\"order\\\\\":\\\\\"popularity\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"name\": \"abcd\",\n      },\n    ],\n  },\n}\n`;\n\nexports[`client should warn if server returns wrong data 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"description\",\n      Object {\n        \"__typename\": \"Todo\",\n        \"id\": \"1\",\n        \"name\": \"Todo 1\",\n        \"price\": 100,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n"
  },
  {
    "path": "src/__tests__/__snapshots__/exports.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`exports of public entry points @apollo/client 1`] = `\nArray [\n  \"ApolloCache\",\n  \"ApolloClient\",\n  \"ApolloLink\",\n  \"CombinedGraphQLErrors\",\n  \"CombinedProtocolErrors\",\n  \"DocumentTransform\",\n  \"HttpLink\",\n  \"InMemoryCache\",\n  \"LinkError\",\n  \"LocalStateError\",\n  \"MissingFieldError\",\n  \"NetworkStatus\",\n  \"Observable\",\n  \"ObservableQuery\",\n  \"ServerError\",\n  \"ServerParseError\",\n  \"UnconventionalError\",\n  \"build\",\n  \"checkFetcher\",\n  \"concat\",\n  \"createHttpLink\",\n  \"createSignalIfSupported\",\n  \"defaultDataIdFromObject\",\n  \"defaultPrinter\",\n  \"disableExperimentalFragmentVariables\",\n  \"disableFragmentWarnings\",\n  \"empty\",\n  \"enableExperimentalFragmentVariables\",\n  \"execute\",\n  \"fallbackHttpConfig\",\n  \"from\",\n  \"gql\",\n  \"isNetworkRequestSettled\",\n  \"isReference\",\n  \"makeVar\",\n  \"parseAndCheckHttpResponse\",\n  \"resetCaches\",\n  \"rewriteURIForGET\",\n  \"selectHttpOptionsAndBody\",\n  \"selectHttpOptionsAndBodyInternal\",\n  \"selectURI\",\n  \"setLogVerbosity\",\n  \"split\",\n  \"version\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/cache 1`] = `\nArray [\n  \"ApolloCache\",\n  \"EntityStore\",\n  \"InMemoryCache\",\n  \"MissingFieldError\",\n  \"Policies\",\n  \"cacheSlot\",\n  \"canonicalStringify\",\n  \"createFragmentRegistry\",\n  \"defaultDataIdFromObject\",\n  \"fieldNameFromStoreName\",\n  \"isReference\",\n  \"makeVar\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/core 1`] = `\nArray [\n  \"ApolloCache\",\n  \"ApolloClient\",\n  \"ApolloLink\",\n  \"CombinedGraphQLErrors\",\n  \"CombinedProtocolErrors\",\n  \"DocumentTransform\",\n  \"HttpLink\",\n  \"InMemoryCache\",\n  \"LinkError\",\n  \"LocalStateError\",\n  \"MissingFieldError\",\n  \"NetworkStatus\",\n  \"Observable\",\n  \"ObservableQuery\",\n  \"ServerError\",\n  \"ServerParseError\",\n  \"UnconventionalError\",\n  \"build\",\n  \"checkFetcher\",\n  \"concat\",\n  \"createHttpLink\",\n  \"createSignalIfSupported\",\n  \"defaultDataIdFromObject\",\n  \"defaultPrinter\",\n  \"disableExperimentalFragmentVariables\",\n  \"disableFragmentWarnings\",\n  \"empty\",\n  \"enableExperimentalFragmentVariables\",\n  \"execute\",\n  \"fallbackHttpConfig\",\n  \"from\",\n  \"gql\",\n  \"isNetworkRequestSettled\",\n  \"isReference\",\n  \"makeVar\",\n  \"parseAndCheckHttpResponse\",\n  \"resetCaches\",\n  \"rewriteURIForGET\",\n  \"selectHttpOptionsAndBody\",\n  \"selectHttpOptionsAndBodyInternal\",\n  \"selectURI\",\n  \"setLogVerbosity\",\n  \"split\",\n  \"version\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/dev 1`] = `\nArray [\n  \"loadDevMessages\",\n  \"loadErrorMessageHandler\",\n  \"loadErrorMessages\",\n  \"setErrorMessageHandler\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/errors 1`] = `\nArray [\n  \"CombinedGraphQLErrors\",\n  \"CombinedProtocolErrors\",\n  \"LinkError\",\n  \"LocalStateError\",\n  \"PROTOCOL_ERRORS_SYMBOL\",\n  \"ServerError\",\n  \"ServerParseError\",\n  \"UnconventionalError\",\n  \"graphQLResultHasProtocolErrors\",\n  \"isErrorLike\",\n  \"registerLinkError\",\n  \"toErrorLike\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/incremental 1`] = `\nArray [\n  \"Defer20220824Handler\",\n  \"GraphQL17Alpha2Handler\",\n  \"GraphQL17Alpha9Handler\",\n  \"NotImplementedHandler\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link 1`] = `\nArray [\n  \"ApolloLink\",\n  \"concat\",\n  \"empty\",\n  \"execute\",\n  \"from\",\n  \"split\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/batch 1`] = `\nArray [\n  \"BatchLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/batch-http 1`] = `\nArray [\n  \"BaseBatchHttpLink\",\n  \"BatchHttpLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/client-awareness 1`] = `\nArray [\n  \"ClientAwarenessLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/context 1`] = `\nArray [\n  \"SetContextLink\",\n  \"setContext\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/error 1`] = `\nArray [\n  \"ErrorLink\",\n  \"onError\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/http 1`] = `\nArray [\n  \"BaseHttpLink\",\n  \"HttpLink\",\n  \"checkFetcher\",\n  \"createHttpLink\",\n  \"createSignalIfSupported\",\n  \"defaultPrinter\",\n  \"fallbackHttpConfig\",\n  \"parseAndCheckHttpResponse\",\n  \"rewriteURIForGET\",\n  \"selectHttpOptionsAndBody\",\n  \"selectHttpOptionsAndBodyInternal\",\n  \"selectURI\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/persisted-queries 1`] = `\nArray [\n  \"PersistedQueryLink\",\n  \"VERSION\",\n  \"createPersistedQueryLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/remove-typename 1`] = `\nArray [\n  \"KEEP\",\n  \"RemoveTypenameFromVariablesLink\",\n  \"removeTypenameFromVariables\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/retry 1`] = `\nArray [\n  \"RetryLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/schema 1`] = `\nArray [\n  \"SchemaLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/subscriptions 1`] = `\nArray [\n  \"GraphQLWsLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/utils 1`] = `\nArray [\n  \"createOperation\",\n  \"filterOperationVariables\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/link/ws 1`] = `\nArray [\n  \"WebSocketLink\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/local-state 1`] = `\nArray [\n  \"LocalState\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/masking 1`] = `\nArray [\n  \"disableWarningsSlot\",\n  \"maskFragment\",\n  \"maskOperation\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/react 1`] = `\nArray [\n  \"ApolloProvider\",\n  \"createQueryPreloader\",\n  \"getApolloContext\",\n  \"reactCompilerVersion\",\n  \"skipToken\",\n  \"useApolloClient\",\n  \"useBackgroundQuery\",\n  \"useFragment\",\n  \"useLazyQuery\",\n  \"useLoadableQuery\",\n  \"useMutation\",\n  \"useQuery\",\n  \"useQueryRefHandlers\",\n  \"useReactiveVar\",\n  \"useReadQuery\",\n  \"useSubscription\",\n  \"useSuspenseFragment\",\n  \"useSuspenseQuery\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/react with conditions [react-server] 1`] = `\nArray [\n  \"ApolloProvider\",\n  \"createQueryPreloader\",\n  \"getApolloContext\",\n  \"useApolloClient\",\n  \"useBackgroundQuery\",\n  \"useFragment\",\n  \"useLazyQuery\",\n  \"useLoadableQuery\",\n  \"useMutation\",\n  \"useQuery\",\n  \"useQueryRefHandlers\",\n  \"useReactiveVar\",\n  \"useReadQuery\",\n  \"useSubscription\",\n  \"useSuspenseFragment\",\n  \"useSuspenseQuery\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/react/internal 1`] = `\nArray [\n  \"InternalQueryReference\",\n  \"assertWrappedQueryRef\",\n  \"getSuspenseCache\",\n  \"getWrappedPromise\",\n  \"unwrapQueryRef\",\n  \"updateWrappedQueryRef\",\n  \"wrapQueryRef\",\n  \"wrapperSymbol\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/react/internal/compiler-runtime 1`] = `\nArray [\n  \"c\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/react/ssr 1`] = `\nArray [\n  \"getDataFromTree\",\n  \"getMarkupFromTree\",\n  \"prerenderStatic\",\n  \"renderToStringWithData\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/testing 1`] = `\nArray [\n  \"MockLink\",\n  \"MockSubscriptionLink\",\n  \"realisticDelay\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/testing/internal 1`] = `\nArray [\n  \"ObservableStream\",\n  \"actAsync\",\n  \"addDelayToMocks\",\n  \"asyncIterableSubject\",\n  \"createClientWrapper\",\n  \"createMockWrapper\",\n  \"createOperationWithDefaultContext\",\n  \"enableFakeTimers\",\n  \"executeSchemaGraphQL17Alpha2\",\n  \"executeSchemaGraphQL17Alpha9\",\n  \"executeWithDefaultContext\",\n  \"friendListSchemaGraphQL17Alpha2\",\n  \"friendListSchemaGraphQL17Alpha9\",\n  \"markAsStreaming\",\n  \"mockDefer20220824\",\n  \"mockDeferStreamGraphQL17Alpha9\",\n  \"mockMultipartSubscriptionStream\",\n  \"promiseWithResolvers\",\n  \"renderAsync\",\n  \"renderHookAsync\",\n  \"resetApolloContext\",\n  \"setupMaskedVariablesCase\",\n  \"setupPaginatedCase\",\n  \"setupSimpleCase\",\n  \"setupVariablesCase\",\n  \"spyOnConsole\",\n  \"wait\",\n  \"withCleanup\",\n  \"withProdMode\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/testing/react 1`] = `\nArray [\n  \"MockedProvider\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities 1`] = `\nArray [\n  \"DocumentTransform\",\n  \"Observable\",\n  \"addTypenameToDocument\",\n  \"cacheSizes\",\n  \"canonicalStringify\",\n  \"concatPagination\",\n  \"getMainDefinition\",\n  \"isFormattedExecutionResult\",\n  \"isMutationOperation\",\n  \"isNetworkRequestInFlight\",\n  \"isNetworkRequestSettled\",\n  \"isQueryOperation\",\n  \"isReference\",\n  \"isSubscriptionOperation\",\n  \"offsetLimitPagination\",\n  \"print\",\n  \"relayStylePagination\",\n  \"stripTypename\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities/environment 1`] = `\nArray [\n  \"__DEV__\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities/internal 1`] = `\nArray [\n  \"AutoCleanedStrongCache\",\n  \"AutoCleanedWeakCache\",\n  \"DeepMerger\",\n  \"argumentsObjectFromField\",\n  \"bindCacheKey\",\n  \"canUseDOM\",\n  \"canonicalStringify\",\n  \"checkDocument\",\n  \"cloneDeep\",\n  \"combineLatestBatched\",\n  \"compact\",\n  \"createFragmentMap\",\n  \"createFulfilledPromise\",\n  \"createRejectedPromise\",\n  \"dealias\",\n  \"decoratePromise\",\n  \"equalByQuery\",\n  \"extensionsSymbol\",\n  \"filterMap\",\n  \"getApolloCacheMemoryInternals\",\n  \"getApolloClientMemoryInternals\",\n  \"getDefaultValues\",\n  \"getFragmentDefinition\",\n  \"getFragmentDefinitions\",\n  \"getFragmentFromSelection\",\n  \"getFragmentQueryDocument\",\n  \"getGraphQLErrorsFromResult\",\n  \"getInMemoryCacheMemoryInternals\",\n  \"getMainDefinition\",\n  \"getOperationDefinition\",\n  \"getOperationName\",\n  \"getQueryDefinition\",\n  \"getStoreKeyName\",\n  \"graphQLResultHasError\",\n  \"hasDirectives\",\n  \"hasForcedResolvers\",\n  \"isArray\",\n  \"isDocumentNode\",\n  \"isField\",\n  \"isNonEmptyArray\",\n  \"isNonNullObject\",\n  \"isPlainObject\",\n  \"makeReference\",\n  \"makeUniqueId\",\n  \"mapObservableFragmentMemoized\",\n  \"maybeDeepFreeze\",\n  \"mergeDeep\",\n  \"mergeDeepArray\",\n  \"mergeOptions\",\n  \"omitDeep\",\n  \"preventUnhandledRejection\",\n  \"registerGlobalCache\",\n  \"removeDirectivesFromDocument\",\n  \"removeMaskedFragmentSpreads\",\n  \"resultKeyNameFromField\",\n  \"shouldInclude\",\n  \"storeKeyNameFromField\",\n  \"streamInfoSymbol\",\n  \"stringifyForDisplay\",\n  \"toQueryResult\",\n  \"variablesUnknownSymbol\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities/internal/globals 1`] = `\nArray [\n  \"global\",\n  \"maybe\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities/internal/ponyfills 1`] = `\nArray [\n  \"FinalizationRegistry\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/utilities/invariant 1`] = `\nArray [\n  \"ApolloErrorMessageHandler\",\n  \"InvariantError\",\n  \"invariant\",\n  \"newInvariantError\",\n  \"setVerbosity\",\n]\n`;\n\nexports[`exports of public entry points @apollo/client/v4-migration 1`] = `Array []`;\n"
  },
  {
    "path": "src/__tests__/__snapshots__/mutationResults.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`mutation results should warn when the result fields don't match the query fields 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"description\",\n      Object {\n        \"__typename\": \"createTodo\",\n        \"id\": \"2\",\n        \"name\": \"Todo 2\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`mutation results should write results to cache according to errorPolicy 1`] = `Object {}`;\n\nexports[`mutation results should write results to cache according to errorPolicy 2`] = `\nObject {\n  \"Person:{\\\\\"name\\\\\":\\\\\"Jenn Creighton\\\\\"}\": Object {\n    \"__typename\": \"Person\",\n    \"name\": \"Jenn Creighton\",\n  },\n  \"ROOT_MUTATION\": Object {\n    \"__typename\": \"Mutation\",\n  },\n}\n`;\n\nexports[`mutation results should write results to cache according to errorPolicy 3`] = `\nObject {\n  \"Person:{\\\\\"name\\\\\":\\\\\"Ellen Shapiro\\\\\"}\": Object {\n    \"__typename\": \"Person\",\n    \"name\": \"Ellen Shapiro\",\n  },\n  \"Person:{\\\\\"name\\\\\":\\\\\"Jenn Creighton\\\\\"}\": Object {\n    \"__typename\": \"Person\",\n    \"name\": \"Jenn Creighton\",\n  },\n  \"ROOT_MUTATION\": Object {\n    \"__typename\": \"Mutation\",\n  },\n}\n`;\n"
  },
  {
    "path": "src/__tests__/client.ts",
    "content": "import { waitFor } from \"@testing-library/react\";\nimport type {\n  DocumentNode,\n  FormattedExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql\";\nimport { GraphQLError, Kind, visit } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { assign, cloneDeep } from \"lodash\";\nimport type { Subscription } from \"rxjs\";\nimport { Observable, of } from \"rxjs\";\n\nimport type {\n  FetchPolicy,\n  ObservableQuery,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport type {\n  NormalizedCacheObject,\n  PossibleTypesMap,\n  Reference,\n} from \"@apollo/client/cache\";\nimport {\n  createFragmentRegistry,\n  InMemoryCache,\n  makeVar,\n} from \"@apollo/client/cache\";\nimport {\n  CombinedGraphQLErrors,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport {\n  DocumentTransform,\n  offsetLimitPagination,\n} from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"client\", () => {\n  it(\"can allow passing in a link\", () => {\n    const link = ApolloLink.empty();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    expect(client.link).toBeInstanceOf(ApolloLink);\n  });\n\n  it('should throw an error if query option is missing or not wrapped with a \"gql\" tag', () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    expect(() => {\n      void client.query(\n        gql`\n          {\n            a\n          }\n        ` as any\n      );\n    }).toThrow(\n      \"query option is required. You must specify your GraphQL document in the query option.\"\n    );\n    expect(() => {\n      void client.query({ query: \"{ a }\" } as any);\n    }).toThrow('You must wrap the query string in a \"gql\" tag.');\n  });\n\n  it(\"should throw an error if mutation option is missing\", () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    expect(() =>\n      client.mutate({\n        query: gql`\n          {\n            a\n          }\n        `,\n      } as any)\n    ).toThrow(\n      \"The `mutation` option is required. Please provide a GraphQL document in the `mutation` option.\"\n    );\n  });\n\n  it(\"should allow for a single query to take place\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n            __typename\n          }\n          __typename\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n            __typename: \"Person\",\n          },\n        ],\n        __typename: \"People\",\n      },\n    };\n\n    await clientRoundtrip(query, { data });\n  });\n\n  it(\"should allow a single query with an apollo-link enabled network interface\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n            __typename\n          }\n          __typename\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n            __typename: \"Person\",\n          },\n        ],\n        __typename: \"People\",\n      },\n    };\n\n    const variables = { first: 1 };\n\n    const link = ApolloLink.from([new ApolloLink(() => of({ data }))]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query, variables });\n\n    expect(actualResult.data).toEqual(data);\n  });\n\n  it(\"should allow for a single query with complex default variables to take place\", async () => {\n    const query = gql`\n      query stuff(\n        $test: Input = { key1: [\"value\", \"value2\"], key2: { key3: 4 } }\n      ) {\n        allStuff(test: $test) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const result = {\n      allStuff: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n          {\n            name: \"Jabba The Hutt\",\n          },\n        ],\n      },\n    };\n\n    const variables = {\n      test: { key1: [\"value\", \"value2\"], key2: { key3: 4 } },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query, variables },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    {\n      const actualResult = await client.query({ query, variables });\n\n      expect(actualResult.data).toEqual(result);\n    }\n\n    {\n      const actualResult = await client.query({ query });\n\n      expect(actualResult.data).toEqual(result);\n    }\n  });\n\n  it(\"should allow for a single query with default values that get overridden with variables\", async () => {\n    const query = gql`\n      query people($first: Int = 1) {\n        allPeople(first: $first) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const variables = { first: 1 };\n    const override = { first: 2 };\n\n    const result = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const overriddenResult = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n          {\n            name: \"Jabba The Hutt\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query, variables },\n        result: { data: result },\n      },\n      {\n        request: { query, variables: override },\n        result: { data: overriddenResult },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    {\n      const actualResult = await client.query({ query, variables });\n\n      expect(actualResult.data).toEqual(result);\n    }\n\n    {\n      const actualResult = await client.query({ query });\n\n      expect(actualResult.data).toEqual(result);\n    }\n\n    {\n      const actualResult = await client.query({ query, variables: override });\n\n      expect(actualResult.data).toEqual(overriddenResult);\n    }\n  });\n\n  it(\"should allow fragments on root query\", async () => {\n    const query = gql`\n      query {\n        ...QueryFragment\n      }\n\n      fragment QueryFragment on Query {\n        records {\n          id\n          name\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const data = {\n      records: [\n        { id: 1, name: \"One\", __typename: \"Record\" },\n        { id: 2, name: \"Two\", __typename: \"Record\" },\n      ],\n      __typename: \"Query\",\n    };\n\n    return clientRoundtrip(query, { data }, null);\n  });\n\n  it(\"should allow fragments on root query with ifm\", async () => {\n    const query = gql`\n      query {\n        ...QueryFragment\n      }\n\n      fragment QueryFragment on Query {\n        records {\n          id\n          name\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const data = {\n      records: [\n        { id: 1, name: \"One\", __typename: \"Record\" },\n        { id: 2, name: \"Two\", __typename: \"Record\" },\n      ],\n      __typename: \"Query\",\n    };\n\n    await clientRoundtrip(query, { data }, null, {\n      Query: [\"Record\"],\n    });\n  });\n\n  it(\"should merge fragments on root query\", async () => {\n    // The fragment should be used after the selected fields for the query.\n    // Otherwise, the results aren't merged.\n    // see: https://github.com/apollographql/apollo-client/issues/1479\n    const query = gql`\n      query {\n        records {\n          id\n          __typename\n        }\n        ...QueryFragment\n      }\n\n      fragment QueryFragment on Query {\n        records {\n          name\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const data = {\n      records: [\n        { id: 1, name: \"One\", __typename: \"Record\" },\n        { id: 2, name: \"Two\", __typename: \"Record\" },\n      ],\n      __typename: \"Query\",\n    };\n\n    await clientRoundtrip(query, { data }, null, {\n      Query: [\"Record\"],\n    });\n  });\n\n  it(\"store can be rehydrated from the server\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data },\n      },\n    ]);\n\n    const initialState: any = {\n      data: {\n        ROOT_QUERY: {\n          'allPeople({\"first\":1})': {\n            people: [\n              {\n                name: \"Luke Skywalker\",\n              },\n            ],\n          },\n        },\n        optimistic: [],\n      },\n    };\n\n    const finalState = assign({}, initialState, {});\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache().restore(initialState.data),\n    });\n\n    const result = await client.query({ query });\n\n    expect(result.data).toEqual(data);\n    expect(finalState.data).toEqual((client.cache as InMemoryCache).extract());\n  });\n\n  it(\"store can be rehydrated from the server using the shadow method\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            __typename: \"Person\",\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data },\n      },\n    ]);\n\n    const initialState: any = {\n      data: {\n        ROOT_QUERY: {\n          'allPeople({\"first\":1})': {\n            people: [\n              {\n                __typename: \"Person\",\n                name: \"Luke Skywalker\",\n              },\n            ],\n          },\n        },\n        optimistic: [],\n      },\n    };\n\n    const finalState = Object.assign({}, initialState);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache().restore(initialState.data),\n    });\n\n    const result = await client.query({ query });\n\n    expect(result.data).toEqual(data);\n    expect(finalState.data).toEqual(client.extract());\n  });\n\n  it(\"stores shadow of restore returns the same result as accessing the method directly on the cache\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data },\n      },\n    ]);\n\n    const initialState: any = {\n      data: {\n        'ROOT_QUERY.allPeople({\"first\":\"1\"}).people.0': {\n          name: \"Luke Skywalker\",\n        },\n        'ROOT_QUERY.allPeople({\"first\":1})': {\n          people: [\n            {\n              type: \"id\",\n              generated: true,\n              id: 'ROOT_QUERY.allPeople({\"first\":\"1\"}).people.0',\n            },\n          ],\n        },\n        ROOT_QUERY: {\n          'allPeople({\"first\":1})': {\n            type: \"id\",\n            id: 'ROOT_QUERY.allPeople({\"first\":1})',\n            generated: true,\n          },\n        },\n        optimistic: [],\n      },\n    };\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache().restore(initialState.data),\n    });\n\n    expect(client.restore(initialState.data)).toEqual(\n      client.cache.restore(initialState.data)\n    );\n  });\n\n  it(\"should return errors correctly for a single query\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const errors: GraphQLError[] = [\n      new GraphQLError(\n        \"Syntax Error GraphQL request (8:9) Expected Name, found EOF\"\n      ),\n    ];\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { errors },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.query({ query })).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors })\n    );\n  });\n\n  it(\"should return GraphQL errors correctly for a single query with an apollo-link enabled network interface\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const errors: GraphQLError[] = [\n      new GraphQLError(\n        \"Syntax Error GraphQL request (8:9) Expected Name, found EOF\"\n      ),\n    ];\n\n    const link = ApolloLink.from([\n      new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.next({ data, errors });\n        });\n      }),\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.query({ query })).rejects.toEqual(\n      new CombinedGraphQLErrors({ data, errors })\n    );\n  });\n\n  it(\"should pass a network error correctly on a query with apollo-link network interface\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const networkError = new Error(\"Some kind of network error.\");\n\n    const link = ApolloLink.from([\n      new ApolloLink(() => {\n        return new Observable((_) => {\n          throw networkError;\n        });\n      }),\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.query({ query })).rejects.toThrow(networkError);\n  });\n\n  it(\"should not warn when receiving multiple results from apollo-link network interface\", () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = ApolloLink.from([\n      new ApolloLink(() => of({ data }, { data })),\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    return client.query({ query }).then((result) => {\n      expect(result.data).toEqual(data);\n    });\n  });\n\n  it(\"emits InvariantError when link chain completes without emitting a result\", async () => {\n    const link = new ApolloLink(() => {\n      return new Observable((observer) => {\n        setTimeout(() => observer.complete(), 10);\n      });\n    });\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n    const expectedError = new InvariantError(\n      \"The link chain completed without emitting a value. This is likely unintentional and should be updated to emit a value before completing.\"\n    );\n\n    await expect(\n      client.query({\n        query: gql`\n          query {\n            hello\n          }\n        `,\n      })\n    ).rejects.toThrow(expectedError);\n\n    await expect(\n      client.mutate({\n        mutation: gql`\n          mutation {\n            foo\n          }\n        `,\n      })\n    ).rejects.toThrow(expectedError);\n\n    const observable = client.watchQuery({\n      query: gql`\n        query {\n          hello\n        }\n      `,\n      notifyOnNetworkStatusChange: false,\n    });\n\n    const stream = new ObservableStream(observable);\n    const emittedValue: ObservableQuery.Result<unknown> = {\n      data: undefined,\n      dataState: \"empty\",\n      error: expectedError,\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    };\n\n    await expect(stream).toEmitTypedValue(emittedValue);\n\n    await expect(observable.refetch()).rejects.toThrow(expectedError);\n    await expect(stream).toEmitTypedValue(emittedValue);\n\n    await expect(observable.fetchMore({})).rejects.toThrow(expectedError);\n    await expect(stream).toEmitTypedValue(emittedValue);\n\n    await expect(observable.setVariables({ ignored: true })).rejects.toThrow(\n      expectedError\n    );\n    await expect(stream).toEmitTypedValue(emittedValue);\n\n    await expect(observable.reobserve()).rejects.toThrow(expectedError);\n    await expect(stream).toEmitTypedValue(emittedValue);\n  });\n\n  it(\"allows subscriptions to terminate without emitting results\", async () => {\n    const link = new ApolloLink(() => {\n      return new Observable((observer) => {\n        setTimeout(() => observer.complete(), 10);\n      });\n    });\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n    const subscription = client.subscribe({\n      query: gql`\n        subscription {\n          hello\n        }\n      `,\n    });\n\n    const stream = new ObservableStream(subscription);\n\n    await expect(stream).toComplete();\n  });\n\n  it.skip(\"should surface errors in observer.next as uncaught\", async () => {\n    const expectedError = new Error(\"this error should not reach the store\");\n    const listeners = process.listeners(\"uncaughtException\");\n    const oldHandler = listeners[listeners.length - 1];\n    const handleUncaught = (e: Error) => {\n      console.log(e);\n      process.removeListener(\"uncaughtException\", handleUncaught);\n      if (typeof oldHandler === \"function\")\n        process.addListener(\"uncaughtException\", oldHandler);\n      if (e !== expectedError) {\n        throw e;\n      }\n    };\n    process.removeListener(\"uncaughtException\", oldHandler);\n    process.addListener(\"uncaughtException\", handleUncaught);\n\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const handle = client.watchQuery({ query });\n\n    handle.subscribe({\n      next() {\n        throw expectedError;\n      },\n    });\n  });\n\n  it.skip(\"should surfaces errors in observer.error as uncaught\", async () => {\n    const expectedError = new Error(\"this error should not reach the store\");\n    const listeners = process.listeners(\"uncaughtException\");\n    const oldHandler = listeners[listeners.length - 1];\n    const handleUncaught = (e: Error) => {\n      process.removeListener(\"uncaughtException\", handleUncaught);\n      process.addListener(\"uncaughtException\", oldHandler);\n      if (e !== expectedError) {\n        throw e;\n      }\n    };\n    process.removeListener(\"uncaughtException\", oldHandler);\n    process.addListener(\"uncaughtException\", handleUncaught);\n\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: {},\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const handle = client.watchQuery({ query });\n    handle.subscribe({\n      next() {\n        throw new Error(\"did not expect next to be called\");\n      },\n      error() {\n        throw expectedError;\n      },\n    });\n  });\n\n  it(\"should allow for subscribing to a request\", async () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const handle = client.watchQuery({ query });\n    const stream = new ObservableStream(handle);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"should be able to transform queries\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const transformedQuery = gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n\n    const transformedResult = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        __typename: \"Author\",\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: transformedResult },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(transformedResult);\n  });\n\n  it(\"should be able to transform queries on network-only fetches\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const transformedQuery = gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n    const transformedResult = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        __typename: \"Author\",\n      },\n    };\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: transformedResult },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({\n      fetchPolicy: \"network-only\",\n      query,\n    });\n\n    expect(actualResult.data).toEqual(transformedResult);\n  });\n\n  it(\"removes @client fields from the query before it reaches the link\", async () => {\n    // Silence warning for unconfigured local resolvers\n    using _ = spyOnConsole(\"warn\");\n    const result: { current: ApolloLink.Operation | undefined } = {\n      current: undefined,\n    };\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n          isInCollection @client\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n\n    const link = new ApolloLink((operation) => {\n      result.current = operation;\n\n      return of({\n        data: {\n          author: {\n            firstName: \"John\",\n            lastName: \"Smith\",\n            __typename: \"Author\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    await client.query({ query });\n\n    expect(result.current!.query).toMatchDocument(transformedQuery);\n  });\n\n  it(\"should handle named fragments on mutations\", async () => {\n    const mutation = gql`\n      mutation {\n        starAuthor(id: 12) {\n          author {\n            __typename\n            ...authorDetails\n          }\n        }\n      }\n\n      fragment authorDetails on Author {\n        firstName\n        lastName\n      }\n    `;\n    const result = {\n      starAuthor: {\n        author: {\n          __typename: \"Author\",\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n    };\n    const link = new MockLink([\n      {\n        request: { query: mutation },\n        result: { data: result },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.mutate({ mutation });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should be able to handle named fragments on network-only queries\", async () => {\n    const query = gql`\n      fragment authorDetails on Author {\n        firstName\n        lastName\n      }\n\n      query {\n        author {\n          __typename\n          ...authorDetails\n        }\n      }\n    `;\n    const result = {\n      author: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({\n      fetchPolicy: \"network-only\",\n      query,\n    });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should be able to handle named fragments with multiple fragments\", async () => {\n    const query = gql`\n      query {\n        author {\n          __typename\n          ...authorDetails\n          ...moreDetails\n        }\n      }\n\n      fragment authorDetails on Author {\n        firstName\n        lastName\n      }\n\n      fragment moreDetails on Author {\n        address\n      }\n    `;\n    const result = {\n      author: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n        address: \"1337 10th St.\",\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: result },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should be able to handle named fragments\", async () => {\n    const query = gql`\n      query {\n        author {\n          __typename\n          ...authorDetails\n        }\n      }\n\n      fragment authorDetails on Author {\n        firstName\n        lastName\n      }\n    `;\n    const result = {\n      author: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: result },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should be able to handle inlined fragments on an Interface type\", async () => {\n    const query = gql`\n      query items {\n        items {\n          ...ItemFragment\n          __typename\n        }\n      }\n\n      fragment ItemFragment on Item {\n        id\n        __typename\n        ... on ColorItem {\n          color\n          __typename\n        }\n      }\n    `;\n    const result = {\n      items: [\n        {\n          __typename: \"ColorItem\",\n          id: \"27tlpoPeXm6odAxj3paGQP\",\n          color: \"red\",\n        },\n        {\n          __typename: \"MonochromeItem\",\n          id: \"1t3iFLsHBm4c4RjOMdMgOO\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: result },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        possibleTypes: {\n          Item: [\"ColorItem\", \"MonochromeItem\"],\n        },\n      }),\n    });\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should be able to handle inlined fragments on an Interface type with introspection fragment matcher\", async () => {\n    const query = gql`\n      query items {\n        items {\n          ...ItemFragment\n          __typename\n        }\n      }\n\n      fragment ItemFragment on Item {\n        id\n        ... on ColorItem {\n          color\n          __typename\n        }\n        __typename\n      }\n    `;\n    const result = {\n      items: [\n        {\n          __typename: \"ColorItem\",\n          id: \"27tlpoPeXm6odAxj3paGQP\",\n          color: \"red\",\n        },\n        {\n          __typename: \"MonochromeItem\",\n          id: \"1t3iFLsHBm4c4RjOMdMgOO\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        possibleTypes: {\n          Item: [\"ColorItem\", \"MonochromeItem\"],\n        },\n      }),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should call updateQueries and update after mutation on query with inlined fragments on an Interface type\", async () => {\n    const query = gql`\n      query items {\n        items {\n          ...ItemFragment\n          __typename\n        }\n      }\n\n      fragment ItemFragment on Item {\n        id\n        ... on ColorItem {\n          color\n          __typename\n        }\n        __typename\n      }\n    `;\n    const result = {\n      items: [\n        {\n          __typename: \"ColorItem\",\n          id: \"27tlpoPeXm6odAxj3paGQP\",\n          color: \"red\",\n        },\n        {\n          __typename: \"MonochromeItem\",\n          id: \"1t3iFLsHBm4c4RjOMdMgOO\",\n        },\n      ],\n    };\n\n    const mutation = gql`\n      mutation myMutationName {\n        fortuneCookie\n      }\n    `;\n    const mutationResult = {\n      fortuneCookie: \"The waiter spit in your food\",\n    };\n\n    const link = new MockLink(\n      [\n        {\n          request: { query },\n          result: { data: result },\n        },\n        {\n          request: { query: mutation },\n          result: { data: mutationResult },\n        },\n      ],\n      { defaultOptions: { delay: 0 } }\n    );\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        possibleTypes: {\n          Item: [\"ColorItem\", \"MonochromeItem\"],\n        },\n      }),\n    });\n\n    const queryUpdater = jest.fn((prev) => prev);\n    const updateQueries = {\n      items: queryUpdater,\n    };\n\n    const updateSpy = jest.fn();\n\n    const obs = client.watchQuery({ query });\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitNext();\n    await client.mutate({ mutation, updateQueries, update: updateSpy });\n\n    expect(queryUpdater).toHaveBeenCalled();\n    expect(updateSpy).toHaveBeenCalled();\n  });\n\n  it(\"should send operationName along with the query to the server\", () => {\n    const query = gql`\n      query myQueryName {\n        fortuneCookie\n      }\n    `;\n    const data = {\n      fortuneCookie: \"The waiter spit in your food\",\n    };\n    const link = ApolloLink.from([\n      new ApolloLink((operation) => {\n        expect(operation.operationName).toBe(\"myQueryName\");\n        return of({ data });\n      }),\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    return client.query({ query }).then((actualResult) => {\n      expect(actualResult.data).toEqual(data);\n    });\n  });\n\n  it(\"should send operationName along with the mutation to the server\", () => {\n    const mutation = gql`\n      mutation myMutationName {\n        fortuneCookie\n      }\n    `;\n    const data = {\n      fortuneCookie: \"The waiter spit in your food\",\n    };\n    const link = ApolloLink.from([\n      new ApolloLink((operation) => {\n        expect(operation.operationName).toBe(\"myMutationName\");\n        return of({ data });\n      }),\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    return client.mutate({ mutation }).then((actualResult) => {\n      expect(actualResult.data).toEqual(data);\n    });\n  });\n\n  it(\"does not deduplicate queries if option is set to false\", async () => {\n    const queryDoc = gql`\n      query {\n        author {\n          name\n        }\n      }\n    `;\n    const data = {\n      author: {\n        name: \"Jonas\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: \"Dhaivat\",\n      },\n    };\n\n    // we have two responses for identical queries, and both should be requested.\n    // the second one should make it through to the network interface.\n    const link = new MockLink([\n      {\n        request: { query: queryDoc },\n        result: { data },\n        delay: 10,\n      },\n      {\n        request: { query: queryDoc },\n        result: { data: data2 },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      queryDeduplication: false,\n    });\n\n    const q1 = client.query({ query: queryDoc });\n    const q2 = client.query({ query: queryDoc });\n\n    // if deduplication happened, result2.data will equal data.\n    const [result1, result2] = await Promise.all([q1, q2]);\n\n    expect(result1.data).toEqual(data);\n    expect(result2.data).toEqual(data2);\n  });\n\n  it(\"deduplicates queries by default\", async () => {\n    const queryDoc = gql`\n      query {\n        author {\n          name\n        }\n      }\n    `;\n    const data = {\n      author: {\n        name: \"Jonas\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: \"Dhaivat\",\n      },\n    };\n\n    // we have two responses for identical queries, but only the first should be requested.\n    // the second one should never make it through to the network interface.\n    const link = new MockLink([\n      {\n        request: { query: queryDoc },\n        result: { data },\n        delay: 10,\n      },\n      {\n        request: { query: queryDoc },\n        result: { data: data2 },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const q1 = client.query({ query: queryDoc });\n    const q2 = client.query({ query: queryDoc });\n\n    // if deduplication didn't happen, result.data will equal data2.\n    const [result1, result2] = await Promise.all([q1, q2]);\n\n    expect(result1.data).toEqual(result2.data);\n  });\n\n  it(\"deduplicates queries if query context.queryDeduplication is set to true\", () => {\n    const queryDoc = gql`\n      query {\n        author {\n          name\n        }\n      }\n    `;\n    const data = {\n      author: {\n        name: \"Jonas\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: \"Dhaivat\",\n      },\n    };\n\n    // we have two responses for identical queries, but only the first should be requested.\n    // the second one should never make it through to the network interface.\n    const link = new MockLink([\n      {\n        request: { query: queryDoc },\n        result: { data },\n        delay: 10,\n      },\n      {\n        request: { query: queryDoc },\n        result: { data: data2 },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      queryDeduplication: false,\n    });\n\n    // Both queries need to be deduplicated, otherwise only one gets tracked\n    const q1 = client.query({\n      query: queryDoc,\n      context: { queryDeduplication: true },\n    });\n    const q2 = client.query({\n      query: queryDoc,\n      context: { queryDeduplication: true },\n    });\n\n    // if deduplication happened, result2.data will equal data.\n    return Promise.all([q1, q2]).then(([result1, result2]) => {\n      expect(result1.data).toEqual(data);\n      expect(result2.data).toEqual(data);\n    });\n  });\n\n  it(\"does not deduplicate queries if query context.queryDeduplication is set to false\", () => {\n    const queryDoc = gql`\n      query {\n        author {\n          name\n        }\n      }\n    `;\n    const data = {\n      author: {\n        name: \"Jonas\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: \"Dhaivat\",\n      },\n    };\n\n    // we have two responses for identical queries, and both should be requested.\n    // the second one should make it through to the network interface.\n    const link = new MockLink([\n      {\n        request: { query: queryDoc },\n        result: { data },\n        delay: 10,\n      },\n      {\n        request: { query: queryDoc },\n        result: { data: data2 },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    // The first query gets tracked in the dedup logic, the second one ignores it and runs anyways\n    const q1 = client.query({ query: queryDoc });\n    const q2 = client.query({\n      query: queryDoc,\n      context: { queryDeduplication: false },\n    });\n\n    // if deduplication happened, result2.data will equal data.\n    return Promise.all([q1, q2]).then(([result1, result2]) => {\n      expect(result1.data).toEqual(data);\n      expect(result2.data).toEqual(data2);\n    });\n  });\n\n  // TODO: This is a bit of an odd test because its half testing that\n  // deduplication kicks in, but its also testing some of the behavior of the\n  // observable itself. With the move to RxJS, the unsubscribe cleanup function\n  // is called with `complete` which means it might be called synchronously\n  // (hence why the `complete` needs to be wrapped in setTimeout for this test).\n  it(\"unsubscribes from deduplicated observables only once\", async () => {\n    const document: DocumentNode = gql`\n      query test1($x: String) {\n        test(x: $x)\n      }\n    `;\n\n    const variables1 = { x: \"Hello World\" };\n    const variables2 = { x: \"Hello World\" };\n\n    let unsubscribeCount = 0;\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          setTimeout(() => observer.complete());\n          return () => {\n            unsubscribeCount++;\n          };\n        });\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    const sub1 = client\n      .watchQuery({\n        query: document,\n        variables: variables1,\n      })\n      .subscribe({});\n\n    const sub2 = client\n      .watchQuery({\n        query: document,\n        variables: variables2,\n      })\n      .subscribe({});\n\n    sub1.unsubscribe();\n    // cleanup happens async\n    expect(unsubscribeCount).toBe(0);\n\n    sub2.unsubscribe();\n\n    await wait(0);\n    expect(unsubscribeCount).toBe(1);\n  });\n\n  describe(\"deprecated options\", () => {\n    const query = gql`\n      query people {\n        name\n      }\n    `;\n\n    it(\"errors when returnPartialData is used on query\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n      expect(() => {\n        void client.query({\n          query,\n          returnPartialData: true,\n        } as ApolloClient.QueryOptions);\n      }).toThrow(/returnPartialData/);\n    });\n\n    it(\"errors when returnPartialData is used on watchQuery\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n      expect(() => {\n        void client.query({\n          query,\n          returnPartialData: true,\n        } as ApolloClient.QueryOptions);\n      }).toThrow(/returnPartialData/);\n    });\n  });\n\n  describe(\"accepts dataIdFromObject option\", () => {\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            id\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      allPeople: {\n        people: [\n          {\n            id: \"1\",\n            name: \"Luke Skywalker\",\n          },\n        ],\n      },\n    };\n\n    it(\"for internal store\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n\n        cache: new InMemoryCache({\n          dataIdFromObject: (obj: any) => obj.id,\n        }),\n      });\n\n      const result = await client.query({ query });\n\n      expect(result.data).toEqual(data);\n      expect((client.cache as InMemoryCache).extract()[\"1\"]).toEqual({\n        id: \"1\",\n        name: \"Luke Skywalker\",\n      });\n    });\n  });\n\n  describe(\"cache-and-network fetchPolicy\", () => {\n    const query = gql`\n      query number {\n        myNumber {\n          n\n        }\n      }\n    `;\n\n    const initialData = {\n      myNumber: {\n        n: 1,\n      },\n    };\n    const networkFetch = {\n      myNumber: {\n        n: 2,\n      },\n    };\n\n    const cacheAndNetworkError =\n      \"The cache-and-network fetchPolicy does not work with client.query, because \" +\n      \"client.query can only return a single result. Please use client.watchQuery \" +\n      \"to receive multiple results from the cache and the network, or consider \" +\n      \"using a different fetchPolicy, such as cache-first or network-only.\";\n\n    // Test that cache-and-network can only be used on watchQuery, not query.\n    it(\"warns when used with client.query\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      expect(() => {\n        void client.query({\n          query,\n          fetchPolicy: \"cache-and-network\" as FetchPolicy,\n        });\n      }).toThrow(new Error(cacheAndNetworkError));\n    });\n\n    it(\"warns when used with client.query with defaultOptions\", () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          query: {\n            fetchPolicy: \"cache-and-network\" as FetchPolicy,\n          },\n        },\n      });\n\n      expect(\n        () =>\n          void client.query({\n            query,\n            // This undefined value should be ignored in favor of\n            // defaultOptions.query.fetchPolicy.\n            fetchPolicy: void 0,\n          })\n      ).toThrow(new Error(cacheAndNetworkError));\n    });\n\n    it(\"fetches from cache first, then network\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: networkFetch },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({ query, data: initialData });\n\n      const obs = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n      });\n\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: initialData,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: networkFetch,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does not fail if cache entry is not present\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: networkFetch },\n        },\n      ]);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const obs = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n      });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: networkFetch,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"fails if network request fails\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          error: new Error(\"Oops\"),\n        },\n      ]);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const obs = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n      });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: new Error(\"Oops\"),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"fetches from cache first, then network and does not have an unhandled error\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { errors: [{ message: \"network failure\" }] },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      client.writeQuery({ query, data: initialData });\n\n      const obs = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n      });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        loading: true,\n        data: initialData,\n        dataState: \"complete\",\n        networkStatus: 1,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: initialData,\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({\n          errors: [{ message: \"network failure\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"standby queries\", () => {\n    it(\"are not watching the store or notifying on updates\", async () => {\n      const query = gql`\n        {\n          test\n        }\n      `;\n      const data = { test: \"ok\" };\n      const data2 = { test: \"not ok\" };\n\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n      ]);\n\n      const client = new ApolloClient({ link, cache: new InMemoryCache() });\n      const obs = client.watchQuery({ query, fetchPolicy: \"cache-first\" });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        obs.reobserve({ query, fetchPolicy: \"standby\" })\n      ).resolves.toStrictEqualTyped({ data: undefined });\n      // this write should be completely ignored by the standby query\n      client.writeQuery({ query, data: data2 });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"return the current result when coming out of standby\", async () => {\n      const query = gql`\n        {\n          test\n        }\n      `;\n      const data = { test: \"ok\" };\n      const data2 = { test: \"not ok\" };\n\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n      ]);\n\n      const client = new ApolloClient({ link, cache: new InMemoryCache() });\n      const obs = client.watchQuery({ query, fetchPolicy: \"cache-first\" });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        obs.reobserve({ query, fetchPolicy: \"standby\" })\n      ).resolves.toStrictEqualTyped({ data: undefined });\n      // this write should be completely ignored by the standby query\n      client.writeQuery({ query, data: data2 });\n      setTimeout(() => {\n        void obs.reobserve({ query, fetchPolicy: \"cache-first\" });\n      }, 10);\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"network-only fetchPolicy\", () => {\n    const query = gql`\n      query number {\n        myNumber {\n          n\n        }\n      }\n    `;\n\n    const firstFetch = {\n      myNumber: {\n        n: 1,\n      },\n    };\n    const secondFetch = {\n      myNumber: {\n        n: 2,\n      },\n    };\n\n    function makeLink() {\n      return new MockLink([\n        {\n          request: { query },\n          result: { data: firstFetch },\n        },\n        {\n          request: { query },\n          result: { data: secondFetch },\n        },\n      ]);\n    }\n\n    it(\"forces the query to rerun\", async () => {\n      const client = new ApolloClient({\n        link: makeLink(),\n        cache: new InMemoryCache(),\n      });\n\n      // Run a query first to initialize the store\n      await client.query({ query });\n      // then query for real\n      const result = await client.query({ query, fetchPolicy: \"network-only\" });\n\n      expect(result.data).toEqual({ myNumber: { n: 2 } });\n    });\n\n    it(\"can be disabled with ssrMode\", async () => {\n      const client = new ApolloClient({\n        link: makeLink(),\n        ssrMode: true,\n        cache: new InMemoryCache(),\n      });\n\n      const options: ApolloClient.QueryOptions = {\n        query,\n        fetchPolicy: \"network-only\",\n      };\n\n      // Run a query first to initialize the store\n      await client.query({ query });\n      // then query for real\n      const result = await client.query(options);\n\n      expect(result.data).toEqual({ myNumber: { n: 1 } });\n      // Test that options weren't mutated, issue #339\n      expect(options).toEqual({\n        query,\n        fetchPolicy: \"network-only\",\n      });\n    });\n\n    it(\"can temporarily be disabled with ssrForceFetchDelay\", async () => {\n      const client = new ApolloClient({\n        link: makeLink(),\n        ssrForceFetchDelay: 100,\n        cache: new InMemoryCache(),\n      });\n\n      // Run a query first to initialize the store\n      await client.query({ query });\n      // then query for real\n      {\n        const result = await client.query({\n          query,\n          fetchPolicy: \"network-only\",\n        });\n\n        expect(result.data).toEqual({ myNumber: { n: 1 } });\n      }\n\n      await wait(100);\n\n      const result = await client.query({ query, fetchPolicy: \"network-only\" });\n\n      expect(result.data).toEqual({ myNumber: { n: 2 } });\n    });\n  });\n\n  it(\"should pass a network error correctly on a mutation\", async () => {\n    const mutation = gql`\n      mutation {\n        person {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const data = {\n      person: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const networkError = new Error(\"Some kind of network error.\");\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data },\n          error: networkError,\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.mutate({ mutation })).rejects.toThrow(networkError);\n  });\n\n  it(\"should pass a GraphQL error correctly on a mutation\", async () => {\n    const mutation = gql`\n      mutation {\n        newPerson {\n          person {\n            firstName\n            lastName\n          }\n        }\n      }\n    `;\n    const data = {\n      person: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const errors = [new Error(\"Some kind of GraphQL error.\")];\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data, errors },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.mutate({ mutation })).rejects.toEqual(\n      new CombinedGraphQLErrors({ data, errors })\n    );\n  });\n\n  it(\"should allow errors to be returned from a mutation\", async () => {\n    const mutation = gql`\n      mutation {\n        newPerson {\n          person {\n            firstName\n            lastName\n          }\n        }\n      }\n    `;\n    const data = {\n      newPerson: {\n        person: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n    };\n    const errors = [{ message: \"Some kind of GraphQL error.\" }];\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: {\n            errors,\n            data,\n          },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.mutate({ mutation, errorPolicy: \"all\" })\n    ).resolves.toStrictEqualTyped({\n      data,\n      error: new CombinedGraphQLErrors({ data, errors }),\n    });\n  });\n\n  it(\"should strip errors on a mutation if ignored\", async () => {\n    const mutation = gql`\n      mutation {\n        newPerson {\n          person {\n            firstName\n            lastName\n          }\n        }\n      }\n    `;\n    const data = {\n      newPerson: {\n        person: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n    };\n    const errors = [new Error(\"Some kind of GraphQL error.\")];\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data, errors },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.mutate({ mutation, errorPolicy: \"ignore\" })\n    ).resolves.toStrictEqualTyped({ data });\n  });\n\n  it(\"should rollback optimistic after mutation got a GraphQL error\", async () => {\n    const mutation = gql`\n      mutation {\n        newPerson {\n          person {\n            firstName\n            lastName\n          }\n        }\n      }\n    `;\n    const data = {\n      newPerson: {\n        person: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n    };\n    const errors = [new Error(\"Some kind of GraphQL error.\")];\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data, errors },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n    const mutatePromise = client.mutate({\n      mutation,\n      optimisticResponse: {\n        newPerson: {\n          person: {\n            firstName: \"John*\",\n            lastName: \"Smith*\",\n          },\n        },\n      },\n    });\n\n    {\n      const { data, optimisticData } = client.cache as any;\n      expect(optimisticData).not.toBe(data);\n      expect(optimisticData.parent).toBe(data.stump);\n      expect(optimisticData.parent.parent).toBe(data);\n    }\n\n    await expect(mutatePromise).rejects.toThrow();\n\n    {\n      const { data, optimisticData } = client.cache as any;\n\n      expect(optimisticData).toBe(data.stump);\n    }\n  });\n\n  it(\"has a clearStore method which calls QueryManager\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    // @ts-ignore\n    const spy = jest.spyOn(client.queryManager, \"clearStore\");\n    await client.clearStore();\n    expect(spy).toHaveBeenCalled();\n  });\n\n  it(\"has an onClearStore method which takes a callback to be called after clearStore\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    const onClearStore = jest.fn();\n    client.onClearStore(onClearStore);\n\n    await client.clearStore();\n\n    expect(onClearStore).toHaveBeenCalled();\n  });\n\n  it(\"onClearStore returns a method that unsubscribes the callback\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    const onClearStore = jest.fn();\n    const unsubscribe = client.onClearStore(onClearStore);\n\n    unsubscribe();\n\n    await client.clearStore();\n    expect(onClearStore).not.toHaveBeenCalled();\n  });\n\n  it(\"has a resetStore method which calls QueryManager\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    // @ts-ignore\n    const spy = jest.spyOn(client.queryManager, \"clearStore\");\n    await client.resetStore();\n    expect(spy).toHaveBeenCalled();\n  });\n\n  it(\"has an onResetStore method which takes a callback to be called after resetStore\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    const onResetStore = jest.fn();\n    client.onResetStore(onResetStore);\n\n    await client.resetStore();\n\n    expect(onResetStore).toHaveBeenCalled();\n  });\n\n  it(\"onResetStore returns a method that unsubscribes the callback\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    const onResetStore = jest.fn();\n    const unsubscribe = client.onResetStore(onResetStore);\n\n    unsubscribe();\n\n    await client.resetStore();\n    expect(onResetStore).not.toHaveBeenCalled();\n  });\n\n  it(\"resetStore waits until all onResetStore callbacks are called\", async () => {\n    const delay = (time: number) => new Promise((r) => setTimeout(r, time));\n\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    let count = 0;\n    const onResetStoreOne = jest.fn(async () => {\n      expect(count).toEqual(0);\n      await delay(10).then(() => count++);\n      expect(count).toEqual(1);\n    });\n\n    const onResetStoreTwo = jest.fn(async () => {\n      expect(count).toEqual(0);\n      await delay(11).then(() => count++);\n      expect(count).toEqual(2);\n    });\n\n    client.onResetStore(onResetStoreOne);\n    client.onResetStore(onResetStoreTwo);\n\n    expect(count).toEqual(0);\n    await client.resetStore();\n    expect(count).toEqual(2);\n  });\n\n  it(\"invokes onResetStore callbacks before notifying queries during resetStore call\", async () => {\n    const delay = (time: number) => new Promise((r) => setTimeout(r, time));\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const data = {\n      author: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const data2 = {\n      author: {\n        __typename: \"Author\",\n        firstName: \"Joe\",\n        lastName: \"Joe\",\n      },\n    };\n\n    const link = ApolloLink.from([\n      new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            observer.next({ data });\n            observer.complete();\n            return;\n          })\n      ),\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    let count = 0;\n    const onResetStoreOne = jest.fn(async () => {\n      expect(count).toEqual(0);\n      await delay(10).then(() => count++);\n      expect(count).toEqual(1);\n    });\n\n    const onResetStoreTwo = jest.fn(async () => {\n      expect(count).toEqual(0);\n      await delay(11).then(() => count++);\n      expect(count).toEqual(2);\n      expect(client.readQuery({ query })).toBe(null);\n      client.cache.writeQuery({ query, data: data2 });\n    });\n\n    client.onResetStore(onResetStoreOne);\n    client.onResetStore(onResetStoreTwo);\n\n    const observable = client.watchQuery<any>({\n      query,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n\n    expect(count).toBe(0);\n    await client.resetStore();\n    expect(count).toBe(2);\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream).toEmitNext();\n\n    expect(onResetStoreOne).toHaveBeenCalled();\n  });\n\n  it(\"has a refetchObservableQueries method which calls QueryManager\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    // @ts-ignore\n    const spy = jest.spyOn(client.queryManager, \"refetchObservableQueries\");\n    await client.refetchObservableQueries();\n    expect(spy).toHaveBeenCalled();\n  });\n\n  it(\"has a refetchQueries method which calls QueryManager\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    const spy = jest.spyOn(client[\"queryManager\"], \"refetchQueries\");\n    spy.mockImplementation(() => new Map());\n\n    const options = { include: [\"Author1\"] };\n    await client.refetchQueries(options);\n\n    expect(spy).toHaveBeenCalledWith(options);\n    spy.mockRestore();\n  });\n\n  // See https://github.com/apollographql/apollo-client/issues/10238\n  it(\"does not call QueryManager.refetchQueries for mutations with no-cache policy\", async () => {\n    const mutation = gql`\n      mutation {\n        noop\n      }\n    `;\n    const link = new MockLink([\n      {\n        request: { query: mutation },\n        result: { data: { noop: false } },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const spy = jest.spyOn(client[\"queryManager\"], \"refetchQueries\");\n    spy.mockImplementation(() => new Map());\n\n    await client.mutate({\n      mutation,\n      fetchPolicy: \"no-cache\",\n    });\n\n    expect(spy).not.toHaveBeenCalled();\n    spy.mockRestore();\n  });\n\n  it(\"has a getObservableQueries method which calls QueryManager\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    // @ts-ignore\n    const spy = jest.spyOn(client.queryManager, \"getObservableQueries\");\n    await client.getObservableQueries();\n    expect(spy).toHaveBeenCalled();\n  });\n\n  it(\"should propagate errors from network interface to observers\", async () => {\n    const link = ApolloLink.from([\n      new ApolloLink(\n        () =>\n          new Observable((x) => {\n            x.error(new Error(\"Uh oh!\"));\n            return;\n          })\n      ),\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const handle = client.watchQuery({\n      query: gql`\n        query {\n          a\n          b\n          c\n        }\n      `,\n    });\n\n    const stream = new ObservableStream(handle);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new Error(\"Uh oh!\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n  });\n\n  it(\"should be able to refetch after there was a network error\", async () => {\n    const query: DocumentNode = gql`\n      query somethingelse {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n    const dataTwo = { allPeople: { people: [{ name: \"Princess Leia\" }] } };\n    const link = new MockLink([\n      { request: { query }, result: { data } },\n      { request: { query }, error: new Error(\"This is an error!\") },\n      { request: { query }, result: { data: dataTwo } },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    let stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data,\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await wait(0);\n    await expect(observable.refetch()).rejects.toThrow();\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      data,\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      error: new Error(\"This is an error!\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    });\n\n    stream.unsubscribe();\n\n    const lastError = observable.getCurrentResult().error;\n    expect(lastError).toBeInstanceOf(Error);\n    expect(lastError).toEqual(new Error(\"This is an error!\"));\n\n    stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data,\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await wait(0);\n    await expect(observable.refetch()).resolves.toBeTruthy();\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      data,\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: dataTwo,\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"should throw a GraphQL error\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const errors: GraphQLError[] = [\n      new GraphQLError('Cannot query field \"foo\" on type \"Post\".'),\n    ];\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { errors },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.query({ query })).rejects.toThrow(\n      'Cannot query field \"foo\" on type \"Post\".'\n    );\n  });\n\n  it(\"rejects network errors\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const error = new Error(\"Oops\");\n    const link = new MockLink([\n      {\n        request: { query },\n        error,\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(client.query({ query })).rejects.toThrow(error);\n  });\n\n  it(\"resolves partial data and GraphQL errors when errorPolicy is 'all'\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const errors: GraphQLFormattedError[] = [\n      { message: 'Cannot query field \"foo\" on type \"Post\".' },\n    ];\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: { posts: null }, errors },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.query({ query, errorPolicy: \"all\" })\n    ).resolves.toStrictEqualTyped({\n      data: { posts: null },\n      error: new CombinedGraphQLErrors({\n        data: { posts: null },\n        errors: [{ message: 'Cannot query field \"foo\" on type \"Post\".' }],\n      }),\n    });\n  });\n\n  it(\"resolves with network error when errorPolicy is 'all'\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const error = new Error(\"Oops\");\n    const link = new MockLink([\n      {\n        request: { query },\n        error,\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.query({ query, errorPolicy: \"all\" })\n    ).resolves.toStrictEqualTyped({ data: undefined, error });\n  });\n\n  it(\"resolves partial data and strips errors when errorPolicy is 'ignore'\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const errors: GraphQLFormattedError[] = [\n      { message: 'Cannot query field \"foo\" on type \"Post\".' },\n    ];\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: { posts: null }, errors },\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.query({ query, errorPolicy: \"ignore\" })\n    ).resolves.toStrictEqualTyped({ data: { posts: null } });\n  });\n\n  it(\"resolves with no data or errors for network error when errorPolicy is 'ignore'\", async () => {\n    const query = gql`\n      query {\n        posts {\n          foo\n          __typename\n        }\n      }\n    `;\n    const error = new Error(\"Oops\");\n    const link = new MockLink([\n      {\n        request: { query },\n        error,\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    await expect(\n      client.query({ query, errorPolicy: \"ignore\" })\n    ).resolves.toStrictEqualTyped({ data: undefined });\n  });\n\n  it(\"should warn if server returns wrong data\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const query = gql`\n      query {\n        todos {\n          id\n          name\n          description\n          __typename\n        }\n      }\n    `;\n    const result = {\n      data: {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n            price: 100,\n            __typename: \"Todo\",\n          },\n        ],\n      },\n    };\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result,\n      },\n    ]);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        // Passing an empty map enables the warning:\n        possibleTypes: {},\n      }),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual(result.data);\n  });\n\n  it(\"runs a query with the connection directive and writes it to the store key defined in the directive\", async () => {\n    const query = gql`\n      {\n        books(skip: 0, limit: 2) @connection(key: \"abc\") {\n          name\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      {\n        books(skip: 0, limit: 2) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"runs query with cache field policy analogous to @connection\", async () => {\n    const query = gql`\n      {\n        books(skip: 0, limit: 2) {\n          name\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      {\n        books(skip: 0, limit: 2) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              books: {\n                keyArgs: () => \"abc\",\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"should remove the connection directive before the link is sent\", async () => {\n    const query = gql`\n      {\n        books(skip: 0, limit: 2) @connection(key: \"books\") {\n          name\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      {\n        books(skip: 0, limit: 2) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  it(\"handles read functions on arrays that return undefined items\", async () => {\n    const query: TypedDocumentNode<{\n      books: Array<{ __typename: \"Book\"; id: number; name: string }>;\n    }> = gql`\n      query {\n        books {\n          id\n          name\n        }\n      }\n    `;\n\n    const link = new MockLink([\n      {\n        request: { query },\n        result: {\n          data: {\n            books: [\n              { __typename: \"Book\", id: 1, name: \"Book 1 (fetch)\" },\n              { __typename: \"Book\", id: 2, name: \"Book 2 (fetch)\" },\n              { __typename: \"Book\", id: 3, name: \"Book 3 (fetch)\" },\n            ],\n          },\n        },\n      },\n    ]);\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            books: (existing: Reference[] = [], { canRead }) => {\n              return existing.map((book) => (canRead(book) ? book : undefined));\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({ link, cache });\n\n    client.writeQuery({\n      query,\n      data: {\n        books: [\n          { __typename: \"Book\", id: 1, name: \"Book 1 (cache)\" },\n          { __typename: \"Book\", id: 2, name: \"Book 2 (cache)\" },\n        ],\n      },\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n    const partialStream = new ObservableStream(\n      client.watchQuery({\n        query,\n        returnPartialData: true,\n      })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        books: [\n          { __typename: \"Book\", id: 1, name: \"Book 1 (cache)\" },\n          { __typename: \"Book\", id: 2, name: \"Book 2 (cache)\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(partialStream).toEmitTypedValue({\n      data: {\n        books: [\n          { __typename: \"Book\", id: 1, name: \"Book 1 (cache)\" },\n          { __typename: \"Book\", id: 2, name: \"Book 2 (cache)\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    cache.evict({ id: cache.identify({ __typename: \"Book\", id: 2 }) });\n\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n      }),\n    });\n    await expect(partialStream).toEmitTypedValue({\n      data: {\n        books: [{ __typename: \"Book\", id: 1, name: \"Book 1 (cache)\" }, {}],\n      },\n      dataState: \"partial\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        data: {\n          books: [\n            { __typename: \"Book\", id: 1, name: \"Book 1 (fetch)\" },\n            { __typename: \"Book\", id: 2, name: \"Book 2 (fetch)\" },\n            { __typename: \"Book\", id: 3, name: \"Book 3 (fetch)\" },\n          ],\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n      }),\n    });\n    await expect(partialStream).toEmitTypedValue({\n      data: {\n        books: [\n          { __typename: \"Book\", id: 1, name: \"Book 1 (fetch)\" },\n          { __typename: \"Book\", id: 2, name: \"Book 2 (fetch)\" },\n          { __typename: \"Book\", id: 3, name: \"Book 3 (fetch)\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n    await expect(partialStream).not.toEmitAnything();\n  });\n});\n\ndescribe(\"@connection\", () => {\n  it(\"should run a query with the @connection directive and write the result to the store key defined in the directive\", async () => {\n    const query = gql`\n      {\n        books(skip: 0, limit: 2) @connection(key: \"abc\") {\n          name\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      {\n        books(skip: 0, limit: 2) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n    expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n  });\n\n  it(\"should run a query with the connection directive and filter arguments and write the result to the correct store key\", async () => {\n    const query = gql`\n      query books($order: string) {\n        books(skip: 0, limit: 2, order: $order)\n          @connection(key: \"abc\", filter: [\"order\"]) {\n          name\n        }\n      }\n    `;\n    const transformedQuery = gql`\n      query books($order: string) {\n        books(skip: 0, limit: 2, order: $order) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const variables = { order: \"popularity\" };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery, variables },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ query, variables });\n\n    expect(actualResult.data).toEqual(result);\n    expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n  });\n\n  it(\"should support cache field policies that filter key arguments\", async () => {\n    const query = gql`\n      query books($order: string) {\n        books(skip: 0, limit: 2, order: $order) {\n          name\n        }\n      }\n    `;\n    const transformedQuery = gql`\n      query books($order: string) {\n        books(skip: 0, limit: 2, order: $order) {\n          name\n          __typename\n        }\n      }\n    `;\n\n    const result = {\n      books: [\n        {\n          name: \"abcd\",\n          __typename: \"Book\",\n        },\n      ],\n    };\n\n    const variables = { order: \"popularity\" };\n\n    const link = new MockLink([\n      {\n        request: { query: transformedQuery, variables },\n        result: { data: result },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              books: {\n                keyArgs: [\"order\"],\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    const actualResult = await client.query({ query, variables });\n\n    expect(actualResult.data).toEqual(result);\n    expect((client.cache as InMemoryCache).extract()).toMatchSnapshot();\n  });\n\n  it(\"should broadcast changes for reactive variables\", async () => {\n    const aVar = makeVar(123);\n    const bVar = makeVar(\"asdf\");\n    const cache: InMemoryCache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            a() {\n              return aVar();\n            },\n            b() {\n              return bVar();\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n    const obsQueries = new Set<ObservableQuery<any>>();\n    function watch(\n      query: DocumentNode,\n      fetchPolicy: WatchQueryFetchPolicy = \"cache-first\"\n    ) {\n      const obsQuery = client.watchQuery({\n        query,\n        fetchPolicy,\n      });\n      obsQueries.add(obsQuery);\n      return new ObservableStream(obsQuery);\n    }\n\n    const aStream = watch(gql`\n      {\n        a\n      }\n    `);\n    const bStream = watch(gql`\n      {\n        b\n      }\n    `);\n    const abStream = watch(gql`\n      {\n        a\n        b\n      }\n    `);\n\n    await expect(aStream).toEmitTypedValue({\n      data: { a: 123 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(bStream).toEmitTypedValue({\n      data: { b: \"asdf\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(abStream).toEmitTypedValue({\n      data: { a: 123, b: \"asdf\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    aVar(aVar() + 111);\n\n    await expect(aStream).toEmitTypedValue({\n      data: { a: 234 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(bStream).not.toEmitAnything({ timeout: 10 });\n\n    await expect(abStream).toEmitTypedValue({\n      data: { a: 234, b: \"asdf\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    bVar(bVar().toUpperCase());\n\n    await expect(aStream).not.toEmitAnything({ timeout: 10 });\n\n    await expect(bStream).toEmitTypedValue({\n      data: { b: \"ASDF\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(abStream).toEmitTypedValue({\n      data: { a: 234, b: \"ASDF\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    aVar(aVar() + 222);\n    bVar(\"oyez\");\n\n    await expect(aStream).toEmitTypedValue({\n      data: { a: 456 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(bStream).toEmitTypedValue({\n      data: { b: \"oyez\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(abStream).toEmitTypedValue({\n      data: { a: 456, b: \"oyez\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    // Now invalidate the ROOT_QUERY.a field.\n    client.cache.evict({ fieldName: \"a\" });\n\n    await expect(aStream).not.toEmitAnything({ timeout: 10 });\n    await expect(bStream).not.toEmitAnything({ timeout: 10 });\n    await expect(abStream).not.toEmitAnything({ timeout: 10 });\n\n    const cQuery = gql`\n      {\n        c\n      }\n    `;\n    // Passing cache-only as the fetchPolicy allows the { c: \"see\" }\n    // result to be delivered even though networkStatus is still loading.\n    const cStream = watch(cQuery, \"cache-only\");\n\n    await expect(cStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n\n    // Now try writing directly to the cache, rather than calling\n    // client.writeQuery.\n    client.cache.writeQuery({\n      query: cQuery,\n      data: {\n        c: \"see\",\n      },\n    });\n\n    await expect(aStream).not.toEmitAnything();\n    await expect(bStream).not.toEmitAnything();\n    await expect(abStream).not.toEmitAnything();\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"see\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    cache.modify({\n      fields: {\n        c(value) {\n          expect(value).toBe(\"see\");\n          return \"saw\";\n        },\n      },\n    });\n\n    await expect(aStream).not.toEmitAnything();\n    await expect(bStream).not.toEmitAnything();\n    await expect(abStream).not.toEmitAnything();\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"saw\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    client.cache.evict({ fieldName: \"c\" });\n\n    await expect(aStream).not.toEmitAnything();\n    await expect(bStream).not.toEmitAnything();\n    await expect(abStream).not.toEmitAnything();\n    await expect(cStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n  });\n\n  function wait(time = 10) {\n    return new Promise((resolve) => setTimeout(resolve, time));\n  }\n\n  it(\"should call forgetCache for reactive vars when stopped\", async () => {\n    const aVar = makeVar(123);\n    const bVar = makeVar(\"asdf\");\n    const aSpy = jest.spyOn(aVar, \"forgetCache\");\n    const bSpy = jest.spyOn(bVar, \"forgetCache\");\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            a() {\n              return aVar();\n            },\n            b() {\n              return bVar();\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n    const obsQueries = new Set<ObservableQuery<any>>();\n    const subs = new Set<Subscription>();\n    function watch(\n      query: DocumentNode,\n      fetchPolicy: WatchQueryFetchPolicy = \"cache-first\"\n    ): any[] {\n      const results: any[] = [];\n      const obsQuery = client.watchQuery({\n        query,\n        fetchPolicy,\n      });\n      obsQueries.add(obsQuery);\n      subs.add(\n        obsQuery.subscribe({\n          next(result) {\n            results.push(result.data);\n          },\n        })\n      );\n      return results;\n    }\n\n    const aQuery = gql`\n      {\n        a\n      }\n    `;\n    const bQuery = gql`\n      {\n        b\n      }\n    `;\n    const abQuery = gql`\n      {\n        a\n        b\n      }\n    `;\n\n    const aResults = watch(aQuery);\n    const bResults = watch(bQuery);\n\n    expect(cache[\"watches\"].size).toBe(2);\n\n    expect(aResults).toEqual([{ a: 123 }]);\n    expect(bResults).toEqual([{ b: \"asdf\" }]);\n\n    expect(aSpy).not.toHaveBeenCalled();\n    expect(bSpy).not.toHaveBeenCalled();\n\n    subs.forEach((sub) => sub.unsubscribe());\n\n    expect(aSpy).toHaveBeenCalledTimes(1);\n    expect(aSpy).toHaveBeenCalledWith(cache);\n    expect(bSpy).toHaveBeenCalledTimes(1);\n    expect(bSpy).toHaveBeenCalledWith(cache);\n\n    expect(aResults).toEqual([{ a: 123 }]);\n    expect(bResults).toEqual([{ b: \"asdf\" }]);\n\n    expect(cache[\"watches\"].size).toBe(0);\n    const abResults = watch(abQuery);\n    expect(abResults).toEqual([{ a: 123, b: \"asdf\" }]);\n    expect(cache[\"watches\"].size).toBe(1);\n\n    await wait();\n\n    expect(aResults).toEqual([{ a: 123 }]);\n    expect(bResults).toEqual([{ b: \"asdf\" }]);\n    expect(abResults).toEqual([{ a: 123, b: \"asdf\" }]);\n\n    client.stop();\n\n    await wait();\n\n    expect(aSpy).toHaveBeenCalledTimes(2);\n    expect(aSpy).toHaveBeenCalledWith(cache);\n    expect(bSpy).toHaveBeenCalledTimes(2);\n    expect(bSpy).toHaveBeenCalledWith(cache);\n  });\n\n  describe(\"default settings\", () => {\n    const query = gql`\n      query number {\n        myNumber {\n          n\n        }\n      }\n    `;\n\n    const initialData = {\n      myNumber: {\n        n: 1,\n      },\n    };\n    const networkFetch = {\n      myNumber: {\n        n: 2,\n      },\n    };\n\n    it(\"allows setting default options for watchQuery\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: networkFetch },\n        },\n      ]);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          watchQuery: {\n            fetchPolicy: \"cache-and-network\",\n          },\n        },\n      });\n\n      client.writeQuery({\n        query,\n        data: initialData,\n      });\n\n      const obs = client.watchQuery({\n        query,\n        // This undefined value should be ignored in favor of\n        // defaultOptions.watchQuery.fetchPolicy.\n        fetchPolicy: void 0,\n      });\n\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: initialData,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: networkFetch,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"allows setting nextFetchPolicy in defaultOptions\", async () => {\n      let networkCounter = 0;\n      let nextFetchPolicyCallCount = 0;\n\n      const client = new ApolloClient({\n        link: new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                observer.next({\n                  data: {\n                    count: networkCounter++,\n                  },\n                });\n                observer.complete();\n              });\n            })\n        ),\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          watchQuery: {\n            nextFetchPolicy(fetchPolicy, context) {\n              expect(++nextFetchPolicyCallCount).toBe(1);\n              expect(this.query).toBe(query);\n              expect(fetchPolicy).toBe(\"cache-first\");\n\n              expect(context.reason).toBe(\"after-fetch\");\n              expect(context.observable).toBe(obs);\n              expect(context.options).toBe(obs.options);\n              expect(context.initialFetchPolicy).toBe(\"cache-first\");\n\n              // Usually options.nextFetchPolicy applies only once, but a\n              // nextFetchPolicy function can set this.nextFetchPolicy\n              // again to perform an additional transition.\n              this.nextFetchPolicy = (fetchPolicy) => {\n                ++nextFetchPolicyCallCount;\n                return \"cache-first\";\n              };\n\n              return \"cache-and-network\";\n            },\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          count\n        }\n      `;\n\n      client.writeQuery({\n        query,\n        data: {\n          count: \"initial\",\n        },\n      });\n\n      const obs = client.watchQuery({ query });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: \"initial\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(nextFetchPolicyCallCount).toBe(1);\n\n      // Refetching makes a copy of the current options, which\n      // includes options.nextFetchPolicy, so the inner\n      // nextFetchPolicy function ends up getting called twice.\n      void obs.refetch();\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: \"initial\" },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: 0 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(nextFetchPolicyCallCount).toBe(2);\n\n      client.writeQuery({\n        query,\n        data: {\n          count: \"secondary\",\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: \"secondary\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(nextFetchPolicyCallCount).toBe(3);\n\n      client.cache.evict({ fieldName: \"count\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: \"secondary\" },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { count: 1 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(nextFetchPolicyCallCount).toBe(4);\n      expect(obs.options.fetchPolicy).toBe(\"cache-first\");\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"can override global defaultOptions.watchQuery.nextFetchPolicy\", async () => {\n      let linkCount = 0;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                observer.next({\n                  data: {\n                    linkCount: ++linkCount,\n                  },\n                });\n                observer.complete();\n              });\n            })\n        ),\n        defaultOptions: {\n          watchQuery: {\n            nextFetchPolicy() {\n              throw new Error(\"should not have called global nextFetchPolicy\");\n            },\n          },\n        },\n      });\n\n      const query: TypedDocumentNode<{\n        linkCount: number;\n      }> = gql`\n        query CountQuery {\n          linkCount\n        }\n      `;\n\n      let fetchPolicyRecord: WatchQueryFetchPolicy[] = [];\n      const observable = client.watchQuery({\n        query,\n        nextFetchPolicy(currentFetchPolicy) {\n          fetchPolicyRecord.push(currentFetchPolicy);\n          return \"cache-first\";\n        },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { linkCount: 1 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(fetchPolicyRecord).toEqual([\"cache-first\"]);\n\n      const results = await client.refetchQueries({\n        include: [\"CountQuery\"],\n      });\n\n      expect(results).toHaveLength(1);\n      expect(results[0]).toStrictEqualTyped({\n        data: { linkCount: 2 },\n      });\n\n      expect(fetchPolicyRecord).toEqual([\"cache-first\", \"network-only\"]);\n\n      await expect(stream).toEmitTypedValue({\n        data: { linkCount: 1 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: { linkCount: 2 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(fetchPolicyRecord).toEqual([\"cache-first\", \"network-only\"]);\n\n      const finalResult = await observable.reobserve({\n        // Force a network request in addition to loading:true cache result.\n        fetchPolicy: \"cache-and-network\",\n      });\n\n      expect(finalResult).toStrictEqualTyped({\n        data: { linkCount: 3 },\n      });\n\n      expect(fetchPolicyRecord).toEqual([\n        \"cache-first\",\n        \"network-only\",\n        \"cache-and-network\",\n      ]);\n\n      await expect(stream).toEmitTypedValue({\n        data: { linkCount: 2 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { linkCount: 3 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(fetchPolicyRecord).toEqual([\n        \"cache-first\",\n        \"network-only\",\n        \"cache-and-network\",\n      ]);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"allows setting default options for query\", async () => {\n      const errors = [{ message: \"failure\", name: \"failure\" }];\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { errors },\n        },\n      ]);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          query: { errorPolicy: \"all\" },\n        },\n      });\n\n      const result = await client.query({ query });\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: new CombinedGraphQLErrors({ errors }),\n      });\n    });\n\n    it(\"allows setting default options for mutation\", async () => {\n      const mutation = gql`\n        mutation upVote($id: ID!) {\n          upvote(id: $id) {\n            success\n          }\n        }\n      `;\n\n      const data = {\n        upvote: { success: true },\n      };\n\n      const link = new MockLink([\n        {\n          request: { query: mutation, variables: { id: 1 } },\n          result: { data },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          mutate: { variables: { id: 1 } },\n        },\n      });\n\n      const result = await client.mutate({\n        mutation,\n        // This undefined value should be ignored in favor of\n        // defaultOptions.mutate.variables.\n        variables: void 0,\n      });\n\n      expect(result.data).toEqual(data);\n    });\n  });\n});\n\ndescribe(\"custom document transforms\", () => {\n  it(\"runs custom document transform when calling `query`\", async () => {\n    const query = gql`\n      query TestQuery {\n        dogs {\n          id\n          name\n          breed @custom\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          dogs: [\n            {\n              id: 1,\n              name: \"Buddy\",\n              breed: \"German Shepard\",\n              __typename: \"Dog\",\n            },\n          ],\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        dogs {\n          id\n          name\n          breed\n          __typename\n        }\n      }\n    `);\n\n    expect(data).toEqual({\n      dogs: [\n        {\n          id: 1,\n          name: \"Buddy\",\n          breed: \"German Shepard\",\n          __typename: \"Dog\",\n        },\n      ],\n    });\n  });\n\n  it(\"requests and caches fields added from custom document transforms when calling `query`\", async () => {\n    const query = gql`\n      query TestQuery {\n        dogs {\n          name\n          breed\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"dogs\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  {\n                    kind: Kind.FIELD,\n                    name: { kind: Kind.NAME, value: \"id\" },\n                  },\n                  ...node.selectionSet.selections,\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          dogs: [\n            {\n              id: 1,\n              name: \"Buddy\",\n              breed: \"German Shepard\",\n              __typename: \"Dog\",\n            },\n          ],\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        dogs {\n          id\n          name\n          breed\n          __typename\n        }\n      }\n    `);\n\n    expect(data).toEqual({\n      dogs: [\n        {\n          id: 1,\n          name: \"Buddy\",\n          breed: \"German Shepard\",\n          __typename: \"Dog\",\n        },\n      ],\n    });\n\n    const cache = client.cache.extract() as NormalizedCacheObject;\n\n    expect(cache[\"Dog:1\"]).toEqual({\n      id: 1,\n      name: \"Buddy\",\n      breed: \"German Shepard\",\n      __typename: \"Dog\",\n    });\n  });\n\n  it(\"runs document transforms before reading from the cache when calling `query`\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          name\n        }\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"product\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  ...node.selectionSet.selections,\n                  {\n                    kind: Kind.FRAGMENT_SPREAD,\n                    name: { kind: Kind.NAME, value: \"ProductFields\" },\n                  },\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink(() => {\n      return of({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 2,\n            name: \"unused\",\n            description: \"unused\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        fragments: createFragmentRegistry(gql`\n          fragment ProductFields on Product {\n            description\n          }\n        `),\n      }),\n      documentTransform,\n    });\n\n    // Use the transformed document to write to the cache to ensure it contains\n    // the fragment spread\n    client.writeQuery({\n      query: documentTransform.transformDocument(query),\n      data: {\n        product: {\n          __typename: \"Product\",\n          id: 1,\n          name: \"Cached product\",\n          description: \"Cached product description\",\n        },\n      },\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      product: {\n        __typename: \"Product\",\n        id: 1,\n        name: \"Cached product\",\n        description: \"Cached product description\",\n      },\n    });\n  });\n\n  it(\"runs @client directives added from custom transforms through local state\", async () => {\n    // Silence local resolvers warning\n    using _ = spyOnConsole(\"warn\");\n    const query = gql`\n      query TestQuery {\n        currentUser {\n          id\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"currentUser\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  ...node.selectionSet.selections,\n                  {\n                    kind: Kind.FIELD,\n                    name: { kind: Kind.NAME, value: \"isLoggedIn\" },\n                    directives: [\n                      {\n                        kind: Kind.DIRECTIVE,\n                        name: { kind: Kind.NAME, value: \"client\" },\n                      },\n                    ],\n                  },\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          currentUser: {\n            id: 1,\n            __typename: \"User\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache({\n        typePolicies: {\n          User: {\n            fields: {\n              isLoggedIn: {\n                read() {\n                  return true;\n                },\n              },\n            },\n          },\n        },\n      }),\n      localState: new LocalState(),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        currentUser {\n          id\n          __typename\n        }\n      }\n    `);\n\n    expect(data).toEqual({\n      currentUser: {\n        id: 1,\n        isLoggedIn: true,\n        __typename: \"User\",\n      },\n    });\n  });\n\n  it(\"runs custom transform only once when calling `query`\", async () => {\n    const query = gql`\n      query TestQuery {\n        currentUser {\n          id\n        }\n      }\n    `;\n\n    const transform = jest.fn((document: DocumentNode) => document);\n    const documentTransform = new DocumentTransform(transform, {\n      cache: false,\n    });\n\n    const link = new ApolloLink(() => {\n      return of({\n        data: {\n          currentUser: {\n            id: 1,\n            __typename: \"User\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query });\n\n    expect(transform).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"runs default transforms with no custom document transform when calling `query`\", async () => {\n    // Silence local resolvers warning\n    using _ = spyOnConsole(\"warn\");\n    const query = gql`\n      query TestQuery {\n        currentUser @nonreactive {\n          id\n          isLoggedIn @client\n          favoriteFlavors @connection {\n            flavor\n          }\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({ data: null });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    // Pass no-cache to silence cache write warnings\n    await client.query({ query, fetchPolicy: \"no-cache\" });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        currentUser {\n          id\n          favoriteFlavors {\n            flavor\n            __typename\n          }\n          __typename\n        }\n      }\n    `);\n  });\n\n  it(\"runs custom transform when calling `mutate`\", async () => {\n    const mutation = gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username @custom\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          changeUsername: {\n            id: 1,\n            username: operation.variables.username,\n            __typename: \"User\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const { data } = await client.mutate({\n      mutation,\n      variables: { username: \"foo\" },\n    });\n\n    expect(document!).toMatchDocument(gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n\n    expect(data).toEqual({\n      changeUsername: {\n        id: 1,\n        username: \"foo\",\n        __typename: \"User\",\n      },\n    });\n  });\n\n  it(\"runs custom transform on queries defined in refetchQueries using legacy option when calling `mutate`\", async () => {\n    const mutation = gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username @custom\n        }\n      }\n    `;\n\n    const query = gql`\n      query TestQuery {\n        currentUser {\n          id\n          username @custom\n        }\n      }\n    `;\n\n    const requests: ApolloLink.Operation[] = [];\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const mocks = [\n      {\n        request: {\n          query: documentTransform.transformDocument(mutation),\n          variables: { username: \"foo\" },\n        },\n        result: {\n          data: {\n            changeUsername: { __typename: \"User\", id: 1, username: \"foo\" },\n          },\n        },\n      },\n      {\n        request: { query: documentTransform.transformDocument(query) },\n        result: {\n          data: {\n            currentUser: { __typename: \"User\", id: 1, username: \"foo\" },\n          },\n        },\n      },\n    ];\n\n    const link = new ApolloLink((operation, forward) => {\n      requests.push(operation);\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const { data } = await client.mutate({\n      mutation,\n      variables: { username: \"foo\" },\n      refetchQueries: [{ query }],\n      awaitRefetchQueries: true,\n    });\n\n    expect(data).toEqual({\n      changeUsername: {\n        id: 1,\n        username: \"foo\",\n        __typename: \"User\",\n      },\n    });\n\n    expect(requests[0].query).toMatchDocument(gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n\n    expect(requests[1].query).toMatchDocument(gql`\n      query TestQuery {\n        currentUser {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n  });\n\n  it(\"requests and caches fields added from custom document transforms when calling `mutate`\", async () => {\n    const mutation = gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          username\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"changeUsername\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  {\n                    kind: Kind.FIELD,\n                    name: { kind: Kind.NAME, value: \"id\" },\n                  },\n                  ...node.selectionSet.selections,\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          changeUsername: {\n            id: 1,\n            username: operation.variables.username,\n            __typename: \"User\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const { data } = await client.mutate({\n      mutation,\n      variables: { username: \"foo\" },\n    });\n\n    expect(document!).toMatchDocument(gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n\n    expect(data).toEqual({\n      changeUsername: {\n        id: 1,\n        username: \"foo\",\n        __typename: \"User\",\n      },\n    });\n\n    const cache = client.cache.extract() as NormalizedCacheObject;\n\n    expect(cache[\"User:1\"]).toEqual({\n      __typename: \"User\",\n      id: 1,\n      username: \"foo\",\n    });\n  });\n\n  it(\"runs custom transforms only once when running `mutation`\", async () => {\n    const mutation = gql`\n      mutation TestMutation($username: String) {\n        changeUsername(username: $username) {\n          id\n          username\n        }\n      }\n    `;\n\n    const transform = jest.fn((document: DocumentNode) => document);\n    const documentTransform = new DocumentTransform(transform, {\n      cache: false,\n    });\n\n    const link = new ApolloLink((operation) => {\n      return of({\n        data: {\n          changeUsername: {\n            id: 1,\n            username: operation.variables.username,\n            __typename: \"User\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    await client.mutate({ mutation, variables: { username: \"foo\" } });\n\n    expect(transform).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"runs default transforms with no custom document transform when calling `mutate`\", async () => {\n    // Silence local resolvers warning\n    using _ = spyOnConsole(\"warn\");\n    const mutation = gql`\n      mutation TestMutation {\n        updateProfile @nonreactive {\n          id\n          isLoggedIn @client\n          favoriteFlavors @connection {\n            flavor\n          }\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          updateProfile: {\n            __typename: \"Profile\",\n            id: 1,\n            favoriteFlavors: [{ __typename: \"Flavor\", flavor: \"Strawberry \" }],\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    await client.mutate({ mutation });\n\n    expect(document!).toMatchDocument(gql`\n      mutation TestMutation {\n        updateProfile {\n          id\n          favoriteFlavors {\n            flavor\n            __typename\n          }\n          __typename\n        }\n      }\n    `);\n  });\n\n  it(\"runs custom document transforms when calling `subscribe`\", async () => {\n    const query = gql`\n      subscription TestSubscription {\n        profileUpdated {\n          id\n          username @custom\n        }\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          profileUpdated: {\n            id: 1,\n            username: \"foo\",\n            __typename: \"Profile\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const onNext = jest.fn();\n\n    const subscription = client.subscribe({ query }).subscribe(onNext);\n\n    await waitFor(() => subscription.closed);\n\n    expect(document!).toMatchDocument(gql`\n      subscription TestSubscription {\n        profileUpdated {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n\n    expect(onNext).toHaveBeenLastCalledWith({\n      data: {\n        profileUpdated: { id: 1, username: \"foo\", __typename: \"Profile\" },\n      },\n    });\n  });\n\n  it(\"requests and caches fields added from custom document transforms when calling `subscribe`\", async () => {\n    const query = gql`\n      subscription TestSubscription {\n        profileUpdated {\n          username\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"profileUpdated\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  {\n                    kind: Kind.FIELD,\n                    name: { kind: Kind.NAME, value: \"id\" },\n                  },\n                  ...node.selectionSet.selections,\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          profileUpdated: {\n            id: 1,\n            username: \"foo\",\n            __typename: \"Profile\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const onNext = jest.fn();\n\n    const subscription = client.subscribe({ query }).subscribe(onNext);\n\n    await waitFor(() => subscription.closed);\n\n    expect(document!).toMatchDocument(gql`\n      subscription TestSubscription {\n        profileUpdated {\n          id\n          username\n          __typename\n        }\n      }\n    `);\n\n    expect(onNext).toHaveBeenLastCalledWith({\n      data: {\n        profileUpdated: { id: 1, username: \"foo\", __typename: \"Profile\" },\n      },\n    });\n\n    const cache = client.cache.extract() as NormalizedCacheObject;\n\n    expect(cache[\"Profile:1\"]).toEqual({\n      __typename: \"Profile\",\n      id: 1,\n      username: \"foo\",\n    });\n  });\n\n  it(\"runs custom transforms only once when calling `subscribe`\", async () => {\n    const query = gql`\n      subscription TestSubscription {\n        profileUpdated {\n          username\n        }\n      }\n    `;\n\n    const transform = jest.fn((document: DocumentNode) => document);\n    const documentTransform = new DocumentTransform(transform, {\n      cache: false,\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      documentTransform,\n      cache: new InMemoryCache(),\n    });\n\n    const subscription = client.subscribe({ query }).subscribe(jest.fn());\n\n    await waitFor(() => subscription.closed);\n\n    expect(transform).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"runs default transforms with no custom document transform when calling `subscribe`\", async () => {\n    // Silence local resolvers warning\n    using _ = spyOnConsole(\"warn\");\n    const query = gql`\n      subscription TestSubscription {\n        profileUpdated @nonreactive {\n          id\n          isLoggedIn @client\n          favoriteFlavors @connection {\n            flavor\n          }\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          profileUpdated: {\n            __typename: \"Profile\",\n            id: 1,\n            favoriteFlavors: [{ __typename: \"Flavor\", flavor: \"Strawberry \" }],\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    const subscription = client.subscribe({ query }).subscribe(jest.fn());\n\n    await waitFor(() => subscription.closed);\n\n    expect(document!).toMatchDocument(gql`\n      subscription TestSubscription {\n        profileUpdated {\n          id\n          favoriteFlavors {\n            flavor\n            __typename\n          }\n          __typename\n        }\n      }\n    `);\n  });\n\n  it(\"runs custom document transforms when subscribing to observable after calling `watchQuery`\", async () => {\n    const query = gql`\n      query TestQuery {\n        currentUser {\n          id\n          name @custom\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      query TestQuery {\n        currentUser {\n          id\n          name\n          __typename\n        }\n      }\n    `;\n\n    const transform = jest.fn((document: DocumentNode) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const documentTransform = new DocumentTransform(transform, {\n      cache: false,\n    });\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: { currentUser: { __typename: \"User\", id: 1, name: \"John Doe\" } },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query });\n\n    expect(transform).toHaveBeenCalledTimes(1);\n    // `options.query` should always reflect the raw, untransformed query\n    expect(observable.options.query).toMatchDocument(query);\n    // The computed `query` property should always reflect the last requested\n    // transformed document.\n    expect(observable.query).toMatchDocument(transformedQuery);\n\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: {\n          currentUser: { __typename: \"User\", id: 1, name: \"John Doe\" },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(document).toMatchDocument(transformedQuery);\n      expect(observable.options.query).toMatchDocument(query);\n      expect(observable.query).toMatchDocument(transformedQuery);\n      expect(transform).toHaveBeenCalledTimes(2);\n    });\n  });\n\n  it(\"runs default transforms with no custom document transform when calling `watchQuery`\", async () => {\n    // Silence local resolvers warning\n    using _ = spyOnConsole(\"warn\");\n    const query = gql`\n      query TestQuery @nonreactive {\n        currentUser {\n          id\n          isLoggedIn @client\n          favorites @connection {\n            id\n          }\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            favorites: [{ __typename: \"Favorite\", id: 1 }],\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    observable.subscribe(jest.fn());\n\n    await waitFor(() => {\n      expect(document!).toMatchDocument(gql`\n        query TestQuery {\n          currentUser {\n            id\n            favorites {\n              id\n              __typename\n            }\n            __typename\n          }\n        }\n      `);\n    });\n  });\n\n  it(\"runs document transforms before reading from the cache when calling `watchQuery`\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          name\n        }\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"product\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  ...node.selectionSet.selections,\n                  {\n                    kind: Kind.FRAGMENT_SPREAD,\n                    name: { kind: Kind.NAME, value: \"ProductFields\" },\n                  },\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink(() => {\n      return of({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 2,\n            name: \"unused\",\n            description: \"unused\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        fragments: createFragmentRegistry(gql`\n          fragment ProductFields on Product {\n            description\n          }\n        `),\n      }),\n      documentTransform,\n    });\n\n    // Use the transformed document to write to the cache to ensure it contains\n    // the fragment spread\n    client.writeQuery({\n      query: documentTransform.transformDocument(query),\n      data: {\n        product: {\n          __typename: \"Product\",\n          id: 1,\n          name: \"Cached product\",\n          description: \"Cached product description\",\n        },\n      },\n    });\n\n    const observable = client.watchQuery({ query });\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 1,\n            name: \"Cached product\",\n            description: \"Cached product description\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n  });\n\n  it(\"re-runs custom document transforms when calling `refetch`\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const enabledQuery = gql`\n      query TestQuery {\n        product {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const disabledQuery = gql`\n      query TestQuery {\n        product {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: enabledQuery },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n          },\n        },\n      },\n      {\n        request: { query: disabledQuery },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 1 },\n          },\n        },\n      },\n    ];\n\n    let enabled = true;\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument(\n          [{ name: \"whenEnabled\", remove: !enabled }],\n          document\n        )!;\n      },\n      { cache: false }\n    );\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query });\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: {\n          product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(document).toMatchDocument(enabledQuery);\n      expect(observable.options.query).toMatchDocument(query);\n      expect(observable.query).toMatchDocument(enabledQuery);\n    });\n\n    enabled = false;\n\n    const { data } = await observable.refetch();\n\n    expect(document!).toMatchDocument(disabledQuery);\n    expect(observable.options.query).toMatchDocument(query);\n    expect(observable.query).toMatchDocument(disabledQuery);\n\n    expect(data).toEqual({\n      product: { __typename: \"Product\", id: 1 },\n    });\n\n    expect(handleNext).toHaveBeenLastCalledWith({\n      data: {\n        product: { __typename: \"Product\", id: 1 },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"re-runs custom document transforms when calling `fetchMore`\", async () => {\n    const query = gql`\n      query TestQuery($offset: Int) {\n        products(offset: $offset) {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const enabledQuery = gql`\n      query TestQuery($offset: Int) {\n        products(offset: $offset) {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const disabledQuery = gql`\n      query TestQuery($offset: Int) {\n        products(offset: $offset) {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: enabledQuery, variables: { offset: 0 } },\n        result: {\n          data: {\n            products: [{ __typename: \"Product\", id: 1, metrics: \"1000/vpm\" }],\n          },\n        },\n      },\n      {\n        request: { query: disabledQuery, variables: { offset: 1 } },\n        result: {\n          data: {\n            products: [{ __typename: \"Product\", id: 2 }],\n          },\n        },\n      },\n    ];\n\n    let enabled = true;\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument(\n          [{ name: \"whenEnabled\", remove: !enabled }],\n          document\n        )!;\n      },\n      { cache: false }\n    );\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              products: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query, variables: { offset: 0 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        products: [{ __typename: \"Product\", id: 1, metrics: \"1000/vpm\" }],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(document!).toMatchDocument(enabledQuery);\n    expect(observable.options.query).toMatchDocument(query);\n    expect(observable.query).toMatchDocument(enabledQuery);\n\n    enabled = false;\n\n    const { data } = await observable.fetchMore({ variables: { offset: 1 } });\n\n    expect(document!).toMatchDocument(disabledQuery);\n    expect(observable.options.query).toMatchDocument(query);\n    expect(observable.query).toMatchDocument(disabledQuery);\n\n    expect(data).toEqual({\n      products: [{ __typename: \"Product\", id: 2 }],\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        products: [{ __typename: \"Product\", id: 1 }],\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        products: [\n          { __typename: \"Product\", id: 1 },\n          { __typename: \"Product\", id: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"runs custom document transforms on the passed query and original query when calling `fetchMore` with a different query\", async () => {\n    const initialQuery = gql`\n      query TestQuery($offset: Int) {\n        currentUser {\n          id\n        }\n        products(offset: $offset) {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const enabledInitialQuery = gql`\n      query TestQuery($offset: Int) {\n        currentUser {\n          id\n          __typename\n        }\n        products(offset: $offset) {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const disabledInitialQuery = gql`\n      query TestQuery($offset: Int) {\n        currentUser {\n          id\n          __typename\n        }\n        products(offset: $offset) {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const productsQuery = gql`\n      query TestQuery($offset: Int) {\n        products(offset: $offset) {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const transformedProductsQuery = gql`\n      query TestQuery($offset: Int) {\n        products(offset: $offset) {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: enabledInitialQuery, variables: { offset: 0 } },\n        result: {\n          data: {\n            currentUser: { id: 1 },\n            products: [{ __typename: \"Product\", id: 1, metrics: \"1000/vpm\" }],\n          },\n        },\n      },\n      {\n        request: { query: transformedProductsQuery, variables: { offset: 1 } },\n        result: {\n          data: {\n            products: [{ __typename: \"Product\", id: 2 }],\n          },\n        },\n      },\n    ];\n\n    let enabled = true;\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument(\n          [{ name: \"whenEnabled\", remove: !enabled }],\n          document\n        )!;\n      },\n      { cache: false }\n    );\n\n    let document!: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              products: {\n                keyArgs: false,\n                merge(existing = [], incoming) {\n                  return [...existing, ...incoming];\n                },\n              },\n            },\n          },\n        },\n      }),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({\n      query: initialQuery,\n      variables: { offset: 0 },\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: { id: 1 },\n        products: [{ __typename: \"Product\", id: 1, metrics: \"1000/vpm\" }],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(document).toMatchDocument(enabledInitialQuery);\n    expect(observable.options.query).toMatchDocument(initialQuery);\n    expect(observable.query).toMatchDocument(enabledInitialQuery);\n\n    enabled = false;\n\n    const { data } = await observable.fetchMore({\n      query: productsQuery,\n      variables: { offset: 1 },\n    });\n\n    expect(data).toEqual({\n      products: [{ __typename: \"Product\", id: 2 }],\n    });\n\n    expect(document!).toMatchDocument(transformedProductsQuery);\n    expect(observable.options.query).toMatchDocument(initialQuery);\n    // Even though we pass a different query to `fetchMore`, we don't want to\n    // override the original query. We do however run transforms on the\n    // initial query to ensure the broadcasted result and the cache match\n    // the expected query document in case the transforms contain a runtime\n    // condition that impacts the query in a significant way (such as removing\n    // a field).\n    expect(observable.query).toMatchDocument(disabledInitialQuery);\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: { id: 1 },\n        products: [{ __typename: \"Product\", id: 1 }],\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: { id: 1 },\n        products: [\n          { __typename: \"Product\", id: 1 },\n          { __typename: \"Product\", id: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"re-runs custom document transforms when calling `setVariables`\", async () => {\n    const query = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const enabledQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const disabledQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: enabledQuery, variables: { id: 1 } },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n          },\n        },\n      },\n      {\n        request: { query: disabledQuery, variables: { id: 2 } },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 2 },\n          },\n        },\n      },\n    ];\n\n    let enabled = true;\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument(\n          [{ name: \"whenEnabled\", remove: !enabled }],\n          document\n        )!;\n      },\n      { cache: false }\n    );\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: {\n          product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(document).toMatchDocument(enabledQuery);\n      expect(observable.options.query).toMatchDocument(query);\n      expect(observable.query).toMatchDocument(enabledQuery);\n    });\n\n    enabled = false;\n\n    const result = await observable.setVariables({ id: 2 });\n\n    expect(document!).toMatchDocument(disabledQuery);\n    expect(observable.options.query).toMatchDocument(query);\n    expect(observable.query).toMatchDocument(disabledQuery);\n\n    expect(result!.data).toEqual({\n      product: { __typename: \"Product\", id: 2 },\n    });\n\n    expect(handleNext).toHaveBeenLastCalledWith({\n      data: {\n        product: { __typename: \"Product\", id: 2 },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"re-runs custom document transforms when calling `reobserve`\", async () => {\n    const query = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics @whenEnabled\n        }\n      }\n    `;\n\n    const enabledQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const disabledQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: enabledQuery, variables: { id: 1 } },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n          },\n        },\n      },\n      {\n        request: { query: disabledQuery, variables: { id: 2 } },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 2 },\n          },\n        },\n      },\n    ];\n\n    let enabled = true;\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument(\n          [{ name: \"whenEnabled\", remove: !enabled }],\n          document\n        )!;\n      },\n      { cache: false }\n    );\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: {\n          product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(document).toMatchDocument(enabledQuery);\n      expect(observable.options.query).toMatchDocument(query);\n      expect(observable.query).toMatchDocument(enabledQuery);\n    });\n\n    enabled = false;\n\n    const { data } = await observable.reobserve({ variables: { id: 2 } });\n\n    expect(document!).toMatchDocument(disabledQuery);\n    expect(observable.options.query).toMatchDocument(query);\n    expect(observable.query).toMatchDocument(disabledQuery);\n\n    expect(data).toEqual({\n      product: { __typename: \"Product\", id: 2 },\n    });\n\n    expect(handleNext).toHaveBeenLastCalledWith({\n      data: {\n        product: { __typename: \"Product\", id: 2 },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"runs custom document transforms when passing a new query to `reobserve`\", async () => {\n    const query = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics @custom\n        }\n      }\n    `;\n\n    const transformedQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const updatedQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          name\n          metrics @custom\n        }\n      }\n    `;\n\n    const transformedUpdatedQuery = gql`\n      query TestQuery($id: ID!) {\n        product(id: $id) {\n          id\n          name\n          metrics\n          __typename\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: transformedQuery, variables: { id: 1 } },\n        result: {\n          data: {\n            product: { __typename: \"Product\", id: 1, metrics: \"1000/vpm\" },\n          },\n        },\n      },\n      {\n        request: { query: transformedUpdatedQuery, variables: { id: 1 } },\n        result: {\n          data: {\n            product: {\n              __typename: \"Product\",\n              id: 1,\n              name: \"Acme Inc Product\",\n              metrics: \"1000/vpm\",\n            },\n          },\n        },\n      },\n    ];\n\n    const documentTransform = new DocumentTransform(\n      (document: DocumentNode) => {\n        return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n      }\n    );\n\n    let document: DocumentNode;\n\n    const link = new ApolloLink((operation, forward) => {\n      document = operation.query;\n\n      return forward(operation);\n    });\n\n    const client = new ApolloClient({\n      link: ApolloLink.from([link, new MockLink(mocks)]),\n      cache: new InMemoryCache(),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const handleNext = jest.fn();\n\n    observable.subscribe(handleNext);\n\n    await waitFor(() => {\n      expect(handleNext).toHaveBeenLastCalledWith({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(document).toMatchDocument(transformedQuery);\n      expect(observable.options.query).toMatchDocument(query);\n      expect(observable.query).toMatchDocument(transformedQuery);\n    });\n\n    const { data } = await observable.reobserve({ query: updatedQuery });\n\n    expect(document!).toMatchDocument(transformedUpdatedQuery);\n    expect(observable.options.query).toMatchDocument(updatedQuery);\n    expect(observable.query).toMatchDocument(transformedUpdatedQuery);\n\n    expect(data).toEqual(mocks[1].result.data);\n\n    expect(handleNext).toHaveBeenLastCalledWith({\n      data: mocks[1].result.data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"runs custom document transforms with fragments defined in the fragment registry\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          name @custom\n          ...ProductFields\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 1,\n            name: \"Product\",\n            description: \"Product description\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        fragments: createFragmentRegistry(gql`\n          fragment ProductFields on Product {\n            description @custom\n          }\n        `),\n      }),\n      documentTransform,\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        product {\n          id\n          name\n          ...ProductFields\n          __typename\n        }\n      }\n\n      fragment ProductFields on Product {\n        description\n        __typename\n      }\n    `);\n\n    expect(data).toEqual({\n      product: {\n        __typename: \"Product\",\n        id: 1,\n        name: \"Product\",\n        description: \"Product description\",\n      },\n    });\n  });\n\n  it(\"runs custom document transforms on fragments that override registered fragments in the fragment registry\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          name @custom\n          ...ProductFields\n        }\n      }\n\n      fragment ProductFields on Product {\n        description @custom\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 1,\n            name: \"Product\",\n            description: \"Product description\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        fragments: createFragmentRegistry(gql`\n          fragment ProductFields on Product {\n            unused @custom\n          }\n        `),\n      }),\n      documentTransform,\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        product {\n          id\n          name\n          ...ProductFields\n          __typename\n        }\n      }\n\n      fragment ProductFields on Product {\n        description\n        __typename\n      }\n    `);\n\n    expect(data).toEqual({\n      product: {\n        __typename: \"Product\",\n        id: 1,\n        name: \"Product\",\n        description: \"Product description\",\n      },\n    });\n  });\n\n  it(\"adds fragment definitions to the query for fragment spreads added from custom document transforms\", async () => {\n    const query = gql`\n      query TestQuery {\n        product {\n          id\n          name\n        }\n      }\n    `;\n\n    let document: DocumentNode;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        Field(node) {\n          if (node.name.value === \"product\" && node.selectionSet) {\n            return {\n              ...node,\n              selectionSet: {\n                ...node.selectionSet,\n                selections: [\n                  ...node.selectionSet.selections,\n                  {\n                    kind: Kind.FRAGMENT_SPREAD,\n                    name: { kind: Kind.NAME, value: \"ProductFields\" },\n                  },\n                ],\n              },\n            };\n          }\n        },\n      });\n    });\n\n    const link = new ApolloLink((operation) => {\n      document = operation.query;\n\n      return of({\n        data: {\n          product: {\n            __typename: \"Product\",\n            id: 1,\n            name: \"Product\",\n            description: \"Product description\",\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        fragments: createFragmentRegistry(gql`\n          fragment ProductFields on Product {\n            description\n          }\n        `),\n      }),\n      documentTransform,\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(document!).toMatchDocument(gql`\n      query TestQuery {\n        product {\n          id\n          name\n          __typename\n          ...ProductFields\n        }\n      }\n\n      fragment ProductFields on Product {\n        description\n        __typename\n      }\n    `);\n\n    expect(data).toEqual({\n      product: {\n        __typename: \"Product\",\n        id: 1,\n        name: \"Product\",\n        description: \"Product description\",\n      },\n    });\n  });\n\n  it('runs custom transforms on active queries when calling `refetchQueries` with \"include\"', async () => {\n    const aQuery = gql`\n      query A {\n        a @custom\n      }\n    `;\n    const bQuery = gql`\n      query B {\n        b @custom\n      }\n    `;\n    const abQuery = gql`\n      query AB {\n        a @custom\n        b\n      }\n    `;\n\n    const requests: ApolloLink.Operation[] = [];\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const client = new ApolloClient({\n      documentTransform,\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        requests.push(operation);\n\n        return of({\n          data: operation\n            .operationName!.split(\"\")\n            .reduce<Record<string, string>>(\n              (memo, letter) => ({\n                ...memo,\n                [letter.toLowerCase()]: letter.toUpperCase(),\n              }),\n              {}\n            ),\n        });\n      }),\n    });\n\n    client.watchQuery({ query: aQuery }).subscribe(jest.fn());\n    client.watchQuery({ query: bQuery }).subscribe(jest.fn());\n    // purposely avoid subscribing to prevent it from being an \"active\" query\n    client.watchQuery({ query: abQuery });\n\n    await waitFor(() => {\n      return (\n        client.readQuery({ query: aQuery }) &&\n        client.readQuery({ query: bQuery })\n      );\n    });\n\n    expect(requests.length).toBe(2);\n    expect(requests[0].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[1].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n\n    const results = await client.refetchQueries({ include: \"active\" });\n\n    expect(results.map((r) => r.data)).toEqual([{ a: \"A\" }, { b: \"B\" }]);\n\n    expect(requests.length).toBe(4);\n    expect(requests[2].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[3].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n  });\n\n  it('runs custom transforms on all queries when calling `refetchQueries` with \"all\"', async () => {\n    const aQuery = gql`\n      query A {\n        a @custom\n      }\n    `;\n    const bQuery = gql`\n      query B {\n        b @custom\n      }\n    `;\n    const abQuery = gql`\n      query AB {\n        a @custom\n        b\n      }\n    `;\n\n    const requests: ApolloLink.Operation[] = [];\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const client = new ApolloClient({\n      documentTransform,\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        requests.push(operation);\n\n        return of({\n          data: operation\n            .operationName!.split(\"\")\n            .reduce<Record<string, string>>(\n              (memo, letter) => ({\n                ...memo,\n                [letter.toLowerCase()]: letter.toUpperCase(),\n              }),\n              {}\n            ),\n        });\n      }),\n    });\n\n    client.watchQuery({ query: aQuery }).subscribe(jest.fn());\n    client.watchQuery({ query: bQuery }).subscribe(jest.fn());\n    client\n      // set `fetchPolicy` to `\"standby\"` to prevent it from being an \"active\" query\n      .watchQuery({ query: abQuery, fetchPolicy: \"standby\" })\n      // need to subscribe to it to ensure it is registered with `QueryManager`\n      .subscribe(jest.fn());\n\n    await waitFor(() => {\n      return (\n        client.readQuery({ query: aQuery }) &&\n        client.readQuery({ query: bQuery })\n      );\n    });\n\n    expect(requests.length).toBe(2);\n    expect(requests[0].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[1].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n\n    const results = await client.refetchQueries({ include: \"all\" });\n\n    expect(results.map((r) => r.data)).toEqual([\n      { a: \"A\" },\n      { b: \"B\" },\n      { a: \"A\", b: \"B\" },\n    ]);\n\n    expect(requests.length).toBe(5);\n    expect(requests[2].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[3].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n    expect(requests[4].query).toMatchDocument(gql`\n      query AB {\n        a\n        b\n      }\n    `);\n  });\n\n  it(\"runs custom transforms on matched queries when calling `refetchQueries` with string array\", async () => {\n    const aQuery = gql`\n      query A {\n        a @custom\n      }\n    `;\n    const bQuery = gql`\n      query B {\n        b @custom\n      }\n    `;\n\n    const requests: ApolloLink.Operation[] = [];\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const client = new ApolloClient({\n      documentTransform,\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        requests.push(operation);\n\n        return of({\n          data: operation\n            .operationName!.split(\"\")\n            .reduce<Record<string, string>>(\n              (memo, letter) => ({\n                ...memo,\n                [letter.toLowerCase()]: letter.toUpperCase(),\n              }),\n              {}\n            ),\n        });\n      }),\n    });\n\n    client.watchQuery({ query: aQuery }).subscribe(jest.fn());\n    client.watchQuery({ query: bQuery }).subscribe(jest.fn());\n\n    await waitFor(() => {\n      return (\n        client.readQuery({ query: aQuery }) &&\n        client.readQuery({ query: bQuery })\n      );\n    });\n\n    expect(requests.length).toBe(2);\n    expect(requests[0].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[1].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n\n    const results = await client.refetchQueries({\n      include: [\"B\"],\n    });\n\n    expect(results.map((r) => r.data)).toEqual([{ b: \"B\" }]);\n\n    expect(requests.length).toBe(3);\n    expect(requests[2].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n  });\n\n  it(\"runs custom transforms on matched queries when calling `refetchQueries` with document nodes\", async () => {\n    const aQuery = gql`\n      query A {\n        a @custom\n      }\n    `;\n    const bQuery = gql`\n      query B {\n        b @custom\n      }\n    `;\n\n    const requests: ApolloLink.Operation[] = [];\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument([{ name: \"custom\" }], document)!;\n    });\n\n    const client = new ApolloClient({\n      documentTransform,\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        requests.push(operation);\n\n        return of({\n          data: operation\n            .operationName!.split(\"\")\n            .reduce<Record<string, string>>(\n              (memo, letter) => ({\n                ...memo,\n                [letter.toLowerCase()]: letter.toUpperCase(),\n              }),\n              {}\n            ),\n        });\n      }),\n    });\n\n    client.watchQuery({ query: aQuery }).subscribe(jest.fn());\n    client.watchQuery({ query: bQuery }).subscribe(jest.fn());\n\n    await waitFor(() => {\n      return (\n        client.readQuery({ query: aQuery }) &&\n        client.readQuery({ query: bQuery })\n      );\n    });\n\n    expect(requests.length).toBe(2);\n    expect(requests[0].query).toMatchDocument(gql`\n      query A {\n        a\n      }\n    `);\n    expect(requests[1].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n\n    const results = await client.refetchQueries({\n      include: [bQuery],\n    });\n\n    expect(results.map((r) => r.data)).toEqual([{ b: \"B\" }]);\n\n    expect(requests.length).toBe(3);\n    expect(requests[2].query).toMatchDocument(gql`\n      query B {\n        b\n      }\n    `);\n  });\n\n  it(\"runs custom document transform when calling `client.readQuery`\", async () => {\n    const query = gql`\n      query TestQuery {\n        dogs {\n          id\n          name\n          breed @custom\n        }\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument(\n        [{ name: \"custom\", remove: true }],\n        document\n      )!;\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache,\n      documentTransform,\n    });\n\n    client.writeQuery({\n      query: gql`\n        query {\n          dogs {\n            id\n            name\n          }\n        }\n      `,\n      data: {\n        dogs: [{ __typename: \"Dog\", id: 1, name: \"Buddy\" }],\n      },\n    });\n\n    expect(client.readQuery({ query })).toStrictEqualTyped({\n      dogs: [\n        {\n          id: 1,\n          name: \"Buddy\",\n          __typename: \"Dog\",\n        },\n      ],\n    });\n\n    // Transforms aren't run on cache.readFragment, so we expect a null result\n    // due to missing `breed` field.\n    expect(cache.readQuery({ query })).toStrictEqualTyped(null);\n  });\n\n  it(\"runs custom document transform when calling `client.readFragment`\", async () => {\n    const fragment = gql`\n      fragment TestFragment on Dog {\n        id\n        name\n        breed @custom\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument(\n        [{ name: \"custom\", remove: true }],\n        document\n      )!;\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache,\n      documentTransform,\n    });\n\n    client.writeFragment({\n      fragment: gql`\n        fragment TestFragment on Dog {\n          id\n          name\n        }\n      `,\n      data: {\n        __typename: \"Dog\",\n        id: 1,\n        name: \"Buddy\",\n      },\n    });\n\n    const id = cache.identify({ __typename: \"Dog\", id: 1 });\n\n    expect(client.readFragment({ fragment, id })).toStrictEqualTyped({\n      id: 1,\n      name: \"Buddy\",\n      __typename: \"Dog\",\n    });\n\n    // Transforms aren't run on cache.readFragment, so we expect a null result\n    // due to missing `breed` field.\n    expect(cache.readFragment({ fragment, id })).toStrictEqualTyped(null);\n  });\n\n  it(\"runs custom document transforms when calling `client.watchFragment`\", async () => {\n    const fragment = gql`\n      fragment TestFragment on Dog {\n        id\n        name\n        breed @custom\n      }\n    `;\n\n    const documentTransform = new DocumentTransform((document) => {\n      return removeDirectivesFromDocument(\n        [{ name: \"custom\", remove: true }],\n        document\n      )!;\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache,\n      documentTransform,\n    });\n\n    client.writeFragment({\n      fragment: gql`\n        fragment TestFragment on Dog {\n          id\n          name\n        }\n      `,\n      data: {\n        __typename: \"Dog\",\n        id: 1,\n        name: \"Buddy\",\n      },\n    });\n\n    const from = { __typename: \"Dog\", id: 1 };\n\n    const clientStream = new ObservableStream(\n      client.watchFragment({ fragment, from })\n    );\n\n    await expect(clientStream).toEmitTypedValue({\n      data: { __typename: \"Dog\", id: 1, name: \"Buddy\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    const cacheStream = new ObservableStream(\n      cache.watchFragment({ fragment, from })\n    );\n\n    // Transforms aren't run on cache.watchFragment, so we expect a partial result\n    // due to missing `breed` field.\n    await expect(cacheStream).toEmitTypedValue({\n      data: { __typename: \"Dog\", id: 1, name: \"Buddy\" },\n      dataState: \"partial\",\n      complete: false,\n      missing: {\n        breed: \"Can't find field 'breed' on Dog:1 object\",\n      },\n    });\n  });\n});\n\ndescribe(\"unconventional errors\", () => {\n  test(\"wraps error message in Error type when erroring with a string\", async () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => {\n        return new Observable((observer) => {\n          setTimeout(() => {\n            observer.error(\"This is an error\");\n          }, 10);\n        });\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    const expectedError = new Error(\"This is an error\");\n\n    await expect(client.query({ query })).rejects.toEqual(expectedError);\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: expectedError,\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(\n      client.mutate({\n        mutation: gql`\n          mutation {\n            foo\n          }\n        `,\n      })\n    ).rejects.toEqual(expectedError);\n\n    const subscription = client.subscribe({\n      query: gql`\n        subscription {\n          foo\n        }\n      `,\n    });\n    const subscriptionStream = new ObservableStream(subscription);\n\n    await expect(subscriptionStream).toEmitTypedValue({\n      data: undefined,\n      error: expectedError,\n    });\n  });\n\n  test(\"wraps unconventional types in UnconventionalError\", async () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n\n    for (const type of [Symbol(), { message: \"This is an error\" }, [\"Error\"]]) {\n      const client = new ApolloClient({\n        link: new ApolloLink(() => {\n          return new Observable((observer) => {\n            setTimeout(() => {\n              observer.error(type);\n            }, 10);\n          });\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      const expectedError = new UnconventionalError(type);\n\n      await expect(client.query({ query })).rejects.toEqual(expectedError);\n\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: expectedError,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      await expect(\n        client.mutate({\n          mutation: gql`\n            mutation {\n              foo\n            }\n          `,\n        })\n      ).rejects.toEqual(expectedError);\n\n      const subscription = client.subscribe({\n        query: gql`\n          subscription {\n            foo\n          }\n        `,\n      });\n      const subscriptionStream = new ObservableStream(subscription);\n\n      await expect(subscriptionStream).toEmitTypedValue({\n        data: undefined,\n        error: expectedError,\n      });\n    }\n  });\n});\n\nasync function clientRoundtrip(\n  query: DocumentNode,\n  data: FormattedExecutionResult,\n  variables?: any,\n  possibleTypes?: PossibleTypesMap\n) {\n  const link = new MockLink([\n    {\n      request: { query: cloneDeep(query) },\n      result: data,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache({\n      possibleTypes,\n    }),\n  });\n\n  const result = await client.query({ query, variables });\n  expect(result.data).toEqual(data.data);\n}\n"
  },
  {
    "path": "src/__tests__/dataMasking.ts",
    "content": "import type { FragmentSpreadNode } from \"graphql\";\nimport { Kind, visit } from \"graphql\";\nimport { of } from \"rxjs\";\n\nimport type { FetchPolicy, TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  DocumentTransform,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { isSubscriptionOperation } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nconst NO_CACHE_WARNING =\n  '[%s]: Fragments masked by data masking are inaccessible when using fetch policy \"no-cache\". Please add `@unmask` to each fragment spread to access the data.';\n\ndescribe(\"client.watchQuery\", () => {\n  test(\"masks queries when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n  });\n\n  test(\"does not mask query when dataMasking is `false`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      });\n    }\n  });\n\n  test(\"does not mask query by default\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      });\n    }\n  });\n\n  test(\"does not mask fragments marked with @unmask\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query UnmaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      });\n    }\n  });\n\n  test(\"does not mask fragments marked with @unmask added by document transforms\", async () => {\n    const documentTransform = new DocumentTransform((document) => {\n      return visit(document, {\n        FragmentSpread(node) {\n          return {\n            ...node,\n            directives: [\n              {\n                kind: Kind.DIRECTIVE,\n                name: { kind: Kind.NAME, value: \"unmask\" },\n              },\n            ],\n          } satisfies FragmentSpreadNode;\n        },\n      });\n    });\n\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query UnmaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n      documentTransform,\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      });\n    }\n  });\n\n  test(\"masks queries updated by the cache\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (updated)\",\n          age: 35,\n        },\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (updated)\",\n        },\n      });\n    }\n  });\n\n  test(\"does not trigger update when updating field in named fragment\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 35,\n        },\n      },\n    });\n\n    await expect(stream.takeNext()).rejects.toThrow(\n      new Error(\"Timeout waiting for next event\")\n    );\n\n    expect(client.readQuery({ query })).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 35,\n      },\n    });\n  });\n\n  it.each([\"cache-first\", \"cache-only\"] as FetchPolicy[])(\n    \"masks result from cache when using with %s fetch policy\",\n    async (fetchPolicy) => {\n      type UserFieldsFragment = {\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      });\n\n      const observable = client.watchQuery({ query, fetchPolicy });\n\n      const stream = new ObservableStream(observable);\n\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n  );\n\n  test(\"masks cache and network result when using cache-and-network fetch policy\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n              age: 35,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 34,\n        },\n      },\n    });\n\n    const observable = client.watchQuery({\n      query,\n      fetchPolicy: \"cache-and-network\",\n    });\n\n    const stream = new ObservableStream(observable);\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      });\n    }\n  });\n\n  test(\"masks partial cache data when returnPartialData is `true`\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n              age: 35,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    {\n      // Silence warning about writing partial data\n      using _ = spyOnConsole(\"error\");\n\n      client.writeQuery({\n        query,\n        data: {\n          // @ts-expect-error writing partial data\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            age: 34,\n          },\n        },\n      });\n    }\n\n    const observable = client.watchQuery({\n      query,\n      returnPartialData: true,\n    });\n\n    const stream = new ObservableStream(observable);\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n        },\n      });\n    }\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      });\n    }\n  });\n\n  test(\"masks partial data returned from data on errors with errorPolicy `all`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string | null;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: null,\n              age: 34,\n            },\n          },\n          errors: [{ message: \"Couldn't get name\" }],\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, errorPolicy: \"all\" });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: null,\n        },\n      },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: null,\n            age: 34,\n          },\n        },\n        errors: [{ message: \"Couldn't get name\" }],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    });\n  });\n\n  it.each([\n    \"cache-first\",\n    \"network-only\",\n    \"cache-and-network\",\n  ] as FetchPolicy[])(\n    \"masks result returned from getCurrentResult when using %s fetchPolicy\",\n    async (fetchPolicy) => {\n      type UserFieldsFragment = {\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 34,\n              },\n            },\n          },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const observable = client.watchQuery({ query, fetchPolicy });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      {\n        const { data } = await stream.takeNext();\n\n        expect(data).toEqual({\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n          },\n        });\n      }\n\n      {\n        const { data } = observable.getCurrentResult();\n\n        expect(data).toEqual({\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n          },\n        });\n      }\n    }\n  );\n\n  test(\"warns when accessing a unmasked field while using @unmask with mode: 'migrate'\", async () => {\n    using consoleSpy = spyOnConsole(\"warn\");\n\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        /** @deprecated */\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query UnmaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask(mode: \"migrate\")\n        }\n      }\n\n      fragment UserFields on User {\n        age\n        name\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 34,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data, dataState } = await stream.takeNext();\n\n      invariant(dataState === \"complete\", \"dataState should be complete\");\n\n      data.currentUser.__typename;\n      data.currentUser.id;\n      data.currentUser.name;\n\n      expect(consoleSpy.warn).not.toHaveBeenCalled();\n\n      data.currentUser.age;\n\n      expect(consoleSpy.warn).toHaveBeenCalledTimes(1);\n      expect(consoleSpy.warn).toHaveBeenCalledWith(\n        \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n        \"query 'UnmaskedQuery'\",\n        \"currentUser.age\"\n      );\n\n      // Ensure we only warn once\n      data.currentUser.age;\n      expect(consoleSpy.warn).toHaveBeenCalledTimes(1);\n    }\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/12043\n  test(\"does not warn when passing @unmask(mode: 'migrate') object to cache.identify\", async () => {\n    using consoleSpy = spyOnConsole(\"warn\");\n\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        /** @deprecated */\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query UnmaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask(mode: \"migrate\")\n        }\n      }\n\n      fragment UserFields on User {\n        age\n        name\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 34,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    const { data, dataState } = await stream.takeNext();\n\n    invariant(dataState === \"complete\", \"dataState should be complete\");\n\n    const id = client.cache.identify(data.currentUser);\n\n    expect(consoleSpy.warn).not.toHaveBeenCalled();\n    expect(id).toEqual(\"User:1\");\n  });\n\n  test(\"reads fragment by passing parent object to `from`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const queryStream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    const { data, dataState } = await queryStream.takeNext();\n\n    invariant(dataState === \"complete\", \"dataState should be complete\");\n\n    const fragmentObservable = client.watchFragment({\n      fragment,\n      from: data.currentUser,\n    });\n\n    const fragmentStream = new ObservableStream(fragmentObservable);\n\n    {\n      const { data, complete } = await fragmentStream.takeNext();\n\n      expect(complete).toBe(true);\n      expect(data).toEqual({ __typename: \"User\", age: 30 });\n    }\n  });\n\n  test(\"warns when passing parent object to `from` when id is masked\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    type UserFieldsFragment = {\n      id: number;\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        age\n      }\n    `;\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          name\n          ...UserFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const queryStream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    const { data, dataState } = await queryStream.takeNext();\n\n    invariant(dataState === \"complete\", \"dataState should be complete\");\n\n    const fragmentObservable = client.watchFragment({\n      fragment,\n      from: data.currentUser,\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n      \"UserFields\"\n    );\n\n    const fragmentStream = new ObservableStream(fragmentObservable);\n\n    {\n      const { data, complete } = await fragmentStream.takeNext();\n\n      expect(data).toEqual({});\n      // TODO: Update when https://github.com/apollographql/apollo-client/issues/12003 is fixed\n      expect(complete).toBe(true);\n    }\n  });\n\n  test(\"warns when passing parent object to `from` that is non-normalized\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          name\n          ...UserFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const queryStream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    const { data, dataState } = await queryStream.takeNext();\n\n    invariant(dataState === \"complete\", \"dataState should be complete\");\n\n    const fragmentObservable = client.watchFragment({\n      fragment,\n      from: data.currentUser,\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n      \"UserFields\"\n    );\n\n    const fragmentStream = new ObservableStream(fragmentObservable);\n\n    {\n      const { data, complete } = await fragmentStream.takeNext();\n\n      expect(data).toEqual({});\n      // TODO: Update when https://github.com/apollographql/apollo-client/issues/12003 is fixed\n      expect(complete).toBe(true);\n    }\n  });\n\n  test(\"can lookup unmasked fragments from the fragment registry in queries\", async () => {\n    const fragments = createFragmentRegistry();\n\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n    `;\n\n    fragments.register(gql`\n      fragment UserFields on User {\n        age\n      }\n    `);\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache({ fragments }),\n      link: new ApolloLink(() => {\n        return of({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        });\n      }),\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      });\n    }\n  });\n\n  test(\"masks result of refetch\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query UnmaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 31,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const result = await observable.refetch();\n\n    expect(result.data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n\n    expect(client.readQuery({ query })).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 31,\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    // Since we don't set notifyOnNetworkStatus to `true`, we don't expect to\n    // see another result since the masked data did not change\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"masks result of setVariables\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      user: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const query: TypedDocumentNode<Query, Variables> = gql`\n      query UnmaskedQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: 1 } },\n        result: {\n          data: {\n            user: {\n              __typename: \"User\",\n              id: 1,\n              name: \"User 1\",\n              age: 30,\n            },\n          },\n        },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: {\n          data: {\n            user: {\n              __typename: \"User\",\n              id: 2,\n              name: \"User 2\",\n              age: 31,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        user: {\n          __typename: \"User\",\n          id: 1,\n          name: \"User 1\",\n        },\n      });\n    }\n\n    const result = await observable.setVariables({ id: 2 });\n\n    expect(result.data).toEqual({\n      user: {\n        __typename: \"User\",\n        id: 2,\n        name: \"User 2\",\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        user: {\n          __typename: \"User\",\n          id: 2,\n          name: \"User 2\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"masks result of reobserve\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      user: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const query: TypedDocumentNode<Query, Variables> = gql`\n      query UnmaskedQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: 1 } },\n        result: {\n          data: {\n            user: {\n              __typename: \"User\",\n              id: 1,\n              name: \"User 1\",\n              age: 30,\n            },\n          },\n        },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: {\n          data: {\n            user: {\n              __typename: \"User\",\n              id: 2,\n              name: \"User 2\",\n              age: 31,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        user: {\n          __typename: \"User\",\n          id: 1,\n          name: \"User 1\",\n        },\n      });\n    }\n\n    const result = await observable.reobserve({ variables: { id: 2 } });\n\n    expect(result.data).toEqual({\n      user: {\n        __typename: \"User\",\n        id: 2,\n        name: \"User 2\",\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        user: {\n          __typename: \"User\",\n          id: 2,\n          name: \"User 2\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"does not mask data passed to updateQuery\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      user: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const query: TypedDocumentNode<Query, Variables> = gql`\n      query UnmaskedQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        user: {\n          __typename: \"User\",\n          id: 1,\n          name: \"User 1\",\n          age: 30,\n        },\n      },\n      variables: { id: 1 },\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        user: {\n          __typename: \"User\",\n          id: 1,\n          name: \"User 1\",\n        },\n      });\n    }\n\n    const updateQuery: Parameters<typeof observable.updateQuery>[0] = jest.fn(\n      (previousResult, { complete, previousData }) => {\n        expect(complete).toBe(true);\n        expect(previousData).toStrictEqual(previousResult);\n        // Type Guard\n        if (!complete) {\n          return;\n        }\n        return {\n          user: { ...previousData.user, name: \"User (updated)\" },\n        };\n      }\n    );\n\n    observable.updateQuery(updateQuery);\n\n    expect(updateQuery).toHaveBeenCalledWith(\n      { user: { __typename: \"User\", id: 1, name: \"User 1\", age: 30 } },\n      {\n        variables: { id: 1 },\n        complete: true,\n        previousData: {\n          user: { __typename: \"User\", id: 1, name: \"User 1\", age: 30 },\n        },\n      }\n    );\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        user: {\n          __typename: \"User\",\n          id: 1,\n          name: \"User (updated)\",\n        },\n      });\n    }\n\n    await expect(stream.takeNext()).rejects.toThrow(\n      new Error(\"Timeout waiting for next event\")\n    );\n  });\n\n  test(\"masks deferred fragments\", async () => {\n    type GreetingFragment = {\n      recipient: {\n        name: string;\n      };\n    } & { \" $fragmentName\"?: \"GreetingFragment\" };\n\n    interface Query {\n      greeting: {\n        __typename: \"Greeting\";\n        message: string;\n      } & { \" $fragmentRefs\"?: { GreetingFragment: GreetingFragment } };\n    }\n\n    const fragment: TypedDocumentNode<GreetingFragment> = gql`\n      fragment GreetingFragment on Greeting {\n        recipient {\n          name\n        }\n      }\n    `;\n\n    const query: TypedDocumentNode<Query> = gql`\n      query {\n        greeting {\n          message\n          ...GreetingFragment @defer\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n        hasNext: true,\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      },\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    link.simulateResult(\n      {\n        result: {\n          incremental: [\n            {\n              data: {\n                recipient: { name: \"Alice\", __typename: \"Person\" },\n                __typename: \"Greeting\",\n              },\n              path: [\"greeting\"],\n            },\n          ],\n          hasNext: false,\n        },\n      },\n      true\n    );\n\n    // Even though `data` didn't change, the `dataState` is updated to reflect\n    // that the full result has been streamed in so we expect another render\n    // value.\n    await expect(stream).toEmitTypedValue({\n      data: {\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(client.readQuery({ query })).toEqual({\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    });\n  });\n\n  test(\"masks deferred fragments within inline fragments\", async () => {\n    type GreetingFragment = {\n      recipient: {\n        name: string;\n      };\n    } & { \" $fragmentName\"?: \"GreetingFragment\" };\n\n    interface Query {\n      greeting: {\n        __typename: \"Greeting\";\n        message: string;\n      } & { \" $fragmentRefs\"?: { GreetingFragment: GreetingFragment } };\n    }\n\n    const fragment: TypedDocumentNode<GreetingFragment> = gql`\n      fragment GreetingFragment on Greeting {\n        recipient {\n          name\n        }\n      }\n    `;\n\n    const query: TypedDocumentNode<Query> = gql`\n      query {\n        greeting {\n          message\n          ... @defer {\n            sentAt\n            ...GreetingFragment\n          }\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n        hasNext: true,\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      });\n    }\n\n    link.simulateResult(\n      {\n        result: {\n          incremental: [\n            {\n              data: {\n                sentAt: \"2024-01-01\",\n                recipient: { name: \"Alice\", __typename: \"Person\" },\n                __typename: \"Greeting\",\n              },\n              path: [\"greeting\"],\n            },\n          ],\n          hasNext: false,\n        },\n      },\n      true\n    );\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n        },\n      });\n    }\n\n    expect(client.readQuery({ query })).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    });\n  });\n\n  test(\"does not mask deferred fragments marked with @unmask\", async () => {\n    type GreetingFragment = {\n      recipient: {\n        name: string;\n      };\n    } & { \" $fragmentName\"?: \"GreetingFragment\" };\n\n    interface Query {\n      greeting: {\n        __typename: \"Greeting\";\n        message: string;\n        recipient: {\n          __typename: \"Person\";\n          name: string;\n        };\n      } & { \" $fragmentRefs\"?: { GreetingFragment: GreetingFragment } };\n    }\n\n    const fragment: TypedDocumentNode<GreetingFragment> = gql`\n      fragment GreetingFragment on Greeting {\n        recipient {\n          name\n        }\n      }\n    `;\n\n    const query: TypedDocumentNode<Query> = gql`\n      query {\n        greeting {\n          message\n          ...GreetingFragment @defer @unmask\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n        hasNext: true,\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      });\n    }\n\n    link.simulateResult(\n      {\n        result: {\n          incremental: [\n            {\n              data: {\n                recipient: { name: \"Alice\", __typename: \"Person\" },\n                __typename: \"Greeting\",\n              },\n              path: [\"greeting\"],\n            },\n          ],\n          hasNext: false,\n        },\n      },\n      true\n    );\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      });\n    }\n\n    expect(client.readQuery({ query })).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    });\n  });\n\n  test(\"handles deferred fragments with a mix of masked and unmasked\", async () => {\n    type GreetingFragment = {\n      recipient: {\n        name: string;\n      };\n    } & { \" $fragmentName\"?: \"GreetingFragment\" };\n\n    type TimeFieldsFragment = {\n      sentAt: string;\n    } & { \" $fragmentName\"?: \"TimeFieldsFragment\" };\n\n    interface Query {\n      greeting: {\n        __typename: \"Greeting\";\n        message: string;\n        recipient: {\n          __typename: \"Person\";\n          name: string;\n        };\n      } & {\n        \" $fragmentRefs\"?: {\n          GreetingFragment: GreetingFragment;\n          TimeFieldsFragment: TimeFieldsFragment;\n        };\n      };\n    }\n\n    const query: TypedDocumentNode<Query> = gql`\n      query {\n        greeting {\n          message\n          ... @defer {\n            ...GreetingFragment @unmask\n            ...TimeFieldsFragment\n          }\n        }\n      }\n\n      fragment GreetingFragment on Greeting {\n        recipient {\n          name\n        }\n      }\n\n      fragment TimeFieldsFragment on Greeting {\n        sentAt\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n        hasNext: true,\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      });\n    }\n\n    link.simulateResult(\n      {\n        result: {\n          incremental: [\n            {\n              data: {\n                sentAt: \"2024-01-01\",\n                recipient: { name: \"Alice\", __typename: \"Person\" },\n                __typename: \"Greeting\",\n              },\n              path: [\"greeting\"],\n            },\n          ],\n          hasNext: false,\n        },\n      },\n      true\n    );\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      });\n    }\n\n    expect(client.readQuery({ query })).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    });\n  });\n\n  test(\"warns and returns masked result when used with no-cache fetch policy\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy: \"no-cache\" });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(NO_CACHE_WARNING, \"MaskedQuery\");\n  });\n\n  test(\"does not warn on no-cache queries when data masking is disabled\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy: \"no-cache\" });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"does not warn on no-cache queries when all fragments use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy: \"no-cache\" });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"warns on no-cache queries when at least one fragment does not use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n        ...ProfileFields\n      }\n\n      fragment ProfileFields on User {\n        username\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n              username: \"testuser\",\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy: \"no-cache\" });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(NO_CACHE_WARNING, \"MaskedQuery\");\n  });\n});\n\ndescribe(\"client.watchFragment\", () => {\n  test(\"masks watched fragments when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { NameFieldsFragment: NameFieldsFragment };\n    };\n\n    type NameFieldsFragment = {\n      __typename: \"User\";\n      firstName: string;\n      lastName: string;\n    } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n    const nameFieldsFragment: TypedDocumentNode<NameFieldsFragment> = gql`\n      fragment NameFields on User {\n        firstName\n        lastName\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<UserFieldsFragment> = gql`\n      fragment UserFields on User {\n        id\n        age\n        ...NameFields\n      }\n\n      ${nameFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n    });\n\n    const fragmentStream = new ObservableStream(\n      client.watchFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        from: { __typename: \"User\", id: 1 },\n      })\n    );\n\n    const result = await fragmentStream.takeNext();\n\n    expect(result).toStrictEqualTyped({\n      data: { __typename: \"User\", id: 1, age: 30 },\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    invariant(result.complete, \"Should never be incomplete\");\n\n    const nestedFragmentStream = new ObservableStream(\n      client.watchFragment({ fragment: nameFieldsFragment, from: result.data })\n    );\n\n    await expect(nestedFragmentStream).toEmitTypedValue({\n      data: { __typename: \"User\", firstName: \"Test\", lastName: \"User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"does not mask watched fragments when dataMasking is disabled\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n    };\n\n    type NameFieldsFragment = {\n      __typename: \"User\";\n      firstName: string;\n      lastName: string;\n    };\n\n    const nameFieldsFragment: TypedDocumentNode<NameFieldsFragment> = gql`\n      fragment NameFields on User {\n        __typename\n        firstName\n        lastName\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<UserFieldsFragment> = gql`\n      fragment UserFields on User {\n        __typename\n        id\n        age\n        ...NameFields\n      }\n\n      ${nameFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n    });\n\n    const fragmentStream = new ObservableStream(\n      client.watchFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        from: { __typename: \"User\", id: 1 },\n      })\n    );\n\n    const result = await fragmentStream.takeNext();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n      dataState: \"complete\",\n      complete: true,\n    });\n    invariant(result.complete, \"Should never be incomplete\");\n\n    const nestedFragmentStream = new ObservableStream(\n      client.watchFragment({ fragment: nameFieldsFragment, from: result.data })\n    );\n\n    await expect(nestedFragmentStream).toEmitTypedValue({\n      data: { __typename: \"User\", firstName: \"Test\", lastName: \"User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"does not mask watched fragments by default\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n    };\n\n    type NameFieldsFragment = {\n      __typename: \"User\";\n      firstName: string;\n      lastName: string;\n    };\n\n    const nameFieldsFragment: TypedDocumentNode<NameFieldsFragment> = gql`\n      fragment NameFields on User {\n        __typename\n        firstName\n        lastName\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<UserFieldsFragment> = gql`\n      fragment UserFields on User {\n        __typename\n        id\n        age\n        ...NameFields\n      }\n\n      ${nameFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n    });\n\n    const fragmentStream = new ObservableStream(\n      client.watchFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        from: { __typename: \"User\", id: 1 },\n      })\n    );\n\n    const result = await fragmentStream.takeNext();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n      dataState: \"complete\",\n      complete: true,\n    });\n    expect(result.complete).toBe(true);\n    invariant(result.complete, \"Should never be incomplete\");\n\n    const nestedFragmentStream = new ObservableStream(\n      client.watchFragment({ fragment: nameFieldsFragment, from: result.data })\n    );\n\n    await expect(nestedFragmentStream).toEmitTypedValue({\n      data: { __typename: \"User\", firstName: \"Test\", lastName: \"User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"does not mask watched fragments marked with @unmask\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"ProfileFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      name: string;\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        name\n        ...ProfileFields @unmask\n      }\n\n      fragment ProfileFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    const observable = client.watchFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"User\", id: 1, name: \"Test User\", age: 30 },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"masks watched fragments updated by the cache\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        name\n        ...ProfileFields\n      }\n\n      fragment ProfileFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    const observable = client.watchFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"User\", id: 1, name: \"Test User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User (updated)\",\n        age: 35,\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"User\", id: 1, name: \"Test User (updated)\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"does not trigger update on watched fragment when updating field in named fragment\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        name\n        ...ProfileFields\n      }\n\n      fragment ProfileFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    const observable = client.watchFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"User\", id: 1, name: \"Test User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 35,\n      },\n    });\n\n    await expect(stream).not.toEmitAnything();\n\n    expect(\n      client.readFragment({\n        fragment,\n        fragmentName: \"UserFields\",\n        id: \"User:1\",\n      })\n    ).toStrictEqualTyped({\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 35,\n    });\n  });\n\n  test(\"triggers update to child watched fragment when updating field in named fragment\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const profileFieldsFragment: TypedDocumentNode<\n      ProfileFieldsFragment,\n      never\n    > = gql`\n      fragment ProfileFields on User {\n        age\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        name\n        ...ProfileFields\n      }\n\n      ${profileFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    const userFieldsObservable = client.watchFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const nameFieldsObservable = client.watchFragment({\n      fragment: profileFieldsFragment,\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const userFieldsStream = new ObservableStream(userFieldsObservable);\n    const nameFieldsStream = new ObservableStream(nameFieldsObservable);\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1, name: \"Test User\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(nameFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 30 },\n        dataState: \"complete\",\n        complete: true,\n      }),\n    ]);\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 35,\n      },\n    });\n\n    await Promise.all([\n      expect(nameFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 35 },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(userFieldsStream).not.toEmitAnything(),\n    ]);\n\n    expect(\n      client.readFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        id: \"User:1\",\n      })\n    ).toStrictEqualTyped({\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 35,\n    });\n  });\n\n  test(\"does not trigger update to watched fragments when updating field in named fragment with @nonreactive\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n      lastUpdatedAt: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      lastUpdatedAt: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const profileFieldsFragment: TypedDocumentNode<\n      ProfileFieldsFragment,\n      never\n    > = gql`\n      fragment ProfileFields on User {\n        age\n        lastUpdatedAt @nonreactive\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        lastUpdatedAt @nonreactive\n        ...ProfileFields\n      }\n\n      ${profileFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        lastUpdatedAt: \"2024-01-01\",\n        age: 30,\n      },\n    });\n\n    const userFieldsObservable = client.watchFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const profileFieldsObservable = client.watchFragment({\n      fragment: profileFieldsFragment,\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const userFieldsStream = new ObservableStream(userFieldsObservable);\n    const profileFieldsStream = new ObservableStream(profileFieldsObservable);\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1, lastUpdatedAt: \"2024-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 30, lastUpdatedAt: \"2024-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n    ]);\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        lastUpdatedAt: \"2024-01-02\",\n        age: 30,\n      },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).not.toEmitAnything(),\n      expect(profileFieldsStream).not.toEmitAnything(),\n    ]);\n\n    expect(\n      client.readFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        id: \"User:1\",\n      })\n    ).toStrictEqualTyped({\n      __typename: \"User\",\n      id: 1,\n      lastUpdatedAt: \"2024-01-02\",\n      age: 30,\n    });\n  });\n\n  test(\"does not trigger update to watched fragments when updating parent field with @nonreactive and child field\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n      lastUpdatedAt: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      lastUpdatedAt: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const profileFieldsFragment: TypedDocumentNode<\n      ProfileFieldsFragment,\n      never\n    > = gql`\n      fragment ProfileFields on User {\n        age\n        lastUpdatedAt @nonreactive\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        lastUpdatedAt @nonreactive\n        ...ProfileFields\n      }\n\n      ${profileFieldsFragment}\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        lastUpdatedAt: \"2024-01-01\",\n        age: 30,\n      },\n    });\n\n    const userFieldsObservable = client.watchFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const profileFieldsObservable = client.watchFragment({\n      fragment: profileFieldsFragment,\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const userFieldsStream = new ObservableStream(userFieldsObservable);\n    const profileFieldsStream = new ObservableStream(profileFieldsObservable);\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1, lastUpdatedAt: \"2024-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 30, lastUpdatedAt: \"2024-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n    ]);\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        lastUpdatedAt: \"2024-01-02\",\n        age: 31,\n      },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).not.toEmitAnything(),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 31, lastUpdatedAt: \"2024-01-02\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n    ]);\n\n    expect(\n      client.readFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        id: \"User:1\",\n      })\n    ).toStrictEqualTyped({\n      __typename: \"User\",\n      id: 1,\n      lastUpdatedAt: \"2024-01-02\",\n      age: 31,\n    });\n  });\n\n  test(\"warns when accessing an unmasked field on a watched fragment while using @unmask with mode: 'migrate'\", async () => {\n    using consoleSpy = spyOnConsole(\"warn\");\n\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n      name: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      name: string;\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const fragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        name\n        ...ProfileFields @unmask(mode: \"migrate\")\n      }\n\n      fragment ProfileFields on User {\n        age\n        name\n      }\n    `;\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      id: client.cache.identify({ __typename: \"User\", id: 1 }),\n      fragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        name: \"Test User\",\n      },\n    });\n\n    const observable = client.watchFragment({\n      fragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n    const stream = new ObservableStream(observable);\n\n    {\n      const { data } = await stream.takeNext();\n      data.__typename;\n      data.id;\n      data.name;\n\n      expect(consoleSpy.warn).not.toHaveBeenCalled();\n\n      data.age;\n\n      expect(consoleSpy.warn).toHaveBeenCalledTimes(1);\n      expect(consoleSpy.warn).toHaveBeenCalledWith(\n        \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n        \"fragment 'UserFields'\",\n        \"age\"\n      );\n\n      // Ensure we only warn once\n      data.age;\n      expect(consoleSpy.warn).toHaveBeenCalledTimes(1);\n    }\n  });\n\n  test(\"can lookup unmasked fragments from the fragment registry in watched fragments\", async () => {\n    const fragments = createFragmentRegistry();\n\n    const profileFieldsFragment = gql`\n      fragment ProfileFields on User {\n        age\n      }\n    `;\n\n    const userFieldsFragment = gql`\n      fragment UserFields on User {\n        id\n        ...ProfileFields @unmask\n      }\n    `;\n\n    fragments.register(profileFieldsFragment);\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache({ fragments }),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n      },\n    });\n\n    const observable = client.watchFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n      },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"reports masked fragment as complete even if masked data is not fully complete\", async () => {\n    type ProfileFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n      lastUpdatedAt: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      birthdate: string;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n\n    const profileFieldsFragment: TypedDocumentNode<\n      ProfileFieldsFragment,\n      never\n    > = gql`\n      fragment ProfileFields on User {\n        age\n        lastUpdatedAt\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<\n      UserFieldsFragment,\n      Record<string, never>\n    > = gql`\n      fragment UserFields on User {\n        id\n        birthdate\n        ...ProfileFields\n      }\n\n      ${profileFieldsFragment}\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache,\n      link: ApolloLink.empty(),\n    });\n\n    const userFieldsObservable = client.watchFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const profileFieldsObservable = client.watchFragment({\n      fragment: profileFieldsFragment,\n      from: { __typename: \"User\", id: 1 },\n    });\n\n    const userFieldsStream = new ObservableStream(userFieldsObservable);\n    const profileFieldsStream = new ObservableStream(profileFieldsObservable);\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: {},\n        dataState: \"partial\",\n        complete: false,\n        missing: \"Dangling reference to missing User:1 object\",\n      }),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: {},\n        dataState: \"partial\",\n        complete: false,\n        missing: \"Dangling reference to missing User:1 object\",\n      }),\n    ]);\n\n    client.writeFragment({\n      fragment: gql`\n        fragment UserFields on User {\n          id\n          birthdate\n        }\n      `,\n      id: cache.identify({ __typename: \"User\", id: 1 }),\n      data: { __typename: \"User\", id: 1, birthdate: \"1994-01-01\" },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1, birthdate: \"1994-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\" },\n        dataState: \"partial\",\n        complete: false,\n        missing: {\n          age: \"Can't find field 'age' on User:1 object\",\n          lastUpdatedAt: \"Can't find field 'lastUpdatedAt' on User:1 object\",\n        },\n      }),\n    ]);\n\n    client.writeFragment({\n      id: cache.identify({ __typename: \"User\", id: 1 }),\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        birthdate: \"1994-01-01\",\n        lastUpdatedAt: \"2024-01-01\",\n      },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).not.toEmitAnything(),\n      expect(profileFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", age: 30, lastUpdatedAt: \"2024-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n    ]);\n\n    cache.modify({\n      id: cache.identify({ __typename: \"User\", id: 1 }),\n      fields: {\n        birthdate: (_, { DELETE }) => DELETE,\n      },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1 },\n        dataState: \"partial\",\n        complete: false,\n        missing: {\n          birthdate: \"Can't find field 'birthdate' on User:1 object\",\n        },\n      }),\n      expect(profileFieldsStream).not.toEmitAnything(),\n    ]);\n\n    client.writeFragment({\n      id: cache.identify({ __typename: \"User\", id: 1 }),\n      fragment: gql`\n        fragment UserFields on User {\n          birthdate\n        }\n      `,\n      data: {\n        __typename: \"User\",\n        birthdate: \"1994-01-01\",\n      },\n    });\n\n    await Promise.all([\n      expect(userFieldsStream).toEmitTypedValue({\n        data: { __typename: \"User\", id: 1, birthdate: \"1994-01-01\" },\n        dataState: \"complete\",\n        complete: true,\n      }),\n      expect(profileFieldsStream).not.toEmitAnything(),\n    ]);\n  });\n});\n\ndescribe(\"cache.watchFragment\", () => {\n  test(\"does not mask fragments when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { NameFieldsFragment: NameFieldsFragment };\n    };\n\n    type NameFieldsFragment = {\n      __typename: \"User\";\n      firstName: string;\n      lastName: string;\n    } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n    const nameFieldsFragment: TypedDocumentNode<NameFieldsFragment> = gql`\n      fragment NameFields on User {\n        firstName\n        lastName\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<UserFieldsFragment> = gql`\n      fragment UserFields on User {\n        id\n        age\n        ...NameFields\n      }\n\n      ${nameFieldsFragment}\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache,\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n    });\n\n    const fragmentStream = new ObservableStream(\n      cache.watchFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        from: { __typename: \"User\", id: 1 },\n      })\n    );\n\n    const result = await fragmentStream.takeNext();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    invariant(result.complete, \"Should never be incomplete\");\n\n    const nestedFragmentStream = new ObservableStream(\n      client.watchFragment({ fragment: nameFieldsFragment, from: result.data })\n    );\n\n    await expect(nestedFragmentStream).toEmitTypedValue({\n      data: { __typename: \"User\", firstName: \"Test\", lastName: \"User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  test(\"does not mask watched fragments when dataMasking is disabled\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n    };\n\n    type NameFieldsFragment = {\n      __typename: \"User\";\n      firstName: string;\n      lastName: string;\n    };\n\n    const nameFieldsFragment: TypedDocumentNode<NameFieldsFragment> = gql`\n      fragment NameFields on User {\n        __typename\n        firstName\n        lastName\n      }\n    `;\n\n    const userFieldsFragment: TypedDocumentNode<UserFieldsFragment> = gql`\n      fragment UserFields on User {\n        __typename\n        id\n        age\n        ...NameFields\n      }\n\n      ${nameFieldsFragment}\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache,\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment: userFieldsFragment,\n      fragmentName: \"UserFields\",\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n    });\n\n    const fragmentStream = new ObservableStream(\n      cache.watchFragment({\n        fragment: userFieldsFragment,\n        fragmentName: \"UserFields\",\n        from: { __typename: \"User\", id: 1 },\n      })\n    );\n\n    const result = await fragmentStream.takeNext();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        firstName: \"Test\",\n        lastName: \"User\",\n      },\n      dataState: \"complete\",\n      complete: true,\n    });\n    invariant(result.complete, \"Should never be incomplete\");\n\n    const nestedFragmentStream = new ObservableStream(\n      cache.watchFragment({ fragment: nameFieldsFragment, from: result.data })\n    );\n\n    await expect(nestedFragmentStream).toEmitTypedValue({\n      data: { __typename: \"User\", firstName: \"Test\", lastName: \"User\" },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n});\n\ndescribe(\"client.query\", () => {\n  test(\"masks data returned from client.query when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n  });\n\n  test(\"does not mask data returned from client.query when dataMasking is `false`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  test(\"does not mask data returned from client.query by default\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  test(\"handles errors returned when using errorPolicy `none`\", async () => {\n    const query = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          errors: [{ message: \"User not logged in\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    await expect(client.query({ query, errorPolicy: \"none\" })).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"User not logged in\" }] })\n    );\n  });\n\n  test(\"handles errors returned when using errorPolicy `all`\", async () => {\n    const query = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: { currentUser: null },\n          errors: [{ message: \"User not logged in\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const result = await client.query({ query, errorPolicy: \"all\" });\n\n    expect(result).toStrictEqualTyped({\n      data: { currentUser: null },\n      error: new CombinedGraphQLErrors({\n        data: { currentUser: null },\n        errors: [{ message: \"User not logged in\" }],\n      }),\n    });\n  });\n\n  test(\"masks fragment data in fields nulled by errors when using errorPolicy `all`\", async () => {\n    const query = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: null,\n            },\n          },\n          errors: [{ message: \"Could not determine age\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const result = await client.query({ query, errorPolicy: \"all\" });\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      error: new CombinedGraphQLErrors({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: null,\n          },\n        },\n        errors: [{ message: \"Could not determine age\" }],\n      }),\n    });\n  });\n\n  test(\"warns and returns masked result when used with no-cache fetch policy\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(NO_CACHE_WARNING, \"MaskedQuery\");\n  });\n\n  test(\"does not warn on no-cache queries when data masking is disabled\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"does not warn on no-cache queries when all fragments use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"warns on no-cache queries when at least one fragment does not use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n        ...ProfileFields\n      }\n\n      fragment ProfileFields on User {\n        username\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n              username: \"testuser\",\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.query({ query, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(NO_CACHE_WARNING, \"MaskedQuery\");\n  });\n});\n\ndescribe(\"client.subscribe\", () => {\n  test(\"masks data returned from subscriptions when dataMasking is `true`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({ query: subscription });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n      },\n    });\n  });\n\n  test(\"does not mask data returned from subscriptions when dataMasking is `false`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({ query: subscription });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n        comment: \"Test comment\",\n        author: \"Test User\",\n      },\n    });\n  });\n\n  test(\"does not mask data returned from subscriptions by default\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({ query: subscription });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n        comment: \"Test comment\",\n        author: \"Test User\",\n      },\n    });\n  });\n\n  test(\"handles errors returned from the subscription when errorPolicy is `none`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      errorPolicy: \"none\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: null,\n        },\n        errors: [{ message: \"Something went wrong\" }],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: { addedComment: null },\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n    });\n  });\n\n  test(\"handles errors returned from the subscription when errorPolicy is `all`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      errorPolicy: \"all\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: null,\n        },\n        errors: [{ message: \"Something went wrong\" }],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { addedComment: null },\n      error: new CombinedGraphQLErrors({\n        data: { addedComment: null },\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n    });\n  });\n\n  test(\"masks partial data for errors returned from the subscription when errorPolicy is `all`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      errorPolicy: \"all\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: null,\n          },\n        },\n        errors: [{ message: \"Could not get author\" }],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { addedComment: { __typename: \"Comment\", id: 1 } },\n      error: new CombinedGraphQLErrors({\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: null,\n          },\n        },\n        errors: [{ message: \"Could not get author\" }],\n      }),\n    });\n  });\n\n  test(\"warns and returns masked result when used with no-cache fetch policy\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      fetchPolicy: \"no-cache\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        addedComment: {\n          __typename: \"Comment\",\n          id: 1,\n        },\n      });\n    }\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 2,\n            comment: \"Test comment 2\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({\n        addedComment: {\n          __typename: \"Comment\",\n          id: 2,\n        },\n      });\n    }\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      NO_CACHE_WARNING,\n      \"NewCommentSubscription\"\n    );\n  });\n\n  test(\"does not warn on no-cache queries when data masking is disabled\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      fetchPolicy: \"no-cache\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n        comment: \"Test comment\",\n        author: \"Test User\",\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"does not warn on no-cache queries when all fragments use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields @unmask\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      fetchPolicy: \"no-cache\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n        comment: \"Test comment\",\n        author: \"Test User\",\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"warns on no-cache queries when at least one fragment does not use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields @unmask\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author {\n          ...AuthorFields\n        }\n      }\n\n      fragment AuthorFields on User {\n        name\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      fetchPolicy: \"no-cache\",\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: { __typename: \"User\", name: \"Test User\" },\n          },\n        },\n      },\n    });\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual({\n      addedComment: {\n        __typename: \"Comment\",\n        id: 1,\n        comment: \"Test comment\",\n        author: { __typename: \"User\" },\n      },\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      NO_CACHE_WARNING,\n      \"NewCommentSubscription\"\n    );\n  });\n});\n\ndescribe(\"observableQuery.subscribeToMore\", () => {\n  test(\"masks query data, does not mask updateQuery callback when dataMasking is `true`\", async () => {\n    const fragment = gql`\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const query = gql`\n      query RecentCommentQuery {\n        recentComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks: MockLink.MockedResponse[] = [\n      {\n        request: { query },\n        result: {\n          data: {\n            recentComment: {\n              __typename: \"Comment\",\n              id: 1,\n              comment: \"Recent comment\",\n              author: \"Test User\",\n            },\n          },\n        },\n      },\n    ];\n\n    const subscriptionLink = new MockSubscriptionLink();\n    const link = ApolloLink.split(\n      (operation) => isSubscriptionOperation(operation.query),\n      subscriptionLink,\n      new MockLink(mocks)\n    );\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery({ query });\n    const queryStream = new ObservableStream(observable);\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({ recentComment: { __typename: \"Comment\", id: 1 } });\n    }\n\n    const updateQuery = jest.fn((_, { subscriptionData }) => {\n      return { recentComment: subscriptionData.data.addedComment };\n    });\n\n    observable.subscribeToMore({ document: subscription, updateQuery });\n\n    subscriptionLink.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 2,\n            comment: \"Most recent comment\",\n            author: \"Test User Jr.\",\n          },\n        },\n      },\n    });\n\n    await wait(0);\n\n    expect(updateQuery).toHaveBeenLastCalledWith(\n      {\n        recentComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Recent comment\",\n          author: \"Test User\",\n        },\n      },\n      {\n        complete: true,\n        variables: {},\n        previousData: {\n          recentComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Recent comment\",\n            author: \"Test User\",\n          },\n        },\n        subscriptionData: {\n          data: {\n            addedComment: {\n              __typename: \"Comment\",\n              id: 2,\n              comment: \"Most recent comment\",\n              author: \"Test User Jr.\",\n            },\n          },\n        },\n      }\n    );\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({ recentComment: { __typename: \"Comment\", id: 2 } });\n    }\n  });\n\n  test(\"does not mask data returned from subscriptions when dataMasking is `false`\", async () => {\n    const fragment = gql`\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const query = gql`\n      query RecentCommentQuery {\n        recentComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks: MockLink.MockedResponse[] = [\n      {\n        request: { query },\n        result: {\n          data: {\n            recentComment: {\n              __typename: \"Comment\",\n              id: 1,\n              comment: \"Recent comment\",\n              author: \"Test User\",\n            },\n          },\n        },\n      },\n    ];\n\n    const subscriptionLink = new MockSubscriptionLink();\n    const link = ApolloLink.split(\n      (operation) => isSubscriptionOperation(operation.query),\n      subscriptionLink,\n      new MockLink(mocks)\n    );\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery({ query });\n    const queryStream = new ObservableStream(observable);\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({\n        recentComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Recent comment\",\n          author: \"Test User\",\n        },\n      });\n    }\n\n    const updateQuery = jest.fn((_, { subscriptionData }) => {\n      return { recentComment: subscriptionData.data.addedComment };\n    });\n\n    observable.subscribeToMore({ document: subscription, updateQuery });\n\n    subscriptionLink.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 2,\n            comment: \"Most recent comment\",\n            author: \"Test User Jr.\",\n          },\n        },\n      },\n    });\n\n    await wait(0);\n\n    expect(updateQuery).toHaveBeenLastCalledWith(\n      {\n        recentComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Recent comment\",\n          author: \"Test User\",\n        },\n      },\n      {\n        complete: true,\n        variables: {},\n        previousData: {\n          recentComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Recent comment\",\n            author: \"Test User\",\n          },\n        },\n        subscriptionData: {\n          data: {\n            addedComment: {\n              __typename: \"Comment\",\n              id: 2,\n              comment: \"Most recent comment\",\n              author: \"Test User Jr.\",\n            },\n          },\n        },\n      }\n    );\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({\n        recentComment: {\n          __typename: \"Comment\",\n          id: 2,\n          comment: \"Most recent comment\",\n          author: \"Test User Jr.\",\n        },\n      });\n    }\n  });\n\n  test(\"does not mask data by default\", async () => {\n    const fragment = gql`\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const query = gql`\n      query RecentCommentQuery {\n        recentComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const subscription = gql`\n      subscription NewCommentSubscription($id: ID!) {\n        addedComment(id: $id) {\n          id\n          ...CommentFields\n        }\n      }\n\n      ${fragment}\n    `;\n\n    const mocks: MockLink.MockedResponse[] = [\n      {\n        request: { query },\n        result: {\n          data: {\n            recentComment: {\n              __typename: \"Comment\",\n              id: 1,\n              comment: \"Recent comment\",\n              author: \"Test User\",\n            },\n          },\n        },\n      },\n    ];\n\n    const subscriptionLink = new MockSubscriptionLink();\n    const link = ApolloLink.split(\n      (operation) => isSubscriptionOperation(operation.query),\n      subscriptionLink,\n      new MockLink(mocks)\n    );\n\n    const client = new ApolloClient({ cache: new InMemoryCache(), link });\n    const observable = client.watchQuery({ query });\n    const queryStream = new ObservableStream(observable);\n\n    await expect(queryStream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({\n        recentComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Recent comment\",\n          author: \"Test User\",\n        },\n      });\n    }\n\n    const updateQuery = jest.fn((_, { subscriptionData }) => {\n      return { recentComment: subscriptionData.data.addedComment };\n    });\n\n    observable.subscribeToMore({\n      document: subscription,\n      updateQuery,\n      variables: { id: 1 },\n    });\n\n    subscriptionLink.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 2,\n            comment: \"Most recent comment\",\n            author: \"Test User Jr.\",\n          },\n        },\n      },\n    });\n\n    await wait(0);\n\n    expect(updateQuery).toHaveBeenLastCalledWith(\n      {\n        recentComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Recent comment\",\n          author: \"Test User\",\n        },\n      },\n      {\n        complete: true,\n        variables: {},\n        previousData: {\n          recentComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Recent comment\",\n            author: \"Test User\",\n          },\n        },\n        subscriptionData: {\n          data: {\n            addedComment: {\n              __typename: \"Comment\",\n              id: 2,\n              comment: \"Most recent comment\",\n              author: \"Test User Jr.\",\n            },\n          },\n        },\n      }\n    );\n\n    {\n      const { data } = await queryStream.takeNext();\n\n      expect(data).toEqual({\n        recentComment: {\n          __typename: \"Comment\",\n          id: 2,\n          comment: \"Most recent comment\",\n          author: \"Test User Jr.\",\n        },\n      });\n    }\n  });\n});\n\ndescribe(\"client.mutate\", () => {\n  test(\"masks data returned from client.mutate when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n  });\n\n  test(\"does not mask data returned from client.mutate when dataMasking is `false`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  test(\"does not mask data returned from client.mutate by default\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  test(\"does not mask data passed to update function\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache,\n      link: new MockLink(mocks),\n    });\n\n    const update = jest.fn();\n    await client.mutate({ mutation, update });\n\n    expect(update).toHaveBeenCalledTimes(1);\n    expect(update).toHaveBeenCalledWith(\n      cache,\n      {\n        data: {\n          updateUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n      { context: undefined, variables: {} }\n    );\n  });\n\n  test(\"handles errors returned when using errorPolicy `none`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          errors: [{ message: \"User not logged in\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    await expect(\n      client.mutate({ mutation, errorPolicy: \"none\" })\n    ).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"User not logged in\" }] })\n    );\n  });\n\n  test(\"handles errors returned when using errorPolicy `all`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser:\n        | ({\n            __typename: \"User\";\n            id: number;\n            name: string;\n          } & {\n            \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n          })\n        | null;\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: { updateUser: null },\n          errors: [{ message: \"User not logged in\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    await expect(\n      client.mutate({\n        mutation,\n        errorPolicy: \"all\",\n      })\n    ).resolves.toStrictEqualTyped({\n      data: { updateUser: null },\n      error: new CombinedGraphQLErrors({\n        data: { updateUser: null },\n        errors: [{ message: \"User not logged in\" }],\n      }),\n    });\n  });\n\n  test(\"masks fragment data in fields nulled by errors when using errorPolicy `all`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: null,\n            },\n          },\n          errors: [{ message: \"Could not determine age\" }],\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    await expect(\n      client.mutate({\n        mutation,\n        errorPolicy: \"all\",\n      })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        updateUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      error: new CombinedGraphQLErrors({\n        data: {\n          updateUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: null,\n          },\n        },\n        errors: [{ message: \"Could not determine age\" }],\n      }),\n    });\n  });\n\n  test(\"warns and returns masked result when used with no-cache fetch policy\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      NO_CACHE_WARNING,\n      \"MaskedMutation\"\n    );\n  });\n\n  test(\"does not warn on no-cache queries when data masking is disabled\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"does not warn on no-cache queries when all fragments use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  test(\"warns on no-cache queries when at least one fragment does not use `@unmask`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n      \" $fragmentRefs\"?: { ProfileFieldsFragment: ProfileFieldsFragment };\n    };\n    type ProfileFieldsFragment = {\n      username: number;\n    } & { \" $fragmentName\"?: \"ProfileFieldsFragment\" };\n\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & {\n        \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment };\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields @unmask\n        }\n      }\n\n      fragment UserFields on User {\n        age\n        ...ProfileFieldsFragment\n      }\n\n      fragment ProfileFieldsFragment on User {\n        username\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n              username: \"testuser\",\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { data } = await client.mutate({ mutation, fetchPolicy: \"no-cache\" });\n\n    expect(data).toEqual({\n      updateUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      NO_CACHE_WARNING,\n      \"MaskedMutation\"\n    );\n  });\n});\n"
  },
  {
    "path": "src/__tests__/exports.ts",
    "content": "/** @jest-environment node */\n// We run this in a node environment because:\n// A) JSDOM doesn't yet support the TextEncoder/TextDecoder globals added in node 11, meaning certain imports (e.g. reactSSR) will fail (See https://github.com/jsdom/jsdom/issues/2524)\n// B) We're just testing imports/exports, so no reason not to use Node for slightly better performance.\n\nimport { resolve } from \"node:path\";\n\nimport { $ } from \"zx\";\n\n// eslint-disable-next-line import/no-duplicates\nimport * as client from \"@apollo/client\";\nimport * as cache from \"@apollo/client/cache\";\n// eslint-disable-next-line import/no-duplicates\nimport * as core from \"@apollo/client/core\";\nimport * as dev from \"@apollo/client/dev\";\nimport * as errors from \"@apollo/client/errors\";\nimport * as incremental from \"@apollo/client/incremental\";\nimport * as linkCore from \"@apollo/client/link\";\nimport * as linkBatch from \"@apollo/client/link/batch\";\nimport * as linkBatchHTTP from \"@apollo/client/link/batch-http\";\nimport * as linkClientAwareness from \"@apollo/client/link/client-awareness\";\nimport * as linkContext from \"@apollo/client/link/context\";\nimport * as linkError from \"@apollo/client/link/error\";\nimport * as linkHTTP from \"@apollo/client/link/http\";\nimport * as linkPersistedQueries from \"@apollo/client/link/persisted-queries\";\nimport * as linkRemoveTypename from \"@apollo/client/link/remove-typename\";\nimport * as linkRetry from \"@apollo/client/link/retry\";\nimport * as linkSchema from \"@apollo/client/link/schema\";\nimport * as linkSubscriptions from \"@apollo/client/link/subscriptions\";\nimport * as linkUtils from \"@apollo/client/link/utils\";\nimport * as linkWS from \"@apollo/client/link/ws\";\nimport * as localState from \"@apollo/client/local-state\";\nimport * as masking from \"@apollo/client/masking\";\nimport * as react from \"@apollo/client/react\";\nimport * as reactInternal from \"@apollo/client/react/internal\";\nimport * as compilerRuntime from \"@apollo/client/react/internal/compiler-runtime\";\nimport * as reactSSR from \"@apollo/client/react/ssr\";\nimport * as testing from \"@apollo/client/testing\";\nimport * as testingInternal from \"@apollo/client/testing/internal\";\nimport * as testingReact from \"@apollo/client/testing/react\";\nimport * as utilities from \"@apollo/client/utilities\";\nimport * as utilitiesEnvironment from \"@apollo/client/utilities/environment\";\nimport * as utilitiesInternal from \"@apollo/client/utilities/internal\";\nimport * as utilitiesInternalGlobals from \"@apollo/client/utilities/internal/globals\";\nimport * as utilitiesInternalPonyfills from \"@apollo/client/utilities/internal/ponyfills\";\nimport * as utilitiesInvariant from \"@apollo/client/utilities/invariant\";\nimport * as v4_migration from \"@apollo/client/v4-migration\";\n\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { entryPoints } from \"../../config/entryPoints.js\";\n\ntype Namespace = object;\n\ndescribe(\"exports of public entry points\", () => {\n  const testedIds = new Set<string>();\n\n  function check(id: string, ns: Namespace) {\n    it(id, () => {\n      testedIds.add(id);\n      expect(Object.keys(ns).sort()).toMatchSnapshot();\n    });\n  }\n  function checkWithConditions(id: string, conditions: string[]) {\n    test(`${id} with conditions [${conditions.join(\",\")}]`, async () => {\n      const exports = await $({\n        cwd: resolve(__dirname, \"../../\"),\n      })`node --experimental-transform-types --no-warnings ${conditions.flatMap(\n        (condition) => [`--conditions`, condition]\n      )} config/listImports.ts ${id}`;\n      expect(\n        exports.stdout.split(\"\\n\").filter((x) => x.trim() !== \"\")\n      ).toMatchSnapshot();\n    });\n  }\n\n  check(\"@apollo/client\", client);\n  check(\"@apollo/client/cache\", cache);\n  check(\"@apollo/client/core\", core);\n  check(\"@apollo/client/dev\", dev);\n  check(\"@apollo/client/errors\", errors);\n  check(\"@apollo/client/incremental\", incremental);\n  check(\"@apollo/client/link/batch\", linkBatch);\n  check(\"@apollo/client/link/batch-http\", linkBatchHTTP);\n  check(\"@apollo/client/link/client-awareness\", linkClientAwareness);\n  check(\"@apollo/client/link/context\", linkContext);\n  check(\"@apollo/client/link\", linkCore);\n  check(\"@apollo/client/link/error\", linkError);\n  check(\"@apollo/client/link/http\", linkHTTP);\n  check(\"@apollo/client/link/persisted-queries\", linkPersistedQueries);\n  check(\"@apollo/client/link/remove-typename\", linkRemoveTypename);\n  check(\"@apollo/client/link/retry\", linkRetry);\n  check(\"@apollo/client/link/schema\", linkSchema);\n  check(\"@apollo/client/link/subscriptions\", linkSubscriptions);\n  check(\"@apollo/client/link/utils\", linkUtils);\n  check(\"@apollo/client/link/ws\", linkWS);\n  check(\"@apollo/client/local-state\", localState);\n  check(\"@apollo/client/masking\", masking);\n  check(\"@apollo/client/react\", react);\n  check(\"@apollo/client/react/internal\", reactInternal);\n  check(\"@apollo/client/react/internal/compiler-runtime\", compilerRuntime);\n  check(\"@apollo/client/react/ssr\", reactSSR);\n  check(\"@apollo/client/testing\", testing);\n  check(\"@apollo/client/testing/internal\", testingInternal);\n  check(\"@apollo/client/testing/react\", testingReact);\n  check(\"@apollo/client/utilities\", utilities);\n  check(\"@apollo/client/utilities/internal\", utilitiesInternal);\n  check(\"@apollo/client/utilities/internal/globals\", utilitiesInternalGlobals);\n  check(\n    \"@apollo/client/utilities/internal/ponyfills\",\n    utilitiesInternalPonyfills\n  );\n  check(\"@apollo/client/utilities/invariant\", utilitiesInvariant);\n  check(\"@apollo/client/utilities/environment\", utilitiesEnvironment);\n  check(\"@apollo/client/v4-migration\", v4_migration);\n\n  checkWithConditions(\"@apollo/client/react\", [\"react-server\"]);\n\n  expect(client).toStrictEqual(core);\n\n  it(\"completeness\", () => {\n    const { join } = require(\"path\").posix;\n    entryPoints.forEach((info: Record<string, any>) => {\n      const id = join(\"@apollo/client\", ...info.dirs);\n      // We don't want to add a devDependency for relay-runtime,\n      // and our API extractor job is already validating its public exports,\n      // so we'll skip the utilities/subscriptions/relay entrypoing here\n      // since it errors on the `relay-runtime` import.\n      if (id === \"@apollo/client/utilities/subscriptions/relay\") return;\n      expect(testedIds).toContain(id);\n    });\n  });\n});\n"
  },
  {
    "path": "src/__tests__/fetchMore.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport { assign, cloneDeep } from \"lodash\";\nimport { Observable } from \"rxjs\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport type {\n  ApolloCache,\n  FieldMergeFunction,\n  InMemoryCacheConfig,\n} from \"@apollo/client/cache\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  markAsStreaming,\n  mockDefer20220824,\n  ObservableStream,\n  setupPaginatedCase,\n} from \"@apollo/client/testing/internal\";\nimport {\n  concatPagination,\n  offsetLimitPagination,\n} from \"@apollo/client/utilities\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"updateQuery on a simple query\", () => {\n  const query = gql`\n    query thing {\n      entry {\n        value\n        __typename\n      }\n      __typename\n    }\n  `;\n  const result = {\n    data: {\n      __typename: \"Query\",\n      entry: {\n        __typename: \"Entry\",\n        value: 1,\n      },\n    },\n  };\n\n  it(\"triggers new result from updateQuery\", async () => {\n    const link = new MockLink([\n      {\n        request: { query },\n        result,\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.watchQuery({ query });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"Query\", entry: { __typename: \"Entry\", value: 1 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    observable.updateQuery((prevResult: any) => {\n      const res = cloneDeep(prevResult);\n      res.entry.value = 2;\n      return res;\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"Query\", entry: { __typename: \"Entry\", value: 2 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n});\n\ndescribe(\"updateQuery on a query with required and optional variables\", () => {\n  const query = gql`\n    query thing($requiredVar: String!, $optionalVar: String) {\n      entry(requiredVar: $requiredVar, optionalVar: $optionalVar) {\n        value\n        __typename\n      }\n      __typename\n    }\n  `;\n  // the test will pass if optionalVar is uncommented\n  const variables = {\n    requiredVar: \"x\",\n    // optionalVar: 'y',\n  };\n  const result = {\n    data: {\n      __typename: \"Query\",\n      entry: {\n        __typename: \"Entry\",\n        value: 1,\n      },\n    },\n  };\n\n  it(\"triggers new result from updateQuery\", async () => {\n    const link = new MockLink([\n      {\n        request: {\n          query,\n          variables,\n        },\n        result,\n        delay: 20,\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables,\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"Query\", entry: { __typename: \"Entry\", value: 1 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    observable.updateQuery((prevResult: any) => {\n      const res = cloneDeep(prevResult);\n      res.entry.value = 2;\n      return res;\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { __typename: \"Query\", entry: { __typename: \"Entry\", value: 2 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n});\n\ndescribe(\"fetchMore on an observable query\", () => {\n  type TCommentData = {\n    entry: {\n      __typename: string;\n      comments: Array<{\n        __typename: string;\n        text: string;\n      }>;\n    };\n  };\n\n  type TCommentVars = {\n    repoName: string;\n    start: number;\n    limit: number;\n  };\n\n  const query: TypedDocumentNode<TCommentData, TCommentVars> = gql`\n    query Comment($repoName: String!, $start: Int!, $limit: Int!) {\n      entry(repoFullName: $repoName) {\n        comments(start: $start, limit: $limit) {\n          text\n          __typename\n        }\n        __typename\n      }\n    }\n  `;\n  const query2: TypedDocumentNode<\n    Omit<TCommentData[\"entry\"], \"__typename\">,\n    Omit<TCommentVars, \"repoName\">\n  > = gql`\n    query NewComments($start: Int!, $limit: Int!) {\n      comments(start: $start, limit: $limit) {\n        text\n        __typename\n      }\n      __typename\n    }\n  `;\n  const variables = {\n    repoName: \"org/repo\",\n    start: 0,\n    limit: 10,\n  };\n  const variablesMore = assign({}, variables, { start: 10, limit: 10 });\n  const variables2 = {\n    start: 10,\n    limit: 20,\n  };\n\n  const result: { data: TCommentData } = {\n    data: {\n      entry: {\n        __typename: \"Entry\",\n        comments: [],\n      },\n    },\n  };\n  const resultMore = cloneDeep(result);\n  const result2: any = {\n    data: {\n      comments: [],\n    },\n  };\n  for (let i = 1; i <= 10; i++) {\n    result.data.entry.comments.push({\n      text: `comment ${i}`,\n      __typename: \"Comment\",\n    });\n  }\n  for (let i = 11; i <= 20; i++) {\n    resultMore.data.entry.comments.push({\n      text: `comment ${i}`,\n      __typename: \"Comment\",\n    });\n    result2.data.comments.push({\n      text: `new comment ${i}`,\n      __typename: \"Comment\",\n    });\n  }\n\n  function setup(...mockedResponses: MockLink.MockedResponse[]) {\n    const link = new MockLink([\n      {\n        request: {\n          query,\n          variables,\n        },\n        result,\n      },\n      ...mockedResponses,\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              entry: {\n                merge: false,\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    return client.watchQuery({\n      query,\n      variables,\n    });\n  }\n\n  function setupWithCacheConfig(\n    cacheConfig: InMemoryCacheConfig,\n    ...mockedResponses: any[]\n  ) {\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: {\n            query,\n            variables,\n          },\n          result,\n        },\n        ...mockedResponses,\n      ]),\n      cache: new InMemoryCache(cacheConfig),\n    });\n\n    return client.watchQuery({\n      query,\n      variables,\n    });\n  }\n\n  describe(\"triggers new result with async new variables\", () => {\n    it(\"updateQuery\", async () => {\n      const observable = setup({\n        request: {\n          query,\n          variables: variablesMore,\n        },\n        result: resultMore,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          // Rely on the fact that the original variables had limit: 10\n          variables: { start: 10 },\n          updateQuery: (prev, options) => {\n            expect(options.variables).toEqual(variablesMore);\n\n            const state = cloneDeep(prev) as any;\n            state.entry.comments = [\n              ...state.entry.comments,\n              ...options.fetchMoreResult.entry.comments,\n            ];\n            return state;\n          },\n        });\n\n        // This is the server result\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"field policy\", async () => {\n      const observable = setupWithCacheConfig(\n        {\n          typePolicies: {\n            Entry: {\n              fields: {\n                comments: concatPagination(),\n              },\n            },\n          },\n        },\n        {\n          request: { query, variables: variablesMore },\n          result: resultMore,\n        }\n      );\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: expect.arrayWithLength(10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          // Rely on the fact that the original variables had limit: 10\n          variables: { start: 10 },\n        });\n\n        // This is the server result\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: expect.arrayWithLength(10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: expect.arrayWithLength(20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"basic fetchMore results merging\", () => {\n    it(\"updateQuery\", async () => {\n      const observable = setup({\n        request: {\n          query,\n          variables: variablesMore,\n        },\n        result: resultMore,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: { start: 10 }, // rely on the fact that the original variables had limit: 10\n          updateQuery: (prev, options) => {\n            expect(options.variables).toEqual(variablesMore);\n            const state = cloneDeep(prev) as any;\n            state.entry.comments = [\n              ...state.entry.comments,\n              ...options.fetchMoreResult.entry.comments,\n            ];\n            return state;\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: expect.arrayWithLength(10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"field policy\", async () => {\n      const observable = setupWithCacheConfig(\n        {\n          typePolicies: {\n            Entry: {\n              fields: {\n                comments: concatPagination(),\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: variablesMore,\n          },\n          result: resultMore,\n        }\n      );\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          // rely on the fact that the original variables had limit: 10\n          variables: { start: 10 },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"fetchMore interaction with network fetch policies\", () => {\n    const tasks = [\n      { __typename: \"Task\", id: 1, text: \"first task\" },\n      { __typename: \"Task\", id: 2, text: \"second task\" },\n      { __typename: \"Task\", id: 3, text: \"third task\" },\n      { __typename: \"Task\", id: 4, text: \"fourth task\" },\n      { __typename: \"Task\", id: 5, text: \"fifth task\" },\n      { __typename: \"Task\", id: 6, text: \"sixth task\" },\n      { __typename: \"Task\", id: 7, text: \"seventh task\" },\n      { __typename: \"Task\", id: 8, text: \"eighth task\" },\n    ];\n\n    const query = gql`\n      query GetTODOs {\n        TODO {\n          id\n          text\n        }\n      }\n    `;\n\n    function makeClient(): {\n      client: ApolloClient;\n      linkRequests: Array<{\n        operationName: string;\n        offset: number;\n        limit: number;\n      }>;\n    } {\n      const linkRequests: Array<{\n        operationName: string;\n        offset: number;\n        limit: number;\n      }> = [];\n\n      const client = new ApolloClient({\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              const {\n                variables: { offset = 0, limit = 2 },\n              } = operation;\n\n              linkRequests.push({\n                operationName: operation.operationName!,\n                offset,\n                limit,\n              });\n\n              observer.next({\n                data: {\n                  TODO: tasks.slice(offset, offset + limit),\n                },\n              });\n\n              observer.complete();\n            })\n        ),\n\n        cache: new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                TODO: concatPagination(),\n              },\n            },\n          },\n        }),\n      });\n\n      return {\n        client,\n        linkRequests,\n      };\n    }\n\n    function checkCacheExtract1234678(cache: ApolloCache) {\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          TODO: [\n            { __ref: \"Task:1\" },\n            { __ref: \"Task:2\" },\n            { __ref: \"Task:3\" },\n            { __ref: \"Task:4\" },\n            { __ref: \"Task:6\" },\n            { __ref: \"Task:7\" },\n            { __ref: \"Task:8\" },\n          ],\n        },\n        \"Task:1\": tasks[0],\n        \"Task:2\": tasks[1],\n        \"Task:3\": tasks[2],\n        \"Task:4\": tasks[3],\n        \"Task:6\": tasks[5],\n        \"Task:7\": tasks[6],\n        \"Task:8\": tasks[7],\n      });\n    }\n\n    it(\"cache-and-network\", async () => {\n      const { client, linkRequests } = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n        variables: {\n          offset: 0,\n          limit: 2,\n        },\n      });\n\n      expect(linkRequests.length).toBe(0);\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 2,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: { TODO: tasks.slice(2, 4) },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: { TODO: tasks.slice(0, 2) },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 5,\n            limit: 3,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(5, 8),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: { TODO: tasks.slice(0, 4) },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: [...tasks.slice(0, 4), ...tasks.slice(5, 8)],\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 5, limit: 3 },\n      ]);\n\n      checkCacheExtract1234678(client.cache);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"cache-and-network with notifyOnNetworkStatusChange: true\", async () => {\n      const { client, linkRequests } = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n        notifyOnNetworkStatusChange: true,\n        variables: {\n          offset: 0,\n          limit: 2,\n        },\n      });\n\n      expect(linkRequests.length).toBe(0);\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 2,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(2, 4),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 5,\n            limit: 3,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(5, 8),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: [...tasks.slice(0, 4), ...tasks.slice(5, 8)],\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 5, limit: 3 },\n      ]);\n\n      checkCacheExtract1234678(client.cache);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"network-only\", async () => {\n      const { client, linkRequests } = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"network-only\",\n        variables: {\n          offset: 0,\n          limit: 2,\n        },\n      });\n\n      expect(linkRequests.length).toBe(0);\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 2,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(2, 4),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: { TODO: tasks.slice(0, 2) },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 5,\n            limit: 3,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(5, 8),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: { TODO: tasks.slice(0, 4) },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: [...tasks.slice(0, 4), ...tasks.slice(5, 8)],\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 5, limit: 3 },\n      ]);\n      checkCacheExtract1234678(client.cache);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"network-only with notifyOnNetworkStatusChange: true\", async () => {\n      const { client, linkRequests } = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"network-only\",\n        notifyOnNetworkStatusChange: true,\n        variables: {\n          offset: 0,\n          limit: 2,\n        },\n      });\n\n      expect(linkRequests.length).toBe(0);\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 2,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(2, 4),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        data: {\n          TODO: tasks.slice(0, 2),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n      ]);\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: {\n            offset: 5,\n            limit: 3,\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            TODO: tasks.slice(5, 8),\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        data: {\n          TODO: tasks.slice(0, 4),\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          TODO: [...tasks.slice(0, 4), ...tasks.slice(5, 8)],\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n\n      expect(linkRequests).toEqual([\n        { operationName: \"GetTODOs\", offset: 0, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 2, limit: 2 },\n        { operationName: \"GetTODOs\", offset: 5, limit: 3 },\n      ]);\n      checkCacheExtract1234678(client.cache);\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  it(\"fetchMore passes new args to field merge function\", async () => {\n    const mergeArgsHistory: (Record<string, any> | null)[] = [];\n    const groceriesFieldPolicy = offsetLimitPagination();\n    const { merge } = groceriesFieldPolicy;\n    groceriesFieldPolicy.merge = function (existing, incoming, options) {\n      mergeArgsHistory.push(options.args);\n      return (merge as FieldMergeFunction<any>).call(\n        this,\n        existing,\n        incoming,\n        options\n      );\n    };\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            groceries: groceriesFieldPolicy,\n          },\n        },\n      },\n    });\n\n    const query = gql`\n      query GroceryList($offset: Int!, $limit: Int!) {\n        groceries(offset: $offset, limit: $limit) {\n          id\n          item\n          found\n        }\n      }\n    `;\n\n    const initialVars = {\n      offset: 0,\n      limit: 2,\n    };\n\n    const initialGroceries = [\n      {\n        __typename: \"GroceryItem\",\n        id: 1,\n        item: \"organic whole milk\",\n        found: false,\n      },\n      {\n        __typename: \"GroceryItem\",\n        id: 2,\n        item: \"beer that we both like\",\n        found: false,\n      },\n    ];\n\n    const additionalVars = {\n      offset: 2,\n      limit: 3,\n    };\n\n    const additionalGroceries = [\n      {\n        __typename: \"GroceryItem\",\n        id: 3,\n        item: \"gluten-free pasta\",\n        found: false,\n      },\n      {\n        __typename: \"GroceryItem\",\n        id: 4,\n        item: \"goat cheese\",\n        found: false,\n      },\n      {\n        __typename: \"GroceryItem\",\n        id: 5,\n        item: \"paper towels\",\n        found: false,\n      },\n    ];\n\n    const finalGroceries = [...initialGroceries, ...additionalGroceries];\n\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: {\n            query,\n            variables: initialVars,\n          },\n          result: {\n            data: {\n              groceries: initialGroceries,\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: additionalVars,\n          },\n          result: {\n            data: {\n              groceries: additionalGroceries,\n            },\n          },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: initialVars,\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        groceries: initialGroceries,\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    expect(mergeArgsHistory).toEqual([{ offset: 0, limit: 2 }]);\n\n    {\n      const fetchMoreResult = await observable.fetchMore({\n        variables: {\n          offset: 2,\n          limit: 3,\n        },\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: {\n          groceries: additionalGroceries,\n        },\n      });\n\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: { groceries: initialGroceries },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n      partial: false,\n    });\n\n    // This result comes entirely from the cache, without updating the\n    // original variables for the ObservableQuery, because the\n    // offsetLimitPagination field policy has keyArgs:false.\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        groceries: finalGroceries,\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    expect(mergeArgsHistory).toEqual([\n      { offset: 0, limit: 2 },\n      { offset: 2, limit: 3 },\n    ]);\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"fetching more with a different query\", async () => {\n    const observable = setup({\n      request: {\n        query: query2,\n        variables: variables2,\n      },\n      result: result2,\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    {\n      const fetchMoreResult = await observable.fetchMore({\n        query: query2,\n        variables: variables2,\n        updateQuery: (prev, options) => {\n          const state = cloneDeep(prev) as any;\n          state.entry.comments = [\n            ...state.entry.comments,\n            ...options.fetchMoreResult.comments,\n          ];\n          return state;\n        },\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: {\n          comments: commentsInRange(11, 20, (i) => `new comment ${i}`),\n        },\n      });\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        entry: {\n          __typename: \"Entry\",\n          comments: expect.arrayWithLength(10),\n        },\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        entry: {\n          __typename: \"Entry\",\n          comments: commentsInRange(1, 20, (i) =>\n            i <= 10 ? `comment ${i}` : `new comment ${i}`\n          ),\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  describe(\"will not get an error from `fetchMore` if thrown\", () => {\n    it(\"updateQuery\", async () => {\n      const fetchMoreError = new Error(\"Uh, oh!\");\n      const link = new MockLink([\n        {\n          request: { query, variables },\n          result,\n          delay: 5,\n        },\n        {\n          request: { query, variables: variablesMore },\n          error: fetchMoreError,\n          delay: 5,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const error = await observable\n        .fetchMore({\n          variables: { start: 10 },\n          updateQuery: () => {\n            throw new Error(\"should not have called updateQuery\");\n          },\n        })\n        .catch((error) => error);\n\n      expect(error).toBe(fetchMoreError);\n    });\n\n    it(\"field policy\", async () => {\n      const fetchMoreError = new Error(\"Uh, oh!\");\n      const link = new MockLink([\n        {\n          request: { query, variables },\n          result,\n          delay: 5,\n        },\n        {\n          request: { query, variables: variablesMore },\n          error: fetchMoreError,\n          delay: 5,\n        },\n      ]);\n\n      let calledFetchMore = false;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            Entry: {\n              fields: {\n                comments: {\n                  keyArgs: false,\n                  merge(_, incoming) {\n                    if (calledFetchMore) {\n                      throw new Error(\"should not have called merge\");\n                    }\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const error = await observable\n        .fetchMore({\n          variables: { start: 10 },\n        })\n        .catch((error) => error);\n\n      expect(error).toBe(fetchMoreError);\n    });\n  });\n\n  it(\"will not leak fetchMore query\", async () => {\n    const observable = setup({\n      request: {\n        query,\n        variables: variablesMore,\n      },\n      result: resultMore,\n    });\n\n    function count(): number {\n      const qm = observable[\"queryManager\"];\n      return qm.obsQueries.size + qm[\"fetchCancelFns\"].size;\n    }\n\n    const beforeQueryCount = count();\n\n    const promise = observable.fetchMore({\n      variables: { start: 10 }, // rely on the fact that the original variables had limit: 10\n    });\n\n    expect(count()).toBeGreaterThan(beforeQueryCount);\n\n    await promise;\n\n    expect(count()).toBe(beforeQueryCount);\n  });\n\n  it(\"delivers all loading states even if data unchanged\", async () => {\n    type TEmptyItems = {\n      emptyItems: Array<{\n        text: string;\n      }>;\n    };\n\n    const query: TypedDocumentNode<TEmptyItems> = gql`\n      query GetNothing {\n        emptyItems {\n          text\n        }\n      }\n    `;\n\n    const variables = {};\n\n    const emptyItemsMock = {\n      request: {\n        query,\n        variables,\n      },\n      result: {\n        data: {\n          emptyItems: [],\n        },\n      },\n    };\n\n    const link = new MockLink([emptyItemsMock, emptyItemsMock, emptyItemsMock]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.watchQuery({ query, variables });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        emptyItems: [],\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    const fetchMoreResult = await observable.fetchMore({\n      variables,\n    });\n\n    expect(fetchMoreResult).toStrictEqualTyped({\n      data: { emptyItems: [] },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n      data: {\n        emptyItems: [],\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        emptyItems: [],\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"`errorPolicy` defaults to `none`\", async () => {\n    const query = gql`\n      query {\n        fail\n      }\n    `;\n    const observable = setup({\n      request: { query },\n      error: new Error(\"This is an error\"),\n    });\n    const stream = new ObservableStream(observable);\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream).toEmitTypedValue({\n      data: result.data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const updateQuery = jest.fn();\n    const promise = observable.fetchMore({\n      query,\n      updateQuery,\n    });\n    await expect(promise).rejects.toThrow(\"This is an error\");\n    expect(updateQuery).not.toHaveBeenCalled();\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n      }),\n    });\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n      }),\n    });\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"`errorPolicy` can be overwritten to `ignore`\", async () => {\n    const query = gql`\n      query {\n        fail\n      }\n    `;\n    const observable = setup({\n      request: { query },\n      error: new Error(\"This is an error\"),\n    });\n    const stream = new ObservableStream(observable);\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream).toEmitTypedValue({\n      data: result.data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const fallbackResult: TCommentData = {\n      entry: {\n        ...result.data.entry,\n        comments: result.data.entry.comments.concat({\n          __typename: \"Comment\",\n          text: \"fallback comment\",\n        }),\n      },\n    };\n\n    const updateQuery = jest.fn(\n      (previousResult: TCommentData): TCommentData => fallbackResult\n    );\n    const promise = observable.fetchMore({\n      query,\n      updateQuery,\n      errorPolicy: \"ignore\",\n    });\n    await expect(promise).resolves.toStrictEqualTyped({ data: undefined });\n    expect(updateQuery).toHaveBeenCalledTimes(1);\n    expect(updateQuery).toHaveBeenNthCalledWith(1, result.data, {\n      fetchMoreResult: undefined,\n      variables: undefined,\n    });\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n      }),\n    });\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        data: fallbackResult,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n      }),\n    });\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"`errorPolicy` can be overwritten to `all`\", async () => {\n    const query = gql`\n      query {\n        fail\n      }\n    `;\n    const observable = setup({\n      request: { query },\n      result: {\n        data: {\n          entry: {\n            __typename: \"Entry\",\n          },\n        },\n        errors: [{ message: \"This is an error\" }],\n      },\n    });\n    const stream = new ObservableStream(observable);\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream).toEmitTypedValue({\n      data: result.data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const fallbackResult: TCommentData = {\n      entry: {\n        ...result.data.entry,\n        comments: result.data.entry.comments.concat({\n          __typename: \"Comment\",\n          text: \"fallback comment\",\n        }),\n      },\n    };\n\n    const updateQuery = jest.fn(\n      (previousResult: TCommentData): TCommentData => fallbackResult\n    );\n    const promise = observable.fetchMore({\n      query,\n      updateQuery,\n      errorPolicy: \"all\",\n    });\n    await expect(promise).resolves.toStrictEqual({\n      data: {\n        entry: {\n          __typename: \"Entry\",\n        },\n      },\n      error: new CombinedGraphQLErrors({\n        data: {\n          entry: {\n            __typename: \"Entry\",\n          },\n        },\n        errors: [{ message: \"This is an error\" }],\n      }),\n    });\n    expect(updateQuery).toHaveBeenCalledTimes(1);\n    expect(updateQuery).toHaveBeenNthCalledWith(1, result.data, {\n      fetchMoreResult: {\n        entry: {\n          __typename: \"Entry\",\n        },\n      },\n      variables: undefined,\n    });\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n      }),\n    });\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        data: fallbackResult,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n      }),\n    });\n    await expect(stream).not.toEmitAnything();\n  });\n});\n\ndescribe(\"fetchMore on an observable query with connection\", () => {\n  type TEntryComments = {\n    entry: {\n      comments: Array<{\n        text: string;\n        __typename?: string;\n      }>;\n      __typename?: string;\n    };\n  };\n\n  type TEntryVars = {\n    repoName: string;\n    start: number;\n    limit: number;\n  };\n\n  const query: TypedDocumentNode<TEntryComments, TEntryVars> = gql`\n    query Comment($repoName: String!, $start: Int!, $limit: Int!) {\n      entry(repoFullName: $repoName, start: $start, limit: $limit)\n        @connection(key: \"repoName\") {\n        comments {\n          text\n        }\n      }\n    }\n  `;\n  const transformedQuery: TypedDocumentNode<TEntryComments, TEntryVars> = gql`\n    query Comment($repoName: String!, $start: Int!, $limit: Int!) {\n      entry(repoFullName: $repoName, start: $start, limit: $limit) {\n        comments {\n          text\n          __typename\n        }\n        __typename\n      }\n    }\n  `;\n\n  const variables = {\n    repoName: \"org/repo\",\n    start: 0,\n    limit: 10,\n  };\n  const variablesMore = assign({}, variables, { start: 10, limit: 10 });\n\n  const result: any = {\n    data: {\n      entry: {\n        __typename: \"Entry\",\n        comments: [],\n      },\n    },\n  };\n  const resultMore = cloneDeep(result);\n\n  for (let i = 1; i <= 10; i++) {\n    result.data.entry.comments.push({\n      text: `comment ${i}`,\n      __typename: \"Comment\",\n    });\n  }\n  for (let i = 11; i <= 20; i++) {\n    resultMore.data.entry.comments.push({\n      text: `comment ${i}`,\n      __typename: \"Comment\",\n    });\n  }\n\n  function setup(...mockedResponses: MockLink.MockedResponse[]) {\n    const link = new MockLink([\n      {\n        request: {\n          query: transformedQuery,\n          variables,\n        },\n        result,\n      },\n      ...mockedResponses,\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              entry: {\n                merge: false,\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    return client.watchQuery({\n      query,\n      variables,\n    });\n  }\n\n  function setupWithCacheConfig(\n    cacheConfig: InMemoryCacheConfig,\n    ...mockedResponses: any[]\n  ) {\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: {\n            query: transformedQuery,\n            variables,\n          },\n          result,\n        },\n        ...mockedResponses,\n      ]),\n      cache: new InMemoryCache(cacheConfig),\n    });\n\n    return client.watchQuery({\n      query,\n      variables,\n    });\n  }\n\n  describe(\"fetchMore with connection results merging\", () => {\n    it(\"updateQuery\", async () => {\n      const observable = setup({\n        request: {\n          query: transformedQuery,\n          variables: variablesMore,\n        },\n        result: resultMore,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          variables: { start: 10 }, // rely on the fact that the original variables had limit: 10\n          updateQuery: (prev, options) => {\n            const state = cloneDeep(prev) as any;\n            state.entry.comments = [\n              ...state.entry.comments,\n              ...options.fetchMoreResult.entry.comments,\n            ];\n            return state;\n          },\n        });\n\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"field policy\", async () => {\n      const observable = setupWithCacheConfig(\n        {\n          typePolicies: {\n            Entry: {\n              fields: {\n                comments: concatPagination(),\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query: transformedQuery,\n            variables: variablesMore,\n          },\n          result: resultMore,\n        }\n      );\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      {\n        const fetchMoreResult = await observable.fetchMore({\n          // rely on the fact that the original variables had limit: 10\n          variables: { start: 10 },\n        });\n\n        // this is the server result\n        expect(fetchMoreResult).toStrictEqualTyped({\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n        });\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: {\n            __typename: \"Entry\",\n            comments: expect.arrayWithLength(10),\n          },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"will set the network status to `fetchMore`\", () => {\n    it(\"updateQuery\", async () => {\n      const link = new MockLink([\n        {\n          request: { query: transformedQuery, variables },\n          result,\n          delay: 5,\n        },\n        {\n          request: { query: transformedQuery, variables: variablesMore },\n          result: resultMore,\n          delay: 5,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void observable.fetchMore({\n        variables: { start: 10 },\n        updateQuery: (prev: any, options: any) => {\n          const state = cloneDeep(prev) as any;\n          state.entry.comments = [\n            ...state.entry.comments,\n            ...options.fetchMoreResult.entry.comments,\n          ];\n          return state;\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"field policy\", async () => {\n      const link = new MockLink([\n        {\n          request: { query: transformedQuery, variables },\n          result,\n          delay: 5,\n        },\n        {\n          request: { query: transformedQuery, variables: variablesMore },\n          result: resultMore,\n          delay: 5,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            Entry: {\n              fields: {\n                comments: concatPagination(),\n              },\n            },\n          },\n        }),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void observable.fetchMore({\n        variables: { start: 10 },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.fetchMore,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n});\n\ntest(\"uses updateQuery to update the result of the query with no-cache queries\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n  const observable = client.watchQuery({\n    query,\n    fetchPolicy: \"no-cache\",\n    variables: { limit: 2 },\n  });\n\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"A\", position: 1 },\n        { __typename: \"Letter\", letter: \"B\", position: 2 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  let fetchMoreResult = await observable.fetchMore({\n    variables: { offset: 2 },\n    updateQuery: (prev, { fetchMoreResult }) => ({\n      letters: prev.letters.concat(fetchMoreResult.letters),\n    }),\n  });\n\n  expect(fetchMoreResult).toStrictEqualTyped({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"C\", position: 3 },\n        { __typename: \"Letter\", letter: \"D\", position: 4 },\n      ],\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"A\", position: 1 },\n        { __typename: \"Letter\", letter: \"B\", position: 2 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.fetchMore,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"A\", position: 1 },\n        { __typename: \"Letter\", letter: \"B\", position: 2 },\n        { __typename: \"Letter\", letter: \"C\", position: 3 },\n        { __typename: \"Letter\", letter: \"D\", position: 4 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  // Ensure we store the merged result as the last result\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"A\", position: 1 },\n        { __typename: \"Letter\", letter: \"B\", position: 2 },\n        { __typename: \"Letter\", letter: \"C\", position: 3 },\n        { __typename: \"Letter\", letter: \"D\", position: 4 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  fetchMoreResult = await observable.fetchMore({\n    variables: { offset: 4 },\n    updateQuery: (_, { fetchMoreResult }) => fetchMoreResult,\n  });\n\n  expect(fetchMoreResult).toStrictEqualTyped({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"E\", position: 5 },\n        { __typename: \"Letter\", letter: \"F\", position: 6 },\n      ],\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"A\", position: 1 },\n        { __typename: \"Letter\", letter: \"B\", position: 2 },\n        { __typename: \"Letter\", letter: \"C\", position: 3 },\n        { __typename: \"Letter\", letter: \"D\", position: 4 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.fetchMore,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"E\", position: 5 },\n        { __typename: \"Letter\", letter: \"F\", position: 6 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: {\n      letters: [\n        { __typename: \"Letter\", letter: \"E\", position: 5 },\n        { __typename: \"Letter\", letter: \"F\", position: 6 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"calling `fetchMore` on an ObservableQuery that hasn't finished deferring yet will not put it into completed state\", async () => {\n  const defer = mockDefer20220824();\n  const baseLink = new MockSubscriptionLink();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.split(\n      (op) => op.operationName === \"DeferQuery\",\n      defer.httpLink,\n      baseLink\n    ),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const deferredQuery = gql`\n    query DeferQuery {\n      people(from: 1, count: 2) {\n        id\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const fetchMoreQuery = gql`\n    query FetchMoreQuery {\n      people(from: 2, count: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observable = client.watchQuery({\n    query: deferredQuery,\n    variables: {},\n    fetchPolicy: \"no-cache\",\n  });\n\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  const initialData = {\n    people: [\n      {\n        __typename: \"Person\",\n        id: 1,\n      },\n      {\n        __typename: \"Person\",\n        id: 2,\n      },\n    ],\n  };\n\n  defer.enqueueInitialChunk({ data: initialData, hasNext: true });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming(initialData),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  defer.enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          name: \"Alice\",\n        },\n        path: [\"people\", 0],\n      },\n    ],\n    hasNext: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      people: [\n        {\n          __typename: \"Person\",\n          id: 1,\n          name: \"Alice\",\n        },\n        {\n          __typename: \"Person\",\n          id: 2,\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  void observable.fetchMore<any>({\n    query: fetchMoreQuery,\n    updateQuery(previousQueryResult: any, options) {\n      const newPeople = options.fetchMoreResult.people;\n      return {\n        ...previousQueryResult,\n        people: [...previousQueryResult.people, ...newPeople],\n      };\n    },\n  });\n\n  await expect(stream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n    }),\n  });\n\n  baseLink.simulateResult(\n    {\n      result: {\n        data: {\n          people: [\n            {\n              __typename: \"Person\",\n              id: 3,\n              name: \"Charles\",\n            },\n          ],\n        },\n      },\n    },\n    true\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      people: [\n        {\n          __typename: \"Person\",\n          id: 1,\n          name: \"Alice\",\n        },\n        {\n          __typename: \"Person\",\n          id: 2,\n        },\n        {\n          __typename: \"Person\",\n          id: 3,\n          name: \"Charles\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    // TODO: This should be streaming. Should be fixed with\n    // https://github.com/apollographql/apollo-client/issues/12668\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n});\n\ntest(\"does not allow fetchMore on a cache-only query\", async () => {\n  const query = gql`\n    query Comment($repoName: String!, $start: Int!, $limit: Int!) {\n      entry(repoFullName: $repoName) {\n        comments(start: $start, limit: $limit) {\n          text\n          __typename\n        }\n        __typename\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: ApolloLink.empty(),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({ query, fetchPolicy: \"cache-only\" });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: true,\n  });\n\n  expect(() =>\n    observable.fetchMore({ variables: { start: 10, limit: 10 } })\n  ).toThrow(\n    new InvariantError(\n      \"Cannot execute `fetchMore` for 'cache-only' query 'Comment'. Please use a different fetch policy.\"\n    )\n  );\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"provides extensions in merge functions\", async () => {\n  const query = gql`\n    query Comment($repoName: String!, $start: Int!, $limit: Int!) {\n      entry(repoFullName: $repoName) {\n        comments(start: $start, limit: $limit) {\n          text\n        }\n      }\n    }\n  `;\n\n  const merge = jest.fn((existing = [], incoming) => existing.concat(incoming));\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Entry: {\n          fields: {\n            comments: {\n              keyArgs: false,\n              merge,\n            },\n          },\n        },\n      },\n    }),\n    link: new MockLink([\n      {\n        request: {\n          query,\n          variables: { repoName: \"apollo-client\", start: 1, limit: 10 },\n        },\n        result: {\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) },\n          },\n          extensions: { pagination: { isComplete: false } },\n        },\n      },\n      {\n        request: {\n          query,\n          variables: { repoName: \"apollo-client\", start: 11, limit: 10 },\n        },\n        result: {\n          data: {\n            entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) },\n          },\n          extensions: { pagination: { isComplete: true } },\n        },\n      },\n    ]),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { repoName: \"apollo-client\", start: 1, limit: 10 },\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { entry: { __typename: \"Entry\", comments: commentsInRange(1, 10) } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    undefined,\n    commentsInRange(1, 10),\n    expect.objectContaining({\n      extensions: { pagination: { isComplete: false } },\n    })\n  );\n\n  merge.mockClear();\n\n  await expect(\n    observable.fetchMore({ variables: { start: 11, limit: 10 } })\n  ).resolves.toStrictEqualTyped({\n    data: { entry: { __typename: \"Entry\", comments: commentsInRange(11, 20) } },\n  });\n\n  await expect(stream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      loading: true,\n      networkStatus: NetworkStatus.fetchMore,\n    }),\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { entry: { __typename: \"Entry\", comments: commentsInRange(1, 20) } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    commentsInRange(1, 10),\n    commentsInRange(11, 20),\n    expect.objectContaining({\n      extensions: { pagination: { isComplete: true } },\n    })\n  );\n});\n\nfunction commentsInRange(\n  start: number,\n  end: number,\n  textGen: (i: number) => string = (i) => `comment ${i}`\n) {\n  return Array.from({ length: end - start + 1 }).map((_, i) => ({\n    __typename: \"Comment\",\n    text: textGen(i + start),\n  }));\n}\n"
  },
  {
    "path": "src/__tests__/graphqlSubscriptions.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport type { Subscriber } from \"rxjs\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, Observable } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n} from \"@apollo/client/errors\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  mockMultipartSubscriptionStream,\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\ndescribe(\"GraphQL Subscriptions\", () => {\n  const results = [\n    \"Dahivat Pandya\",\n    \"Vyacheslav Kim\",\n    \"Changping Chen\",\n    \"Amanda Liu\",\n  ].map((name) => ({\n    result: { data: { user: { __typename: \"User\" as const, name } } },\n    delay: 10,\n  }));\n\n  const subscription: TypedDocumentNode<\n    { user: { __typename: \"User\"; name: string } },\n    { name?: string }\n  > = gql`\n    subscription UserInfo($name: String) {\n      user(name: $name) {\n        name\n      }\n    }\n  `;\n\n  it(\"should start a subscription on network interface and unsubscribe\", async () => {\n    const link = new MockSubscriptionLink();\n    // This test calls directly through Apollo Client\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: gql`\n          subscription UserInfo($name: String = \"Changping Chen\") {\n            user(name: $name) {\n              name\n            }\n          }\n        `,\n      })\n    );\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n\n    stream.unsubscribe();\n  });\n\n  it(\"should subscribe with default values\", async () => {\n    const link = new MockSubscriptionLink();\n    // This test calls directly through Apollo Client\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        variables: { name: \"Changping Chen\" },\n      })\n    );\n\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n\n    stream.unsubscribe();\n  });\n\n  test(\"does not eagerly start subscription until subscribing to the returned observable\", async () => {\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n\n    expect(onSubscribe).not.toHaveBeenCalled();\n\n    observable.subscribe();\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should multiplex subscriptions\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream1 = new ObservableStream(obs);\n    const stream2 = new ObservableStream(obs);\n\n    link.simulateResult(results[0]);\n\n    await expect(stream1).toEmitTypedValue(results[0].result);\n    await expect(stream2).toEmitTypedValue(results[0].result);\n  });\n\n  it(\"tears down subscription only after all subscribers are unsubscribed\", async () => {\n    const onUnsubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n\n    const stream1 = new ObservableStream(obs);\n    const stream2 = new ObservableStream(obs);\n\n    link.simulateResult(results[0]);\n\n    await expect(stream1).toEmitTypedValue(results[0].result);\n    await expect(stream2).toEmitTypedValue(results[0].result);\n\n    stream1.unsubscribe();\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n\n    link.simulateResult(results[1]);\n\n    await expect(stream1).not.toEmitAnything();\n    await expect(stream2).toEmitTypedValue(results[1].result);\n\n    stream2.unsubscribe();\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should receive multiple results for a subscription\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        variables: { name: \"Changping Chen\" },\n      })\n    );\n\n    for (let i = 0; i < 4; i++) {\n      link.simulateResult(results[i]);\n    }\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n    await expect(stream).toEmitTypedValue(results[1].result);\n    await expect(stream).toEmitTypedValue(results[2].result);\n    await expect(stream).toEmitTypedValue(results[3].result);\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"provides extensions to merge functions\", async () => {\n    const merge = jest.fn((_, incoming) => incoming);\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          User: {\n            fields: {\n              name: {\n                merge,\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        variables: { name: \"Changping Chen\" },\n      })\n    );\n\n    {\n      const { result } = results[0];\n      link.simulateResult({\n        result: { ...result, extensions: { keepAlive: true } },\n        delay: 10,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        ...result,\n        extensions: { keepAlive: true },\n      });\n\n      expect(merge).toHaveBeenCalledTimes(1);\n      expect(merge).toHaveBeenCalledWith(\n        undefined,\n        result.data.user.name,\n        expect.objectContaining({ extensions: { keepAlive: true } })\n      );\n    }\n\n    merge.mockClear();\n\n    {\n      const { result } = results[1];\n      link.simulateResult({\n        result: { ...result, extensions: { keepAlive: false } },\n        delay: 10,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        ...result,\n        extensions: { keepAlive: false },\n      });\n\n      expect(merge).toHaveBeenCalledTimes(1);\n      expect(merge).toHaveBeenCalledWith(\n        results[0].result.data.user.name,\n        result.data.user.name,\n        expect.objectContaining({ extensions: { keepAlive: false } })\n      );\n    }\n\n    merge.mockClear();\n\n    {\n      const { result } = results[2];\n      link.simulateResult({ result, delay: 10 });\n\n      await expect(stream).toEmitTypedValue(result);\n      expect(merge).toHaveBeenCalledTimes(1);\n      expect(merge).toHaveBeenCalledWith(\n        results[1].result.data.user.name,\n        result.data.user.name,\n        expect.objectContaining({ extensions: undefined })\n      );\n    }\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"should not cache subscription data if a `no-cache` fetch policy is used\", async () => {\n    const link = new MockSubscriptionLink();\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      link,\n      cache,\n    });\n\n    expect(cache.extract()).toEqual({});\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        fetchPolicy: \"no-cache\",\n        variables: { name: \"Changping Chen\" },\n      })\n    );\n\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitNext();\n    expect(cache.extract()).toEqual({});\n  });\n\n  it(\"emits an error if the result has GraphQL errors\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({\n      result: {\n        data: null,\n        errors: [\n          {\n            message: \"This is an error\",\n            locations: [\n              {\n                column: 3,\n                line: 2,\n              },\n            ],\n            path: [\"result\"],\n          },\n        ],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [\n          {\n            message: \"This is an error\",\n            locations: [\n              {\n                column: 3,\n                line: 2,\n              },\n            ],\n            path: [\"result\"],\n          },\n        ],\n      }),\n    });\n  });\n\n  it(\"can continue receiving results after GraphQL errors when the connection remains open\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({\n      result: {\n        data: null,\n        errors: [\n          {\n            message: \"This is an error\",\n            locations: [\n              {\n                column: 3,\n                line: 2,\n              },\n            ],\n            path: [\"result\"],\n          },\n        ],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [\n          {\n            message: \"This is an error\",\n            locations: [\n              {\n                column: 3,\n                line: 2,\n              },\n            ],\n            path: [\"result\"],\n          },\n        ],\n      }),\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue({ data: results[0].result.data });\n  });\n\n  it(\"emits a result with error if the result has network errors\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({ error: new Error(\"Oops\") });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new Error(\"Oops\"),\n    });\n\n    await expect(stream).toComplete();\n  });\n\n  it('returns errors in next result when `errorPolicy` is \"all\"', async () => {\n    const query = gql`\n      subscription UserInfo($name: String) {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query,\n      variables: { name: \"Iron Man\" },\n      errorPolicy: \"all\",\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult(\n      {\n        result: {\n          data: null,\n          errors: [{ message: \"This is an error\" }],\n        },\n      },\n      true\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [{ message: \"This is an error\" }],\n      }),\n    });\n\n    await expect(stream).toComplete();\n  });\n\n  it(\"emits a result with error and completes when the result has network errors with `errorPolicy: 'all'`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      errorPolicy: \"all\",\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({ error: new Error(\"Oops\") });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new Error(\"Oops\"),\n    });\n    await expect(stream).toComplete();\n  });\n\n  it('emits protocol errors when `errorPolicy` is \"all\"', async () => {\n    const { httpLink, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const client = new ApolloClient({\n      link: httpLink,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Iron Man\" },\n      errorPolicy: \"all\",\n    });\n    const stream = new ObservableStream(obs);\n\n    // Silence warning about missing field for cache write\n    // TODO: Investigate this to see if we can silence this since this should\n    // not be expected.\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    enqueueProtocolErrors([\n      {\n        message: \"cannot read message from websocket\",\n        extensions: {\n          code: \"WEBSOCKET_MESSAGE_ERROR\",\n        },\n      },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedProtocolErrors([\n        {\n          message: \"cannot read message from websocket\",\n          extensions: {\n            code: \"WEBSOCKET_MESSAGE_ERROR\",\n          },\n        },\n      ]),\n    });\n\n    await expect(stream).toComplete();\n  });\n\n  it('does not emit anything for GraphQL errors with no data in next result when `errorPolicy` is \"ignore\"', async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Iron Man\" },\n      errorPolicy: \"ignore\",\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({\n      result: {\n        data: null,\n        errors: [{ message: \"This is an error\" }],\n      },\n    });\n\n    await expect(stream).not.toEmitAnything();\n\n    link.simulateComplete();\n    await expect(stream).toComplete();\n  });\n\n  it('does not emit anything for network errors with no data in next result when `errorPolicy` is \"ignore\"', async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Iron Man\" },\n      errorPolicy: \"ignore\",\n    });\n    const stream = new ObservableStream(obs);\n\n    link.simulateResult({ error: new Error(\"Oops\") });\n\n    await expect(stream).toComplete();\n  });\n\n  it('does not emit anything and completes observable for protocolErrors when `errorPolicy` is \"ignore\"', async () => {\n    const { httpLink, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n    const client = new ApolloClient({\n      link: httpLink,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Iron Man\" },\n      errorPolicy: \"ignore\",\n    });\n    const stream = new ObservableStream(obs);\n\n    // Silence warning about missing field for cache write\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    enqueueProtocolErrors([\n      {\n        message: \"cannot read message from websocket\",\n        extensions: {\n          code: \"WEBSOCKET_MESSAGE_ERROR\",\n        },\n      },\n    ]);\n\n    await expect(stream).toComplete();\n  });\n\n  it(\"should call complete handler when the subscription completes\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    setTimeout(() => link.simulateComplete(), 50);\n\n    await expect(stream).toComplete();\n  });\n\n  it(\"should pass a context object through the link execution chain\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        variables: { name: \"Changping Chen\" },\n        context: { someVar: \"Some value\" },\n      })\n    );\n\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n\n    expect(link.operation?.getContext().someVar).toEqual(\"Some value\");\n  });\n\n  it(\"emits an error if the result has protocolErrors on it\", async () => {\n    const { httpLink, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const client = new ApolloClient({\n      link: httpLink,\n      cache: new InMemoryCache(),\n    });\n\n    const obs = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(obs);\n\n    // Silence warning about missing field for cache write\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    enqueueProtocolErrors([\n      {\n        message: \"cannot read message from websocket\",\n        extensions: {\n          code: \"WEBSOCKET_MESSAGE_ERROR\",\n        },\n      },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      error: new CombinedProtocolErrors([\n        {\n          message: \"cannot read message from websocket\",\n          extensions: {\n            code: \"WEBSOCKET_MESSAGE_ERROR\",\n          },\n        },\n      ]),\n    });\n\n    await expect(stream).toComplete();\n  });\n\n  it(\"deduplicates subscriptions by default\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const observers = new Set<Subscriber<ApolloLink.Result>>();\n    const link = new ApolloLink((_operation) => {\n      return new Observable((observer) => {\n        observers.add(observer);\n        return () => observers.delete(observer);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    using sub1 = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n    using sub2 = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    expect(observers.size).toBe(1);\n\n    const [observer] = Array.from(observers);\n\n    observer.next(results[0].result);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    await expect(sub2).toEmitTypedValue(results[0].result);\n\n    observer.next(results[1].result);\n\n    await expect(sub1).toEmitTypedValue(results[1].result);\n    await expect(sub2).toEmitTypedValue(results[1].result);\n\n    using sub3 = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    expect(observers.size).toBe(1);\n\n    observer.next(results[2].result);\n\n    await expect(sub1).toEmitTypedValue(results[2].result);\n    await expect(sub2).toEmitTypedValue(results[2].result);\n    await expect(sub3).toEmitTypedValue(results[2].result);\n\n    observer.complete();\n\n    await expect(sub1).toComplete();\n    await expect(sub2).toComplete();\n    await expect(sub3).toComplete();\n  });\n\n  it(\"does not deduplicate new request after unsubscribing from previous deduped request\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    let lastOperation!: ApolloLink.Operation;\n    const observers = new Set<Subscriber<ApolloLink.Result>>();\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        lastOperation = operation;\n        observers.add(observer);\n        return () => observers.delete(observer);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    using sub1 = new ObservableStream(\n      client.subscribe({ query: subscription, context: { count: 1 } })\n    );\n\n    expect(observers.size).toBe(1);\n    expect(lastOperation.getContext()).toMatchObject({ count: 1 });\n\n    const [observer1] = Array.from(observers);\n    observer1.next(results[0].result);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    sub1.unsubscribe();\n\n    expect(observers.size).toBe(0);\n\n    using sub2 = new ObservableStream(\n      client.subscribe({ query: subscription, context: { count: 2 } })\n    );\n\n    expect(observers.size).toBe(1);\n    expect(lastOperation.getContext()).toMatchObject({ count: 2 });\n\n    const [observer2] = Array.from(observers);\n\n    observer2.next(results[2].result);\n\n    await expect(sub2).toEmitTypedValue(results[2].result);\n  });\n\n  it(\"does not deduplicate requests when disabling queryDeduplication\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const observers = new Set<Subscriber<ApolloLink.Result>>();\n    const link = new ApolloLink((_operation) => {\n      return new Observable((observer) => {\n        observers.add(observer);\n        return () => observers.delete(observer);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    using sub1 = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        context: { queryDeduplication: false },\n      })\n    );\n    using sub2 = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        context: { queryDeduplication: false },\n      })\n    );\n\n    expect(observers.size).toBe(2);\n\n    const [observer1, observer2] = Array.from(observers);\n\n    observer1.next(results[0].result);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    await expect(sub2).not.toEmitAnything();\n\n    observer2.next(results[0].result);\n\n    await expect(sub1).not.toEmitAnything();\n    await expect(sub2).toEmitTypedValue(results[0].result);\n\n    using sub3 = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        context: { queryDeduplication: false },\n      })\n    );\n\n    expect(observers.size).toBe(3);\n\n    const [, , observer3] = Array.from(observers);\n\n    observer3.next(results[1].result);\n\n    await expect(sub1).not.toEmitAnything();\n    await expect(sub2).not.toEmitAnything();\n    await expect(sub3).toEmitTypedValue(results[1].result);\n\n    observer1.complete();\n\n    await expect(sub1).toComplete();\n    await expect(sub2).not.toEmitAnything();\n    await expect(sub3).not.toEmitAnything();\n\n    observer2.complete();\n\n    await expect(sub2).toComplete();\n    await expect(sub3).not.toEmitAnything();\n\n    observer3.complete();\n\n    await expect(sub3).toComplete();\n  });\n\n  it(\"can mix deduplicated requests and new subscriptions with `queryDeduplication: false`\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const observers = new Set<Subscriber<ApolloLink.Result>>();\n    const link = new ApolloLink((_operation) => {\n      return new Observable((observer) => {\n        observers.add(observer);\n        return () => observers.delete(observer);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    using sub1 = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n    using sub2 = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    expect(observers.size).toBe(1);\n\n    const [observer1] = Array.from(observers);\n\n    observer1.next(results[0].result);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    await expect(sub2).toEmitTypedValue(results[0].result);\n\n    using sub3 = new ObservableStream(\n      client.subscribe({\n        query: subscription,\n        context: { queryDeduplication: false },\n      })\n    );\n\n    expect(observers.size).toBe(2);\n\n    const [, observer2] = Array.from(observers);\n\n    observer2.next(results[1].result);\n\n    await expect(sub1).not.toEmitAnything();\n    await expect(sub2).not.toEmitAnything();\n    await expect(sub3).toEmitTypedValue(results[1].result);\n\n    observer1.next(results[2].result);\n\n    await expect(sub1).toEmitTypedValue(results[2].result);\n    await expect(sub2).toEmitTypedValue(results[2].result);\n    await expect(sub3).not.toEmitAnything();\n\n    observer2.next(results[3].result);\n\n    await expect(sub1).not.toEmitAnything();\n    await expect(sub2).not.toEmitAnything();\n    await expect(sub3).toEmitTypedValue(results[3].result);\n\n    observer1.complete();\n\n    await expect(sub1).toComplete();\n    await expect(sub2).toComplete();\n    await expect(sub3).not.toEmitAnything();\n\n    observer2.complete();\n\n    await expect(sub3).toComplete();\n  });\n\n  test(\"can restart a subscription\", async () => {\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(observable);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n\n    observable.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n    // Ensure restarting the connection doesn't complete the existing observable\n    await expect(stream).not.toEmitAnything();\n\n    link.simulateResult(results[1], true);\n\n    await expect(stream).toEmitTypedValue(results[1].result);\n    await expect(stream).toComplete();\n  });\n\n  test(\"restarts subscription with multiple observers\", async () => {\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream1 = new ObservableStream(observable);\n    const stream2 = new ObservableStream(observable);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult(results[0]);\n\n    await expect(stream1).toEmitTypedValue(results[0].result);\n    await expect(stream2).toEmitTypedValue(results[0].result);\n\n    observable.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n    // Ensure restarting the connection doesn't complete the existing observable\n    await expect(stream1).not.toEmitAnything();\n    await expect(stream2).not.toEmitAnything();\n\n    link.simulateResult(results[1], true);\n\n    await expect(stream1).toEmitTypedValue(results[1].result);\n    await expect(stream1).toComplete();\n\n    await expect(stream2).toEmitTypedValue(results[1].result);\n    await expect(stream2).toComplete();\n  });\n\n  test(\"restarts subscriptions on deduplicated subscriptions\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable1 = client.subscribe({ query: subscription });\n    const observable2 = client.subscribe({ query: subscription });\n\n    // Ensure we aren't eagerly subscribing\n    expect(onSubscribe).not.toHaveBeenCalled();\n\n    using sub1 = new ObservableStream(observable1);\n    using sub2 = new ObservableStream(observable2);\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult(results[0]);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    await expect(sub2).toEmitTypedValue(results[0].result);\n\n    observable1.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n    link.simulateResult(results[1]);\n\n    await expect(sub1).toEmitTypedValue(results[1].result);\n    await expect(sub2).toEmitTypedValue(results[1].result);\n\n    observable2.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(2);\n    expect(onSubscribe).toHaveBeenCalledTimes(3);\n\n    const observable3 = client.subscribe({ query: subscription });\n    using sub3 = new ObservableStream(observable3);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(3);\n\n    link.simulateResult(results[2]);\n\n    await expect(sub1).toEmitTypedValue(results[2].result);\n    await expect(sub2).toEmitTypedValue(results[2].result);\n    await expect(sub3).toEmitTypedValue(results[2].result);\n\n    observable3.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(3);\n    expect(onSubscribe).toHaveBeenCalledTimes(4);\n\n    link.simulateResult(results[3], true);\n\n    await expect(sub1).toEmitTypedValue(results[3].result);\n    await expect(sub2).toEmitTypedValue(results[3].result);\n    await expect(sub3).toEmitTypedValue(results[3].result);\n\n    await expect(sub1).toComplete();\n    await expect(sub2).toComplete();\n    await expect(sub3).toComplete();\n  });\n\n  test(\"restarts only own connection on non deduplicated subscriptions\", async () => {\n    const subscription = gql`\n      subscription UserInfo($name: String = \"Changping Chen\") {\n        user(name: $name) {\n          name\n        }\n      }\n    `;\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const observable1 = client.subscribe({\n      query: subscription,\n      context: { queryDeduplication: false },\n    });\n    const observable2 = client.subscribe({\n      query: subscription,\n      context: { queryDeduplication: false },\n    });\n\n    // Ensure we aren't eagerly subscribing\n    expect(onSubscribe).not.toHaveBeenCalled();\n\n    using sub1 = new ObservableStream(observable1);\n    using sub2 = new ObservableStream(observable2);\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n    link.simulateResult(results[0]);\n\n    await expect(sub1).toEmitTypedValue(results[0].result);\n    await expect(sub2).toEmitTypedValue(results[0].result);\n\n    observable1.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(3);\n\n    link.simulateResult(results[1]);\n\n    await expect(sub1).toEmitTypedValue(results[1].result);\n    await expect(sub2).toEmitTypedValue(results[1].result);\n\n    observable2.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(2);\n    expect(onSubscribe).toHaveBeenCalledTimes(4);\n\n    const observable3 = client.subscribe({\n      query: subscription,\n      context: { queryDeduplication: false },\n    });\n    using sub3 = new ObservableStream(observable3);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(5);\n\n    link.simulateResult(results[2]);\n\n    await expect(sub1).toEmitTypedValue(results[2].result);\n    await expect(sub2).toEmitTypedValue(results[2].result);\n    await expect(sub3).toEmitTypedValue(results[2].result);\n\n    observable3.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(3);\n    expect(onSubscribe).toHaveBeenCalledTimes(6);\n\n    link.simulateResult(results[3], true);\n\n    await expect(sub1).toEmitTypedValue(results[3].result);\n    await expect(sub2).toEmitTypedValue(results[3].result);\n    await expect(sub3).toEmitTypedValue(results[3].result);\n\n    await expect(sub1).toComplete();\n    await expect(sub2).toComplete();\n    await expect(sub3).toComplete();\n  });\n\n  test(\"does not start link subscription after observable is unsubscribed\", async () => {\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(observable);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    stream.unsubscribe();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    onSubscribe.mockReset();\n    onUnsubscribe.mockReset();\n\n    observable.restart();\n\n    expect(onUnsubscribe).not.toHaveBeenCalled();\n    expect(onSubscribe).not.toHaveBeenCalled();\n  });\n\n  test(\"does not start link subscription after observable is complete\", async () => {\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(observable);\n\n    link.simulateResult(results[0], true);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n    await expect(stream).toComplete();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    onSubscribe.mockReset();\n    onUnsubscribe.mockReset();\n\n    observable.restart();\n\n    expect(onUnsubscribe).not.toHaveBeenCalled();\n    expect(onSubscribe).not.toHaveBeenCalled();\n  });\n\n  test(\"restart does not affect future subscriptions\", async () => {\n    const onUnsubscribe = jest.fn();\n    const onSubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onUnsubscribe(onUnsubscribe);\n    link.onSetup(onSubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable1 = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream = new ObservableStream(observable1);\n\n    link.simulateResult(results[0], true);\n\n    await expect(stream).toEmitTypedValue(results[0].result);\n    await expect(stream).toComplete();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    const observable2 = client.subscribe({\n      query: subscription,\n      variables: { name: \"Changping Chen\" },\n    });\n    const stream2 = new ObservableStream(observable2);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult(results[0]);\n\n    await expect(stream2).toEmitTypedValue(results[0].result);\n\n    onSubscribe.mockReset();\n    onUnsubscribe.mockReset();\n\n    observable1.restart();\n\n    expect(onUnsubscribe).not.toHaveBeenCalled();\n    expect(onSubscribe).not.toHaveBeenCalled();\n\n    link.simulateResult(results[1]);\n\n    await expect(stream2).toEmitTypedValue(results[1].result);\n  });\n});\n"
  },
  {
    "path": "src/__tests__/local-state/__snapshots__/export.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`@client @export tests should NOT refetch if an @export variable has not changed, the current fetch policy is not cache-only, and the query includes fields that need to be resolved remotely 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"postCount\",\n      Object {\n        \"currentAuthorId\": 100,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`@client @export tests should allow @client @export variables to be used with remote queries 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"postCount\",\n      Object {\n        \"currentAuthor\": Object {\n          \"__typename\": \"Author\",\n          \"authorId\": 100,\n          \"name\": \"John Smith\",\n        },\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`@client @export tests should refetch if an @export variable changes, the current fetch policy is not cache-only, and the query includes fields that need to be resolved remotely 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"postCount\",\n      Object {\n        \"currentAuthorId\": 100,\n      },\n    ],\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"postCount\",\n      Object {\n        \"currentAuthorId\": 101,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n"
  },
  {
    "path": "src/__tests__/local-state/__snapshots__/general.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`Combining client and server state/operations should handle a simple query with both server and client fields 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"lastCount\",\n      Object {\n        \"count\": 0,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`Combining client and server state/operations should support nested querying of both server and client fields 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"lastName\",\n      Object {\n        \"__typename\": \"User\",\n        \"firstName\": \"John\",\n        \"id\": 123,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n"
  },
  {
    "path": "src/__tests__/local-state/export.ts",
    "content": "import { print } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { of } from \"rxjs\";\n\nimport { ApolloClient, LocalStateError, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"@client @export tests\", () => {\n  test(\"throws when exported variable has no definition\", async () => {\n    const query = gql`\n      {\n        field @client @export(as: \"someVar\")\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query,\n      data: { field: 1 },\n    });\n\n    await expect(client.query({ query })).rejects.toEqual(\n      new LocalStateError(\n        \"`@export` directive on field 'field' cannot export the '$someVar' variable as it is missing in the query definition.\",\n        { path: [\"field\"] }\n      )\n    );\n  });\n\n  test(\"throws when nested @export does not contain variable definition\", async () => {\n    const query = gql`\n      {\n        car @client {\n          engine {\n            torque @export(as: \"torque\")\n          }\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        car: {\n          engine: {\n            cylinders: 8,\n            torque: 7200,\n            __typename: \"Engine\",\n          },\n          __typename: \"Car\",\n        },\n      },\n    });\n\n    await expect(client.query({ query })).rejects.toEqual(\n      new LocalStateError(\n        \"`@export` directive on field 'torque' cannot export the '$torque' variable as it is missing in the query definition.\",\n        { path: [\"car\", \"engine\", \"torque\"] }\n      )\n    );\n  });\n\n  test(\"should store the @client field value in the specified @export variable, and make it available to a subsequent resolver\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId) @client\n      }\n    `;\n\n    const testAuthorId = 100;\n    const testPostCount = 200;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            postCount(_, { authorId }) {\n              return authorId === testAuthorId ? testPostCount : 0;\n            },\n          },\n        },\n      }),\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        currentAuthorId: testAuthorId,\n      },\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      currentAuthorId: testAuthorId,\n      postCount: testPostCount,\n    });\n  });\n\n  test(\"should store the @client nested field value in the specified @export variable, and make it available to a subsequent resolver\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthor @client {\n          name\n          authorId @export(as: \"authorId\")\n        }\n        postCount(authorId: $authorId) @client\n      }\n    `;\n\n    const testAuthor = {\n      name: \"John Smith\",\n      authorId: 100,\n      __typename: \"Author\",\n    };\n\n    const testPostCount = 200;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            postCount(_, { authorId }) {\n              return authorId === testAuthor.authorId ? testPostCount : 0;\n            },\n          },\n        },\n      }),\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        currentAuthor: testAuthor,\n      },\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toMatchObject({\n      currentAuthor: testAuthor,\n      postCount: testPostCount,\n    });\n  });\n\n  test(\"should allow @client @export variables to be used with remote queries\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    await new Promise<void>((resolve, reject) => {\n      const query = gql`\n        query currentAuthorPostCount($authorId: Int!) {\n          currentAuthor @client {\n            name\n            authorId @export(as: \"authorId\")\n          }\n          postCount(authorId: $authorId)\n        }\n      `;\n\n      const testAuthor = {\n        name: \"John Smith\",\n        authorId: 100,\n        __typename: \"Author\",\n      };\n\n      const testPostCount = 200;\n\n      const link = new ApolloLink(() =>\n        of({\n          data: {\n            postCount: testPostCount,\n          },\n        })\n      );\n\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link,\n        localState: new LocalState(),\n      });\n\n      cache.writeQuery({\n        query,\n        data: {\n          currentAuthor: testAuthor,\n        },\n      });\n\n      return client.query({ query }).then(({ data }: any) => {\n        expect({ ...data }).toMatchObject({\n          currentAuthor: testAuthor,\n          postCount: testPostCount,\n        });\n        resolve();\n      });\n    });\n  });\n\n  test(\"should support @client @export variables that are nested multiple levels deep\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        appContainer @client {\n          systemDetails {\n            currentAuthor {\n              name\n              authorId @export(as: \"authorId\")\n            }\n          }\n        }\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const appContainer = {\n      systemDetails: {\n        currentAuthor: {\n          name: \"John Smith\",\n          authorId: 100,\n          __typename: \"Author\",\n        },\n        __typename: \"SystemDetails\",\n      },\n      __typename: \"AppContainer\",\n    };\n\n    const testPostCount = 200;\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          postCount: testPostCount,\n        },\n      })\n    );\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    {\n      using _ = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          appContainer,\n        },\n      });\n    }\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      appContainer,\n      postCount: testPostCount,\n    });\n  });\n\n  test(\"should ignore @export directives if not used with @client\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthor {\n          name\n          authorId @export(as: \"authorId\")\n        }\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const testAuthor = {\n      name: \"John Smith\",\n      authorId: 100,\n      __typename: \"Author\",\n    };\n    const testPostCount = 200;\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          currentAuthor: testAuthor,\n          postCount: testPostCount,\n        },\n      })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState(),\n    });\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      currentAuthor: testAuthor,\n      postCount: testPostCount,\n    });\n  });\n\n  test(\"should support setting an @client @export variable, loaded from the cache, on a virtual field that is combined into a remote query.\", async () => {\n    const query = gql`\n      query postRequiringReview($reviewerId: Int!) {\n        postRequiringReview {\n          id\n          title\n          loggedInReviewerId @client @export(as: \"reviewerId\")\n        }\n        reviewerDetails(reviewerId: $reviewerId) {\n          name\n        }\n      }\n    `;\n\n    const postRequiringReview = {\n      id: 10,\n      title: \"The Local State Conundrum\",\n      __typename: \"Post\",\n    };\n    const reviewerDetails = {\n      name: \"John Smith\",\n      __typename: \"Reviewer\",\n    };\n    const loggedInReviewerId = 100;\n\n    const link = new ApolloLink(({ variables }) => {\n      expect(variables).toMatchObject({ reviewerId: loggedInReviewerId });\n\n      return of({\n        data: {\n          postRequiringReview,\n          reviewerDetails,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    {\n      using _ = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          postRequiringReview: {\n            loggedInReviewerId,\n            __typename: \"Post\",\n            id: 10,\n          },\n        },\n      });\n    }\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      postRequiringReview: {\n        __typename: \"Post\",\n        id: postRequiringReview.id,\n        title: postRequiringReview.title,\n        loggedInReviewerId,\n      },\n      reviewerDetails,\n    });\n  });\n\n  test(\"should support setting a @client @export variable, loaded via a local resolver, on a virtual field that is combined into a remote query.\", async () => {\n    const query = gql`\n      query postRequiringReview($reviewerId: Int!) {\n        postRequiringReview {\n          id\n          title\n          currentReviewer @client {\n            id @export(as: \"reviewerId\")\n          }\n        }\n        reviewerDetails(reviewerId: $reviewerId) {\n          name\n        }\n      }\n    `;\n\n    const postRequiringReview = {\n      id: 10,\n      title: \"The Local State Conundrum\",\n      __typename: \"Post\",\n    };\n    const reviewerDetails = {\n      name: \"John Smith\",\n      __typename: \"Reviewer\",\n    };\n    const currentReviewer = {\n      id: 100,\n      __typename: \"CurrentReviewer\",\n    };\n\n    const link = new ApolloLink(({ variables }) => {\n      expect(variables).toMatchObject({ reviewerId: currentReviewer.id });\n      return of({\n        data: {\n          postRequiringReview,\n          reviewerDetails,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Post: {\n            currentReviewer() {\n              return currentReviewer;\n            },\n          },\n        },\n      }),\n    });\n\n    {\n      using _ = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          postRequiringReview: {\n            __typename: \"Post\",\n          },\n        },\n      });\n    }\n\n    const { data } = await client.query({ query });\n\n    expect(data).toMatchObject({\n      postRequiringReview: {\n        id: postRequiringReview.id,\n        title: postRequiringReview.title,\n        currentReviewer,\n      },\n      reviewerDetails,\n    });\n  });\n\n  test(\"should support combining @client @export variables, calculated by a local resolver, with remote mutations\", async () => {\n    const mutation = gql`\n      mutation upvotePost($postId: Int!) {\n        topPost @client @export(as: \"postId\")\n        upvotePost(postId: $postId) {\n          title\n          votes\n        }\n      }\n    `;\n\n    const testPostId = 100;\n    const testPost = {\n      title: \"The Day of the Jackal\",\n      votes: 10,\n      __typename: \"post\",\n    };\n\n    const link = new ApolloLink(({ variables }) => {\n      expect(variables).toMatchObject({ postId: testPostId });\n      return of({\n        data: {\n          upvotePost: testPost,\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            topPost() {\n              return testPostId;\n            },\n          },\n        },\n      }),\n    });\n\n    const { data } = await client.mutate({ mutation });\n\n    expect(data).toEqual({\n      topPost: 100,\n      upvotePost: testPost,\n    });\n  });\n\n  test(\"should support combining @client @export variables, calculated by reading from the cache, with remote mutations\", async () => {\n    const mutation = gql`\n      mutation upvotePost($postId: Int!) {\n        topPost @client @export(as: \"postId\")\n        upvotePost(postId: $postId) {\n          title\n          votes\n        }\n      }\n    `;\n\n    const testPostId = 100;\n    const testPost = {\n      title: \"The Day of the Jackal\",\n      votes: 10,\n      __typename: \"post\",\n    };\n\n    const link = new ApolloLink(({ variables }) => {\n      expect(variables).toMatchObject({ postId: testPostId });\n      return of({\n        data: {\n          upvotePost: testPost,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query: gql`\n        {\n          topPost\n        }\n      `,\n      data: {\n        topPost: testPostId,\n      },\n    });\n\n    const { data } = await client.mutate({ mutation });\n\n    expect(data).toStrictEqualTyped({\n      topPost: testPostId,\n      upvotePost: testPost,\n    });\n  });\n\n  test(\"should not add __typename to @export-ed objects (#4691)\", async () => {\n    const query = gql`\n      query GetListItems($where: LessonFilter) {\n        currentFilter @client @export(as: \"where\") {\n          title_contains\n          enabled\n        }\n        lessonCollection(where: $where) {\n          items {\n            title\n            slug\n          }\n        }\n      }\n    `;\n\n    const expectedServerQuery = gql`\n      query GetListItems($where: LessonFilter) {\n        lessonCollection(where: $where) {\n          items {\n            title\n            slug\n            __typename\n          }\n          __typename\n        }\n      }\n    `;\n\n    const currentFilter = {\n      title_contains: \"full\",\n      enabled: true,\n    };\n\n    const data = {\n      lessonCollection: {\n        __typename: \"LessonCollection\",\n        items: [\n          {\n            __typename: \"ListItem\",\n            title: \"full title\",\n            slug: \"slug-title\",\n          },\n        ],\n      },\n    };\n\n    const client = new ApolloClient({\n      link: new ApolloLink((request) => {\n        expect(request.variables.where).toEqual(currentFilter);\n        expect(print(request.query)).toBe(print(expectedServerQuery));\n        return of({ data });\n      }),\n      cache: new InMemoryCache(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            currentFilter() {\n              return { __typename: \"LessonFilter\", ...currentFilter };\n            },\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query });\n\n    expect(result.data).toEqual({\n      currentFilter,\n      ...data,\n    });\n  });\n\n  test(\"should use the value of the last @export variable defined, if multiple variables are defined with the same name\", async () => {\n    const query = gql`\n      query reviewerPost($reviewerId: Int!) {\n        primaryReviewerId @client @export(as: \"reviewerId\")\n        secondaryReviewerId @client @export(as: \"reviewerId\")\n        post(reviewerId: $reviewerId) {\n          title\n        }\n      }\n    `;\n\n    const post = {\n      title: \"The One Post to Rule Them All\",\n      __typename: \"Post\",\n    };\n    const primaryReviewerId = 100;\n    const secondaryReviewerId = 200;\n\n    const link = new ApolloLink(({ variables }) => {\n      expect(variables).toMatchObject({ reviewerId: secondaryReviewerId });\n      return of({\n        data: {\n          post,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    {\n      using _ = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          primaryReviewerId,\n          secondaryReviewerId,\n        },\n      });\n    }\n\n    const { data } = await client.query({ query });\n\n    expect(data).toEqual({\n      post,\n      primaryReviewerId,\n      secondaryReviewerId,\n    });\n  });\n\n  test(\"should refetch if an @export variable changes, the current fetch policy is not cache-only, and the query includes fields that need to be resolved remotely\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const testAuthorId1 = 100;\n    const testPostCount1 = 200;\n\n    const testAuthorId2 = 101;\n    const testPostCount2 = 201;\n\n    let currentAuthorId = testAuthorId1;\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          postCount:\n            currentAuthorId === testAuthorId1 ? testPostCount1 : testPostCount2,\n        },\n      })\n    );\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    client.writeQuery({\n      query,\n      data: { currentAuthorId },\n    });\n\n    const obs = client.watchQuery({ query });\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentAuthorId: testAuthorId1,\n        postCount: testPostCount1,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    currentAuthorId = testAuthorId2;\n    client.writeQuery({\n      query,\n      data: { currentAuthorId },\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n      }),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentAuthorId: testAuthorId2,\n        postCount: testPostCount2,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should NOT refetch if an @export variable has not changed, the current fetch policy is not cache-only, and the query includes fields that need to be resolved remotely\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const testAuthorId1 = 100;\n    const testPostCount1 = 200;\n\n    const testPostCount2 = 201;\n\n    let fetchCount = 0;\n    const link = new ApolloLink(() => {\n      fetchCount += 1;\n      return of({\n        data: {\n          postCount: testPostCount1,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    client.writeQuery({\n      query,\n      data: { currentAuthorId: testAuthorId1 },\n    });\n\n    const obs = client.watchQuery({ query });\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentAuthorId: testAuthorId1,\n        postCount: testPostCount1,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(fetchCount).toBe(1);\n\n    client.writeQuery({\n      query,\n      variables: { authorId: testAuthorId1 },\n      data: { postCount: testPostCount2 },\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        data: { ...previous.data!, postCount: testPostCount2 },\n        dataState: \"complete\",\n      }),\n    });\n    expect(fetchCount).toBe(1);\n  });\n\n  test(\"should NOT attempt to refetch over the network if an @export variable has changed, the current fetch policy is cache-first, and the remote part of the query (that leverages the @export variable) can be fully found in the cache.\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const testAuthorId1 = 1;\n    const testPostCount1 = 100;\n\n    const testAuthorId2 = 2;\n    const testPostCount2 = 200;\n\n    let fetchCount = 0;\n    const link = new ApolloLink(() => {\n      fetchCount += 1;\n      return of({\n        data: {\n          postCount: testPostCount1,\n        },\n      });\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    client.writeQuery({\n      query: gql`\n        {\n          currentAuthorId\n        }\n      `,\n      data: { currentAuthorId: testAuthorId1 },\n    });\n\n    const obs = client.watchQuery({ query, fetchPolicy: \"cache-first\" });\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentAuthorId: testAuthorId1,\n        postCount: testPostCount1,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    // The initial result is fetched over the network.\n    expect(fetchCount).toBe(1);\n\n    client.writeQuery({\n      query,\n      variables: { authorId: testAuthorId2 },\n      data: { postCount: testPostCount2 },\n    });\n    client.writeQuery({\n      query: gql`\n        {\n          currentAuthorId\n        }\n      `,\n      data: { currentAuthorId: testAuthorId2 },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        currentAuthorId: testAuthorId2,\n        postCount: testPostCount2,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    // The updated result should not have been fetched over the\n    // network, as it can be found in the cache.\n    expect(fetchCount).toBe(1);\n  });\n\n  test(\"should update @client @export variables on each broadcast if they've changed\", async () => {\n    const cache = new InMemoryCache();\n\n    const widgetCountQuery = gql`\n      {\n        widgetCount @client\n      }\n    `;\n    cache.writeQuery({\n      query: widgetCountQuery,\n      data: {\n        widgetCount: 100,\n      },\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            doubleWidgets(_, { widgetCount }) {\n              return widgetCount ? widgetCount * 2 : 0;\n            },\n          },\n        },\n      }),\n    });\n\n    const doubleWidgetsQuery = gql`\n      query DoubleWidgets($widgetCount: Int!) {\n        widgetCount @client @export(as: \"widgetCount\")\n        doubleWidgets(widgetCount: $widgetCount) @client\n      }\n    `;\n\n    const obs = client.watchQuery({ query: doubleWidgetsQuery });\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        widgetCount: 100,\n        doubleWidgets: 200,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    client.writeQuery({\n      query: widgetCountQuery,\n      data: {\n        widgetCount: 500,\n      },\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n      }),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        widgetCount: 500,\n        doubleWidgets: 1000,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"adds exported variables to subscriptions\", async () => {\n    const subscription = gql`\n      subscription ($userId: ID!) {\n        currentUserId @client @export(as: \"userId\")\n        count(for: $userId)\n      }\n    `;\n\n    const link = new ApolloLink((operation) =>\n      operation.variables.userId === 1 ?\n        of({ data: { count: 1 } }, { data: { count: 2 } })\n      : of({ errors: [{ message: \"Wrong user id\" }] })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Subscription: {\n            currentUserId: () => 1,\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: { currentUserId: 1, count: 1 },\n    });\n    await expect(stream).toEmitTypedValue({\n      data: { currentUserId: 1, count: 2 },\n    });\n    await expect(stream).toComplete();\n  });\n\n  test(\"can use exported variables with restart function\", async () => {\n    const subscription = gql`\n      subscription ($userId: ID!) {\n        currentUserId @client @export(as: \"userId\")\n        count(for: $userId)\n      }\n    `;\n\n    const onSubscribe = jest.fn();\n    const onUnsubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(onSubscribe);\n    link.onUnsubscribe(onUnsubscribe);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Subscription: {\n            currentUserId: () => {\n              return 1;\n            },\n          },\n        },\n      }),\n    });\n\n    const observable = client.subscribe({ query: subscription });\n    const stream = new ObservableStream(observable);\n\n    // Ensure we wait for the local resolver to run\n    await wait(0);\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n    expect(onUnsubscribe).not.toHaveBeenCalled();\n\n    link.simulateResult({ result: { data: { count: 1 } } });\n\n    await expect(stream).toEmitTypedValue({\n      data: { currentUserId: 1, count: 1 },\n    });\n\n    observable.restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n    link.simulateResult({ result: { data: { count: 2 } } }, true);\n\n    await expect(stream).toEmitTypedValue({\n      data: { currentUserId: 1, count: 2 },\n    });\n    await expect(stream).toComplete();\n  });\n\n  test(\"throws when running a query with exported client fields when local state is not configured\", async () => {\n    const query = gql`\n      query currentAuthorPostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const testPostCount = 200;\n\n    const link = new ApolloLink((operation) => {\n      return operation.variables.authorId === undefined ?\n          of({ errors: [{ message: \"Did not export author ID\" }] })\n        : of({ data: { postCount: testPostCount } });\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    await expect(client.query({ query })).rejects.toEqual(\n      new InvariantError(\n        \"Query 'currentAuthorPostCount' contains `@client` fields with variables provided by `@export` but local state has not been configured.\"\n      )\n    );\n  });\n\n  test(\"throws when running a mutation with exported client fields when local state is not configured\", async () => {\n    const mutation = gql`\n      mutation UpdatePostCount($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        updatePostCount(authorId: $authorId)\n      }\n    `;\n\n    const testPostCount = 200;\n\n    const link = new ApolloLink((operation) => {\n      return operation.variables.authorId === undefined ?\n          of({ errors: [{ message: \"Did not export author ID\" }] })\n        : of({ data: { updatePostCount: testPostCount } });\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    await expect(client.mutate({ mutation })).rejects.toEqual(\n      new InvariantError(\n        \"Mutation 'UpdatePostCount' contains `@client` fields with variables provided by `@export` but local state has not been configured.\"\n      )\n    );\n  });\n\n  test(\"throws when running a subscription with exported client fields when local state is not configured\", async () => {\n    const subscription = gql`\n      subscription OnPostCountUpdated($authorId: Int!) {\n        currentAuthorId @client @export(as: \"authorId\")\n        postCount(authorId: $authorId)\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    expect(() => client.subscribe({ query: subscription })).toThrow(\n      new InvariantError(\n        \"Subscription 'OnPostCountUpdated' contains `@client` fields with variables provided by `@export` but local state has not been configured.\"\n      )\n    );\n  });\n});\n"
  },
  {
    "path": "src/__tests__/local-state/general.ts",
    "content": "import type { DocumentNode, GraphQLFormattedError } from \"graphql\";\nimport {\n  getIntrospectionQuery,\n  graphql,\n  GraphQLError,\n  GraphQLID,\n  GraphQLInt,\n  GraphQLObjectType,\n  GraphQLSchema,\n  GraphQLString,\n  print,\n} from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Observable } from \"rxjs\";\nimport { defer, delay, of } from \"rxjs\";\n\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nconst WARNINGS = {\n  MISSING_RESOLVER:\n    \"Could not find a resolver for the '%s' field nor does the cache resolve the field. The field value has been set to `null`. Either define a resolver for the field or ensure the cache can resolve the value, for example, by adding a 'read' function to a field policy in 'InMemoryCache'.\",\n  NO_CACHE:\n    \"The '%s' field resolves the value from the cache, for example from a 'read' function, but a 'no-cache' fetch policy was used. The field value has been set to `null`. Either define a local resolver or use a fetch policy that uses the cache to ensure the field is resolved correctly.\",\n};\n\ndescribe(\"General functionality\", () => {\n  test(\"should not impact normal non-@client use\", async () => {\n    const query = gql`\n      {\n        field\n      }\n    `;\n\n    const link = new ApolloLink(() => of({ data: { field: 1 } }));\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            count: () => 0,\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n  });\n\n  test(\"should not interfere with server introspection queries\", async () => {\n    const query = gql`\n      ${getIntrospectionQuery()}\n    `;\n\n    const error = new GraphQLError(\"no introspection result found\");\n    const link = new ApolloLink(() => of({ errors: [error] }));\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            count: () => 0,\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).rejects.toThrow(/no introspection/);\n  });\n\n  test(\"should support returning default values from resolvers\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            field: () => 1,\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n  });\n\n  test(\"should cache data for future lookups\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    let count = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            field: () => {\n              count += 1;\n              return 1;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n    expect(count).toBe(1);\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n    expect(count).toBe(1);\n  });\n\n  test(\"should honour `fetchPolicy` settings\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    let count = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            field: () => {\n              count += 1;\n              return 1;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n    expect(count).toBe(1);\n\n    await expect(\n      client.query({ query, fetchPolicy: \"network-only\" })\n    ).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n    expect(count).toBe(2);\n  });\n\n  test(\"can configure local state after client is initialized\", async () => {\n    const query = gql`\n      query {\n        count @client\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          count: () => 0,\n        },\n      },\n    });\n\n    client.localState = localState;\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { count: 0 },\n    });\n  });\n});\n\ndescribe(\"Cache manipulation\", () => {\n  test(\"should be able to query @client fields and the cache without defining resolvers in local state\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({ query, data: { field: \"yo\" } });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: \"yo\" },\n    });\n  });\n\n  test(\"should be able to write to the cache using a local mutation\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const mutation = gql`\n      mutation start {\n        start @client\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Mutation: {\n          start: (_, __, { client }) => {\n            client.cache.writeQuery({ query, data: { field: 1 } });\n            return true;\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState,\n    });\n\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: { start: true },\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: 1 },\n    });\n  });\n\n  test(\"should be able to write to the cache with a local mutation and have things rerender automatically\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const mutation = gql`\n      mutation start {\n        start @client\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          field: () => 0,\n        },\n        Mutation: {\n          start: (_1: any, _2: any, { client }) => {\n            client.cache.writeQuery({ query, data: { field: 1 } });\n            return true;\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState,\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { field: 0 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: { start: true },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { field: 1 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should support writing to the cache with a local mutation using variables\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const mutation = gql`\n      mutation start($id: ID!) {\n        start(field: $id) @client {\n          field\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Mutation: {\n          start: (_, variables: { field: string }, { client }) => {\n            client.cache.writeQuery({\n              query,\n              data: { field: variables.field },\n            });\n            return {\n              __typename: \"Field\",\n              field: variables.field,\n            };\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState,\n    });\n\n    await expect(\n      client.mutate({ mutation, variables: { id: \"1234\" } })\n    ).resolves.toStrictEqualTyped({\n      data: { start: { field: \"1234\", __typename: \"Field\" } },\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { field: \"1234\" },\n    });\n  });\n\n  test(\"should read @client fields from cache on refetch (#4741)\", async () => {\n    const query = gql`\n      query FetchInitialData {\n        serverData {\n          id\n          title\n        }\n        selectedItemId @client\n      }\n    `;\n\n    const mutation = gql`\n      mutation Select {\n        select(itemId: $id) @client\n      }\n    `;\n\n    const serverData = {\n      __typename: \"ServerData\",\n      id: 123,\n      title: \"Oyez and Onoz\",\n    };\n\n    let selectedItemId = -1;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(() => of({ data: { serverData } })),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            selectedItemId() {\n              return selectedItemId;\n            },\n          },\n          Mutation: {\n            select(_, { itemId }) {\n              selectedItemId = itemId;\n              return itemId;\n            },\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        serverData,\n        selectedItemId: -1,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: { id: 123 },\n        refetchQueries: [\"FetchInitialData\"],\n      })\n    ).resolves.toStrictEqualTyped({ data: { select: 123 } });\n\n    await expect(stream).toEmitTypedValue({\n      data: { serverData, selectedItemId: -1 },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        serverData,\n        selectedItemId: 123,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  test(\"should rerun @client(always: true) fields on entity update\", async () => {\n    const query = gql`\n      query GetClientData($id: ID) {\n        clientEntity(id: $id) @client(always: true) {\n          id\n          title\n          titleLength @client(always: true)\n        }\n      }\n    `;\n\n    const mutation = gql`\n      mutation AddOrUpdate {\n        addOrUpdate(id: $id, title: $title) @client\n      }\n    `;\n\n    const fragment = gql`\n      fragment ClientDataFragment on ClientData {\n        id\n        title\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(() => of({ data: {} })),\n      localState: new LocalState({\n        resolvers: {\n          ClientData: {\n            titleLength(data) {\n              return data.title.length;\n            },\n          },\n          Query: {\n            clientEntity(_root, { id }, { client }) {\n              const { cache } = client;\n\n              return cache.readFragment({\n                id: cache.identify({ id, __typename: \"ClientData\" }),\n                fragment,\n              });\n            },\n          },\n          Mutation: {\n            addOrUpdate(_root, { id, title }, { client }) {\n              const { cache } = client;\n\n              return cache.writeFragment({\n                id: cache.identify({ id, __typename: \"ClientData\" }),\n                fragment,\n                data: { id, title, __typename: \"ClientData\" },\n              });\n            },\n          },\n        },\n      }),\n    });\n\n    const entityId = 1;\n    const shortTitle = \"Short\";\n    const longerTitle = \"A little longer\";\n    await client.mutate({\n      mutation,\n      variables: {\n        id: entityId,\n        title: shortTitle,\n      },\n    });\n    const stream = new ObservableStream(\n      client.watchQuery<any>({ query, variables: { id: entityId } })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const result = await stream.takeNext();\n\n      expect(result.data.clientEntity).toEqual({\n        id: entityId,\n        title: shortTitle,\n        titleLength: shortTitle.length,\n        __typename: \"ClientData\",\n      });\n    }\n\n    await client.mutate({\n      mutation,\n      variables: {\n        id: entityId,\n        title: longerTitle,\n      },\n    });\n\n    {\n      const result = await stream.takeNext();\n\n      expect(result.data.clientEntity).toEqual({\n        id: entityId,\n        title: longerTitle,\n        titleLength: longerTitle.length,\n        __typename: \"ClientData\",\n      });\n    }\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"runs read functions for nested @client fields without resolver warnings\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const query = gql`\n      query {\n        color {\n          hex\n          saved @client\n        }\n      }\n    `;\n\n    const link = new ApolloLink(() => {\n      return of({ data: { color: { __typename: \"Color\", hex: \"#000\" } } }).pipe(\n        delay(20)\n      );\n    });\n\n    const read = jest.fn(() => false);\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Color: {\n          keyFields: [\"hex\"],\n          fields: {\n            saved: { read },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache,\n      localState: new LocalState(),\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { color: { __typename: \"Color\", hex: \"#000\", saved: false } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(read).toHaveBeenCalledTimes(1);\n    expect(read).toHaveBeenCalledWith(undefined, expect.anything());\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n});\n\ndescribe(\"Sample apps\", () => {\n  test(\"should support a simple counter app using local state\", async () => {\n    const query = gql`\n      query GetCount {\n        count @client\n        lastCount # stored in db on server\n      }\n    `;\n\n    const increment = gql`\n      mutation Increment($amount: Int = 1) {\n        increment(amount: $amount) @client\n      }\n    `;\n\n    const decrement = gql`\n      mutation Decrement($amount: Int = 1) {\n        decrement(amount: $amount) @client\n      }\n    `;\n\n    const link = new ApolloLink((operation) => {\n      expect(operation.operationName).toBe(\"GetCount\");\n      return of({ data: { lastCount: 1 } });\n    });\n\n    const localState = new LocalState();\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState,\n    });\n\n    const update = (\n      query: DocumentNode,\n      updater: (data: { count: number }, variables: { amount: number }) => any\n    ): LocalState.Resolver<any, any, any, any> => {\n      return (_result: {}, variables: { amount: number }, { client }): null => {\n        const { cache } = client;\n\n        const read = client.readQuery<{ count: number }>({\n          query,\n          variables,\n        });\n        if (read) {\n          const data = updater(read, variables);\n          cache.writeQuery({ query, variables, data });\n          return data.count;\n        }\n\n        throw new Error(\"readQuery returned a falsy value\");\n      };\n    };\n\n    localState.addResolvers({\n      Query: {\n        count: () => 0,\n      },\n      Mutation: {\n        increment: update(query, ({ count, ...rest }, { amount }) => ({\n          ...rest,\n          count: count + amount,\n        })),\n        decrement: update(query, ({ count, ...rest }, { amount }) => ({\n          ...rest,\n          count: count - amount,\n        })),\n      },\n    });\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { count: 0, lastCount: 1 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(\n      client.mutate({ mutation: increment, variables: { amount: 2 } })\n    ).resolves.toStrictEqualTyped({ data: { increment: 2 } });\n\n    await expect(stream).toEmitTypedValue({\n      data: { count: 2, lastCount: 1 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await client.mutate({ mutation: decrement, variables: { amount: 1 } });\n\n    await expect(stream).toEmitTypedValue({\n      data: { count: 1, lastCount: 1 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should support a simple todo app using local state\", async () => {\n    const query = gql`\n      query GetTasks {\n        todos @client {\n          message\n          title\n        }\n      }\n    `;\n\n    const mutation = gql`\n      mutation AddTodo($message: String, $title: String) {\n        addTodo(message: $message, title: $title) @client\n      }\n    `;\n\n    const localState = new LocalState();\n\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n      localState,\n    });\n\n    interface Todo {\n      title: string;\n      message: string;\n      __typename: string;\n    }\n\n    const update = (\n      query: DocumentNode,\n      updater: (todos: any, variables: Todo) => any\n    ): LocalState.Resolver<any, any, any, any> => {\n      return (_result, variables: Todo, { client }): null => {\n        const { cache } = client;\n\n        const data = updater(client.readQuery({ query, variables }), variables);\n        cache.writeQuery({ query, variables, data });\n        return null;\n      };\n    };\n\n    localState.addResolvers({\n      Query: {\n        todos: () => [],\n      },\n      Mutation: {\n        addTodo: update(query, ({ todos }, { title, message }: Todo) => ({\n          todos: todos.concat([{ message, title, __typename: \"Todo\" }]),\n        })),\n      },\n    });\n\n    const stream = new ObservableStream(client.watchQuery<any>({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data).toEqual({ todos: [] });\n    }\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          title: \"Apollo Client 2.0\",\n          message: \"ship it\",\n        },\n      })\n    ).resolves.toStrictEqualTyped({ data: { addTodo: null } });\n\n    {\n      const { data } = await stream.takeNext();\n\n      expect(data.todos).toEqual([\n        {\n          title: \"Apollo Client 2.0\",\n          message: \"ship it\",\n          __typename: \"Todo\",\n        },\n      ]);\n    }\n  });\n});\n\ndescribe(\"Combining client and server state/operations\", () => {\n  test(\"should merge remote and local state\", async () => {\n    const query = gql`\n      query list {\n        list(name: \"my list\") {\n          items {\n            id\n            name\n            isDone\n            isSelected @client\n          }\n        }\n      }\n    `;\n\n    const data = {\n      list: {\n        __typename: \"List\",\n        items: [\n          { __typename: \"ListItem\", id: 1, name: \"first\", isDone: true },\n          { __typename: \"ListItem\", id: 2, name: \"second\", isDone: false },\n        ],\n      },\n    };\n\n    const link = new ApolloLink(() => of({ data }).pipe(delay(20)));\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            toggleItem: async (_, { id }, { client }) => {\n              const { cache } = client;\n\n              id = `ListItem:${id}`;\n              const fragment = gql`\n                fragment item on ListItem {\n                  __typename\n                  isSelected\n                }\n              `;\n              const previous = cache.readFragment<any>({ fragment, id });\n              const data = {\n                ...previous,\n                isSelected: !previous.isSelected,\n              };\n              cache.writeFragment({\n                id,\n                fragment,\n                data,\n              });\n\n              return data;\n            },\n          },\n          ListItem: {\n            isSelected(source) {\n              expect(source.name).toBeDefined();\n              // List items default to an unselected state\n              return false;\n            },\n          },\n        },\n      }),\n    });\n\n    const observer = client.watchQuery({ query });\n\n    const stream = new ObservableStream(observer);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    {\n      const response = await stream.takeNext();\n      const initial = { ...data };\n      initial.list.items = initial.list.items.map((x) => ({\n        ...x,\n        isSelected: false,\n      }));\n\n      expect(response.data).toStrictEqualTyped(initial);\n    }\n\n    await client.mutate({\n      mutation: gql`\n        mutation SelectItem($id: Int!) {\n          toggleItem(id: $id) @client\n        }\n      `,\n      variables: { id: 1 },\n    });\n\n    {\n      const response = await stream.takeNext();\n\n      expect((response.data as any).list.items[0].isSelected).toBe(true);\n      expect((response.data as any).list.items[1].isSelected).toBe(false);\n    }\n  });\n\n  test(\"query resolves with loading: false if subsequent responses contain the same data\", async () => {\n    const request = {\n      query: gql`\n        query people($id: Int) {\n          people(id: $id) {\n            id\n            name\n          }\n        }\n      `,\n      variables: {\n        id: 1,\n      },\n    };\n\n    const PersonType = new GraphQLObjectType({\n      name: \"Person\",\n      fields: {\n        id: { type: GraphQLID },\n        name: { type: GraphQLString },\n      },\n    });\n\n    const peopleData = [\n      { id: 1, name: \"John Smith\" },\n      { id: 2, name: \"Sara Smith\" },\n      { id: 3, name: \"Budd Deey\" },\n    ];\n\n    const QueryType = new GraphQLObjectType({\n      name: \"Query\",\n      fields: {\n        people: {\n          type: PersonType,\n          args: {\n            id: {\n              type: GraphQLInt,\n            },\n          },\n          resolve: (_, { id }) => {\n            return peopleData.find((p) => p.id === id);\n          },\n        },\n      },\n    });\n\n    const schema = new GraphQLSchema({ query: QueryType });\n\n    const link = new ApolloLink((operation) => {\n      return defer(() => {\n        const { query, operationName, variables } = operation;\n\n        return graphql({\n          schema,\n          source: print(query),\n          variableValues: variables,\n          operationName,\n        });\n      });\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery(request);\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { people: { __typename: \"Person\", id: \"1\", name: \"John Smith\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await observable.refetch({ id: 2 });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: true,\n    });\n    await expect(stream).toEmitTypedValue({\n      data: { people: { __typename: \"Person\", id: \"2\", name: \"Sara Smith\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should correctly propagate an error from a client resolver\", async () => {\n    const data = {\n      list: {\n        __typename: \"List\",\n        items: [\n          { __typename: \"ListItem\", id: 1, name: \"first\", isDone: true },\n          { __typename: \"ListItem\", id: 2, name: \"second\", isDone: false },\n        ],\n      },\n    };\n\n    const link = new ApolloLink(() => of({ data }));\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            hasBeenIllegallyTouched: (_, _v, _c) => {\n              throw new Error(\"Illegal Query Operation Occurred\");\n            },\n          },\n\n          Mutation: {\n            touchIllegally: (_, _v, _c) => {\n              throw new Error(\"Illegal Mutation Operation Occurred\");\n            },\n          },\n        },\n      }),\n    });\n\n    const variables = { id: 1 };\n    const query = gql`\n      query hasBeenIllegallyTouched($id: Int!) {\n        hasBeenIllegallyTouched(id: $id) @client\n      }\n    `;\n    const mutation = gql`\n      mutation SelectItem($id: Int!) {\n        touchIllegally(id: $id) @client\n      }\n    `;\n\n    await expect(client.query({ query, variables })).rejects.toStrictEqualTyped(\n      new CombinedGraphQLErrors({\n        data: { hasBeenIllegallyTouched: null },\n        errors: [\n          {\n            message: \"Illegal Query Operation Occurred\",\n            path: [\"hasBeenIllegallyTouched\"],\n            extensions: {\n              localState: {\n                resolver: \"Query.hasBeenIllegallyTouched\",\n                cause: new Error(\"Illegal Query Operation Occurred\"),\n              },\n            },\n          },\n        ],\n      })\n    );\n\n    await expect(\n      client.mutate({ mutation, variables })\n    ).rejects.toStrictEqualTyped(\n      new CombinedGraphQLErrors({\n        data: { touchIllegally: null },\n        errors: [\n          {\n            message: \"Illegal Mutation Operation Occurred\",\n            path: [\"touchIllegally\"],\n            extensions: {\n              localState: {\n                resolver: \"Mutation.touchIllegally\",\n                cause: new Error(\"Illegal Mutation Operation Occurred\"),\n              },\n            },\n          },\n        ],\n      })\n    );\n  });\n\n  test(\"should handle a simple query with both server and client fields\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const query = gql`\n      query GetCount {\n        count @client\n        lastCount\n      }\n    `;\n    const cache = new InMemoryCache();\n\n    const link = new ApolloLink((operation) => {\n      expect(operation.operationName).toBe(\"GetCount\");\n      return of({ data: { lastCount: 1 } });\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        count: 0,\n      },\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { count: 0, lastCount: 1 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should support nested querying of both server and client fields\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const query = gql`\n      query GetUser {\n        user {\n          firstName @client\n          lastName\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const link = new ApolloLink((operation) => {\n      expect(operation.operationName).toBe(\"GetUser\");\n      return of({\n        data: {\n          user: {\n            __typename: \"User\",\n            // We need an id (or a keyFields policy) because, if the User\n            // object is not identifiable, the call to cache.writeQuery\n            // below will simply replace the existing data rather than\n            // merging the new data with the existing data.\n            id: 123,\n            lastName: \"Doe\",\n          },\n        },\n      }).pipe(delay(20));\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        user: {\n          __typename: \"User\",\n          id: 123,\n          firstName: \"John\",\n        },\n      },\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        user: {\n          firstName: \"John\",\n          lastName: \"Doe\",\n          __typename: \"User\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"should combine both server and client mutations\", async () => {\n    const query = gql`\n      query SampleQuery {\n        count @client\n        user {\n          firstName\n        }\n      }\n    `;\n\n    const mutation = gql`\n      mutation SampleMutation {\n        incrementCount @client\n        updateUser(firstName: \"Harry\") {\n          firstName\n        }\n      }\n    `;\n\n    const counterQuery = gql`\n      {\n        count @client\n      }\n    `;\n\n    const userQuery = gql`\n      {\n        user {\n          firstName\n        }\n      }\n    `;\n\n    const link = new ApolloLink((operation): Observable<{}> => {\n      if (operation.operationName === \"SampleQuery\") {\n        return of({\n          data: { user: { __typename: \"User\", firstName: \"John\" } },\n        }).pipe(delay(20));\n      }\n      if (operation.operationName === \"SampleMutation\") {\n        return of({\n          data: { updateUser: { __typename: \"User\", firstName: \"Harry\" } },\n        }).pipe(delay(20));\n      }\n      return of({\n        errors: [new Error(`Unknown operation ${operation.operationName}`)],\n      }).pipe(delay(20));\n    });\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            incrementCount: (_, __, { client }) => {\n              const { cache } = client;\n\n              const { count } = cache.readQuery<any>({ query: counterQuery });\n              const data = { count: count + 1 };\n              cache.writeQuery({\n                query: counterQuery,\n                data,\n              });\n              return null;\n            },\n          },\n        },\n      }),\n    });\n\n    cache.writeQuery({\n      query: counterQuery,\n      data: {\n        count: 0,\n      },\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        count: 0,\n        user: { __typename: \"User\", firstName: \"John\" },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await client.mutate<any>({\n      mutation,\n      update(proxy, { data: { updateUser } }) {\n        proxy.writeQuery({\n          query: userQuery,\n          data: {\n            user: { ...updateUser },\n          },\n        });\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        count: 1,\n        user: { __typename: \"User\", firstName: \"Harry\" },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  test(\"handles server errors when root data property is null\", async () => {\n    const query = gql`\n      query GetUser {\n        user {\n          firstName @client\n          lastName\n        }\n      }\n    `;\n\n    const error: GraphQLFormattedError = {\n      message: \"something went wrong\",\n      extensions: {\n        code: \"INTERNAL_SERVER_ERROR\",\n      },\n      path: [\"user\"],\n    };\n\n    const cache = new InMemoryCache();\n    const link = new ApolloLink((operation) => {\n      return of({\n        data: null,\n        errors: [error],\n      });\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link,\n      localState: new LocalState(),\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [error],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n  });\n});\n\ntest(\"throws when executing queries with client fields when local state is not configured\", async () => {\n  const query = gql`\n    query GetUser {\n      user {\n        firstName @client\n        lastName\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return of({ data: { user: { __typename: \"User\", lastName: \"Smith\" } } });\n    }),\n  });\n\n  await expect(client.query({ query })).rejects.toEqual(\n    new InvariantError(\n      \"Query 'GetUser' contains `@client` fields but local state has not been configured.\"\n    )\n  );\n});\n\ntest(\"throws when executing mutations with client fields when local state is not configured\", async () => {\n  const mutation = gql`\n    mutation UpdateUser {\n      updateUser {\n        firstName @client\n        lastName\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return of({\n        data: { updateUser: { __typename: \"User\", lastName: \"Smith\" } },\n      });\n    }),\n  });\n\n  await expect(client.mutate({ mutation })).rejects.toEqual(\n    new InvariantError(\n      \"Mutation 'UpdateUser' contains `@client` fields but local state has not been configured.\"\n    )\n  );\n});\n\ntest(\"throws when executing subscriptions with client fields when local state is not configured\", async () => {\n  const subscription = gql`\n    subscription OnUserUpdate {\n      onUpdateUser {\n        firstName @client\n        lastName\n      }\n    }\n  `;\n\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link,\n  });\n  const stream = new ObservableStream(\n    client.subscribe({ query: subscription })\n  );\n\n  await expect(stream).toEmitError(\n    new InvariantError(\n      \"Subscription 'OnUserUpdate' contains `@client` fields but local state has not been configured.\"\n    )\n  );\n});\n\ntest.each([\"cache-first\", \"network-only\"] as const)(\n  \"sets existing value of `@client` field to undefined when read function is present\",\n  async (fetchPolicy) => {\n    const query = gql`\n      query GetUser {\n        user {\n          firstName @client\n          lastName\n        }\n      }\n    `;\n\n    const read = jest.fn((value = \"Fallback\") => value);\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        typePolicies: {\n          User: {\n            fields: {\n              firstName: {\n                read,\n              },\n            },\n          },\n        },\n      }),\n      link: new ApolloLink(() => {\n        return of({\n          data: { user: { __typename: \"User\", lastName: \"Smith\" } },\n        }).pipe(delay(10));\n      }),\n      localState: new LocalState(),\n    });\n\n    await expect(\n      client.query({ query, fetchPolicy })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        user: { __typename: \"User\", firstName: \"Fallback\", lastName: \"Smith\" },\n      },\n    });\n\n    expect(read).toHaveBeenCalledTimes(1);\n    expect(read).toHaveBeenCalledWith(undefined, expect.anything());\n  }\n);\n\ntest(\"sets existing value of `@client` field to null and warns when using no-cache with read function\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query GetUser {\n      user {\n        firstName @client\n        lastName\n      }\n    }\n  `;\n\n  const read = jest.fn((value) => value ?? \"Fallback\");\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        User: {\n          fields: {\n            firstName: {\n              read,\n            },\n          },\n        },\n      },\n    }),\n    link: new ApolloLink(() => {\n      return of({\n        data: { user: { __typename: \"User\", lastName: \"Smith\" } },\n      }).pipe(delay(10));\n    }),\n    localState: new LocalState(),\n  });\n\n  await expect(\n    client.query({ query, fetchPolicy: \"no-cache\" })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: { __typename: \"User\", firstName: null, lastName: \"Smith\" },\n    },\n  });\n\n  expect(read).not.toHaveBeenCalled();\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.NO_CACHE,\n    \"User.firstName\"\n  );\n});\n\ntest(\"sets existing value of `@client` field to null and warns when merge function but not read function is present\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query GetUser {\n      user {\n        firstName @client\n        lastName\n      }\n    }\n  `;\n\n  const merge = jest.fn(() => \"Fallback\");\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        User: {\n          fields: {\n            firstName: {\n              merge,\n            },\n          },\n        },\n      },\n    }),\n    link: new ApolloLink(() => {\n      return of({\n        data: { user: { __typename: \"User\", lastName: \"Smith\" } },\n      }).pipe(delay(10));\n    }),\n    localState: new LocalState(),\n  });\n\n  await expect(client.query({ query })).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        firstName: \"Fallback\",\n        lastName: \"Smith\",\n      },\n    },\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(undefined, null, expect.anything());\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"User.firstName\"\n  );\n});\n"
  },
  {
    "path": "src/__tests__/local-state/resolvers.ts",
    "content": "import type { DocumentNode, ExecutionResult } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { delay, of } from \"rxjs\";\n\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache, isReference } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\n\nconst setupTestWithResolvers = ({\n  localState,\n  query,\n  serverQuery,\n  variables = {},\n  queryOptions = {},\n  serverResult,\n  error,\n  delay,\n}: {\n  localState: LocalState;\n  query: DocumentNode;\n  serverQuery?: DocumentNode;\n  variables?: object;\n  queryOptions?: object;\n  error?: Error;\n  serverResult?: ExecutionResult;\n  delay?: number;\n}) => {\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query: serverQuery || query, variables },\n        result: serverResult,\n        error,\n        delay,\n      },\n    ]),\n    localState,\n  });\n\n  return new ObservableStream(\n    client.watchQuery<any>({ query, variables, ...queryOptions })\n  );\n};\n\ndescribe(\"Basic resolver capabilities\", () => {\n  test(\"should run resolvers for @client queries\", async () => {\n    const query = gql`\n      query Test {\n        foo @client {\n          bar\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ __typename: \"Foo\", bar: true }),\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      localState,\n      cache: new InMemoryCache(),\n      // Local resolvers handle this query\n      link: ApolloLink.empty(),\n    });\n\n    const stream = new ObservableStream(client.watchQuery({ query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: { __typename: \"Foo\", bar: true } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should handle queries with a mix of @client and server fields\", async () => {\n    const query = gql`\n      query Mixed {\n        foo @client {\n          bar\n        }\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const serverQuery = gql`\n      query Mixed {\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ __typename: \"Foo\", bar: true }),\n        },\n      },\n    });\n\n    const stream = setupTestWithResolvers({\n      localState,\n      query,\n      serverQuery,\n      serverResult: { data: { bar: { __typename: \"Bar\", baz: true } } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        foo: { __typename: \"Foo\", bar: true },\n        bar: { __typename: \"Bar\", baz: true },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should handle a mix of @client fields with fragments and server fields\", async () => {\n    const query = gql`\n      fragment client on ClientData {\n        bar\n        __typename\n      }\n\n      query Mixed {\n        foo @client {\n          ...client\n        }\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const serverQuery = gql`\n      query Mixed {\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ bar: true, __typename: \"ClientData\" }),\n        },\n      },\n    });\n\n    const stream = setupTestWithResolvers({\n      localState,\n      query,\n      serverQuery,\n      serverResult: { data: { bar: { baz: true, __typename: \"Bar\" } } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        foo: { bar: true, __typename: \"ClientData\" },\n        bar: { baz: true, __typename: \"Bar\" },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should handle @client fields inside fragments\", async () => {\n    const query = gql`\n      fragment Foo on Foo {\n        bar\n        ...Foo2\n      }\n      fragment Foo2 on Foo {\n        __typename\n        baz @client\n      }\n      query Mixed {\n        foo {\n          ...Foo\n        }\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const serverQuery = gql`\n      fragment Foo on Foo {\n        bar\n      }\n      query Mixed {\n        foo {\n          ...Foo\n        }\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Foo: {\n          baz: () => false,\n        },\n      },\n    });\n\n    const stream = setupTestWithResolvers({\n      localState,\n      query,\n      serverQuery,\n      serverResult: {\n        data: { foo: { bar: true, __typename: `Foo` }, bar: { baz: true } },\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        foo: { bar: true, baz: false, __typename: \"Foo\" },\n        bar: { baz: true },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should have access to query variables when running @client resolvers\", async () => {\n    const query = gql`\n      query WithVariables($id: ID!) {\n        foo @client {\n          bar(id: $id)\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ __typename: \"Foo\" }),\n        },\n        Foo: {\n          bar: (_data, { id }: { id: number }) => id,\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      localState,\n      cache: new InMemoryCache(),\n      // Local resolvers handle this query\n      link: ApolloLink.empty(),\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, variables: { id: 1 } })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: { __typename: \"Foo\", bar: 1 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should pass context to @client resolvers\", async () => {\n    const query = gql`\n      query WithContext {\n        foo @client {\n          bar\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ __typename: \"Foo\" }),\n        },\n        Foo: {\n          bar: (_data, _args, { requestContext }) => requestContext.id,\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      localState,\n      cache: new InMemoryCache(),\n      // The resolvers will handle the full response\n      link: ApolloLink.empty(),\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, context: { id: 1 } })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: { __typename: \"Foo\", bar: 1 } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should combine local @client resolver results with server results, for the same field\", async () => {\n    const query = gql`\n      query author {\n        author {\n          name\n          stats {\n            totalPosts\n            postsToday @client\n          }\n        }\n      }\n    `;\n\n    const serverQuery = gql`\n      query author {\n        author {\n          name\n          stats {\n            totalPosts\n          }\n        }\n      }\n    `;\n\n    const localState = new LocalState({\n      resolvers: {\n        Stats: {\n          postsToday: () => 10,\n        },\n      },\n    });\n\n    const stream = setupTestWithResolvers({\n      localState,\n      query,\n      serverQuery,\n      serverResult: {\n        data: {\n          author: {\n            name: \"John Smith\",\n            stats: {\n              totalPosts: 100,\n              __typename: \"Stats\",\n            },\n            __typename: \"Author\",\n          },\n        },\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        author: {\n          __typename: \"Author\",\n          name: \"John Smith\",\n          stats: {\n            __typename: \"Stats\",\n            totalPosts: 100,\n            postsToday: 10,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  test(\"should handle resolvers that work with booleans properly\", async () => {\n    const query = gql`\n      query CartDetails {\n        isInCart @client\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    cache.writeQuery({ query, data: { isInCart: true } });\n\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            isInCart: () => false,\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query, fetchPolicy: \"network-only\" });\n\n    expect(result).toStrictEqualTyped({ data: { isInCart: false } });\n  });\n\n  test(\"should handle nested asynchronous @client resolvers (issue #4841)\", () => {\n    const query = gql`\n      query DeveloperTicketComments($id: ID) {\n        developer(id: $id) @client {\n          id\n          handle\n          tickets @client {\n            id\n            comments @client {\n              id\n            }\n          }\n        }\n      }\n    `;\n\n    function randomDelay(range: number) {\n      return new Promise((resolve) =>\n        setTimeout(resolve, Math.round(Math.random() * range))\n      );\n    }\n\n    function uuid() {\n      return Math.random().toString(36).slice(2);\n    }\n\n    const developerId = uuid();\n\n    function times<T>(n: number, thunk: () => T): Promise<T[]> {\n      const result: T[] = [];\n      for (let i = 0; i < n; ++i) {\n        result.push(thunk());\n      }\n      return Promise.all(result);\n    }\n\n    const ticketsPerDev = 5;\n    const commentsPerTicket = 5;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            async developer(_, { id }) {\n              await randomDelay(50);\n              expect(id).toBe(developerId);\n              return {\n                __typename: \"Developer\",\n                id,\n                handle: \"@benjamn\",\n              };\n            },\n          },\n          Developer: {\n            async tickets(developer) {\n              await randomDelay(50);\n              expect(developer.__typename).toBe(\"Developer\");\n              return times(ticketsPerDev, () => ({\n                __typename: \"Ticket\",\n                id: uuid(),\n              }));\n            },\n          },\n          Ticket: {\n            async comments(ticket) {\n              await randomDelay(50);\n              expect(ticket.__typename).toBe(\"Ticket\");\n              return times(commentsPerTicket, () => ({\n                __typename: \"Comment\",\n                id: uuid(),\n              }));\n            },\n          },\n        },\n      }),\n    });\n\n    function check(result: ApolloClient.QueryResult<any>) {\n      return new Promise<void>((resolve) => {\n        expect(result.data.developer.id).toBe(developerId);\n        expect(result.data.developer.handle).toBe(\"@benjamn\");\n        expect(result.data.developer.tickets.length).toBe(ticketsPerDev);\n        const commentIds = new Set<string>();\n        result.data.developer.tickets.forEach((ticket: any) => {\n          expect(ticket.__typename).toBe(\"Ticket\");\n          expect(ticket.comments.length).toBe(commentsPerTicket);\n          ticket.comments.forEach((comment: any) => {\n            expect(comment.__typename).toBe(\"Comment\");\n            commentIds.add(comment.id);\n          });\n        });\n        expect(commentIds.size).toBe(ticketsPerDev * commentsPerTicket);\n        resolve();\n      });\n    }\n\n    return Promise.all([\n      new Promise((resolve, reject) => {\n        client\n          .watchQuery({\n            query,\n            variables: {\n              id: developerId,\n            },\n            notifyOnNetworkStatusChange: false,\n          })\n          .subscribe({\n            next(result) {\n              check(result).then(resolve, reject);\n            },\n            error: reject,\n          });\n      }),\n      client\n        .query({\n          query,\n          variables: {\n            id: developerId,\n          },\n        })\n        .then(check),\n    ]);\n  });\n\n  test(\"should not run resolvers without @client directive (issue #9571)\", async () => {\n    const query = gql`\n      query Mixed {\n        foo @client {\n          bar\n        }\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const serverQuery = gql`\n      query Mixed {\n        bar {\n          baz\n        }\n      }\n    `;\n\n    const barResolver = jest.fn(() => ({ __typename: `Bar`, baz: false }));\n\n    const localState = new LocalState({\n      resolvers: {\n        Query: {\n          foo: () => ({ __typename: `Foo`, bar: true }),\n          bar: barResolver,\n        },\n      },\n    });\n\n    const stream = setupTestWithResolvers({\n      localState,\n      query,\n      serverQuery,\n      serverResult: { data: { bar: { __typename: \"Bar\", baz: true } } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        foo: { __typename: \"Foo\", bar: true },\n        bar: { __typename: \"Bar\", baz: true },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(barResolver).not.toHaveBeenCalled();\n  });\n});\n\ndescribe(\"Writing cache data from resolvers\", () => {\n  test(\"should let you write to the cache with a mutation\", async () => {\n    const query = gql`\n      {\n        field @client\n      }\n    `;\n\n    const mutation = gql`\n      mutation start {\n        start @client\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            start(_data, _args, { client }) {\n              client.cache.writeQuery({ query, data: { field: 1 } });\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: { start: true },\n    });\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({ data: { field: 1 } });\n  });\n\n  test(\"should let you write to the cache with a mutation using an ID\", async () => {\n    const query = gql`\n      {\n        obj @client {\n          field\n        }\n      }\n    `;\n\n    const mutation = gql`\n      mutation start {\n        start @client\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            start() {\n              cache.writeQuery({\n                query,\n                data: {\n                  obj: { field: 1, id: \"uniqueId\", __typename: \"Object\" },\n                },\n              });\n\n              cache.modify({\n                id: \"Object:uniqueId\",\n                fields: {\n                  field(value) {\n                    expect(value).toBe(1);\n                    return 2;\n                  },\n                },\n              });\n\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: { start: true },\n    });\n\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({\n      data: { obj: { __typename: \"Object\", field: 2 } },\n    });\n  });\n\n  test(\"should not overwrite __typename when writing to the cache with an id\", async () => {\n    const query = gql`\n      {\n        obj @client {\n          field {\n            field2\n          }\n          id\n        }\n      }\n    `;\n\n    const mutation = gql`\n      mutation start {\n        start @client\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Mutation: {\n            start() {\n              cache.writeQuery({\n                query,\n                data: {\n                  obj: {\n                    field: { field2: 1, __typename: \"Field\" },\n                    id: \"uniqueId\",\n                    __typename: \"Object\",\n                  },\n                },\n              });\n              cache.modify<{ field: { field2: number } }>({\n                id: \"Object:uniqueId\",\n                fields: {\n                  field(value) {\n                    if (isReference(value)) {\n                      fail(\"Should not be a reference\");\n                    }\n                    expect(value.field2).toBe(1);\n                    return { ...value, field2: 2 };\n                  },\n                },\n              });\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: { start: true },\n    });\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        obj: {\n          __typename: \"Object\",\n          field: { __typename: \"Field\", field2: 2 },\n          id: \"uniqueId\",\n        },\n      },\n    });\n  });\n});\n\ndescribe(\"Resolving field aliases\", () => {\n  test(\"should run resolvers for missing client queries with aliased field\", async () => {\n    const query = gql`\n      query Aliased {\n        foo @client {\n          bar\n        }\n        baz: bar {\n          foo\n        }\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      // Each link is responsible for implementing their own aliasing so it\n      // returns baz not bar\n      of({ data: { baz: { foo: true, __typename: \"Baz\" } } })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            foo: () => ({ bar: true, __typename: \"Foo\" }),\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        foo: { bar: true, __typename: \"Foo\" },\n        baz: { foo: true, __typename: \"Baz\" },\n      },\n    });\n  });\n\n  test(\"should run resolvers for client queries when aliases are in use on the @client-tagged node\", async () => {\n    const aliasedQuery = gql`\n      query Test {\n        fie: foo @client {\n          bar\n        }\n      }\n    `;\n\n    const fie = jest.fn();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            foo: () => ({ bar: true, __typename: \"Foo\" }),\n            fie,\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query: aliasedQuery });\n\n    expect(result).toStrictEqualTyped({\n      data: { fie: { bar: true, __typename: \"Foo\" } },\n    });\n    expect(fie).not.toHaveBeenCalled();\n  });\n\n  test(\"should respect aliases for *nested fields* on the @client-tagged node\", async () => {\n    const aliasedQuery = gql`\n      query Test {\n        fie: foo @client {\n          fum: bar\n        }\n        baz: bar {\n          foo\n        }\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      of({ data: { baz: { foo: true, __typename: \"Baz\" } } })\n    );\n\n    const fie = jest.fn();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            foo: () => ({ bar: true, __typename: \"Foo\" }),\n            fie,\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query: aliasedQuery });\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        fie: { fum: true, __typename: \"Foo\" },\n        baz: { foo: true, __typename: \"Baz\" },\n      },\n    });\n    expect(fie).not.toHaveBeenCalled();\n  });\n\n  test(\"should pull initialized values for aliased fields tagged with @client from the cache\", async () => {\n    const query = gql`\n      {\n        fie: foo @client {\n          bar\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState: new LocalState(),\n    });\n\n    cache.writeQuery({\n      query: gql`\n        {\n          foo {\n            bar\n          }\n        }\n      `,\n      data: {\n        foo: {\n          bar: \"yo\",\n          __typename: \"Foo\",\n        },\n      },\n    });\n\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({\n      data: { fie: { bar: \"yo\", __typename: \"Foo\" } },\n    });\n  });\n\n  test(\"should resolve @client fields using local resolvers and not have their value overridden when a fragment is loaded\", async () => {\n    const query = gql`\n      fragment LaunchDetails on Launch {\n        id\n        __typename\n      }\n      query Launch {\n        launch {\n          isInCart @client\n          ...LaunchDetails\n        }\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          launch: {\n            id: 1,\n            __typename: \"Launch\",\n          },\n        },\n      })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Launch: {\n            isInCart() {\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    client.writeQuery({\n      query: gql`\n        {\n          launch {\n            isInCart\n          }\n        }\n      `,\n      data: {\n        launch: {\n          isInCart: false,\n          __typename: \"Launch\",\n        },\n      },\n    });\n\n    // `isInCart` resolver is fired, returning `true` (which is then\n    // stored in the cache).\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { launch: { __typename: \"Launch\", id: 1, isInCart: true } },\n    });\n\n    // When the same query fires again, `isInCart` should be pulled from\n    // the cache and have a value of `true`.\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: { launch: { __typename: \"Launch\", id: 1, isInCart: true } },\n    });\n  });\n});\n\ndescribe(\"Force local resolvers\", () => {\n  test(\"should force the running of local resolvers marked with `@client(always: true)` when using `ApolloClient.query`\", async () => {\n    const query = gql`\n      query Author {\n        author {\n          name\n          isLoggedIn @client(always: true)\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    const localState = new LocalState();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n      localState,\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        author: {\n          name: \"John Smith\",\n          isLoggedIn: false,\n          __typename: \"Author\",\n        },\n      },\n    });\n\n    // When the resolver isn't defined, there isn't anything to force, so\n    // make sure the query resolves from the cache properly.\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: {\n        author: { __typename: \"Author\", isLoggedIn: false, name: \"John Smith\" },\n      },\n    });\n\n    localState.addResolvers({\n      Author: {\n        isLoggedIn() {\n          return true;\n        },\n      },\n    });\n\n    // A resolver is defined, so make sure it's forced, and the result\n    // resolves properly as a combination of cache and local resolver\n    // data.\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: {\n        author: { __typename: \"Author\", isLoggedIn: true, name: \"John Smith\" },\n      },\n    });\n  });\n\n  test(\"should avoid running forced resolvers a second time when loading results over the network (so not from the cache)\", async () => {\n    const query = gql`\n      query Author {\n        author {\n          name\n          isLoggedIn @client(always: true)\n        }\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          author: {\n            name: \"John Smith\",\n            __typename: \"Author\",\n          },\n        },\n      })\n    );\n\n    let count = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Author: {\n            isLoggedIn() {\n              count += 1;\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({\n      data: {\n        author: {\n          __typename: \"Author\",\n          isLoggedIn: true,\n          name: \"John Smith\",\n        },\n      },\n    });\n    expect(count).toEqual(1);\n  });\n\n  test(\"should only force resolvers for fields marked with `@client(always: true)`, not all `@client` fields\", async () => {\n    const query = gql`\n      query UserDetails {\n        name @client\n        isLoggedIn @client(always: true)\n      }\n    `;\n\n    let nameCount = 0;\n    let isLoggedInCount = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            name() {\n              nameCount += 1;\n              return \"John Smith\";\n            },\n            isLoggedIn() {\n              isLoggedInCount += 1;\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    await client.query({ query });\n    expect(nameCount).toEqual(1);\n    expect(isLoggedInCount).toEqual(1);\n\n    // On the next request, `name` will be loaded from the cache only,\n    // whereas `isLoggedIn` will be loaded from the cache then overwritten\n    // by running its forced local resolver.\n    await client.query({ query });\n    expect(nameCount).toEqual(1);\n    expect(isLoggedInCount).toEqual(2);\n  });\n\n  test(\"should force the running of local resolvers marked with `@client(always: true)` when using `ApolloClient.watchQuery`\", async () => {\n    const query = gql`\n      query IsUserLoggedIn {\n        isUserLoggedIn @client(always: true)\n      }\n    `;\n\n    const queryNoForce = gql`\n      query IsUserLoggedIn {\n        isUserLoggedIn @client\n      }\n    `;\n\n    let callCount = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            isUserLoggedIn() {\n              callCount += 1;\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    {\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n      expect(callCount).toBe(1);\n    }\n\n    {\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n      expect(callCount).toBe(2);\n    }\n\n    {\n      const stream = new ObservableStream(\n        client.watchQuery({ query: queryNoForce })\n      );\n\n      await expect(stream).toEmitNext();\n      // Result is loaded from the cache since the resolver\n      // isn't being forced.\n      expect(callCount).toBe(2);\n    }\n  });\n\n  test(\"should allow client-only virtual resolvers (#4731)\", async () => {\n    const query = gql`\n      query UserData {\n        userData @client {\n          firstName\n          lastName\n          fullName\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            userData() {\n              return {\n                __typename: \"User\",\n                firstName: \"Ben\",\n                lastName: \"Newman\",\n              };\n            },\n          },\n          User: {\n            fullName(data) {\n              return data.firstName + \" \" + data.lastName;\n            },\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        userData: {\n          __typename: \"User\",\n          firstName: \"Ben\",\n          lastName: \"Newman\",\n          fullName: \"Ben Newman\",\n        },\n      },\n    });\n  });\n\n  test(\"runs forced resolvers and returns result when returnPartialData is true\", async () => {\n    const query = gql`\n      query {\n        user {\n          id\n          name\n        }\n        isLoggedIn @client(always: true)\n      }\n    `;\n\n    let isLoggedInCount = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(() => {\n        return of({\n          data: { user: { __typename: \"User\", id: 1, name: \"Test User\" } },\n        }).pipe(delay(10));\n      }),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            isLoggedIn: () => {\n              isLoggedInCount++;\n              return true;\n            },\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, returnPartialData: true })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        isLoggedIn: true,\n      },\n      dataState: \"partial\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        user: { __typename: \"User\", id: 1, name: \"Test User\" },\n        isLoggedIn: true,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n\n    expect(isLoggedInCount).toBe(2);\n  });\n});\n\ndescribe(\"Async resolvers\", () => {\n  test(\"should support async @client resolvers\", async () => {\n    const query = gql`\n      query Member {\n        isLoggedIn @client\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            isLoggedIn() {\n              return Promise.resolve(true);\n            },\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query })!;\n\n    expect(result).toStrictEqualTyped({\n      data: { isLoggedIn: true },\n    });\n  });\n\n  test(\"should support async @client resolvers mixed with remotely resolved data\", async () => {\n    const query = gql`\n      query Member {\n        member {\n          name\n          sessionCount @client\n          isLoggedIn @client\n        }\n      }\n    `;\n\n    const testMember = {\n      name: \"John Smithsonian\",\n      isLoggedIn: true,\n      sessionCount: 10,\n    };\n\n    const link = new ApolloLink(() =>\n      of({\n        data: {\n          member: {\n            name: testMember.name,\n            __typename: \"Member\",\n          },\n        },\n      })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Member: {\n            isLoggedIn() {\n              return Promise.resolve(testMember.isLoggedIn);\n            },\n            sessionCount() {\n              return testMember.sessionCount;\n            },\n          },\n        },\n      }),\n    });\n\n    const result = await client.query({ query })!;\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        member: {\n          name: testMember.name,\n          isLoggedIn: testMember.isLoggedIn,\n          sessionCount: testMember.sessionCount,\n          __typename: \"Member\",\n        },\n      },\n    });\n  });\n});\n\ntest(\"does not execute resolver when using cache-only fetch policy with no data in the cache\", async () => {\n  const query = gql`\n    query {\n      user {\n        id\n        name\n      }\n      isLoggedIn @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n    localState: new LocalState({\n      resolvers: {\n        Query: {\n          isLoggedIn: () => {\n            return true;\n          },\n        },\n      },\n    }),\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-only\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not execute resolver if client field is not in the cache when using cache-only fetch policy\", async () => {\n  const query = gql`\n    query {\n      user {\n        id\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n    localState: new LocalState({\n      resolvers: {\n        Query: {\n          isLoggedIn: () => {\n            return true;\n          },\n        },\n      },\n    }),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      user: { __typename: \"User\", id: \"1\", name: \"Test User\" },\n    },\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-only\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns cache @client field data when using cache-only fetch policy\", async () => {\n  const query = gql`\n    query {\n      user {\n        id\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n    localState: new LocalState({\n      resolvers: {\n        Query: {\n          isLoggedIn: () => {\n            return true;\n          },\n        },\n      },\n    }),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: \"1\",\n        name: \"Test User\",\n        isLoggedIn: false,\n      },\n    },\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-only\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: \"1\",\n        name: \"Test User\",\n        isLoggedIn: false,\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n"
  },
  {
    "path": "src/__tests__/local-state/subscriptions.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport { of } from \"rxjs\";\n\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\n\ndescribe(\"Basic functionality\", () => {\n  it(\"should not break subscriptions\", async () => {\n    const query = gql`\n      subscription {\n        field\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      of({ data: { field: 1 } }, { data: { field: 2 } })\n    );\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            count: () => 0,\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(client.subscribe({ query }));\n\n    await expect(stream).toEmitTypedValue({ data: { field: 1 } });\n    await expect(stream).toEmitTypedValue({ data: { field: 2 } });\n    await expect(stream).toComplete();\n  });\n\n  it(\"should be able to mix @client fields with subscription results\", async () => {\n    const query = gql`\n      subscription {\n        field\n        count @client\n      }\n    `;\n\n    const link = new ApolloLink(() =>\n      of({ data: { field: 1 } }, { data: { field: 2 } })\n    );\n\n    let subCounter = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      localState: new LocalState({\n        resolvers: {\n          Subscription: {\n            count: () => {\n              subCounter += 1;\n              return subCounter;\n            },\n          },\n        },\n      }),\n    });\n\n    const stream = new ObservableStream(client.subscribe({ query }));\n\n    await expect(stream).toEmitTypedValue({ data: { field: 1, count: 1 } });\n    await expect(stream).toEmitTypedValue({ data: { field: 2, count: 2 } });\n    await expect(stream).toComplete();\n  });\n});\n"
  },
  {
    "path": "src/__tests__/mutationResults.ts",
    "content": "import type { GraphQLFormattedError } from \"graphql\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { cloneDeep } from \"lodash\";\nimport type { Subscription } from \"rxjs\";\nimport { firstValueFrom, from, Observable } from \"rxjs\";\n\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\ndescribe(\"mutation results\", () => {\n  const query = gql`\n    query todoList {\n      todoList(id: 5) {\n        id\n        todos {\n          id\n          text\n          completed\n        }\n        filteredTodos: todos(completed: true) {\n          id\n          text\n          completed\n        }\n      }\n      noIdList: todoList(id: 6) {\n        id\n        todos {\n          text\n          completed\n        }\n      }\n    }\n  `;\n\n  const queryWithTypename = gql`\n    query todoList {\n      todoList(id: 5) {\n        id\n        todos {\n          id\n          text\n          completed\n          __typename\n        }\n        filteredTodos: todos(completed: true) {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n      noIdList: todoList(id: 6) {\n        id\n        todos {\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    }\n  `;\n\n  const result: any = {\n    data: {\n      __typename: \"Query\",\n      todoList: {\n        __typename: \"TodoList\",\n        id: \"5\",\n        todos: [\n          {\n            __typename: \"Todo\",\n            id: \"3\",\n            text: \"Hello world\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            id: \"6\",\n            text: \"Second task\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            id: \"12\",\n            text: \"Do other stuff\",\n            completed: false,\n          },\n        ],\n        filteredTodos: [],\n      },\n      noIdList: {\n        __typename: \"TodoList\",\n        id: \"7\",\n        todos: [\n          {\n            __typename: \"Todo\",\n            text: \"Hello world\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            text: \"Second task\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            text: \"Do other stuff\",\n            completed: false,\n          },\n        ],\n      },\n    },\n  };\n\n  function setupObsQuery(...mockedResponses: MockLink.MockedResponse[]) {\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: queryWithTypename } as any,\n          result,\n        },\n        ...mockedResponses,\n      ]),\n      cache: new InMemoryCache({\n        dataIdFromObject: (obj: any) => {\n          if (obj.id && obj.__typename) {\n            return obj.__typename + obj.id;\n          }\n          return null;\n        },\n        // Passing an empty map enables warnings about missing fields:\n        possibleTypes: {},\n      }),\n    });\n\n    return {\n      client,\n      obsQuery: client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      }),\n    };\n  }\n\n  function setupDelayObsQuery(delay: number, ...mockedResponses: any[]) {\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: queryWithTypename } as any,\n          result,\n          delay,\n        },\n        ...mockedResponses,\n      ]),\n      cache: new InMemoryCache({\n        dataIdFromObject: (obj: any) => {\n          if (obj.id && obj.__typename) {\n            return obj.__typename + obj.id;\n          }\n          return null;\n        },\n        // Passing an empty map enables warnings about missing fields:\n        possibleTypes: {},\n      }),\n    });\n\n    return {\n      client,\n      obsQuery: client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      }),\n    };\n  }\n\n  it(\"correctly integrates field changes by default\", async () => {\n    const mutation = gql`\n      mutation setCompleted {\n        setCompleted(todoId: \"3\") {\n          id\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        setCompleted: {\n          __typename: \"Todo\",\n          id: \"3\",\n          completed: true,\n        },\n      },\n    };\n\n    const { client, obsQuery } = setupObsQuery({\n      request: { query: mutation },\n      result: mutationResult,\n    });\n\n    await firstValueFrom(from(obsQuery));\n    await expect(client.mutate({ mutation })).resolves.toStrictEqualTyped({\n      data: mutationResult.data,\n    });\n    const newResult = await client.query<any>({ query });\n    expect(newResult.data.todoList.todos[0].completed).toBe(true);\n  });\n\n  it(\"correctly integrates field changes by default with variables\", async () => {\n    const query = gql`\n      query getMini($id: ID!) {\n        mini(id: $id) {\n          id\n          cover(maxWidth: 600, maxHeight: 400)\n          __typename\n        }\n      }\n    `;\n    const mutation = gql`\n      mutation upload($signature: String!) {\n        mini: submitMiniCoverS3DirectUpload(signature: $signature) {\n          id\n          cover(maxWidth: 600, maxHeight: 400)\n          __typename\n        }\n      }\n    `;\n\n    const link = new MockLink([\n      {\n        request: {\n          query,\n          variables: { id: 1 },\n        } as any,\n        delay: 100,\n        result: {\n          data: { mini: { id: 1, cover: \"image\", __typename: \"Mini\" } },\n        },\n      },\n      {\n        request: {\n          query: mutation,\n          variables: { signature: \"1234\" },\n        } as any,\n        delay: 150,\n        result: {\n          data: { mini: { id: 1, cover: \"image2\", __typename: \"Mini\" } },\n        },\n      },\n    ]);\n\n    interface Data {\n      mini: { id: number; cover: string; __typename: string };\n    }\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        dataIdFromObject: (obj: any) => {\n          if (obj.id && obj.__typename) {\n            return obj.__typename + obj.id;\n          }\n          return null;\n        },\n      }),\n    });\n\n    const obs = client.watchQuery<Data>({\n      query,\n      variables: { id: 1 },\n      notifyOnNetworkStatusChange: false,\n    });\n\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      data: { mini: { id: 1, cover: \"image\", __typename: \"Mini\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(\n      client.mutate({ mutation, variables: { signature: \"1234\" } })\n    ).resolves.toStrictEqualTyped({\n      data: { mini: { id: 1, cover: \"image2\", __typename: \"Mini\" } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { mini: { id: 1, cover: \"image2\", __typename: \"Mini\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"should write results to cache according to errorPolicy\", async () => {\n    const expectedFakeError: GraphQLFormattedError = {\n      message: \"expected/fake error\",\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        typePolicies: {\n          Person: {\n            keyFields: [\"name\"],\n          },\n        },\n      }),\n\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            observer.next({\n              errors: [expectedFakeError],\n              data: {\n                newPerson: {\n                  __typename: \"Person\",\n                  name: operation.variables.newName,\n                },\n              },\n            });\n            observer.complete();\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n      })\n    ).rejects.toThrow(\n      new CombinedGraphQLErrors({\n        data: { newPerson: { __typename: \"Person\", name: \"Hugh Willson\" } },\n        errors: [expectedFakeError],\n      })\n    );\n\n    expect(client.cache.extract()).toMatchSnapshot();\n\n    const ignoreErrorsResult = await client.mutate({\n      mutation,\n      errorPolicy: \"ignore\",\n      variables: {\n        newName: \"Jenn Creighton\",\n      },\n    });\n\n    expect(ignoreErrorsResult).toStrictEqualTyped({\n      data: {\n        newPerson: {\n          __typename: \"Person\",\n          name: \"Jenn Creighton\",\n        },\n      },\n    });\n\n    expect(client.cache.extract()).toMatchSnapshot();\n\n    const allErrorsResult = await client.mutate({\n      mutation,\n      errorPolicy: \"all\",\n      variables: {\n        newName: \"Ellen Shapiro\",\n      },\n    });\n\n    expect(allErrorsResult).toStrictEqualTyped({\n      data: {\n        newPerson: {\n          __typename: \"Person\",\n          name: \"Ellen Shapiro\",\n        },\n      },\n      error: new CombinedGraphQLErrors({\n        data: { newPerson: { __typename: \"Person\", name: \"Ellen Shapiro\" } },\n        errors: [expectedFakeError],\n      }),\n    });\n\n    expect(client.cache.extract()).toMatchSnapshot();\n  });\n\n  it(\"returns correct results for network errors with each errorPolicy option\", async () => {\n    const networkError = new Error(\"Oops\");\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            setTimeout(() => observer.error(networkError));\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n      })\n    ).rejects.toThrow(networkError);\n\n    await expect(\n      client.mutate({\n        mutation,\n        errorPolicy: \"ignore\",\n        variables: {\n          newName: \"Jenn Creighton\",\n        },\n      })\n    ).resolves.toStrictEqualTyped({ data: undefined });\n\n    await expect(\n      client.mutate({\n        mutation,\n        errorPolicy: \"all\",\n        variables: {\n          newName: \"Ellen Shapiro\",\n        },\n      })\n    ).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: networkError,\n    });\n  });\n\n  it(\"returns extensions provided by server\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  newPerson: {\n                    __typename: \"Person\",\n                    name: operation.variables.newName,\n                  },\n                },\n                extensions: {\n                  requestLimit: 10,\n                },\n              });\n            }, 10);\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n      })\n    ).resolves.toStrictEqualTyped({\n      data: { newPerson: { __typename: \"Person\", name: \"Hugh Willson\" } },\n      extensions: {\n        requestLimit: 10,\n      },\n    });\n  });\n\n  it(\"returns extensions with GraphQL errors with errorPolicy: 'all'\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  newPerson: null,\n                },\n                errors: [{ message: \"Oops\" }],\n                extensions: {\n                  requestLimit: 10,\n                },\n              });\n            }, 10);\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n        errorPolicy: \"all\",\n      })\n    ).resolves.toStrictEqualTyped({\n      data: { newPerson: null },\n      error: new CombinedGraphQLErrors({\n        data: { newPerson: null },\n        errors: [{ message: \"Oops\" }],\n        extensions: { requestLimit: 10 },\n      }),\n      extensions: {\n        requestLimit: 10,\n      },\n    });\n  });\n\n  it(\"returns extensions with GraphQL errors with errorPolicy: 'ignore'\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  newPerson: null,\n                },\n                errors: [{ message: \"Oops\" }],\n                extensions: {\n                  requestLimit: 10,\n                },\n              });\n            }, 10);\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n        errorPolicy: \"ignore\",\n      })\n    ).resolves.toStrictEqualTyped({\n      data: { newPerson: null },\n      extensions: {\n        requestLimit: 10,\n      },\n    });\n  });\n\n  it(\"provides extensions in merge functions\", async () => {\n    const merge = jest.fn((_, incoming) => incoming);\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Person: {\n          fields: {\n            name: {\n              merge,\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  newPerson: {\n                    __typename: \"Person\",\n                    name: operation.variables.newName,\n                  },\n                },\n                extensions: {\n                  requestLimit: 10,\n                },\n              });\n              observer.complete();\n            }, 10);\n          })\n      ),\n    });\n\n    const mutation = gql`\n      mutation AddNewPerson($newName: String!) {\n        newPerson(name: $newName) {\n          name\n        }\n      }\n    `;\n\n    await expect(\n      client.mutate({\n        mutation,\n        variables: {\n          newName: \"Hugh Willson\",\n        },\n        errorPolicy: \"ignore\",\n      })\n    ).resolves.toStrictEqualTyped({\n      data: { newPerson: { __typename: \"Person\", name: \"Hugh Willson\" } },\n      extensions: {\n        requestLimit: 10,\n      },\n    });\n\n    expect(merge).toHaveBeenCalledTimes(1);\n    expect(merge).toHaveBeenCalledWith(\n      undefined,\n      \"Hugh Willson\",\n      expect.objectContaining({ extensions: { requestLimit: 10 } })\n    );\n  });\n\n  it(\"should warn when the result fields don't match the query fields\", async () => {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    let handle: any;\n    let subscriptionHandle: Subscription;\n\n    const queryTodos = gql`\n      query todos {\n        todos {\n          id\n          name\n          description\n          __typename\n        }\n      }\n    `;\n\n    const queryTodosResult = {\n      data: {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n            description: \"Description 1\",\n            __typename: \"todos\",\n          },\n        ],\n      },\n    };\n\n    const mutationTodo = gql`\n      mutation createTodo {\n        createTodo {\n          id\n          name\n          # missing field: description\n          __typename\n        }\n      }\n    `;\n\n    const mutationTodoResult = {\n      data: {\n        createTodo: {\n          id: \"2\",\n          name: \"Todo 2\",\n          __typename: \"createTodo\",\n        },\n      },\n    };\n\n    const { client, obsQuery } = setupObsQuery(\n      {\n        request: { query: queryTodos },\n        result: queryTodosResult,\n        delay: 0,\n      },\n      {\n        request: { query: mutationTodo },\n        result: mutationTodoResult,\n        delay: 0,\n      }\n    );\n\n    await firstValueFrom(from(obsQuery));\n\n    // we have to actually subscribe to the query to be able to update it\n    await new Promise((resolve) => {\n      handle = client.watchQuery({ query: queryTodos });\n      subscriptionHandle = handle.subscribe({\n        next(res: any) {\n          resolve(res);\n        },\n      });\n    });\n\n    try {\n      // Silence mock link warning\n      using _ = spyOnConsole(\"warn\");\n      await expect(\n        client.mutate({\n          mutation: mutationTodo,\n          updateQueries: {\n            todos: (prev, { mutationResult }) => {\n              const newTodo = (mutationResult as any).data.createTodo;\n              const newResults = {\n                todos: [...(prev as any).todos, newTodo],\n              };\n              return newResults;\n            },\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationTodoResult.data });\n    } finally {\n      subscriptionHandle!.unsubscribe();\n    }\n  });\n\n  describe(\"InMemoryCache type/field policies\", () => {\n    const startTime = Date.now();\n    const link = new ApolloLink(\n      (operation) =>\n        new Observable((observer) => {\n          observer.next({\n            data: {\n              __typename: \"Mutation\",\n              doSomething: {\n                __typename: \"MutationPayload\",\n                time: startTime,\n              },\n            },\n          });\n          observer.complete();\n        })\n    );\n\n    const mutation = gql`\n      mutation DoSomething {\n        doSomething {\n          time\n        }\n      }\n    `;\n\n    it(\"mutation update function receives result from cache\", async () => {\n      let timeReadCount = 0;\n      let timeMergeCount = 0;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            MutationPayload: {\n              fields: {\n                time: {\n                  read(ms: number = Date.now()) {\n                    ++timeReadCount;\n                    return new Date(ms);\n                  },\n                  merge(existing, incoming: number) {\n                    ++timeMergeCount;\n                    expect(existing).toBeUndefined();\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      const result = await client.mutate<any>({\n        mutation,\n        update(\n          cache,\n          {\n            data: {\n              doSomething: { __typename, time },\n            },\n          }\n        ) {\n          expect(__typename).toBe(\"MutationPayload\");\n          expect(time).toBeInstanceOf(Date);\n          expect(time.getTime()).toBe(startTime);\n          expect(timeReadCount).toBe(1);\n          expect(timeMergeCount).toBe(1);\n          expect(cache.extract()).toEqual({\n            ROOT_MUTATION: {\n              __typename: \"Mutation\",\n              doSomething: {\n                __typename: \"MutationPayload\",\n                time: startTime,\n              },\n            },\n          });\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: new Date(startTime),\n          },\n        },\n      });\n\n      expect(timeReadCount).toBe(1);\n      expect(timeMergeCount).toBe(1);\n\n      // The contents of the ROOT_MUTATION object exist only briefly, for the\n      // duration of the mutation update, and are removed after the mutation\n      // write is finished.\n      expect(client.cache.extract()).toEqual({\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n        },\n      });\n    });\n\n    it(\"mutations can preserve ROOT_MUTATION cache data with keepRootFields: true\", async () => {\n      let timeReadCount = 0;\n      let timeMergeCount = 0;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            MutationPayload: {\n              fields: {\n                time: {\n                  read(ms: number = Date.now()) {\n                    ++timeReadCount;\n                    return new Date(ms);\n                  },\n                  merge(existing, incoming: number) {\n                    ++timeMergeCount;\n                    expect(existing).toBeUndefined();\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      const result = await client.mutate<any>({\n        mutation,\n        keepRootFields: true,\n        update(\n          cache,\n          {\n            data: {\n              doSomething: { __typename, time },\n            },\n          }\n        ) {\n          expect(__typename).toBe(\"MutationPayload\");\n          expect(time).toBeInstanceOf(Date);\n          expect(time.getTime()).toBe(startTime);\n          expect(timeReadCount).toBe(1);\n          expect(timeMergeCount).toBe(1);\n          expect(cache.extract()).toEqual({\n            ROOT_MUTATION: {\n              __typename: \"Mutation\",\n              doSomething: {\n                __typename: \"MutationPayload\",\n                time: startTime,\n              },\n            },\n          });\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: new Date(startTime),\n          },\n        },\n      });\n\n      expect(timeReadCount).toBe(1);\n      expect(timeMergeCount).toBe(1);\n\n      expect(client.cache.extract()).toEqual({\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: startTime,\n          },\n        },\n      });\n    });\n\n    it('mutation update function runs even when fetchPolicy is \"no-cache\"', async () => {\n      let timeReadCount = 0;\n      let timeMergeCount = 0;\n      let mutationUpdateCount = 0;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            MutationPayload: {\n              fields: {\n                time: {\n                  read(ms: number = Date.now()) {\n                    ++timeReadCount;\n                    return new Date(ms);\n                  },\n                  merge(existing, incoming: number) {\n                    ++timeMergeCount;\n                    expect(existing).toBeUndefined();\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      const result = await client.mutate<any>({\n        mutation,\n        fetchPolicy: \"no-cache\",\n        update(\n          cache,\n          {\n            data: {\n              doSomething: { __typename, time },\n            },\n          }\n        ) {\n          expect(++mutationUpdateCount).toBe(1);\n          expect(__typename).toBe(\"MutationPayload\");\n          expect(time).not.toBeInstanceOf(Date);\n          expect(time).toBe(startTime);\n          expect(timeReadCount).toBe(0);\n          expect(timeMergeCount).toBe(0);\n          expect(cache.extract()).toEqual({});\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          __typename: \"Mutation\",\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: startTime,\n          },\n        },\n      });\n\n      expect(timeReadCount).toBe(0);\n      expect(timeMergeCount).toBe(0);\n      expect(mutationUpdateCount).toBe(1);\n      expect(client.cache.extract()).toEqual({});\n    });\n  });\n\n  describe(\"updateQueries\", () => {\n    const mutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: \"99\",\n          __typename: \"Todo\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    it(\"analogous of ARRAY_INSERT\", async () => {\n      const { client, obsQuery } = setupObsQuery({\n        request: { query: mutation },\n        result: mutationResult,\n      });\n\n      // firstValueFrom immediately unsubscribed from the observable, which\n      // stops the observable from watching the query.\n      // As `updateQueries` only updates actively watched queries,\n      // we need to subscribe in a way that keeps the observable alive.\n      using stream = new ObservableStream(obsQuery);\n      await stream.takeNext();\n      await firstValueFrom(from(client.watchQuery({ query })));\n\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              expect(mResult.data.createTodo.id).toBe(\"99\");\n              expect(mResult.data.createTodo.text).toBe(\n                \"This one was created with a mutation.\"\n              );\n              const state = cloneDeep(prev) as any;\n              state.todoList.todos.unshift(mResult.data.createTodo);\n              return state;\n            },\n          },\n        })\n      ).resolves.toStrictEqualTyped({\n        data: mutationResult.data,\n      });\n\n      const newResult = await client.query<any>({ query });\n\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"does not fail if optional query variables are not supplied\", async () => {\n      const mutationWithVars = gql`\n        mutation createTodo($requiredVar: String!, $optionalVar: String) {\n          createTodo(requiredVar: $requiredVar, optionalVar: $optionalVar) {\n            id\n            text\n            completed\n            __typename\n          }\n          __typename\n        }\n      `;\n\n      // the test will pass if optionalVar is uncommented\n      const variables = {\n        requiredVar: \"x\",\n        // optionalVar: 'y',\n      };\n      const { client, obsQuery } = setupObsQuery({\n        request: {\n          query: mutationWithVars,\n          variables,\n        },\n        result: mutationResult,\n      });\n\n      await firstValueFrom(from(obsQuery));\n\n      // we have to actually subscribe to the query to be able to update it\n\n      const handle = client.watchQuery({\n        query,\n        variables,\n      });\n      const stream = new ObservableStream(handle);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation: mutationWithVars,\n          variables,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              expect(mResult.data.createTodo.id).toBe(\"99\");\n              expect(mResult.data.createTodo.text).toBe(\n                \"This one was created with a mutation.\"\n              );\n              const state = cloneDeep(prev) as any;\n              state.todoList.todos.unshift(mResult.data.createTodo);\n              return state;\n            },\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationResult.data });\n\n      const newResult = await client.query<any>({ query });\n\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"does not fail if the query did not complete correctly\", async () => {\n      const { client, obsQuery } = setupObsQuery({\n        request: { query: mutation },\n        result: mutationResult,\n      });\n      const subs = obsQuery.subscribe({\n        next: () => null,\n      });\n      // Cancel the query right away!\n      subs.unsubscribe();\n\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              expect(mResult.data.createTodo.id).toBe(\"99\");\n              expect(mResult.data.createTodo.text).toBe(\n                \"This one was created with a mutation.\"\n              );\n\n              const state = cloneDeep(prev) as any;\n              state.todoList.todos.unshift(mResult.data.createTodo);\n              return state;\n            },\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationResult.data });\n    });\n\n    it(\"does not fail if the query did not finish loading\", async () => {\n      const { client, obsQuery } = setupDelayObsQuery(15, {\n        request: { query: mutation },\n        result: mutationResult,\n      });\n      obsQuery.subscribe({\n        next: () => null,\n      });\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              expect(mResult.data.createTodo.id).toBe(\"99\");\n              expect(mResult.data.createTodo.text).toBe(\n                \"This one was created with a mutation.\"\n              );\n\n              const state = cloneDeep(prev) as any;\n              state.todoList.todos.unshift(mResult.data.createTodo);\n              return state;\n            },\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationResult.data });\n    });\n\n    it(\"does not make next queries fail if a mutation fails\", async () => {\n      const { client, obsQuery } = setupObsQuery(\n        {\n          request: { query: mutation },\n          result: { errors: [{ message: \"mock error\" }] },\n          maxUsageCount: 2,\n        },\n        {\n          request: { query: queryWithTypename },\n          result,\n        }\n      );\n      const stream = new ObservableStream(obsQuery);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              const state = cloneDeep(prev) as any;\n              // It's unfortunate that this function is called at all, but we are removing\n              // the updateQueries API soon so it won't matter.\n              state.todoList.todos.unshift(\n                mResult.data && mResult.data.createTodo\n              );\n              return state;\n            },\n          },\n        })\n      ).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: \"mock error\" }] })\n      );\n\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: (prev, options) => {\n              const mResult = options.mutationResult as any;\n              const state = cloneDeep(prev) as any;\n              state.todoList.todos.unshift(mResult.data.createTodo);\n              return state;\n            },\n          },\n        })\n      ).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: \"mock error\" }] })\n      );\n      await obsQuery.refetch();\n    });\n\n    it(\"error handling in reducer functions\", async () => {\n      const { client, obsQuery } = setupObsQuery({\n        request: { query: mutation },\n        result: mutationResult,\n      });\n\n      await firstValueFrom(from(obsQuery));\n\n      // we have to actually subscribe to the query to be able to update it\n\n      const handle = client.watchQuery({ query });\n      const stream = new ObservableStream(handle);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation,\n          updateQueries: {\n            todoList: () => {\n              throw new Error(`Hello... It's me.`);\n            },\n          },\n        })\n      ).rejects.toThrow(Error(`Hello... It's me.`));\n    });\n  });\n\n  it(\"does not fail if one of the previous queries did not complete correctly\", async () => {\n    const variableQuery = gql`\n      query Echo($message: String) {\n        echo(message: $message)\n      }\n    `;\n\n    const variables1 = {\n      message: \"a\",\n    };\n\n    const result1 = {\n      data: {\n        echo: \"a\",\n      },\n    };\n\n    const variables2 = {\n      message: \"b\",\n    };\n\n    const result2 = {\n      data: {\n        echo: \"b\",\n      },\n    };\n\n    const resetMutation = gql`\n      mutation Reset {\n        reset {\n          echo\n        }\n      }\n    `;\n\n    const resetMutationResult = {\n      data: {\n        reset: {\n          echo: \"0\",\n        },\n      },\n    };\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: variableQuery, variables: variables1 },\n          result: result1,\n          // Needed since unsubscribing from the first query will cancel the\n          // request and remove it from inFlightObservables for query\n          // deduplication.\n          maxUsageCount: 2,\n        },\n        {\n          request: { query: variableQuery, variables: variables2 },\n          result: result2,\n        },\n        {\n          request: { query: resetMutation },\n          result: resetMutationResult,\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const watchedQuery = client.watchQuery({\n      query: variableQuery,\n      variables: variables1,\n    });\n\n    const firstSubs = watchedQuery.subscribe({\n      next: () => null,\n      error: (error) => {\n        throw error;\n      },\n    });\n\n    // Cancel the query right away!\n    firstSubs.unsubscribe();\n\n    const stream = new ObservableStream(watchedQuery);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await watchedQuery.refetch(variables2);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { echo: \"b\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(\n      client.mutate({\n        mutation: resetMutation,\n        updateQueries: {\n          Echo: () => {\n            return { echo: \"0\" };\n          },\n        },\n      })\n    ).resolves.toStrictEqualTyped({ data: resetMutationResult.data });\n\n    await expect(stream).toEmitTypedValue({\n      data: { echo: \"0\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"allows mutations with optional arguments\", async () => {\n    let count = 0;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.from([\n        new ApolloLink(\n          ({ variables }) =>\n            new Observable((observer) => {\n              switch (count++) {\n                case 0:\n                  expect(variables).toEqual({ a: 1, b: 2 });\n                  observer.next({ data: { result: \"hello\" } });\n                  observer.complete();\n                  return;\n                case 1:\n                  expect(variables).toEqual({ a: 1, c: 3 });\n                  observer.next({ data: { result: \"world\" } });\n                  observer.complete();\n                  return;\n                case 2:\n                  expect(variables).toEqual({\n                    a: undefined,\n                    b: 2,\n                    c: 3,\n                  });\n                  observer.next({ data: { result: \"goodbye\" } });\n                  observer.complete();\n                  return;\n                case 3:\n                  expect(variables).toEqual({});\n                  observer.next({ data: { result: \"moon\" } });\n                  observer.complete();\n                  return;\n                default:\n                  observer.error(new Error(\"Too many network calls.\"));\n                  return;\n              }\n            })\n        ),\n      ]),\n    });\n\n    const mutation = gql`\n      mutation ($a: Int!, $b: Int, $c: Int) {\n        result(a: $a, b: $b, c: $c)\n      }\n    `;\n\n    const results = await Promise.all([\n      client.mutate({\n        mutation,\n        variables: { a: 1, b: 2 },\n      }),\n      client.mutate({\n        mutation,\n        variables: { a: 1, c: 3 },\n      }),\n      client.mutate({\n        mutation,\n        variables: { a: undefined, b: 2, c: 3 },\n      }),\n      client.mutate({\n        mutation,\n      }),\n    ]);\n    expect(client.cache.extract()).toEqual({\n      ROOT_MUTATION: {\n        __typename: \"Mutation\",\n      },\n    });\n    expect(results).toStrictEqualTyped([\n      { data: { result: \"hello\" } },\n      { data: { result: \"world\" } },\n      { data: { result: \"goodbye\" } },\n      { data: { result: \"moon\" } },\n    ]);\n  });\n\n  it(\"allows mutations with default values\", async () => {\n    let count = 0;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.from([\n        new ApolloLink(\n          ({ variables }) =>\n            new Observable((observer) => {\n              switch (count++) {\n                case 0:\n                  expect(variables).toEqual({\n                    a: 1,\n                    b: \"water\",\n                  });\n                  observer.next({ data: { result: \"hello\" } });\n                  observer.complete();\n                  return;\n                case 1:\n                  expect(variables).toEqual({\n                    a: 2,\n                    b: \"cheese\",\n                    c: 3,\n                  });\n                  observer.next({ data: { result: \"world\" } });\n                  observer.complete();\n                  return;\n                case 2:\n                  expect(variables).toEqual({\n                    a: 1,\n                    b: \"cheese\",\n                    c: 3,\n                  });\n                  observer.next({ data: { result: \"goodbye\" } });\n                  observer.complete();\n                  return;\n                default:\n                  observer.error(new Error(\"Too many network calls.\"));\n                  return;\n              }\n            })\n        ),\n      ]),\n    });\n\n    const mutation = gql`\n      mutation ($a: Int = 1, $b: String = \"cheese\", $c: Int) {\n        result(a: $a, b: $b, c: $c)\n      }\n    `;\n\n    const results = await Promise.all([\n      client.mutate({\n        mutation,\n        variables: { a: 1, b: \"water\" },\n      }),\n      client.mutate({\n        mutation,\n        variables: { a: 2, c: 3 },\n      }),\n      client.mutate({\n        mutation,\n        variables: { c: 3 },\n      }),\n    ]);\n    expect(client.cache.extract()).toEqual({\n      ROOT_MUTATION: {\n        __typename: \"Mutation\",\n      },\n    });\n    expect(results).toStrictEqualTyped([\n      { data: { result: \"hello\" } },\n      { data: { result: \"world\" } },\n      { data: { result: \"goodbye\" } },\n    ]);\n  });\n\n  it(\"will pass null to the network interface when provided\", async () => {\n    let count = 0;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.from([\n        new ApolloLink(\n          ({ variables }) =>\n            new Observable((observer) => {\n              switch (count++) {\n                case 0:\n                  expect(variables).toEqual({\n                    a: 1,\n                    b: 2,\n                    c: null,\n                  });\n                  observer.next({ data: { result: \"hello\" } });\n                  observer.complete();\n                  return;\n                case 1:\n                  expect(variables).toEqual({\n                    a: 1,\n                    b: null,\n                    c: 3,\n                  });\n                  observer.next({ data: { result: \"world\" } });\n                  observer.complete();\n                  return;\n                case 2:\n                  expect(variables).toEqual({\n                    a: null,\n                    b: null,\n                    c: null,\n                  });\n                  observer.next({ data: { result: \"moon\" } });\n                  observer.complete();\n                  return;\n                default:\n                  observer.error(new Error(\"Too many network calls.\"));\n                  return;\n              }\n            })\n        ),\n      ]),\n    });\n\n    const mutation = gql`\n      mutation ($a: Int!, $b: Int, $c: Int) {\n        result(a: $a, b: $b, c: $c)\n      }\n    `;\n\n    const results = await Promise.all([\n      client.mutate({\n        mutation,\n        variables: { a: 1, b: 2, c: null },\n      }),\n      client.mutate({\n        mutation,\n        variables: { a: 1, b: null, c: 3 },\n      }),\n      client.mutate({\n        mutation,\n        variables: { a: null, b: null, c: null },\n      }),\n    ]);\n    expect(client.cache.extract()).toEqual({\n      ROOT_MUTATION: {\n        __typename: \"Mutation\",\n      },\n    });\n    expect(results).toStrictEqualTyped([\n      { data: { result: \"hello\" } },\n      { data: { result: \"world\" } },\n      { data: { result: \"moon\" } },\n    ]);\n  });\n\n  describe(\"store transaction updater\", () => {\n    const mutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: \"99\",\n          __typename: \"Todo\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    it(\"analogous of ARRAY_INSERT\", async () => {\n      const { client, obsQuery } = setupObsQuery({\n        request: { query: mutation },\n        result: mutationResult,\n      });\n\n      await firstValueFrom(from(obsQuery));\n\n      // we have to actually subscribe to the query to be able to update it\n\n      const handle = client.watchQuery({ query });\n      const stream = new ObservableStream(handle);\n      await stream.takeNext();\n      await expect(\n        client.mutate({\n          mutation,\n          update: (proxy, mResult: any) => {\n            expect(mResult.data.createTodo.id).toBe(\"99\");\n            expect(mResult.data.createTodo.text).toBe(\n              \"This one was created with a mutation.\"\n            );\n\n            const id = \"TodoList5\";\n            const fragment = gql`\n              fragment todoList on TodoList {\n                todos {\n                  id\n                  text\n                  completed\n                  __typename\n                }\n              }\n            `;\n\n            const data: any = proxy.readFragment({ id, fragment });\n\n            proxy.writeFragment({\n              data: {\n                ...data,\n                todos: [mResult.data.createTodo, ...data.todos],\n              },\n              id,\n              fragment,\n            });\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationResult.data });\n\n      const newResult = await client.query<any>({ query });\n\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"does not fail if optional query variables are not supplied\", async () => {\n      const mutationWithVars = gql`\n        mutation createTodo($requiredVar: String!, $optionalVar: String) {\n          createTodo(requiredVar: $requiredVar, optionalVar: $optionalVar) {\n            id\n            text\n            completed\n            __typename\n          }\n          __typename\n        }\n      `;\n\n      // the test will pass if optionalVar is uncommented\n      const variables = {\n        requiredVar: \"x\",\n        // optionalVar: 'y',\n      };\n\n      const { client, obsQuery } = setupObsQuery({\n        request: {\n          query: mutationWithVars,\n          variables,\n        },\n        result: mutationResult,\n      });\n\n      await firstValueFrom(from(obsQuery));\n\n      // we have to actually subscribe to the query to be able to update it\n\n      const handle = client.watchQuery({\n        query,\n        variables,\n      });\n      const stream = new ObservableStream(handle);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation: mutationWithVars,\n          variables,\n          update: (proxy, mResult: any) => {\n            expect(mResult.data.createTodo.id).toBe(\"99\");\n            expect(mResult.data.createTodo.text).toBe(\n              \"This one was created with a mutation.\"\n            );\n\n            const id = \"TodoList5\";\n            const fragment = gql`\n              fragment todoList on TodoList {\n                todos {\n                  id\n                  text\n                  completed\n                  __typename\n                }\n              }\n            `;\n\n            const data: any = proxy.readFragment({ id, fragment });\n\n            proxy.writeFragment({\n              data: {\n                ...data,\n                todos: [mResult.data.createTodo, ...data.todos],\n              },\n              id,\n              fragment,\n            });\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: mutationResult.data });\n\n      const newResult = await client.query<any>({ query });\n\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"does not make next queries fail if a mutation fails\", async () => {\n      const { client, obsQuery } = setupObsQuery(\n        {\n          request: { query: mutation },\n          result: { errors: [{ message: \"mock error\" }] },\n          maxUsageCount: 2,\n        },\n        {\n          request: { query: queryWithTypename },\n          result,\n        }\n      );\n\n      const stream = new ObservableStream(obsQuery);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation,\n          update: (proxy, mResult: any) => {\n            expect(mResult.data.createTodo.id).toBe(\"99\");\n            expect(mResult.data.createTodo.text).toBe(\n              \"This one was created with a mutation.\"\n            );\n\n            const id = \"TodoList5\";\n            const fragment = gql`\n              fragment todoList on TodoList {\n                todos {\n                  id\n                  text\n                  completed\n                  __typename\n                }\n              }\n            `;\n\n            const data: any = proxy.readFragment({ id, fragment });\n\n            proxy.writeFragment({\n              data: {\n                ...data,\n                todos: [mResult.data.createTodo, ...data.todos],\n              },\n              id,\n              fragment,\n            });\n          },\n        })\n      ).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: \"mock error\" }] })\n      );\n\n      await expect(\n        client.mutate({\n          mutation,\n          update: (proxy, mResult: any) => {\n            expect(mResult.data.createTodo.id).toBe(\"99\");\n            expect(mResult.data.createTodo.text).toBe(\n              \"This one was created with a mutation.\"\n            );\n\n            const id = \"TodoList5\";\n            const fragment = gql`\n              fragment todoList on TodoList {\n                todos {\n                  id\n                  text\n                  completed\n                  __typename\n                }\n              }\n            `;\n\n            const data: any = proxy.readFragment({ id, fragment });\n\n            proxy.writeFragment({\n              data: {\n                ...data,\n                todos: [mResult.data.createTodo, ...data.todos],\n              },\n              id,\n              fragment,\n            });\n          },\n        })\n      ).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: \"mock error\" }] })\n      );\n\n      await obsQuery.refetch();\n    });\n\n    it(\"error handling in reducer functions\", async () => {\n      const { client, obsQuery } = setupObsQuery({\n        request: { query: mutation },\n        result: mutationResult,\n      });\n\n      await firstValueFrom(from(obsQuery));\n      // we have to actually subscribe to the query to be able to update it\n\n      const handle = client.watchQuery({ query });\n      const stream = new ObservableStream(handle);\n      await stream.takeNext();\n\n      await expect(\n        client.mutate({\n          mutation,\n          update: () => {\n            throw new Error(`Hello... It's me.`);\n          },\n        })\n      ).rejects.toThrow(Error(`Hello... It's me.`));\n    });\n\n    it(\"mutate<MyType>() data should never be `undefined` in case of success\", async () => {\n      const mutation = gql`\n        mutation Foo {\n          foo {\n            bar\n          }\n        }\n      `;\n\n      const result1 = {\n        data: {\n          foo: {\n            bar: \"a\",\n          },\n        },\n      };\n\n      const client = new ApolloClient({\n        link: new MockLink([\n          {\n            request: { query: mutation } as any,\n            result: result1,\n          },\n        ]),\n        cache: new InMemoryCache(),\n      });\n\n      const result = await client.mutate<{ foo: { bar: string } }>({\n        mutation: mutation,\n      });\n\n      expect(result).toStrictEqualTyped({ data: result1.data });\n    });\n\n    it(\"data might be undefined in case of failure with errorPolicy = ignore\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          () =>\n            new Observable<ApolloLink.Result<{ foo: string }>>((observer) => {\n              observer.next({\n                errors: [new GraphQLError(\"Oops\")],\n              });\n              observer.complete();\n            })\n        ),\n      });\n\n      const ignoreErrorsResult = await client.mutate({\n        mutation: gql`\n          mutation Foo {\n            foo\n          }\n        `,\n        fetchPolicy: \"no-cache\",\n        errorPolicy: \"ignore\",\n      });\n\n      expect(ignoreErrorsResult).toStrictEqualTyped({\n        data: undefined,\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/__tests__/optimistic.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport { assign, cloneDeep } from \"lodash\";\nimport { firstValueFrom, from, lastValueFrom, Observable } from \"rxjs\";\nimport { map, take, toArray } from \"rxjs/operators\";\n\nimport type {\n  ApolloCache,\n  MutationQueryReducersMap,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, ApolloLink } from \"@apollo/client\";\nimport type { Cache, NormalizedCacheObject } from \"@apollo/client/cache\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\nimport { addTypenameToDocument } from \"@apollo/client/utilities\";\nimport { makeReference } from \"@apollo/client/utilities/internal\";\n\nimport type { QueryManager } from \"../core/QueryManager.js\";\n\nconst mutationByAccessIndex = (queryManager: QueryManager) => {\n  return new Proxy(queryManager.mutationStore!, {\n    get: (mutationStore, idx) => {\n      return mutationStore[Object.keys(mutationStore)[(idx as any) - 1]];\n    },\n  });\n};\n\ndescribe(\"optimistic mutation results\", () => {\n  const query = gql`\n    query todoList {\n      __typename\n      todoList(id: 5) {\n        __typename\n        id\n        todos {\n          id\n          __typename\n          text\n          completed\n        }\n        filteredTodos: todos(completed: true) {\n          id\n          __typename\n          text\n          completed\n        }\n      }\n      noIdList: todoList(id: 6) {\n        __typename\n        id\n        todos {\n          __typename\n          text\n          completed\n        }\n      }\n    }\n  `;\n\n  const result: any = {\n    data: {\n      __typename: \"Query\",\n      todoList: {\n        __typename: \"TodoList\",\n        id: \"5\",\n        todos: [\n          {\n            __typename: \"Todo\",\n            id: \"3\",\n            text: \"Hello world\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            id: \"6\",\n            text: \"Second task\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            id: \"12\",\n            text: \"Do other stuff\",\n            completed: false,\n          },\n        ],\n        filteredTodos: [],\n      },\n      noIdList: {\n        __typename: \"TodoList\",\n        id: \"7\",\n        todos: [\n          {\n            __typename: \"Todo\",\n            text: \"Hello world\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            text: \"Second task\",\n            completed: false,\n          },\n          {\n            __typename: \"Todo\",\n            text: \"Do other stuff\",\n            completed: false,\n          },\n        ],\n      },\n    },\n  };\n\n  async function setup(...mockedResponses: MockLink.MockedResponse[]) {\n    const link = new MockLink([\n      {\n        request: { query },\n        result,\n      },\n      ...mockedResponses,\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          TodoList: {\n            fields: {\n              todos: {\n                // Deliberately silence \"Cache data may be lost...\"\n                // warnings by favoring the incoming data, rather than\n                // (say) concatenating the arrays together.\n                merge: false,\n              },\n            },\n          },\n        },\n        dataIdFromObject: (obj: any) => {\n          if (obj.id && obj.__typename) {\n            return obj.__typename + obj.id;\n          }\n          return null;\n        },\n      }),\n      // Enable client.queryManager.mutationStore tracking.\n      devtools: { enabled: true },\n    });\n\n    const obsHandle = client.watchQuery({\n      query,\n      notifyOnNetworkStatusChange: false,\n    });\n    // We can't use firstValueFrom here because we need to unsubscribe in the\n    // setTimeout\n    await new Promise((resolve) => {\n      const subscription = obsHandle.subscribe((value) => {\n        resolve(value);\n        setTimeout(() => subscription.unsubscribe());\n      });\n    });\n\n    return client;\n  }\n\n  describe(\"error handling\", () => {\n    const mutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"Todo\",\n          id: \"99\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    const mutationResult2 = {\n      data: assign({}, mutationResult.data, {\n        createTodo: assign({}, mutationResult.data.createTodo, {\n          id: \"66\",\n          text: \"Second mutation.\",\n        }),\n      }),\n    };\n\n    const optimisticResponse = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"99\",\n        text: \"Optimistically generated\",\n        completed: true,\n      },\n    };\n\n    const optimisticResponse2 = assign({}, optimisticResponse, {\n      createTodo: assign({}, optimisticResponse.createTodo, {\n        id: \"66\",\n        text: \"Optimistically generated 2\",\n      }),\n    });\n\n    describe(\"with `updateQueries`\", () => {\n      const updateQueries = {\n        todoList: (prev: any, options: any) => {\n          const state = cloneDeep(prev);\n          state.todoList.todos.unshift(options.mutationResult.data.createTodo);\n          return state;\n        },\n      };\n\n      it(\"handles a single error for a single mutation\", async () => {\n        expect.assertions(5);\n        const client = await setup({\n          request: { query: mutation },\n          error: new Error(\"forbidden (test error)\"),\n        });\n        const promise = client.mutate({\n          mutation,\n          optimisticResponse,\n          updateQueries,\n        });\n\n        {\n          const dataInStore = client.cache.extract(\n            true\n          ) as NormalizedCacheObject;\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n          expect((dataInStore[\"Todo99\"] as any).text).toBe(\n            \"Optimistically generated\"\n          );\n        }\n\n        await expect(promise).rejects.toThrow(\n          new Error(\"forbidden (test error)\")\n        );\n\n        {\n          const dataInStore = client.cache.extract(\n            true\n          ) as NormalizedCacheObject;\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(3);\n          expect(dataInStore).not.toHaveProperty(\"Todo99\");\n        }\n      });\n\n      it(\"handles errors produced by one mutation in a series\", async () => {\n        expect.assertions(11);\n        const client = await setup(\n          {\n            request: { query: mutation },\n            error: new Error(\"forbidden (test error)\"),\n          },\n          {\n            request: { query: mutation },\n            result: mutationResult2,\n          }\n        );\n\n        const stream = new ObservableStream(client.watchQuery({ query }));\n\n        await expect(stream).toEmitNext();\n\n        const promise = client\n          .mutate({\n            mutation,\n            optimisticResponse,\n            updateQueries,\n          })\n          .catch((err: any) => {\n            // it is ok to fail here\n            expect(err).toBeInstanceOf(Error);\n            expect(err.message).toBe(\"forbidden (test error)\");\n            return null;\n          });\n\n        const promise2 = client.mutate({\n          mutation,\n          optimisticResponse: optimisticResponse2,\n          updateQueries,\n        });\n\n        const dataInStore = (client.cache as InMemoryCache).extract(true);\n        expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n        expect((dataInStore[\"Todo99\"] as any).text).toBe(\n          \"Optimistically generated\"\n        );\n        expect((dataInStore[\"Todo66\"] as any).text).toBe(\n          \"Optimistically generated 2\"\n        );\n\n        await Promise.all([promise, promise2]);\n\n        stream.unsubscribe();\n\n        {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n          expect(dataInStore).not.toHaveProperty(\"Todo99\");\n          expect(dataInStore).toHaveProperty(\"Todo66\");\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo66\")\n          );\n          expect((dataInStore[\"TodoList5\"] as any).todos).not.toContainEqual(\n            makeReference(\"Todo99\")\n          );\n        }\n      });\n\n      it(\"can run 2 mutations concurrently and handles all intermediate states well\", async () => {\n        expect.assertions(35);\n        function checkBothMutationsAreApplied(\n          expectedText1: any,\n          expectedText2: any\n        ) {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n          expect(dataInStore).toHaveProperty(\"Todo99\");\n          expect(dataInStore).toHaveProperty(\"Todo66\");\n          // <any> can be removed once @types/chai adds deepInclude\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo66\")\n          );\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo99\")\n          );\n          expect((dataInStore[\"Todo99\"] as any).text).toBe(expectedText1);\n          expect((dataInStore[\"Todo66\"] as any).text).toBe(expectedText2);\n        }\n        const client = await setup(\n          {\n            request: { query: mutation },\n            result: mutationResult,\n          },\n          {\n            request: { query: mutation },\n            result: mutationResult2,\n            // make sure it always happens later\n            delay: 100,\n          }\n        );\n        const stream = new ObservableStream(client.watchQuery({ query }));\n\n        await expect(stream).toEmitNext();\n\n        const queryManager = client[\"queryManager\"];\n\n        const promise = client\n          .mutate({\n            mutation,\n            optimisticResponse,\n            updateQueries,\n          })\n          .then((res: any) => {\n            checkBothMutationsAreApplied(\n              \"This one was created with a mutation.\",\n              \"Optimistically generated 2\"\n            );\n\n            const latestState = mutationByAccessIndex(queryManager);\n            expect(latestState[1].loading).toBe(false);\n            expect(latestState[2].loading).toBe(true);\n\n            return res;\n          });\n\n        const promise2 = client\n          .mutate({\n            mutation,\n            optimisticResponse: optimisticResponse2,\n            updateQueries,\n          })\n          .then((res: any) => {\n            checkBothMutationsAreApplied(\n              \"This one was created with a mutation.\",\n              \"Second mutation.\"\n            );\n\n            // @ts-ignore\n            const latestState = mutationByAccessIndex(queryManager);\n            expect(latestState[1].loading).toBe(false);\n            expect(latestState[2].loading).toBe(false);\n\n            return res;\n          });\n\n        const mutationsState = mutationByAccessIndex(queryManager);\n        expect(mutationsState[1].loading).toBe(true);\n        expect(mutationsState[2].loading).toBe(true);\n\n        checkBothMutationsAreApplied(\n          \"Optimistically generated\",\n          \"Optimistically generated 2\"\n        );\n\n        await Promise.all([promise, promise2]);\n\n        stream.unsubscribe();\n        checkBothMutationsAreApplied(\n          \"This one was created with a mutation.\",\n          \"Second mutation.\"\n        );\n      });\n    });\n\n    describe(\"with `update`\", () => {\n      const update = (proxy: any, mResult: any) => {\n        const data: any = proxy.readFragment({\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n\n        proxy.writeFragment({\n          data: { ...data, todos: [mResult.data.createTodo, ...data.todos] },\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n      };\n\n      it(\"handles a single error for a single mutation\", async () => {\n        expect.assertions(5);\n\n        const client = await setup({\n          request: { query: mutation },\n          error: new Error(\"forbidden (test error)\"),\n        });\n\n        const promise = client.mutate({\n          mutation,\n          optimisticResponse,\n          update,\n        });\n\n        {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n          expect((dataInStore[\"Todo99\"] as any).text).toBe(\n            \"Optimistically generated\"\n          );\n        }\n\n        await expect(promise).rejects.toThrow(\n          new Error(\"forbidden (test error)\")\n        );\n\n        {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(3);\n          expect(dataInStore).not.toHaveProperty(\"Todo99\");\n        }\n      });\n\n      it(\"handles errors produced by one mutation in a series\", async () => {\n        expect.assertions(11);\n        const client = await setup(\n          {\n            request: { query: mutation },\n            error: new Error(\"forbidden (test error)\"),\n          },\n          {\n            request: { query: mutation },\n            result: mutationResult2,\n          }\n        );\n\n        const stream = new ObservableStream(client.watchQuery({ query }));\n\n        await expect(stream).toEmitNext();\n\n        const promise = client\n          .mutate({\n            mutation,\n            optimisticResponse,\n            update,\n          })\n          .catch((err: any) => {\n            // it is ok to fail here\n            expect(err).toBeInstanceOf(Error);\n            expect(err.message).toBe(\"forbidden (test error)\");\n            return null;\n          });\n\n        const promise2 = client.mutate({\n          mutation,\n          optimisticResponse: optimisticResponse2,\n          update,\n        });\n\n        const dataInStore = (client.cache as InMemoryCache).extract(true);\n        expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n        expect((dataInStore[\"Todo99\"] as any).text).toBe(\n          \"Optimistically generated\"\n        );\n        expect((dataInStore[\"Todo66\"] as any).text).toBe(\n          \"Optimistically generated 2\"\n        );\n\n        await Promise.all([promise, promise2]);\n\n        stream.unsubscribe();\n        {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n          expect(dataInStore).not.toHaveProperty(\"Todo99\");\n          expect(dataInStore).toHaveProperty(\"Todo66\");\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo66\")\n          );\n          expect((dataInStore[\"TodoList5\"] as any).todos).not.toContainEqual(\n            makeReference(\"Todo99\")\n          );\n        }\n      });\n\n      it(\"can run 2 mutations concurrently and handles all intermediate states well\", async () => {\n        expect.assertions(35);\n        function checkBothMutationsAreApplied(\n          expectedText1: any,\n          expectedText2: any\n        ) {\n          const dataInStore = (client.cache as InMemoryCache).extract(true);\n          expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n          expect(dataInStore).toHaveProperty(\"Todo99\");\n          expect(dataInStore).toHaveProperty(\"Todo66\");\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo66\")\n          );\n          expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n            makeReference(\"Todo99\")\n          );\n          expect((dataInStore[\"Todo99\"] as any).text).toBe(expectedText1);\n          expect((dataInStore[\"Todo66\"] as any).text).toBe(expectedText2);\n        }\n\n        const client = await setup(\n          {\n            request: { query: mutation },\n            result: mutationResult,\n          },\n          {\n            request: { query: mutation },\n            result: mutationResult2,\n            // make sure it always happens later\n            delay: 100,\n          }\n        );\n        const stream = new ObservableStream(client.watchQuery({ query }));\n\n        await expect(stream).toEmitNext();\n\n        const promise = client\n          .mutate({\n            mutation,\n            optimisticResponse,\n            update,\n          })\n          .then((res: any) => {\n            checkBothMutationsAreApplied(\n              \"This one was created with a mutation.\",\n              \"Optimistically generated 2\"\n            );\n\n            const latestState = mutationByAccessIndex(client[\"queryManager\"]);\n            expect(latestState[1].loading).toBe(false);\n            expect(latestState[2].loading).toBe(true);\n\n            return res;\n          });\n\n        const promise2 = client\n          .mutate({\n            mutation,\n            optimisticResponse: optimisticResponse2,\n            update,\n          })\n          .then((res: any) => {\n            checkBothMutationsAreApplied(\n              \"This one was created with a mutation.\",\n              \"Second mutation.\"\n            );\n\n            const latestState = mutationByAccessIndex(client[\"queryManager\"]);\n            expect(latestState[1].loading).toBe(false);\n            expect(latestState[2].loading).toBe(false);\n\n            return res;\n          });\n\n        const mutationsState = mutationByAccessIndex(client[\"queryManager\"]);\n        expect(mutationsState[1].loading).toBe(true);\n        expect(mutationsState[2].loading).toBe(true);\n\n        checkBothMutationsAreApplied(\n          \"Optimistically generated\",\n          \"Optimistically generated 2\"\n        );\n\n        await Promise.all([promise, promise2]);\n\n        stream.unsubscribe();\n        checkBothMutationsAreApplied(\n          \"This one was created with a mutation.\",\n          \"Second mutation.\"\n        );\n      });\n    });\n  });\n\n  describe(\"Apollo Client readQuery/readFragment optimistic results\", () => {\n    const todoListMutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          __typename\n          id\n          todos {\n            id\n            text\n            completed\n            __typename\n          }\n        }\n      }\n    `;\n\n    const todoListMutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"TodoList\",\n          id: \"5\",\n          todos: [\n            {\n              __typename: \"Todo\",\n              id: \"99\",\n              text: \"This one was created with a mutation.\",\n              completed: true,\n            },\n          ],\n        },\n      },\n    };\n\n    const todoListOptimisticResponse = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"TodoList\",\n        id: \"5\",\n        todos: [\n          {\n            __typename: \"Todo\",\n            id: \"99\",\n            text: \"Optimistically generated\",\n            completed: true,\n          },\n        ],\n      },\n    };\n\n    const todoListQuery = gql`\n      query todoList {\n        todoList(id: 5) {\n          __typename\n          id\n          todos {\n            id\n            __typename\n            text\n            completed\n          }\n        }\n      }\n    `;\n\n    it(\"client.readQuery should read the optimistic response of a mutation only when update function is called optimistically\", async () => {\n      expect.assertions(2);\n      const client = await setup({\n        request: { query: todoListMutation },\n        result: todoListMutationResult,\n      });\n\n      let updateCount = 0;\n      await client.mutate({\n        mutation: todoListMutation,\n        optimisticResponse: todoListOptimisticResponse,\n        update: (proxy: any, mResult: any) => {\n          ++updateCount;\n          const data = proxy.readQuery({ query: todoListQuery });\n          const readText = data.todoList.todos[0].text;\n          if (updateCount === 1) {\n            const optimisticText =\n              todoListOptimisticResponse.createTodo.todos[0].text;\n            expect(readText).toEqual(optimisticText);\n          } else if (updateCount === 2) {\n            const incomingText = mResult.data.createTodo.todos[0].text;\n            expect(readText).toEqual(incomingText);\n          } else {\n            throw new Error(\"too many update calls\");\n          }\n        },\n      });\n    });\n\n    const todoListFragment = gql`\n      fragment todoList on TodoList {\n        todos {\n          id\n          text\n          completed\n          __typename\n        }\n      }\n    `;\n\n    it(\"should read the optimistic response of a mutation when making an ApolloClient.readFragment() call, if the `optimistic` param is set to true\", async () => {\n      expect.assertions(3);\n      const client = await setup({\n        request: { query: todoListMutation },\n        result: todoListMutationResult,\n      });\n\n      let updateCount = 0;\n      await client.mutate({\n        mutation: todoListMutation,\n        optimisticResponse: todoListOptimisticResponse,\n        update: (proxy: any, mResult: any) => {\n          ++updateCount;\n          const data: any = proxy.readFragment(\n            {\n              id: \"TodoList5\",\n              fragment: todoListFragment,\n            },\n            true\n          );\n          if (updateCount === 1) {\n            expect(data.todos[0].text).toEqual(\n              todoListOptimisticResponse.createTodo.todos[0].text\n            );\n          } else if (updateCount === 2) {\n            expect(data.todos[0].text).toEqual(\n              mResult.data.createTodo.todos[0].text\n            );\n            expect(data.todos[0].text).toEqual(\n              todoListMutationResult.data.createTodo.todos[0].text\n            );\n          } else {\n            throw new Error(\"too many update calls\");\n          }\n        },\n      });\n    });\n\n    it(\"should not read the optimistic response of a mutation when making an ApolloClient.readFragment() call, if the `optimistic` param is set to false\", async () => {\n      expect.assertions(2);\n      const client = await setup({\n        request: { query: todoListMutation },\n        result: todoListMutationResult,\n      });\n\n      await client.mutate({\n        mutation: todoListMutation,\n        optimisticResponse: todoListOptimisticResponse,\n        update: (proxy: any, mResult: any) => {\n          const incomingText = mResult.data.createTodo.todos[0].text;\n          const data: any = proxy.readFragment(\n            {\n              id: \"TodoList5\",\n              fragment: todoListFragment,\n            },\n            false\n          );\n          expect(data.todos[0].text).toEqual(incomingText);\n        },\n      });\n    });\n  });\n\n  describe(\"passing a function to optimisticResponse\", () => {\n    const mutation = gql`\n      mutation createTodo($text: String) {\n        createTodo(text: $text) {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const variables = { text: \"Optimistically generated from variables\" };\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: \"99\",\n          __typename: \"Todo\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    const optimisticResponse = ({ text }: { text: string }) => ({\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"99\",\n        text,\n        completed: true,\n      },\n    });\n\n    it(\"will use a passed variable in optimisticResponse\", async () => {\n      expect.assertions(7);\n      const client = await setup({\n        request: { query: mutation, variables },\n        result: mutationResult,\n      });\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const promise = client.mutate({\n        mutation,\n        variables,\n        optimisticResponse,\n        update: (proxy: any, mResult: any) => {\n          expect(mResult.data.createTodo.id).toBe(\"99\");\n\n          const id = \"TodoList5\";\n          const fragment = gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `;\n\n          const data: any = proxy.readFragment({ id, fragment });\n\n          proxy.writeFragment({\n            data: {\n              ...data,\n              todos: [mResult.data.createTodo, ...data.todos],\n            },\n            id,\n            fragment,\n          });\n        },\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toEqual(4);\n      expect((dataInStore[\"Todo99\"] as any).text).toEqual(\n        \"Optimistically generated from variables\"\n      );\n\n      await promise;\n\n      const newResult: any = await client.query({ query });\n\n      stream.unsubscribe();\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toEqual(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toEqual(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"will not update optimistically if optimisticResponse returns IGNORE sentinel object\", async () => {\n      expect.assertions(6);\n\n      const client = await setup({\n        request: { query: mutation, variables },\n        result: mutationResult,\n      });\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const id = \"TodoList5\";\n      const isTodoList = (\n        list: unknown\n      ): list is { todos: { text: string }[] } =>\n        typeof initialList === \"object\" &&\n        initialList !== null &&\n        \"todos\" in initialList &&\n        Array.isArray(initialList.todos);\n\n      const initialList = (client.cache.extract(true) as NormalizedCacheObject)[\n        id\n      ];\n\n      if (!isTodoList(initialList)) {\n        throw new Error(\"Expected TodoList\");\n      }\n\n      expect(initialList.todos.length).toEqual(3);\n\n      const promise = client.mutate({\n        mutation,\n        variables,\n        optimisticResponse: (vars, { IGNORE }) => {\n          return IGNORE;\n        },\n        update: (proxy: any, mResult: any) => {\n          expect(mResult.data.createTodo.id).toBe(\"99\");\n\n          const fragment = gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `;\n\n          const data: any = proxy.readFragment({ id, fragment });\n\n          proxy.writeFragment({\n            data: {\n              ...data,\n              todos: [mResult.data.createTodo, ...data.todos],\n            },\n            id,\n            fragment,\n          });\n        },\n      });\n\n      const list = (client.cache.extract(true) as NormalizedCacheObject)[id];\n\n      if (!isTodoList(list)) {\n        throw new Error(\"Expected TodoList\");\n      }\n\n      expect(list.todos.length).toEqual(3);\n\n      await promise;\n\n      const result = await client.query<any>({ query });\n\n      stream.unsubscribe();\n\n      const newList = result.data.todoList;\n\n      if (!isTodoList(newList)) {\n        throw new Error(\"Expected TodoList\");\n      }\n\n      // There should be one more todo item than before\n      expect(newList.todos.length).toEqual(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"allows IgnoreModifier as return value when inferring from a TypedDocumentNode mutation\", () => {\n      const mutation: TypedDocumentNode<{ bar: string }> = gql`\n        mutation foo {\n          foo {\n            bar\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      client\n        .mutate({\n          mutation,\n          optimisticResponse: (vars, { IGNORE }) => IGNORE,\n        })\n        .catch(() => {});\n    });\n  });\n\n  describe(\"optimistic updates using `updateQueries`\", () => {\n    const mutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    type IMutationResult = {\n      __typename: string;\n      createTodo: {\n        id: string;\n        __typename: string;\n        text: string;\n        completed: boolean;\n      };\n    };\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: \"99\",\n          __typename: \"Todo\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    const optimisticResponse = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"99\",\n        text: \"Optimistically generated\",\n        completed: true,\n      },\n    };\n\n    const mutationResult2 = {\n      data: assign({}, mutationResult.data, {\n        createTodo: assign({}, mutationResult.data.createTodo, {\n          id: \"66\",\n          text: \"Second mutation.\",\n        }),\n      }),\n    };\n\n    const optimisticResponse2 = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"66\",\n        text: \"Optimistically generated 2\",\n        completed: true,\n      },\n    };\n\n    it(\"will insert a single itemAsync to the beginning\", async () => {\n      expect.assertions(7);\n      const link = new MockLink([\n        {\n          request: { query },\n          result,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            TodoList: {\n              fields: {\n                todos: {\n                  // Deliberately silence \"Cache data may be lost...\"\n                  // warnings by favoring the incoming data, rather than\n                  // (say) concatenating the arrays together.\n                  merge: false,\n                },\n              },\n            },\n          },\n          dataIdFromObject: (obj: any) => {\n            if (obj.id && obj.__typename) {\n              return obj.__typename + obj.id;\n            }\n            return null;\n          },\n        }),\n      });\n\n      const stream = new ObservableStream(\n        client.watchQuery({ query, notifyOnNetworkStatusChange: false })\n      );\n\n      await expect(stream).toEmitNext();\n\n      const promise = client.mutate({\n        mutation,\n        optimisticResponse,\n        updateQueries: {\n          todoList(prev: any, options: any) {\n            const mResult = options.mutationResult as any;\n            expect(mResult.data.createTodo.id).toEqual(\"99\");\n            return {\n              ...prev,\n              todoList: {\n                ...prev.todoList,\n                todos: [mResult.data.createTodo, ...prev.todoList.todos],\n              },\n            };\n          },\n        },\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toEqual(4);\n      expect((dataInStore[\"Todo99\"] as any).text).toEqual(\n        \"Optimistically generated\"\n      );\n\n      await promise;\n\n      const newResult: any = await client.query({ query });\n\n      stream.unsubscribe();\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toEqual(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toEqual(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"two array insert like mutations\", async () => {\n      expect.assertions(10);\n      const client = await setup(\n        {\n          request: { query: mutation },\n          result: mutationResult,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          delay: 50,\n        }\n      );\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const updateQueries = {\n        todoList: (prev, options) => {\n          const mResult = options.mutationResult;\n\n          const state = cloneDeep<any>(prev);\n\n          if (mResult.data) {\n            state.todoList.todos.unshift(mResult.data.createTodo);\n          }\n\n          return state;\n        },\n      } as MutationQueryReducersMap<IMutationResult>;\n      const promise = client\n        .mutate({\n          mutation,\n          optimisticResponse,\n          updateQueries,\n        })\n        .then((res: any) => {\n          const currentDataInStore = (client.cache as InMemoryCache).extract(\n            true\n          );\n          expect((currentDataInStore[\"TodoList5\"] as any).todos.length).toEqual(\n            5\n          );\n          expect((currentDataInStore[\"Todo99\"] as any).text).toEqual(\n            \"This one was created with a mutation.\"\n          );\n          expect((currentDataInStore[\"Todo66\"] as any).text).toEqual(\n            \"Optimistically generated 2\"\n          );\n          return res;\n        });\n\n      const promise2 = client.mutate({\n        mutation,\n        optimisticResponse: optimisticResponse2,\n        updateQueries,\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toEqual(5);\n      expect((dataInStore[\"Todo99\"] as any).text).toEqual(\n        \"Optimistically generated\"\n      );\n      expect((dataInStore[\"Todo66\"] as any).text).toEqual(\n        \"Optimistically generated 2\"\n      );\n\n      await Promise.all([promise, promise2]);\n\n      const newResult: any = await client.query({ query });\n\n      stream.unsubscribe();\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toEqual(5);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toEqual(\"Second mutation.\");\n      expect(newResult.data.todoList.todos[1].text).toEqual(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"two mutations, one fails\", async () => {\n      expect.assertions(11);\n      const client = await setup(\n        {\n          request: { query: mutation },\n          error: new Error(\"forbidden (test error)\"),\n          delay: 20,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          // XXX this test will uncover a flaw in the design of optimistic responses combined with\n          // updateQueries or result reducers if you un-comment the line below. The issue is that\n          // optimistic updates are not commutative but are treated as such. When undoing an\n          // optimistic update, other optimistic updates should be rolled back and re-applied in the\n          // same order as before, otherwise the store can end up in an inconsistent state.\n          // delay: 50,\n        }\n      );\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const updateQueries = {\n        todoList: (prev, options) => {\n          const mResult = options.mutationResult;\n\n          const state = cloneDeep<any>(prev);\n\n          if (mResult.data) {\n            state.todoList.todos.unshift(mResult.data.createTodo);\n          }\n\n          return state;\n        },\n      } as MutationQueryReducersMap<IMutationResult>;\n      const promise = client\n        .mutate({\n          mutation,\n          optimisticResponse,\n          updateQueries,\n        })\n        .catch((err: any) => {\n          // it is ok to fail here\n          expect(err).toBeInstanceOf(Error);\n          expect(err.message).toEqual(\"forbidden (test error)\");\n          return null;\n        });\n\n      const promise2 = client.mutate({\n        mutation,\n        optimisticResponse: optimisticResponse2,\n        updateQueries,\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toEqual(5);\n      expect((dataInStore[\"Todo99\"] as any).text).toEqual(\n        \"Optimistically generated\"\n      );\n      expect((dataInStore[\"Todo66\"] as any).text).toEqual(\n        \"Optimistically generated 2\"\n      );\n\n      await Promise.all([promise, promise2]);\n\n      stream.unsubscribe();\n      {\n        const dataInStore = (client.cache as InMemoryCache).extract(true);\n        expect((dataInStore[\"TodoList5\"] as any).todos.length).toEqual(4);\n        expect(dataInStore).not.toHaveProperty(\"Todo99\");\n        expect(dataInStore).toHaveProperty(\"Todo66\");\n        expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n          makeReference(\"Todo66\")\n        );\n        expect((dataInStore[\"TodoList5\"] as any).todos).not.toContainEqual(\n          makeReference(\"Todo99\")\n        );\n      }\n    });\n\n    it(\"will handle dependent updates\", async () => {\n      const link = new MockLink([\n        {\n          request: { query },\n          result,\n          delay: 0,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult,\n          delay: 10,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          delay: 20,\n        },\n      ]);\n\n      const customOptimisticResponse1 = {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"Todo\",\n          id: \"optimistic-99\",\n          text: \"Optimistically generated\",\n          completed: true,\n        },\n      };\n\n      const customOptimisticResponse2 = {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"Todo\",\n          id: \"optimistic-66\",\n          text: \"Optimistically generated 2\",\n          completed: true,\n        },\n      };\n\n      const updateQueries = {\n        todoList: (prev, options) => {\n          const mResult = options.mutationResult;\n\n          const state = cloneDeep<any>(prev);\n\n          if (mResult.data) {\n            state.todoList.todos.unshift(mResult.data.createTodo);\n          }\n\n          return state;\n        },\n      } as MutationQueryReducersMap<IMutationResult>;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          dataIdFromObject: (obj: any) => {\n            if (obj.id && obj.__typename) {\n              return obj.__typename + obj.id;\n            }\n            return null;\n          },\n        }),\n      });\n\n      // wrap the QueryObservable with an rxjs observable\n      const promise = lastValueFrom(\n        client\n          .watchQuery<any>({ query, notifyOnNetworkStatusChange: false })\n          .pipe(\n            map((value) => value.data.todoList.todos),\n            take(5),\n            toArray()\n          )\n      );\n\n      // Mutations will not trigger a watchQuery with the results of an optimistic response\n      // if set in the same tick of the event loop.\n      // https://github.com/apollographql/apollo-client/issues/3723\n      await new Promise((resolve) => setTimeout(resolve));\n\n      void client.mutate({\n        mutation,\n        optimisticResponse: customOptimisticResponse1,\n        updateQueries,\n      });\n\n      void client.mutate({\n        mutation,\n        optimisticResponse: customOptimisticResponse2,\n        updateQueries,\n      });\n\n      const responses = await promise;\n      const defaultTodos = result.data.todoList.todos;\n\n      expect(responses).toEqual([\n        defaultTodos,\n        [customOptimisticResponse1.createTodo, ...defaultTodos],\n        [\n          customOptimisticResponse2.createTodo,\n          customOptimisticResponse1.createTodo,\n          ...defaultTodos,\n        ],\n        [\n          customOptimisticResponse2.createTodo,\n          mutationResult.data.createTodo,\n          ...defaultTodos,\n        ],\n        [\n          mutationResult2.data.createTodo,\n          mutationResult.data.createTodo,\n          ...defaultTodos,\n        ],\n      ]);\n    });\n  });\n\n  describe(\"optimistic updates using `update`\", () => {\n    const mutation = gql`\n      mutation createTodo {\n        # skipping arguments in the test since they don't matter\n        createTodo {\n          id\n          text\n          completed\n          __typename\n        }\n        __typename\n      }\n    `;\n\n    const mutationResult = {\n      data: {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: \"99\",\n          __typename: \"Todo\",\n          text: \"This one was created with a mutation.\",\n          completed: true,\n        },\n      },\n    };\n\n    const optimisticResponse = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"99\",\n        text: \"Optimistically generated\",\n        completed: true,\n      },\n    };\n\n    const mutationResult2 = {\n      data: assign({}, mutationResult.data, {\n        createTodo: assign({}, mutationResult.data.createTodo, {\n          id: \"66\",\n          text: \"Second mutation.\",\n        }),\n      }),\n    };\n\n    const optimisticResponse2 = {\n      __typename: \"Mutation\",\n      createTodo: {\n        __typename: \"Todo\",\n        id: \"66\",\n        text: \"Optimistically generated 2\",\n        completed: true,\n      },\n    };\n\n    it(\"will insert a single itemAsync to the beginning\", async () => {\n      expect.assertions(7);\n      const client = await setup({\n        request: { query: mutation },\n        delay: 300,\n        result: mutationResult,\n      });\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      let firstTime = true;\n      let before = Date.now();\n      const promise = client.mutate({\n        mutation,\n        optimisticResponse,\n        update: (proxy: any, mResult: any) => {\n          const after = Date.now();\n          const duration = after - before;\n          if (firstTime) {\n            expect(duration < 300).toBe(true);\n            firstTime = false;\n          } else {\n            expect(duration > 300).toBe(true);\n          }\n          let data = proxy.readQuery({ query });\n\n          proxy.writeQuery({\n            query,\n            data: {\n              ...data,\n              todoList: {\n                ...data.todoList,\n                todos: [mResult.data.createTodo, ...data.todoList.todos],\n              },\n            },\n          });\n        },\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n      expect((dataInStore[\"Todo99\"] as any).text).toBe(\n        \"Optimistically generated\"\n      );\n      await promise;\n      const newResult = await client.query<any>({ query });\n\n      stream.unsubscribe();\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(4);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"two array insert like mutations\", async () => {\n      expect.assertions(10);\n      const client = await setup(\n        {\n          request: { query: mutation },\n          result: mutationResult,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          delay: 50,\n        }\n      );\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const update = (proxy: any, mResult: any) => {\n        const data: any = proxy.readFragment({\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n\n        proxy.writeFragment({\n          data: {\n            ...data,\n            todos: [mResult.data.createTodo, ...data.todos],\n          },\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n      };\n      const promise = client\n        .mutate({\n          mutation,\n          optimisticResponse,\n          update,\n        })\n        .then((res: any) => {\n          const currentDataInStore = (client.cache as InMemoryCache).extract(\n            true\n          );\n          expect((currentDataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n          expect((currentDataInStore[\"Todo99\"] as any).text).toBe(\n            \"This one was created with a mutation.\"\n          );\n          expect((currentDataInStore[\"Todo66\"] as any).text).toBe(\n            \"Optimistically generated 2\"\n          );\n          return res;\n        });\n\n      const promise2 = client.mutate({\n        mutation,\n        optimisticResponse: optimisticResponse2,\n        update,\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n      expect((dataInStore[\"Todo99\"] as any).text).toBe(\n        \"Optimistically generated\"\n      );\n      expect((dataInStore[\"Todo66\"] as any).text).toBe(\n        \"Optimistically generated 2\"\n      );\n\n      await Promise.all([promise, promise2]);\n\n      const newResult: any = await client.query({ query });\n\n      stream.unsubscribe();\n      // There should be one more todo item than before\n      expect(newResult.data.todoList.todos.length).toBe(5);\n\n      // Since we used `prepend` it should be at the front\n      expect(newResult.data.todoList.todos[0].text).toBe(\"Second mutation.\");\n      expect(newResult.data.todoList.todos[1].text).toBe(\n        \"This one was created with a mutation.\"\n      );\n    });\n\n    it(\"two mutations, one fails\", async () => {\n      expect.assertions(11);\n      const client = await setup(\n        {\n          request: { query: mutation },\n          error: new Error(\"forbidden (test error)\"),\n          delay: 20,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          // XXX this test will uncover a flaw in the design of optimistic responses combined with\n          // updateQueries or result reducers if you un-comment the line below. The issue is that\n          // optimistic updates are not commutative but are treated as such. When undoing an\n          // optimistic update, other optimistic updates should be rolled back and re-applied in the\n          // same order as before, otherwise the store can end up in an inconsistent state.\n          // delay: 50,\n        }\n      );\n      const stream = new ObservableStream(client.watchQuery({ query }));\n\n      await expect(stream).toEmitNext();\n\n      const update = (proxy: any, mResult: any) => {\n        const data: any = proxy.readFragment({\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n\n        proxy.writeFragment({\n          data: {\n            ...data,\n            todos: [mResult.data.createTodo, ...data.todos],\n          },\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n      };\n      const promise = client\n        .mutate({\n          mutation,\n          optimisticResponse,\n          update,\n        })\n        .catch((err: any) => {\n          // it is ok to fail here\n          expect(err).toBeInstanceOf(Error);\n          expect(err.message).toBe(\"forbidden (test error)\");\n          return null;\n        });\n\n      const promise2 = client.mutate({\n        mutation,\n        optimisticResponse: optimisticResponse2,\n        update,\n      });\n\n      const dataInStore = (client.cache as InMemoryCache).extract(true);\n      expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(5);\n      expect((dataInStore[\"Todo99\"] as any).text).toBe(\n        \"Optimistically generated\"\n      );\n      expect((dataInStore[\"Todo66\"] as any).text).toBe(\n        \"Optimistically generated 2\"\n      );\n\n      await Promise.all([promise, promise2]);\n\n      stream.unsubscribe();\n      {\n        const dataInStore = (client.cache as InMemoryCache).extract(true);\n        expect((dataInStore[\"TodoList5\"] as any).todos.length).toBe(4);\n        expect(dataInStore).not.toHaveProperty(\"Todo99\");\n        expect(dataInStore).toHaveProperty(\"Todo66\");\n        expect((dataInStore[\"TodoList5\"] as any).todos).toContainEqual(\n          makeReference(\"Todo66\")\n        );\n        expect((dataInStore[\"TodoList5\"] as any).todos).not.toContainEqual(\n          makeReference(\"Todo99\")\n        );\n      }\n    });\n\n    it(\"will handle dependent updates\", async () => {\n      expect.assertions(1);\n      const link = new MockLink([\n        {\n          request: { query },\n          result,\n          delay: 0,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult,\n          delay: 10,\n        },\n        {\n          request: { query: mutation },\n          result: mutationResult2,\n          delay: 20,\n        },\n      ]);\n\n      const customOptimisticResponse1 = {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"Todo\",\n          id: \"optimistic-99\",\n          text: \"Optimistically generated\",\n          completed: true,\n        },\n      };\n\n      const customOptimisticResponse2 = {\n        __typename: \"Mutation\",\n        createTodo: {\n          __typename: \"Todo\",\n          id: \"optimistic-66\",\n          text: \"Optimistically generated 2\",\n          completed: true,\n        },\n      };\n\n      const update = (proxy: any, mResult: any) => {\n        const data: any = proxy.readFragment({\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n\n        proxy.writeFragment({\n          data: { ...data, todos: [mResult.data.createTodo, ...data.todos] },\n          id: \"TodoList5\",\n          fragment: gql`\n            fragment todoList on TodoList {\n              todos {\n                id\n                text\n                completed\n                __typename\n              }\n            }\n          `,\n        });\n      };\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          dataIdFromObject: (obj: any) => {\n            if (obj.id && obj.__typename) {\n              return obj.__typename + obj.id;\n            }\n            return null;\n          },\n        }),\n      });\n\n      const promise = lastValueFrom(\n        client\n          .watchQuery<any>({ query, notifyOnNetworkStatusChange: false })\n          .pipe(\n            map((value) => value.data.todoList.todos),\n            take(5),\n            toArray()\n          )\n      );\n\n      await new Promise((resolve) => setTimeout(resolve));\n\n      void client.mutate({\n        mutation,\n        optimisticResponse: customOptimisticResponse1,\n        update,\n      });\n\n      void client.mutate({\n        mutation,\n        optimisticResponse: customOptimisticResponse2,\n        update,\n      });\n\n      const responses = await promise;\n      const defaultTodos = result.data.todoList.todos;\n      expect(responses).toEqual([\n        defaultTodos,\n        [customOptimisticResponse1.createTodo, ...defaultTodos],\n        [\n          customOptimisticResponse2.createTodo,\n          customOptimisticResponse1.createTodo,\n          ...defaultTodos,\n        ],\n        [\n          customOptimisticResponse2.createTodo,\n          mutationResult.data.createTodo,\n          ...defaultTodos,\n        ],\n        [\n          mutationResult2.data.createTodo,\n          mutationResult.data.createTodo,\n          ...defaultTodos,\n        ],\n      ]);\n    });\n\n    it(\"final update ignores optimistic data\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              observer.next({\n                data: {\n                  addItem: operation.variables.item,\n                },\n              });\n              observer.complete();\n            })\n        ),\n      });\n\n      const query: TypedDocumentNode<Data> = gql`\n        query {\n          items {\n            text\n          }\n        }\n      `;\n\n      let itemCount = 0;\n      function makeItem(source: string) {\n        return {\n          __typename: \"Item\",\n          text: `${source} ${++itemCount}`,\n        };\n      }\n\n      type Item = ReturnType<typeof makeItem>;\n      type Data = { items: Item[] };\n\n      function append(cache: ApolloCache, item: Item) {\n        const data = cache.readQuery({ query });\n        cache.writeQuery({\n          query,\n          data: {\n            ...data,\n            items: [...((data && data.items) || []), item],\n          },\n        });\n        return item;\n      }\n      const cancelFns: (() => any)[] = [];\n      const optimisticDiffs: Cache.DiffResult<Data>[] = [];\n      const realisticDiffs: Cache.DiffResult<Data>[] = [];\n\n      cancelFns.push(\n        cache.watch({\n          query,\n          optimistic: true,\n          callback(diff) {\n            optimisticDiffs.push(diff);\n          },\n        })\n      );\n\n      cancelFns.push(\n        cache.watch({\n          query,\n          optimistic: false,\n          callback(diff) {\n            realisticDiffs.push(diff);\n          },\n        })\n      );\n\n      const manualItem1 = makeItem(\"manual\");\n      const manualItem2 = makeItem(\"manual\");\n      const manualItems = [manualItem1, manualItem2];\n\n      expect(optimisticDiffs).toEqual([]);\n      expect(realisticDiffs).toEqual([]);\n\n      // So that we can have more control over the optimistic data in the\n      // cache, we add two items manually using the underlying cache API.\n      cache.recordOptimisticTransaction((cache) => {\n        append(cache, manualItem1);\n        append(cache, manualItem2);\n      }, \"manual\");\n\n      expect(cache.extract(false)).toEqual({});\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          items: manualItems,\n        },\n      });\n\n      expect(optimisticDiffs).toEqual([\n        {\n          complete: true,\n          fromOptimisticTransaction: true,\n          result: {\n            items: manualItems,\n          },\n        },\n      ]);\n\n      expect(realisticDiffs).toEqual([\n        {\n          complete: false,\n          missing: expect.anything(),\n          result: null,\n        },\n      ]);\n\n      const mutation = gql`\n        mutation AddItem($item: Item!) {\n          addItem(item: $item) {\n            text\n          }\n        }\n      `;\n\n      let updateCount = 0;\n      const optimisticItem = makeItem(\"optimistic\");\n      const mutationItem = makeItem(\"mutation\");\n\n      const result = await client.mutate({\n        mutation,\n        optimisticResponse: {\n          addItem: optimisticItem,\n        },\n        variables: {\n          item: mutationItem,\n        },\n        update: (cache, mutationResult) => {\n          ++updateCount;\n          if (updateCount === 1) {\n            expect(mutationResult).toEqual({\n              data: {\n                addItem: optimisticItem,\n              },\n            });\n\n            append(cache, optimisticItem);\n\n            const expected = {\n              ROOT_QUERY: {\n                __typename: \"Query\",\n                items: [manualItem1, manualItem2, optimisticItem],\n              },\n              ROOT_MUTATION: {\n                __typename: \"Mutation\",\n                // Although ROOT_MUTATION field data gets removed immediately\n                // after the mutation finishes, it is still temporarily visible\n                // to the update function.\n                'addItem({\"item\":{\"__typename\":\"Item\",\"text\":\"mutation 4\"}})': {\n                  __typename: \"Item\",\n                  text: \"optimistic 3\",\n                },\n              },\n            };\n\n            // Since we're in an optimistic update function, reading\n            // non-optimistically still returns optimistic data.\n            expect(cache.extract(false)).toEqual(expected);\n            expect(cache.extract(true)).toEqual(expected);\n          } else if (updateCount === 2) {\n            expect(mutationResult).toEqual({\n              data: {\n                addItem: mutationItem,\n              },\n            });\n\n            append(cache, mutationItem);\n\n            const expected = {\n              ROOT_QUERY: {\n                __typename: \"Query\",\n                items: [mutationItem],\n              },\n              ROOT_MUTATION: {\n                __typename: \"Mutation\",\n                'addItem({\"item\":{\"__typename\":\"Item\",\"text\":\"mutation 4\"}})': {\n                  __typename: \"Item\",\n                  text: \"mutation 4\",\n                },\n              },\n            };\n\n            // Since we're in the final (non-optimistic) update function,\n            // optimistic data is invisible, even if we try to read\n            // optimistically.\n            expect(cache.extract(false)).toEqual(expected);\n            expect(cache.extract(true)).toEqual(expected);\n          } else {\n            throw new Error(\"too many updates\");\n          }\n        },\n      });\n\n      expect(result).toEqual({\n        data: {\n          addItem: mutationItem,\n        },\n      });\n\n      // Only the final update function ever touched non-optimistic\n      // cache data.\n      expect(cache.extract(false)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          items: [mutationItem],\n        },\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n        },\n      });\n\n      // Now that the mutation is finished, reading optimistically from\n      // the cache should return the manually added items again.\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          items: [\n            // If we wanted to keep optimistic data as up-to-date as\n            // possible, we could rerun all optimistic transactions\n            // after writing to the root (non-optimistic) layer of the\n            // cache, which would result in mutationItem appearing in\n            // this list along with manualItem1 and manualItem2\n            // (presumably in that order). However, rerunning those\n            // optimistic transactions would trigger additional\n            // broadcasts for optimistic query watches, with\n            // intermediate results that (re)combine optimistic and\n            // non-optimistic data. Since rerendering the UI tends to be\n            // expensive, we should prioritize broadcasting states that\n            // matter most, and in this case that means broadcasting the\n            // initial optimistic state (for perceived performance),\n            // followed by the final, authoritative, non-optimistic\n            // state. Other intermediate states are a distraction, as\n            // they will probably soon be superseded by another (more\n            // authoritative) update. This particular state is visible\n            // only because we haven't rolled back this manual Layer\n            // just yet (see cache.removeOptimistic below).\n            manualItem1,\n            manualItem2,\n          ],\n        },\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n        },\n      });\n\n      cache.removeOptimistic(\"manual\");\n\n      // After removing the manual optimistic layer, only the\n      // non-optimistic data remains.\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          items: [mutationItem],\n        },\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n        },\n      });\n\n      cancelFns.forEach((cancel) => cancel());\n\n      expect(optimisticDiffs).toEqual([\n        {\n          complete: true,\n          fromOptimisticTransaction: true,\n          result: {\n            items: manualItems,\n          },\n        },\n        {\n          complete: true,\n          fromOptimisticTransaction: true,\n          result: {\n            items: [...manualItems, optimisticItem],\n          },\n        },\n        {\n          complete: true,\n          result: {\n            items: manualItems,\n          },\n        },\n        {\n          complete: true,\n          result: {\n            items: [mutationItem],\n          },\n        },\n      ]);\n\n      expect(realisticDiffs).toEqual([\n        {\n          complete: false,\n          missing: expect.anything(),\n          result: null,\n        },\n        {\n          complete: true,\n          result: {\n            items: [mutationItem],\n          },\n        },\n      ]);\n    });\n  });\n});\n\ndescribe(\"optimistic mutation - githunt comments\", () => {\n  const query = gql`\n    query Comment($repoName: String!) {\n      entry(repoFullName: $repoName) {\n        comments {\n          postedBy {\n            login\n            html_url\n          }\n        }\n      }\n    }\n  `;\n  const queryWithFragment = gql`\n    query Comment($repoName: String!) {\n      entry(repoFullName: $repoName) {\n        comments {\n          ...authorFields\n        }\n      }\n    }\n\n    fragment authorFields on User {\n      postedBy {\n        login\n        html_url\n      }\n    }\n  `;\n  const variables = {\n    repoName: \"org/repo\",\n  };\n  const userDoc = {\n    __typename: \"User\",\n    login: \"stubailo\",\n    html_url: \"http://avatar.com/stubailo.png\",\n  };\n\n  const result = {\n    data: {\n      __typename: \"Query\",\n      entry: {\n        __typename: \"Entry\",\n        comments: [\n          {\n            __typename: \"Comment\",\n            postedBy: userDoc,\n          },\n        ],\n      },\n    },\n  };\n\n  async function setup(...mockedResponses: MockLink.MockedResponse[]) {\n    const link = new MockLink([\n      {\n        request: {\n          query: addTypenameToDocument(query),\n          variables,\n        },\n        result,\n      },\n      {\n        request: {\n          query: addTypenameToDocument(queryWithFragment),\n          variables,\n        },\n        result,\n      },\n      ...mockedResponses,\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        dataIdFromObject: (obj: any) => {\n          if (obj.id && obj.__typename) {\n            return obj.__typename + obj.id;\n          }\n          return null;\n        },\n      }),\n    });\n\n    const obsHandle = client.watchQuery({\n      query,\n      variables,\n      notifyOnNetworkStatusChange: false,\n    });\n\n    await firstValueFrom(from(obsHandle));\n\n    return client;\n  }\n\n  const mutation = gql`\n    mutation submitComment($repoFullName: String!, $commentContent: String!) {\n      submitComment(\n        repoFullName: $repoFullName\n        commentContent: $commentContent\n      ) {\n        postedBy {\n          login\n          html_url\n        }\n      }\n    }\n  `;\n\n  type IMutationResult = {\n    __typename: string;\n    submitComment: {\n      __typename: string;\n      postedBy: {\n        __typename: string;\n        login: string;\n        html_url: string;\n      };\n    };\n  };\n  const mutationResult = {\n    data: {\n      __typename: \"Mutation\",\n      submitComment: {\n        __typename: \"Comment\",\n        postedBy: userDoc,\n      },\n    },\n  };\n  const updateQueries = {\n    Comment: (prev, { mutationResult: mutationResultArg }) => {\n      if (mutationResultArg.data) {\n        const newComment = mutationResultArg.data.submitComment;\n        const state = cloneDeep<any>(prev);\n        state.entry.comments.unshift(newComment);\n        return state;\n      }\n\n      return prev;\n    },\n  } as MutationQueryReducersMap<IMutationResult>;\n  const optimisticResponse = {\n    __typename: \"Mutation\",\n    submitComment: {\n      __typename: \"Comment\",\n      postedBy: userDoc,\n    },\n  };\n\n  it(\"can post a new comment\", async () => {\n    expect.assertions(2);\n    const mutationVariables = {\n      repoFullName: \"org/repo\",\n      commentContent: \"New Comment\",\n    };\n\n    const client = await setup({\n      request: {\n        query: addTypenameToDocument(mutation),\n        variables: mutationVariables,\n      },\n      result: mutationResult,\n    });\n    const stream = new ObservableStream(\n      client.watchQuery({ query, variables })\n    );\n\n    await expect(stream).toEmitNext();\n\n    await client.mutate({\n      mutation,\n      optimisticResponse,\n      variables: mutationVariables,\n      updateQueries,\n    });\n\n    const newResult: any = await client.query({ query, variables });\n\n    stream.unsubscribe();\n    expect(newResult.data.entry.comments.length).toBe(2);\n  });\n});\n"
  },
  {
    "path": "src/__tests__/refetchQueries.ts",
    "content": "import type { Subscription } from \"rxjs\";\nimport { Observable, Subject } from \"rxjs\";\n\nimport type { OnQueryUpdated, TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n  ObservableQuery,\n} from \"@apollo/client\";\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\n\ndescribe(\"client.refetchQueries\", () => {\n  it(\"is public and callable\", async () => {\n    expect.assertions(6);\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    expect(typeof client.refetchQueries).toBe(\"function\");\n    const onQueryUpdated = jest.fn();\n\n    const result = client.refetchQueries({\n      updateCache(cache) {\n        expect(cache).toBe(client.cache);\n        expect(cache.extract()).toEqual({});\n      },\n      onQueryUpdated,\n    });\n\n    expect(result.queries).toEqual([]);\n    expect(result.results).toEqual([]);\n\n    await result;\n\n    expect(onQueryUpdated).not.toHaveBeenCalled();\n  });\n\n  const aQuery: TypedDocumentNode<{ a: string }> = gql`\n    query A {\n      a\n    }\n  `;\n  const bQuery: TypedDocumentNode<{ b: string }> = gql`\n    query B {\n      b\n    }\n  `;\n  const abQuery: TypedDocumentNode<{\n    a: string;\n    b: string;\n  }> = gql`\n    query AB {\n      a\n      b\n    }\n  `;\n\n  function makeClient() {\n    return new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            const data: Record<string, string> = {};\n            operation.operationName!.split(\"\").forEach((letter) => {\n              data[letter.toLowerCase()] = letter.toUpperCase();\n            });\n            function finish(delay: number) {\n              // We need to add a delay here since RxJS emits synchronously.\n              // Some tests fail if this value is emitted synchronously.\n              // TODO: Determine root cause\n              setTimeout(() => {\n                observer.next({ data });\n                observer.complete();\n              }, delay);\n            }\n            if (typeof operation.variables.delay === \"number\") {\n              finish(operation.variables.delay);\n            } else finish(0);\n          })\n      ),\n    });\n  }\n\n  const subs: Subscription[] = [];\n  function unsubscribe() {\n    subs.splice(0).forEach((sub) => sub.unsubscribe());\n  }\n\n  function setup(client = makeClient()) {\n    function watch<T>(query: TypedDocumentNode<T>) {\n      const obsQuery = client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      });\n      return new Promise<ObservableQuery<T>>((resolve, reject) => {\n        subs.push(\n          obsQuery.subscribe({\n            error: reject,\n            next(result) {\n              expect(result.loading).toBe(false);\n              resolve(obsQuery);\n            },\n          })\n        );\n      });\n    }\n\n    return Promise.all([watch(aQuery), watch(bQuery), watch(abQuery)]);\n  }\n\n  // Not a great way to sort objects, but it will give us stable orderings in\n  // these specific tests (especially since the keys are all \"a\" and/or \"b\").\n  function sortObjects<T extends object[]>(array: T) {\n    array.sort((a, b) => {\n      const aKey = Object.keys(a).join(\",\");\n      const bKey = Object.keys(b).join(\",\");\n      if (aKey < bKey) return -1;\n      if (bKey < aKey) return 1;\n      return 0;\n    });\n  }\n\n  function obsUpdatedCheck(cb: OnQueryUpdated<any>) {\n    const subject = new Subject<Parameters<OnQueryUpdated<unknown>>>();\n    const stream = new ObservableStream(subject);\n    const onQueryUpdated = (...args: Parameters<OnQueryUpdated<any>>) => {\n      subject.next(args);\n      return cb(...args);\n    };\n    const check = async (\n      expectations: [obs: ObservableQuery<any>, result: unknown][]\n    ) => {\n      for (const [obs, result] of expectations) {\n        const [obsResult, diff] = await stream.takeNext();\n        expect(obsResult).toBe(obs);\n        expect(diff.result).toEqual(result);\n      }\n\n      await expect(stream).not.toEmitAnything();\n    };\n    return { onQueryUpdated, check, stream };\n  }\n\n  it(\"includes watched queries affected by updateCache\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const ayyCheck = obsUpdatedCheck((obs, diff) =>\n      Promise.resolve(diff.result)\n    );\n\n    const ayyResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: aQuery,\n          data: {\n            a: \"Ayy\",\n          },\n        });\n      },\n\n      onQueryUpdated: ayyCheck.onQueryUpdated,\n    });\n\n    await ayyCheck.check([\n      [aObs, { a: \"Ayy\" }],\n      [abObs, { a: \"Ayy\", b: \"B\" }],\n    ]);\n\n    sortObjects(ayyResults);\n\n    expect(ayyResults).toEqual([\n      { a: \"Ayy\" },\n      { a: \"Ayy\", b: \"B\" },\n      // Note that no bQuery result is included here.\n    ]);\n\n    const beeOQU = obsUpdatedCheck((obs, diff) => diff.result);\n\n    const beeResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: bQuery,\n          data: {\n            b: \"Bee\",\n          },\n        });\n      },\n\n      onQueryUpdated: beeOQU.onQueryUpdated,\n    });\n\n    await beeOQU.check([\n      [bObs, { b: \"Bee\" }],\n      [abObs, { a: \"Ayy\", b: \"Bee\" }],\n    ]);\n\n    sortObjects(beeResults);\n\n    expect(beeResults).toEqual([\n      // Note that no aQuery result is included here.\n      { a: \"Ayy\", b: \"Bee\" },\n      { b: \"Bee\" },\n    ]);\n\n    unsubscribe();\n  });\n\n  it(\"includes watched queries named in options.include\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const ayyOQU = obsUpdatedCheck((obs, diff) => Promise.resolve(diff.result));\n    const ayyResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: aQuery,\n          data: {\n            a: \"Ayy\",\n          },\n        });\n      },\n\n      // This is the options.include array mentioned in the test description.\n      include: [\"B\"],\n\n      onQueryUpdated: ayyOQU.onQueryUpdated,\n    });\n\n    await ayyOQU.check([\n      [aObs, { a: \"Ayy\" }],\n      [abObs, { a: \"Ayy\", b: \"B\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    sortObjects(ayyResults);\n\n    expect(ayyResults).toEqual([\n      { a: \"Ayy\" },\n      { a: \"Ayy\", b: \"B\" },\n      // Included this time!\n      { b: \"B\" },\n    ]);\n\n    const beeOQU = obsUpdatedCheck((obs, diff) => diff.result);\n    const beeResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: bQuery,\n          data: {\n            b: \"Bee\",\n          },\n        });\n      },\n\n      // The \"A\" here causes aObs to be included, but the \"AB\" should be\n      // redundant because that query is already included.\n      include: [\"A\", \"AB\"],\n\n      onQueryUpdated: beeOQU.onQueryUpdated,\n    });\n\n    await beeOQU.check([\n      [bObs, { b: \"Bee\" }],\n      [abObs, { a: \"Ayy\", b: \"Bee\" }],\n      [aObs, { a: \"Ayy\" }],\n    ]);\n\n    sortObjects(beeResults);\n\n    expect(beeResults).toEqual([\n      { a: \"Ayy\" }, // Included this time!\n      { a: \"Ayy\", b: \"Bee\" },\n      { b: \"Bee\" },\n    ]);\n\n    unsubscribe();\n  });\n\n  it(\"includes query DocumentNode objects specified in options.include\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const ayyOQU = obsUpdatedCheck((obs, diff) => Promise.resolve(diff.result));\n    const ayyResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: aQuery,\n          data: {\n            a: \"Ayy\",\n          },\n        });\n      },\n\n      // Note that we're passing query DocumentNode objects instead of query\n      // name strings, in this test.\n      include: [bQuery, abQuery],\n\n      onQueryUpdated: ayyOQU.onQueryUpdated,\n    });\n\n    await ayyOQU.check([\n      [aObs, { a: \"Ayy\" }],\n      [abObs, { a: \"Ayy\", b: \"B\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    sortObjects(ayyResults);\n\n    expect(ayyResults).toEqual([\n      { a: \"Ayy\" },\n      { a: \"Ayy\", b: \"B\" },\n      // Included this time!\n      { b: \"B\" },\n    ]);\n\n    const beeOQU = obsUpdatedCheck((obs, diff) => diff.result);\n    const beeResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: bQuery,\n          data: {\n            b: \"Bee\",\n          },\n        });\n      },\n\n      // The abQuery and \"AB\" should be redundant, but the aQuery here is\n      // important for aObs to be included.\n      include: [abQuery, \"AB\", aQuery],\n\n      onQueryUpdated: beeOQU.onQueryUpdated,\n    });\n\n    await beeOQU.check([\n      [bObs, { b: \"Bee\" }],\n      [abObs, { a: \"Ayy\", b: \"Bee\" }],\n      [aObs, { a: \"Ayy\" }],\n    ]);\n\n    sortObjects(beeResults);\n\n    expect(beeResults).toEqual([\n      { a: \"Ayy\" }, // Included this time!\n      { a: \"Ayy\", b: \"Bee\" },\n      { b: \"Bee\" },\n    ]);\n\n    unsubscribe();\n  });\n\n  it('includes all queries when options.include === \"all\"', async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const ayyOQU = obsUpdatedCheck((obs, diff) => Promise.resolve(diff.result));\n    const ayyResults = await client.refetchQueries({\n      include: \"all\",\n\n      updateCache(cache) {\n        cache.writeQuery({\n          query: aQuery,\n          data: {\n            a: \"Ayy\",\n          },\n        });\n      },\n\n      onQueryUpdated: ayyOQU.onQueryUpdated,\n    });\n\n    await ayyOQU.check([\n      [aObs, { a: \"Ayy\" }],\n      [abObs, { a: \"Ayy\", b: \"B\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    sortObjects(ayyResults);\n\n    expect(ayyResults).toEqual([\n      { a: \"Ayy\" },\n      { a: \"Ayy\", b: \"B\" },\n      { b: \"B\" },\n    ]);\n\n    const beeOQU = obsUpdatedCheck((obs, diff) => diff.result);\n    const beeResults = await client.refetchQueries({\n      include: \"all\",\n\n      updateCache(cache) {\n        cache.writeQuery({\n          query: bQuery,\n          data: {\n            b: \"Bee\",\n          },\n        });\n      },\n\n      onQueryUpdated: beeOQU.onQueryUpdated,\n    });\n\n    await beeOQU.check([\n      [bObs, { b: \"Bee\" }],\n      [abObs, { a: \"Ayy\", b: \"Bee\" }],\n      [aObs, { a: \"Ayy\" }],\n    ]);\n\n    sortObjects(beeResults);\n\n    expect(beeResults).toEqual([\n      { a: \"Ayy\" },\n      { a: \"Ayy\", b: \"Bee\" },\n      { b: \"Bee\" },\n    ]);\n\n    unsubscribe();\n  });\n\n  it('includes all active queries when options.include === \"active\"', async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const extraObs = client.watchQuery({ query: abQuery });\n    expect(extraObs.hasObservers()).toBe(false);\n\n    const activeOQU = obsUpdatedCheck((obs, diff) =>\n      Promise.resolve(diff.result)\n    );\n    const activeResults = await client.refetchQueries({\n      include: \"active\",\n\n      onQueryUpdated: activeOQU.onQueryUpdated,\n    });\n\n    await activeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(activeResults);\n\n    expect(activeResults).toEqual([{ a: \"A\" }, { a: \"A\", b: \"B\" }, { b: \"B\" }]);\n\n    subs.push(\n      extraObs.subscribe({\n        next(result) {\n          expect(result).toStrictEqualTyped({\n            data: { a: \"A\", b: \"B\" },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          });\n        },\n      })\n    );\n    expect(extraObs.hasObservers()).toBe(true);\n\n    const afterSubscribeOQU = obsUpdatedCheck((obs, diff) =>\n      Promise.resolve(diff.result)\n    );\n    const resultsAfterSubscribe = await client.refetchQueries({\n      include: \"active\",\n\n      onQueryUpdated: afterSubscribeOQU.onQueryUpdated,\n    });\n\n    await afterSubscribeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n      [extraObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(resultsAfterSubscribe);\n\n    expect(resultsAfterSubscribe).toEqual([\n      { a: \"A\" },\n      { a: \"A\", b: \"B\" },\n      // Included thanks to extraObs this time.\n      { a: \"A\", b: \"B\" },\n      // Sorted last by sortObjects.\n      { b: \"B\" },\n    ]);\n\n    unsubscribe();\n  });\n\n  it('does not include cache-only queries when options.include === \"active\"', async () => {\n    const cQuery = gql`\n      query {\n        c\n      }\n    `;\n    const client = makeClient();\n    client.writeQuery({ query: cQuery, data: { c: \"C\" } });\n\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const cObs = client.watchQuery({\n      query: cQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const cStream = new ObservableStream(cObs);\n\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"C\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const activeOQU = obsUpdatedCheck(() => true);\n    const activeResults = await client.refetchQueries({\n      include: \"active\",\n      onQueryUpdated: activeOQU.onQueryUpdated,\n    });\n\n    await activeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(activeResults);\n\n    expect(activeResults).toEqual([\n      { data: { a: \"A\" } },\n      { data: { b: \"B\" } },\n      { data: { a: \"A\", b: \"B\" } },\n    ]);\n\n    unsubscribe();\n  });\n\n  it('does not include cache-only queries when options.include === \"all\"', async () => {\n    const cQuery = gql`\n      query {\n        c\n      }\n    `;\n    const client = makeClient();\n    client.writeQuery({ query: cQuery, data: { c: \"C\" } });\n\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const cObs = client.watchQuery({\n      query: cQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const cStream = new ObservableStream(cObs);\n\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"C\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const activeOQU = obsUpdatedCheck(() => true);\n    const activeResults = await client.refetchQueries({\n      include: \"all\",\n      onQueryUpdated: activeOQU.onQueryUpdated,\n    });\n\n    await activeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(activeResults);\n\n    expect(activeResults).toEqual([\n      { data: { a: \"A\" } },\n      { data: { b: \"B\" } },\n      { data: { a: \"A\", b: \"B\" } },\n    ]);\n\n    unsubscribe();\n  });\n\n  it(\"does not include cache-only queries when affected by updateCache\", async () => {\n    const cQuery = gql`\n      query {\n        c\n      }\n    `;\n    const client = makeClient();\n    client.writeQuery({ query: cQuery, data: { c: \"C\" } });\n\n    await setup(client);\n\n    const cObs = client.watchQuery({\n      query: cQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const cStream = new ObservableStream(cObs);\n\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"C\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const activeResults = await client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: cQuery,\n          data: { c: \"See\" },\n        });\n      },\n    });\n\n    sortObjects(activeResults);\n\n    expect(activeResults).toEqual([]);\n\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"See\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    unsubscribe();\n  });\n\n  it(\"includes queries named in refetchQueries even if they have `standby` fetchPolicy\", async () => {\n    const client = makeClient();\n\n    const aObs = client.watchQuery({ query: aQuery, fetchPolicy: \"standby\" });\n    using aStream = new ObservableStream(aObs);\n    const bObs = client.watchQuery({ query: bQuery, fetchPolicy: \"standby\" });\n    using bStream = new ObservableStream(bObs);\n    const abObs = client.watchQuery({ query: abQuery, fetchPolicy: \"standby\" });\n    using abStream = new ObservableStream(abObs);\n\n    // These ObservableQuery objects fetchPolicy standby, but should\n    // nevertheless be refetched if identified explicitly in an options.include\n    // array passed to client.refetchQueries.\n\n    const activeOQU = obsUpdatedCheck(() => true);\n    using OQUStream = activeOQU.stream;\n\n    await Promise.all([\n      expect(aStream).not.toEmitAnything(),\n      expect(bStream).not.toEmitAnything(),\n      expect(abStream).not.toEmitAnything(),\n    ]);\n\n    const activeResults = await client.refetchQueries({\n      include: [\"A\", abQuery],\n      onQueryUpdated: activeOQU.onQueryUpdated,\n    });\n\n    {\n      const [observable, diff] = await OQUStream.takeNext();\n      expect(observable).toBe(aObs);\n      expect(diff.complete).toBe(false);\n      expect(diff.result).toEqual(null);\n    }\n    {\n      const [observable, diff] = await OQUStream.takeNext();\n      expect(observable).toBe(abObs);\n      expect(diff.complete).toBe(false);\n      expect(diff.result).toEqual(null);\n    }\n    await expect(OQUStream).not.toEmitAnything();\n\n    expect(activeResults).toEqual([\n      {\n        data: {\n          a: \"A\",\n        },\n      },\n      {\n        data: {\n          a: \"A\",\n          b: \"B\",\n        },\n      },\n    ]);\n\n    const afterSubscribeOQU = obsUpdatedCheck((obs, diff) =>\n      Promise.resolve(diff.result)\n    );\n    const resultsAfterSubscribe = await client.refetchQueries({\n      include: [aQuery, \"B\"],\n\n      onQueryUpdated: afterSubscribeOQU.onQueryUpdated,\n    });\n\n    await afterSubscribeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    sortObjects(resultsAfterSubscribe);\n    expect(resultsAfterSubscribe).toEqual([{ a: \"A\" }, { b: \"B\" }]);\n\n    unsubscribe();\n  });\n\n  it(\"does not include named cache-only queries in refetchQueries\", async () => {\n    const cQuery = gql`\n      query C {\n        c\n      }\n    `;\n    const client = makeClient();\n    client.writeQuery({ query: cQuery, data: { c: \"C\" } });\n\n    const aObs = client.watchQuery({\n      query: aQuery,\n      notifyOnNetworkStatusChange: false,\n    });\n\n    using aStream = new ObservableStream(aObs);\n\n    await expect(aStream).toEmitTypedValue({\n      data: { a: \"A\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const cObs = client.watchQuery({\n      query: cQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    using cStream = new ObservableStream(cObs);\n\n    await expect(cStream).toEmitTypedValue({\n      data: { c: \"C\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const activeOQU = obsUpdatedCheck(() => true);\n    await expect(\n      client.refetchQueries({\n        include: [aQuery, cQuery],\n        onQueryUpdated: activeOQU.onQueryUpdated,\n      })\n    ).resolves.toEqual([{ data: { a: \"A\" } }]);\n\n    await activeOQU.check([[aObs, { a: \"A\" }]]);\n\n    await expect(aStream).toEmitTypedValue({\n      data: { a: \"A\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(aStream).not.toEmitAnything();\n    await expect(cStream).not.toEmitAnything();\n  });\n\n  it(\"should not include unwatched single queries\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const delayedQuery = gql`\n      query DELAYED {\n        d\n        e\n        l\n        a\n        y\n        e\n        d\n      }\n    `;\n\n    void client\n      .query({\n        query: delayedQuery,\n        variables: {\n          // Delay this query by 10 seconds so it stays in-flight.\n          delay: 10000,\n        },\n      })\n      .catch(() => {\n        // swallow error when QueryManager is stopped later\n      });\n\n    const queries = client[\"queryManager\"][\"obsQueries\"];\n    expect(queries.size).toBe(3);\n\n    const activeOQU = obsUpdatedCheck((obs, diff) =>\n      Promise.resolve(diff.result)\n    );\n    const activeResults = await client.refetchQueries({\n      include: \"active\",\n\n      onQueryUpdated: activeOQU.onQueryUpdated,\n    });\n    await activeOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(activeResults);\n\n    expect(activeResults).toEqual([{ a: \"A\" }, { a: \"A\", b: \"B\" }, { b: \"B\" }]);\n\n    const allOQU = obsUpdatedCheck((obs, diff) => Promise.resolve(diff.result));\n    const allResults = await client.refetchQueries({\n      include: \"all\",\n\n      onQueryUpdated: allOQU.onQueryUpdated,\n    });\n    await allOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(allResults);\n\n    expect(allResults).toEqual([{ a: \"A\" }, { a: \"A\", b: \"B\" }, { b: \"B\" }]);\n\n    unsubscribe();\n    client.stop();\n\n    expect(queries.size).toBe(0);\n  });\n\n  it(\"refetches watched queries if onQueryUpdated not provided\", async () => {\n    expect.assertions(10);\n    const client = makeClient();\n    const [aObs, bObs, abObs] = await setup(client);\n\n    const aSpy = jest.spyOn(aObs, \"refetch\");\n    const bSpy = jest.spyOn(bObs, \"refetch\");\n    const abSpy = jest.spyOn(abObs, \"refetch\");\n\n    const ayyResults = (\n      await client.refetchQueries({\n        include: [\"B\"],\n        updateCache(cache) {\n          cache.writeQuery({\n            query: aQuery,\n            data: {\n              a: \"Ayy\",\n            },\n          });\n        },\n      })\n    ).map((result) => result.data as object);\n\n    sortObjects(ayyResults);\n\n    // These results have reverted back to what the ApolloLink returns (\"A\"\n    // rather than \"Ayy\"), because we let them be refetched (by not providing\n    // an onQueryUpdated function).\n    expect(ayyResults).toEqual([{ a: \"A\" }, { a: \"A\", b: \"B\" }, { b: \"B\" }]);\n\n    expect(aSpy).toHaveBeenCalledTimes(1);\n    expect(bSpy).toHaveBeenCalledTimes(1);\n    expect(abSpy).toHaveBeenCalledTimes(1);\n\n    unsubscribe();\n  });\n\n  it(\"can run updateQuery function against optimistic cache layer\", async () => {\n    const client = makeClient();\n    const [aObs, _bObs, abObs] = await setup(client);\n\n    client.cache.watch({\n      query: abQuery,\n      optimistic: false,\n      callback(diff) {\n        throw new Error(\"should not have notified non-optimistic watcher\");\n      },\n    });\n\n    expect(client.cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: \"A\",\n        b: \"B\",\n      },\n    });\n\n    const OQU = obsUpdatedCheck((obs, diff) => diff.result);\n    const results = await client.refetchQueries({\n      // This causes the update to run against a temporary optimistic layer.\n      optimistic: true,\n\n      updateCache(cache) {\n        const modified = cache.modify({\n          fields: {\n            a(value, { DELETE }) {\n              expect(value).toEqual(\"A\");\n              return DELETE;\n            },\n          },\n        });\n        expect(modified).toBe(true);\n      },\n\n      onQueryUpdated: OQU.onQueryUpdated,\n    });\n\n    await OQU.check([\n      [aObs, { a: \"A\" }],\n      [abObs, { a: \"A\", b: \"B\" }],\n    ]);\n\n    sortObjects(results);\n\n    expect(results).toEqual([{ a: \"A\" }, { a: \"A\", b: \"B\" }]);\n\n    expect(client.cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: \"A\",\n        b: \"B\",\n      },\n    });\n  });\n\n  it(\"can return true from onQueryUpdated to choose default refetching behavior\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, _abObs] = await setup(client);\n\n    const refetchOQU = obsUpdatedCheck((obs, diff) => true);\n    const refetchResult = client.refetchQueries({\n      include: [\"A\", \"B\"],\n      onQueryUpdated: refetchOQU.onQueryUpdated,\n    });\n    await refetchOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    expect(refetchResult.results.length).toBe(2);\n    refetchResult.results.forEach((result) => {\n      expect(result).toBeInstanceOf(Promise);\n    });\n\n    expect(\n      refetchResult.queries\n        .map((obs) => {\n          expect(obs).toBeInstanceOf(ObservableQuery);\n          return obs.queryName;\n        })\n        .sort()\n    ).toEqual([\"A\", \"B\"]);\n\n    const results = (await refetchResult).map((result) => {\n      // These results are ApolloQueryResult<any>, as inferred by TypeScript.\n      expect(Object.keys(result).sort()).toEqual([\"data\"]);\n      return result.data;\n    });\n\n    sortObjects(results);\n\n    expect(results).toEqual([{ a: \"A\" }, { b: \"B\" }]);\n  });\n\n  it(\"can return true from onQueryUpdated when using options.updateCache\", async () => {\n    const client = makeClient();\n    const [_aObs, bObs, abObs] = await setup(client);\n\n    const refetchOQU = obsUpdatedCheck((obs, diff) => true);\n    const refetchResult = client.refetchQueries({\n      updateCache(cache) {\n        cache.writeQuery({\n          query: bQuery,\n          data: {\n            b: \"Beetlejuice\",\n          },\n        });\n      },\n\n      onQueryUpdated: (obs, diff, lastDiff) => {\n        expect(client.cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            a: \"A\",\n            b: \"Beetlejuice\",\n          },\n        });\n        return refetchOQU.onQueryUpdated(obs, diff, lastDiff);\n      },\n    });\n\n    await refetchOQU.check([\n      [bObs, { b: \"Beetlejuice\" }],\n      [abObs, { a: \"A\", b: \"Beetlejuice\" }],\n    ]);\n\n    expect(refetchResult.results.length).toBe(2);\n    refetchResult.results.forEach((result) => {\n      expect(result).toBeInstanceOf(Promise);\n    });\n\n    expect(\n      refetchResult.queries\n        .map((obs) => {\n          expect(obs).toBeInstanceOf(ObservableQuery);\n          return obs.queryName;\n        })\n        .sort()\n    ).toEqual([\"AB\", \"B\"]);\n\n    const results = (await refetchResult).map((result) => {\n      // These results are QueryResult<any>, as inferred by TypeScript.\n      expect(Object.keys(result).sort()).toEqual([\"data\"]);\n      return result.data;\n    });\n\n    sortObjects(results);\n\n    expect(results).toEqual([\n      // Since we returned true from onQueryUpdated, the results were refetched,\n      // replacing \"Beetlejuice\" with \"B\" again.\n      { a: \"A\", b: \"B\" },\n      { b: \"B\" },\n    ]);\n\n    expect(client.cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: \"A\",\n        b: \"B\",\n      },\n    });\n  });\n\n  it(\"can return false from onQueryUpdated to skip/ignore a query\", async () => {\n    const client = makeClient();\n    const [aObs, bObs, _abObs] = await setup(client);\n\n    const refetchOQU = obsUpdatedCheck((obs, diff) => obs.queryName === \"B\");\n    const refetchResult = client.refetchQueries({\n      include: [\"A\", \"B\"],\n      onQueryUpdated: refetchOQU.onQueryUpdated,\n    });\n    await refetchOQU.check([\n      [aObs, { a: \"A\" }],\n      [bObs, { b: \"B\" }],\n    ]);\n\n    expect(refetchResult.results.length).toBe(1);\n    refetchResult.results.forEach((result) => {\n      expect(result).toBeInstanceOf(Promise);\n    });\n\n    expect(\n      refetchResult.queries\n        .map((obs) => {\n          expect(obs).toBeInstanceOf(ObservableQuery);\n          return obs.queryName;\n        })\n        .sort()\n    ).toEqual([\"B\"]);\n\n    const results = (await refetchResult).map((result) => {\n      // These results are ApolloQueryResult<any>, as inferred by TypeScript.\n      expect(Object.keys(result).sort()).toEqual([\"data\"]);\n      return result.data;\n    });\n\n    sortObjects(results);\n\n    expect(results).toEqual([{ b: \"B\" }]);\n  });\n\n  it(\"can refetch no-cache queries\", () => {\n    // TODO The options.updateCache function won't work for these queries, but\n    // the options.include array should work, at least.\n  });\n});\n"
  },
  {
    "path": "src/__tests__/resultCacheCleaning.ts",
    "content": "import { makeExecutableSchema } from \"@graphql-tools/schema\";\n\nimport { ApolloClient, gql } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { SchemaLink } from \"@apollo/client/link/schema\";\n\ntype Resolvers = Parameters<typeof makeExecutableSchema>[0][\"resolvers\"];\n\ndescribe(\"resultCache cleaning\", () => {\n  const fragments = gql`\n    fragment user on User {\n      id\n      name\n    }\n\n    fragment reaction on Reaction {\n      id\n      type\n      author {\n        ...user\n      }\n    }\n\n    fragment message on Message {\n      id\n      author {\n        ...user\n      }\n      reactions {\n        ...reaction\n      }\n      viewedBy {\n        ...user\n      }\n    }\n  `;\n\n  const query = gql`\n    query getChat($id: ID!) {\n      chat(id: $id) {\n        id\n        name\n        members {\n          ...user\n        }\n        messages {\n          ...message\n        }\n      }\n    }\n    ${{ ...fragments }}\n  `;\n\n  function uuid(label: string) {\n    return () => `${label}-${Math.random().toString(16).substr(2)}`;\n  }\n\n  function emptyList(len: number) {\n    return new Array(len).fill(true);\n  }\n\n  const typeDefs = gql`\n    type Query {\n      chat(id: ID!): Chat!\n    }\n\n    type Chat {\n      id: ID!\n      name: String!\n      messages: [Message!]!\n      members: [User!]!\n    }\n\n    type Message {\n      id: ID!\n      author: User!\n      reactions: [Reaction!]!\n      viewedBy: [User!]!\n      content: String!\n    }\n\n    type User {\n      id: ID!\n      name: String!\n    }\n\n    type Reaction {\n      id: ID!\n      type: String!\n      author: User!\n    }\n  `;\n\n  const resolvers: Resolvers = {\n    Query: {\n      chat(_, { id }) {\n        return id;\n      },\n    },\n    Chat: {\n      id(id) {\n        return id;\n      },\n      name(id) {\n        return id;\n      },\n      messages() {\n        return emptyList(10);\n      },\n      members() {\n        return emptyList(10);\n      },\n    },\n    Message: {\n      id: uuid(\"Message\"),\n      author() {\n        return { foo: true };\n      },\n      reactions() {\n        return emptyList(10);\n      },\n      viewedBy() {\n        return emptyList(10);\n      },\n      content: uuid(\"Message-Content\"),\n    },\n    User: {\n      id: uuid(\"User\"),\n      name: uuid(\"User.name\"),\n    },\n    Reaction: {\n      id: uuid(\"Reaction\"),\n      type: uuid(\"Reaction.type\"),\n      author() {\n        return { foo: true };\n      },\n    },\n  };\n\n  let client: ApolloClient;\n\n  beforeEach(() => {\n    client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new SchemaLink({\n        schema: makeExecutableSchema({\n          typeDefs,\n          resolvers,\n        }),\n      }),\n    });\n  });\n\n  afterEach(() => {\n    const storeReader = (client.cache as InMemoryCache)[\"storeReader\"];\n    expect(storeReader[\"executeSubSelectedArray\"].size).toBeGreaterThan(0);\n    expect(storeReader[\"executeSelectionSet\"].size).toBeGreaterThan(0);\n    client.cache.evict({\n      id: \"ROOT_QUERY\",\n    });\n    client.cache.gc();\n    expect(storeReader[\"executeSubSelectedArray\"].size).toEqual(0);\n    expect(storeReader[\"executeSelectionSet\"].size).toEqual(0);\n  });\n\n  it(`empties all result caches after eviction - query`, async () => {\n    await client.query({\n      query,\n      variables: { id: 1 },\n    });\n  });\n\n  it(`empties all result caches after eviction - watchQuery`, async () => {\n    return new Promise<void>((r) => {\n      const observable = client.watchQuery({\n        query,\n        variables: { id: 1 },\n      });\n      const unsubscribe = observable.subscribe(() => {\n        unsubscribe.unsubscribe();\n        r();\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/__tests__/subscribeToMore.ts",
    "content": "import type { DocumentNode, OperationDefinitionNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\nconst isSub = (operation: ApolloLink.Operation) =>\n  (operation.query as DocumentNode).definitions\n    .filter(\n      (x): x is OperationDefinitionNode => x.kind === \"OperationDefinition\"\n    )\n    .some((x) => x.operation === \"subscription\");\n\ndescribe(\"subscribeToMore\", () => {\n  const query = gql`\n    query aQuery {\n      entry {\n        value\n      }\n    }\n  `;\n  const result = {\n    data: {\n      entry: {\n        value: \"1\",\n      },\n    },\n  };\n\n  const req1 = { request: { query } as ApolloLink.Operation, result };\n\n  const results = [\"Dahivat Pandya\", \"Amanda Liu\"].map((name) => ({\n    result: { data: { name } },\n    delay: 10,\n  }));\n\n  const results2 = [\n    { result: { data: { name: \"Amanda Liu\" } }, delay: 10 },\n    { error: new Error(\"You can't touch this\"), delay: 10 },\n  ];\n\n  const results3 = [\n    { error: new Error(\"You can't touch this\"), delay: 10 },\n    { result: { data: { name: \"Amanda Liu\" } }, delay: 10 },\n  ];\n\n  const result4 = {\n    data: {\n      entry: [{ value: \"1\" }, { value: \"2\" }],\n    },\n  };\n  const req4 = { request: { query } as ApolloLink.Operation, result: result4 };\n\n  interface SubscriptionData {\n    name: string;\n  }\n\n  it(\"triggers new result from subscription data\", async () => {\n    const wSLink = new MockSubscriptionLink();\n    const httpLink = new MockLink([req1]);\n\n    const link = ApolloLink.split(isSub, wSLink, httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const obsHandle = client.watchQuery({ query });\n    const stream = new ObservableStream(obsHandle);\n\n    obsHandle.subscribeToMore<SubscriptionData>({\n      document: gql`\n        subscription newValues {\n          name\n        }\n      `,\n      updateQuery: (_, { subscriptionData }) => {\n        return { entry: { value: subscriptionData.data.name } };\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    wSLink.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"Dahivat Pandya\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await wait(10);\n    wSLink.simulateResult(results[1]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"Amanda Liu\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  it(\"calls error callback on error\", async () => {\n    const wSLink = new MockSubscriptionLink();\n    const httpLink = new MockLink([req1]);\n    const link = ApolloLink.split(isSub, wSLink, httpLink);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obsHandle = client.watchQuery<(typeof req1)[\"result\"][\"data\"]>({\n      query,\n    });\n    const stream = new ObservableStream(obsHandle);\n\n    const onError = jest.fn();\n\n    obsHandle.subscribeToMore<SubscriptionData>({\n      document: gql`\n        subscription newValues {\n          name\n        }\n      `,\n      updateQuery: (_, { subscriptionData }) => {\n        return { entry: { value: subscriptionData.data.name } };\n      },\n      onError,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    for (const result of results2) {\n      wSLink.simulateResult(result);\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"Amanda Liu\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await wait(15);\n\n    expect(onError).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenCalledWith(new Error(\"You can't touch this\"));\n  });\n\n  it(\"prints unhandled subscription errors to the console\", async () => {\n    using _ = spyOnConsole(\"error\");\n\n    const wSLink = new MockSubscriptionLink();\n    const httpLink = new MockLink([req1]);\n    const link = ApolloLink.split(isSub, wSLink, httpLink);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const obsHandle = client.watchQuery({\n      query,\n    });\n    const stream = new ObservableStream(obsHandle);\n\n    obsHandle.subscribeToMore({\n      document: gql`\n        subscription newValues {\n          name\n        }\n      `,\n      updateQuery: () => {\n        throw new Error(\"should not be called because of initial error\");\n      },\n    });\n\n    for (const result of results3) {\n      wSLink.simulateResult(result);\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await wait(15);\n\n    expect(console.error).toHaveBeenCalledTimes(1);\n    expect(console.error).toHaveBeenCalledWith(\n      \"Unhandled GraphQL subscription error\",\n      new Error(\"You can't touch this\")\n    );\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"should not corrupt the cache (#3062)\", async () => {\n    const wSLink = new MockSubscriptionLink();\n    const httpLink = new MockLink([req4]);\n    const link = ApolloLink.split(isSub, wSLink, httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache().restore({\n        ROOT_QUERY: {\n          entry: [\n            {\n              value: \"1\",\n            },\n            {\n              value: \"2\",\n            },\n          ],\n        },\n      }),\n      link,\n    });\n\n    const obsHandle = client.watchQuery<(typeof req4)[\"result\"][\"data\"]>({\n      query,\n    });\n    const stream = new ObservableStream(obsHandle);\n\n    let nextMutation: { value: string };\n    obsHandle.subscribeToMore<SubscriptionData>({\n      document: gql`\n        subscription createdEntry {\n          name\n        }\n      `,\n      updateQuery: (prev, { subscriptionData, complete, previousData }) => {\n        expect(complete).toBe(true);\n        expect(previousData).toStrictEqual(prev);\n        // Type Guard\n        if (!complete) {\n          return;\n        }\n\n        expect(previousData.entry).not.toContainEqual(nextMutation);\n        return {\n          entry: [...previousData.entry, { value: subscriptionData.data.name }],\n        };\n      },\n    });\n\n    for (let i = 0; i < 2; i++) {\n      // init optimistic mutation\n      let data = client.cache.readQuery<(typeof req4)[\"result\"][\"data\"]>(\n        { query },\n        false\n      );\n      client.cache.recordOptimisticTransaction((proxy) => {\n        nextMutation = { value: results[i].result.data.name };\n        proxy.writeQuery({\n          data: { entry: [...((data && data.entry) || []), nextMutation] },\n          query,\n        });\n      }, i.toString());\n      // on slow networks, subscription can happen first\n      wSLink.simulateResult(results[i]);\n      await wait(results[i].delay + 1);\n      // complete mutation\n      client.cache.removeOptimistic(i.toString());\n      // note: we don't complete mutation with performTransaction because a real example would detect duplicates\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: [{ value: \"1\" }, { value: \"2\" }] },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        entry: [{ value: \"1\" }, { value: \"2\" }, { value: \"Dahivat Pandya\" }],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        entry: [\n          { value: \"1\" },\n          { value: \"2\" },\n          { value: \"Dahivat Pandya\" },\n          { value: \"Amanda Liu\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n  // TODO add a test that checks that subscriptions are cancelled when obs is unsubscribed from.\n\n  it(\"allows specification of custom types for variables and payload (#4246)\", async () => {\n    interface TypedOperation extends ApolloLink.Operation {\n      variables: {\n        someNumber: number;\n      };\n    }\n    const typedReq = {\n      request: { query, variables: { someNumber: 1 } } as TypedOperation,\n      result,\n    };\n    interface TypedSubscriptionVariables {\n      someString: string;\n    }\n\n    const wSLink = new MockSubscriptionLink();\n    const httpLink = new MockLink([typedReq]);\n    const link = ApolloLink.split(isSub, wSLink, httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    type TData = (typeof typedReq)[\"result\"][\"data\"];\n    type TVariables = (typeof typedReq)[\"request\"][\"variables\"];\n    const obsHandle = client.watchQuery<TData, TVariables>({\n      query,\n      variables: { someNumber: 1 },\n    });\n    const stream = new ObservableStream(obsHandle);\n\n    obsHandle.subscribeToMore<SubscriptionData, TypedSubscriptionVariables>({\n      document: gql`\n        subscription newValues {\n          name\n        }\n      `,\n      variables: {\n        someString: \"foo\",\n      },\n      updateQuery: (_, { subscriptionData }) => {\n        return { entry: { value: subscriptionData.data.name } };\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    wSLink.simulateResult(results[0]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"Dahivat Pandya\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    await wait(10);\n    wSLink.simulateResult(results[1]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { entry: { value: \"Amanda Liu\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/core/__tests__/cache.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\nimport type { FragmentDefinitionNode, InlineFragmentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport type { OperationVariables, Unmasked } from \"@apollo/client\";\nimport type { Cache } from \"@apollo/client/cache\";\nimport { ApolloCache } from \"@apollo/client/cache\";\n\nimport type { Reference } from \"../../../utilities/graphql/storeUtils.js\";\n\nclass TestCache extends ApolloCache {\n  constructor() {\n    super();\n  }\n\n  public diff<T>(query: Cache.DiffOptions<T>): Cache.DiffResult<T> {\n    return { result: null, complete: false };\n  }\n\n  public evict(): boolean {\n    return false;\n  }\n\n  public extract(optimistic?: boolean): unknown {\n    return undefined;\n  }\n\n  public fragmentMatches(\n    fragment: InlineFragmentNode | FragmentDefinitionNode,\n    typename: string\n  ): boolean {\n    return true;\n  }\n\n  public performTransaction(transaction: (c: ApolloCache) => void): void {\n    transaction(this);\n  }\n\n  public read<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(query: Cache.ReadOptions<TData, TVariables>): Unmasked<TData> | null {\n    return null;\n  }\n\n  public recordOptimisticTransaction(\n    transaction: (c: ApolloCache) => void,\n    id: string\n  ): void {}\n\n  public removeOptimistic(id: string): void {}\n\n  public reset(): Promise<void> {\n    return new Promise<void>(() => null);\n  }\n\n  public restore(serializedState: unknown) {\n    return this;\n  }\n\n  public watch<\n    T = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(watch: Cache.WatchOptions<T, TVariables>): () => void {\n    return function () {};\n  }\n\n  public write<\n    TResult = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(_: Cache.WriteOptions<TResult, TVariables>): Reference | undefined {\n    return;\n  }\n}\nconst query = gql`\n  {\n    a\n  }\n`;\ndescribe(\"abstract cache\", () => {\n  describe(\"transformDocument\", () => {\n    it(\"returns the document\", () => {\n      const test = new TestCache();\n      expect(test.transformDocument(query)).toBe(query);\n    });\n  });\n\n  describe(\"transformForLink\", () => {\n    it(\"returns the document\", () => {\n      const test = new TestCache();\n      expect(test.transformForLink(query)).toBe(query);\n    });\n  });\n\n  describe(\"readQuery\", () => {\n    it(\"runs the read method\", () => {\n      const test = new TestCache();\n      test.read = jest.fn();\n\n      test.readQuery({ query });\n      expect(test.read).toHaveBeenCalled();\n    });\n\n    it(\"defaults optimistic to false\", () => {\n      const test = new TestCache();\n      test.read = ({ optimistic }) => optimistic as any;\n\n      expect(test.readQuery({ query })).toBe(false);\n      expect(test.readQuery({ query }, true)).toBe(true);\n    });\n  });\n\n  describe(\"readFragment\", () => {\n    it(\"runs the read method\", () => {\n      const test = new TestCache();\n      test.read = jest.fn();\n      const fragment = {\n        id: \"frag\",\n        fragment: gql`\n          fragment a on b {\n            name\n          }\n        `,\n      };\n\n      test.readFragment(fragment);\n      expect(test.read).toHaveBeenCalled();\n    });\n\n    it(\"defaults optimistic to false\", () => {\n      const test = new TestCache();\n      test.read = ({ optimistic }) => optimistic as any;\n      const fragment = {\n        id: \"frag\",\n        fragment: gql`\n          fragment a on b {\n            name\n          }\n        `,\n      };\n\n      expect(test.readFragment(fragment)).toBe(false);\n      expect(test.readFragment(fragment, true)).toBe(true);\n    });\n  });\n\n  describe(\"writeQuery\", () => {\n    it(\"runs the write method\", () => {\n      const test = new TestCache();\n      test.write = jest.fn();\n\n      test.writeQuery({\n        query: query,\n        data: \"foo\",\n      });\n      expect(test.write).toHaveBeenCalled();\n    });\n  });\n\n  describe(\"writeFragment\", () => {\n    it(\"runs the write method\", () => {\n      const test = new TestCache();\n      test.write = jest.fn();\n      const fragment = {\n        id: \"frag\",\n        fragment: gql`\n          fragment a on b {\n            name\n          }\n        `,\n        data: \"foo\",\n      };\n\n      test.writeFragment(fragment);\n      expect(test.write).toHaveBeenCalled();\n    });\n  });\n\n  describe(\"updateQuery\", () => {\n    it(\"runs the readQuery & writeQuery methods\", () => {\n      const test = new TestCache();\n      test.readQuery = jest.fn();\n      test.writeQuery = jest.fn();\n\n      test.updateQuery({ query }, (data) => \"foo\");\n\n      expect(test.readQuery).toHaveBeenCalled();\n      expect(test.writeQuery).toHaveBeenCalled();\n    });\n\n    it(\"does not call writeQuery method if data is null\", () => {\n      const test = new TestCache();\n      test.readQuery = jest.fn();\n      test.writeQuery = jest.fn();\n\n      test.updateQuery({ query }, (data) => null);\n\n      expect(test.readQuery).toHaveBeenCalled();\n      expect(test.writeQuery).not.toHaveBeenCalled();\n    });\n\n    it(\"does not call writeQuery method if data is undefined\", () => {\n      const test = new TestCache();\n      test.readQuery = jest.fn();\n      test.writeQuery = jest.fn();\n\n      test.updateQuery({ query }, (data) => {\n        return;\n      });\n\n      expect(test.readQuery).toHaveBeenCalled();\n      expect(test.writeQuery).not.toHaveBeenCalled();\n    });\n\n    it(\"calls the readQuery & writeQuery methods with the options object\", () => {\n      const test = new TestCache();\n      const options: Cache.UpdateQueryOptions<string, any> = {\n        query,\n        broadcast: true,\n        variables: { test: 1 },\n        optimistic: true,\n        returnPartialData: true,\n      };\n      test.readQuery = jest.fn();\n      test.writeQuery = jest.fn();\n\n      test.updateQuery(options, (data) => \"foo\");\n\n      expect(test.readQuery).toHaveBeenCalledWith(\n        expect.objectContaining(options)\n      );\n\n      expect(test.writeQuery).toHaveBeenCalledWith(\n        expect.objectContaining({ ...options, data: \"foo\" })\n      );\n    });\n\n    it(\"returns current value in memory if no update was made\", () => {\n      const test = new TestCache();\n      test.readQuery = jest.fn().mockReturnValue(\"foo\");\n      expect(test.updateQuery({ query }, (data) => null)).toBe(\"foo\");\n    });\n\n    it(\"returns the updated value in memory if an update was made\", () => {\n      const test = new TestCache();\n      let currentValue = \"foo\";\n      test.readQuery = jest.fn().mockImplementation(() => currentValue);\n      test.writeQuery = jest\n        .fn()\n        .mockImplementation(({ data }) => (currentValue = data));\n      expect(test.updateQuery({ query }, (data) => \"bar\")).toBe(\"bar\");\n    });\n\n    it(\"calls update function with the current value in memory\", () => {\n      const test = new TestCache();\n      test.readQuery = jest.fn().mockReturnValue(\"foo\");\n      test.updateQuery({ query }, (data) => {\n        expect(data).toBe(\"foo\");\n      });\n    });\n  });\n\n  describe(\"updateFragment\", () => {\n    const fragmentId = \"frag\";\n    const fragment = gql`\n      fragment a on b {\n        name\n      }\n    `;\n\n    it(\"runs the readFragment & writeFragment methods\", () => {\n      const test = new TestCache();\n      test.readFragment = jest.fn();\n      test.writeFragment = jest.fn();\n\n      test.updateFragment({ id: fragmentId, fragment }, (data) => \"foo\");\n\n      expect(test.readFragment).toHaveBeenCalled();\n      expect(test.writeFragment).toHaveBeenCalled();\n    });\n\n    it(\"does not call writeFragment method if data is null\", () => {\n      const test = new TestCache();\n      test.readFragment = jest.fn();\n      test.writeFragment = jest.fn();\n\n      test.updateFragment({ id: fragmentId, fragment }, (data) => null);\n\n      expect(test.readFragment).toHaveBeenCalled();\n      expect(test.writeFragment).not.toHaveBeenCalled();\n    });\n\n    it(\"does not call writeFragment method if data is undefined\", () => {\n      const test = new TestCache();\n      test.readFragment = jest.fn();\n      test.writeFragment = jest.fn();\n\n      test.updateFragment({ id: fragmentId, fragment }, (data) => {\n        return;\n      });\n\n      expect(test.readFragment).toHaveBeenCalled();\n      expect(test.writeFragment).not.toHaveBeenCalled();\n    });\n\n    it(\"calls the readFragment & writeFragment methods with the options object\", () => {\n      const test = new TestCache();\n      const options: Cache.UpdateFragmentOptions<string, any> = {\n        id: fragmentId,\n        fragment,\n        fragmentName: \"a\",\n        broadcast: true,\n        variables: { test: 1 },\n        optimistic: true,\n        returnPartialData: true,\n      };\n      test.readFragment = jest.fn();\n      test.writeFragment = jest.fn();\n\n      test.updateFragment(options, (data) => \"foo\");\n\n      expect(test.readFragment).toHaveBeenCalledWith(\n        expect.objectContaining(options)\n      );\n\n      expect(test.writeFragment).toHaveBeenCalledWith(\n        expect.objectContaining({ ...options, data: \"foo\" })\n      );\n    });\n\n    it(\"returns current value in memory if no update was made\", () => {\n      const test = new TestCache();\n      test.readFragment = jest.fn().mockReturnValue(\"foo\");\n      expect(\n        test.updateFragment({ id: fragmentId, fragment }, (data) => {\n          return;\n        })\n      ).toBe(\"foo\");\n    });\n\n    it(\"returns the updated value in memory if an update was made\", () => {\n      const test = new TestCache();\n      let currentValue = \"foo\";\n      test.readFragment = jest.fn().mockImplementation(() => currentValue);\n      test.writeFragment = jest\n        .fn()\n        .mockImplementation(({ data }) => (currentValue = data));\n      expect(\n        test.updateFragment({ id: fragmentId, fragment }, (data) => \"bar\")\n      ).toBe(\"bar\");\n    });\n\n    it(\"calls update function with the current value in memory\", () => {\n      const test = new TestCache();\n      test.readFragment = jest.fn().mockReturnValue(\"foo\");\n      test.updateFragment({ id: fragmentId, fragment }, (data) => {\n        expect(data).toBe(\"foo\");\n      });\n    });\n  });\n});\n\ndescribe.skip(\"Cache type tests\", () => {\n  describe(\"modify\", () => {\n    test(\"field types are inferred correctly from passed entity type\", () => {\n      const cache = new TestCache();\n      cache.modify<{\n        prop1: string;\n        prop2: number;\n        child: {\n          someObject: true;\n        };\n        children: {\n          anotherObject: false;\n        }[];\n      }>({\n        fields: {\n          prop1(field) {\n            expectTypeOf(field).toEqualTypeOf<string>();\n            return field;\n          },\n          prop2(field) {\n            expectTypeOf(field).toEqualTypeOf<number>();\n            return field;\n          },\n          child(field) {\n            expectTypeOf(field).toEqualTypeOf<\n              { someObject: true } | Reference\n            >();\n            return field;\n          },\n          children(field) {\n            expectTypeOf(field).toEqualTypeOf<\n              ReadonlyArray<{ anotherObject: false } | Reference>\n            >();\n            return field;\n          },\n        },\n      });\n    });\n    test(\"field method needs to return a value of the correct type\", () => {\n      const cache = new TestCache();\n      cache.modify<{\n        p1: string;\n        p2: string;\n        p3: string;\n        p4: string;\n        p5: string;\n      }>({\n        fields: {\n          p1() {\n            return \"\";\n          },\n          // @ts-expect-error returns wrong type\n          p2() {\n            return 1;\n          },\n          // @ts-expect-error needs return statement\n          p3() {},\n          p4(_, { DELETE }) {\n            return DELETE;\n          },\n          p5(_, { INVALIDATE }) {\n            return INVALIDATE;\n          },\n        },\n      });\n    });\n    test(\"passing a function as `field` should infer all entity properties as possible input (interfaces)\", () => {\n      interface ParentEntity {\n        prop1: string;\n        prop2: number;\n        child: ChildEntity;\n      }\n      interface ChildEntity {\n        prop1: boolean;\n        prop2: symbol;\n        children: OtherChildEntry[];\n      }\n      interface OtherChildEntry {\n        foo: false;\n      }\n\n      const cache = new TestCache();\n      // with reference\n      cache.modify<ParentEntity>({\n        id: \"foo\",\n        fields(field) {\n          expectTypeOf(field).toEqualTypeOf<\n            string | number | ChildEntity | Reference\n          >();\n          return field;\n        },\n      });\n      // without reference\n      cache.modify<ChildEntity>({\n        id: \"foo\",\n        fields(field) {\n          expectTypeOf(field).toEqualTypeOf<\n            boolean | symbol | ReadonlyArray<OtherChildEntry | Reference>\n          >();\n          return field;\n        },\n      });\n    });\n    test(\"passing a function as `field` should infer all entity properties as possible input (types)\", () => {\n      type ParentEntity = {\n        prop1: string;\n        prop2: number;\n        child: ChildEntity;\n      };\n      type ChildEntity = {\n        prop1: boolean;\n        prop2: symbol;\n        children: OtherChildEntry[];\n      };\n      type OtherChildEntry = {\n        foo: false;\n      };\n\n      const cache = new TestCache();\n      // with reference\n      cache.modify<ParentEntity>({\n        id: \"foo\",\n        fields(field) {\n          expectTypeOf(field).toEqualTypeOf<\n            string | number | ChildEntity | Reference\n          >();\n          return field;\n        },\n      });\n      // without reference\n      cache.modify<ChildEntity>({\n        id: \"foo\",\n        fields(field) {\n          expectTypeOf(field).toEqualTypeOf<\n            boolean | symbol | ReadonlyArray<OtherChildEntry | Reference>\n          >();\n          return field;\n        },\n      });\n    });\n    test(\"passing a function as `field` w/o specifying an entity type\", () => {\n      const cache = new TestCache();\n      cache.modify({\n        id: \"foo\",\n        fields(field) {\n          expectTypeOf(field).toEqualTypeOf<any>();\n          return field;\n        },\n      });\n    });\n    test(\"passing a function as `field` property w/o specifying an entity type\", () => {\n      const cache = new TestCache();\n      cache.modify({\n        id: \"foo\",\n        fields: {\n          p1(field) {\n            expectTypeOf(field).toEqualTypeOf<any>();\n            return field;\n          },\n        },\n      });\n    });\n\n    test(\"allows undefined as return value\", () => {\n      const cache = new TestCache();\n      cache.modify<{ foo: string }>({\n        id: \"foo\",\n        fields: {\n          foo: () => undefined,\n          // @ts-expect-error needs return statement\n          bar: () => {},\n        },\n      });\n    });\n\n    test(\"Allow for mixed arrays on union fields\", () => {\n      const cache = new TestCache();\n      cache.modify<{\n        union: Array<\n          | { __typename: \"Type1\"; a: string }\n          | { __typename: \"Type2\"; b: string }\n        >;\n      }>({\n        fields: {\n          union(field) {\n            expectTypeOf(field).toEqualTypeOf<\n              ReadonlyArray<\n                | Reference\n                | { __typename: \"Type1\"; a: string }\n                | { __typename: \"Type2\"; b: string }\n              >\n            >();\n            return field;\n          },\n        },\n      });\n    });\n\n    test(\"Allows partial return data\", () => {\n      const cache = new TestCache();\n      cache.modify<{\n        union: ReadonlyArray<\n          | { __typename: \"Type1\"; a: string; c: { foo: string } }\n          | { __typename: \"Type2\"; b: string; d: { bar: number } }\n        >;\n      }>({\n        fields: {\n          union(field) {\n            expectTypeOf(field).toEqualTypeOf<\n              ReadonlyArray<\n                | Reference\n                | {\n                    __typename: \"Type1\";\n                    a: string;\n                    c: { foo: string };\n                  }\n                | {\n                    __typename: \"Type2\";\n                    b: string;\n                    d: { bar: number };\n                  }\n              >\n            >();\n            return [{ __typename: \"Type1\", a: \"foo\" }];\n          },\n        },\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/core/__tests__/cache.watchFragment/types.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport type {\n  DataValue,\n  Reference,\n  StoreObject,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client\";\nimport type { ApolloCache, MissingTree } from \"@apollo/client/cache\";\n\ndescribe.skip(\"type tests\", () => {\n  interface Item {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const cache = new InMemoryCache();\n  let fragment!: TypedDocumentNode<Item, Record<string, never>>;\n\n  test(\"from: null -> null\", () => {\n    const observable = cache.watchFragment({ fragment, from: null });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<{\n      data: null;\n      dataState: \"complete\";\n      complete: true;\n      missing?: never;\n    }>();\n  });\n\n  test(\"from: StoreObject -> TData\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: string -> TData\", () => {\n    const observable = cache.watchFragment({ fragment, from: \"Item:1\" });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Reference -> TData\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: { __ref: \"Item:1\" },\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: StoreObject | null -> TData | null\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 } as StoreObject | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: string | null -> TData | null\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: \"Item:1\" as string | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Reference | null -> TData | null\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: { __ref: \"Item:1\" } as Reference | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Array<null> -> Array<null>\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: [null],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Array<null>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<{\n      data: Array<null>;\n      dataState: \"complete\";\n      complete: true;\n      missing?: never;\n    }>();\n  });\n\n  test(\"from: Array<FromValue> -> Array<TData>\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: [{ __typename: \"Item\", id: 1 }, \"Item:1\", { __ref: \"Item:1\" }],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Array<Item>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Array<Item>;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Array<DataValue.Partial<Item> | null>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Array<FromValue | null> -> Array<TData | null>\", () => {\n    const observable = cache.watchFragment({\n      fragment,\n      from: [{ __typename: \"Item\", id: 1 }, null],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloCache.ObservableFragment<Array<Item | null>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Array<Item | null>;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Array<DataValue.Partial<Item> | null>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n});\n"
  },
  {
    "path": "src/cache/core/cache.ts",
    "content": "import { WeakCache } from \"@wry/caches\";\nimport { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  InlineFragmentNode,\n} from \"graphql\";\nimport { wrap } from \"optimism\";\nimport {\n  distinctUntilChanged,\n  map,\n  Observable,\n  ReplaySubject,\n  share,\n  shareReplay,\n  tap,\n  timer,\n} from \"rxjs\";\n\nimport type {\n  DataValue,\n  GetDataState,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport type { FragmentType, Unmasked } from \"@apollo/client/masking\";\nimport type { Reference, StoreObject } from \"@apollo/client/utilities\";\nimport { cacheSizes, canonicalStringify } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  IsAny,\n  NoInfer,\n  Prettify,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  bindCacheKey,\n  combineLatestBatched,\n  equalByQuery,\n  getApolloCacheMemoryInternals,\n  getFragmentDefinition,\n  getFragmentQueryDocument,\n  mapObservableFragmentMemoized,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\n\nimport type { Cache } from \"./types/Cache.js\";\nimport type { MissingTree } from \"./types/common.js\";\n\nexport type Transaction = (c: ApolloCache) => void;\n\nexport declare namespace ApolloCache {\n  /**\n   * Acceptable values provided to the `from` option.\n   */\n  export type FromOptionValue<TData> =\n    | StoreObject\n    | Reference\n    | FragmentType<NoInfer<TData>>\n    | string;\n\n  /**\n   * Watched fragment options.\n   */\n  export interface WatchFragmentOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /**\n     * A GraphQL fragment document parsed into an AST with the `gql`\n     * template literal.\n     *\n     * @docGroup 1. Required options\n     */\n    fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    /**\n     * An object containing a `__typename` and primary key fields\n     * (such as `id`) identifying the entity object from which the fragment will\n     * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n     * (uncommon).\n     *\n     * @docGroup 1. Required options\n     */\n    from:\n      | ApolloCache.FromOptionValue<TData>\n      | Array<ApolloCache.FromOptionValue<TData> | null>\n      | null;\n    /**\n     * Any variables that the GraphQL fragment may depend on.\n     *\n     * @docGroup 2. Cache options\n     */\n    variables?: TVariables;\n    /**\n     * The name of the fragment defined in the fragment document.\n     *\n     * Required if the fragment document includes more than one fragment,\n     * optional otherwise.\n     *\n     * @docGroup 2. Cache options\n     */\n    fragmentName?: string;\n    /**\n     * If `true`, `watchFragment` returns optimistic results.\n     *\n     * The default value is `true`.\n     *\n     * @docGroup 2. Cache options\n     */\n    optimistic?: boolean;\n  }\n\n  /**\n   * Watched fragment results.\n   */\n  export type WatchFragmentResult<TData = unknown> =\n    true extends IsAny<TData> ?\n      | ({\n          complete: true;\n          missing?: never;\n        } & GetDataState<any, \"complete\">)\n      | ({\n          complete: false;\n          missing?: MissingTree;\n        } & GetDataState<any, \"partial\">)\n    : TData extends null | null[] ?\n      Prettify<\n        {\n          complete: true;\n          missing?: never;\n        } & GetDataState<TData, \"complete\">\n      >\n    : | Prettify<\n          {\n            complete: true;\n            missing?: never;\n          } & GetDataState<TData, \"complete\">\n        >\n      | {\n          complete: false;\n          missing?: MissingTree;\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n          data: TData extends Array<infer TItem> ?\n            Array<DataValue.Partial<TItem> | null>\n          : DataValue.Partial<TData>;\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n          dataState: \"partial\";\n        };\n\n  export interface ObservableFragment<TData = unknown>\n    extends Observable<ApolloCache.WatchFragmentResult<TData>> {\n    /**\n     * Return the current result for the fragment.\n     */\n    getCurrentResult: () => ApolloCache.WatchFragmentResult<TData>;\n  }\n}\n\nexport abstract class ApolloCache {\n  public readonly assumeImmutableResults: boolean = false;\n\n  // required to implement\n  // core API\n  public abstract read<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(query: Cache.ReadOptions<TData, TVariables>): Unmasked<TData> | null;\n  public abstract write<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(write: Cache.WriteOptions<TData, TVariables>): Reference | undefined;\n\n  /**\n   * Returns data read from the cache for a given query along with information\n   * about the cache result such as whether the result is complete and details\n   * about missing fields.\n   *\n   * Will return `complete` as `true` if it can fulfill the full cache result or\n   * `false` if not. When no data can be fulfilled from the cache, `null` is\n   * returned. When `returnPartialData` is `true`, non-null partial results are\n   * returned if it contains at least one field that can be fulfilled from the\n   * cache.\n   */\n  public abstract diff<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(query: Cache.DiffOptions<TData, TVariables>): Cache.DiffResult<TData>;\n  public abstract watch<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(watch: Cache.WatchOptions<TData, TVariables>): () => void;\n\n  // Empty the cache and restart all current watches (unless\n  // options.discardWatches is true).\n  public abstract reset(options?: Cache.ResetOptions): Promise<void>;\n\n  // Remove whole objects from the cache by passing just options.id, or\n  // specific fields by passing options.field and/or options.args. If no\n  // options.args are provided, all fields matching options.field (even\n  // those with arguments) will be removed. Returns true iff any data was\n  // removed from the cache.\n  public abstract evict(options: Cache.EvictOptions): boolean;\n\n  // initializer / offline / ssr API\n  /**\n   * Replaces existing state in the cache (if any) with the values expressed by\n   * `serializedState`.\n   *\n   * Called when hydrating a cache (server side rendering, or offline storage),\n   * and also (potentially) during hot reloads.\n   */\n  public abstract restore(serializedState: unknown): this;\n\n  /**\n   * Exposes the cache's complete state, in a serializable format for later restoration.\n   */\n  public abstract extract(optimistic?: boolean): unknown;\n\n  // Optimistic API\n\n  public abstract removeOptimistic(id: string): void;\n\n  // Used by data masking to determine if an inline fragment with a type\n  // condition matches a given typename. Also used by local resolvers to match a\n  // fragment against a typename.\n  //\n  // If not implemented by a cache subclass, data masking will effectively be\n  // disabled since we will not be able to accurately determine if a given type\n  // condition for a union or interface matches a particular type.\n  public abstract fragmentMatches(\n    fragment: InlineFragmentNode | FragmentDefinitionNode,\n    typename: string\n  ): boolean;\n\n  // Function used to lookup a fragment when a fragment definition is not part\n  // of the GraphQL document. This is useful for caches, such as InMemoryCache,\n  // that register fragments ahead of time so they can be referenced by name.\n  public lookupFragment(fragmentName: string): FragmentDefinitionNode | null {\n    return null;\n  }\n\n  // Local state API\n\n  /**\n   * Determines whether a `@client` field can be resolved by the cache. Used\n   * when `LocalState` does not have a local resolver that can resolve the\n   * field.\n   *\n   * @remarks Cache implementations should return `true` if a mechanism in the\n   * cache is expected to provide a value for the field. `LocalState` will set\n   * the value of the field to `undefined` in order for the cache to handle it.\n   *\n   * Cache implementations should return `false` to indicate that it cannot\n   * handle resolving the field (either because it doesn't have a mechanism to\n   * do so, or because the user hasn't provided enough information to resolve\n   * the field). Returning `false` will emit a warning and set the value of the\n   * field to `null`.\n   *\n   * A cache that doesn't implement `resolvesClientField` will be treated the\n   * same as returning `false`.\n   */\n  public resolvesClientField?(typename: string, fieldName: string): boolean;\n\n  // Transactional API\n\n  /**\n   * Executes multiple cache operations as a single batch, ensuring that\n   * watchers are only notified once after all operations complete. This is\n   * useful for improving performance when making multiple cache updates, as it\n   * prevents unnecessary re-renders or query refetches between individual\n   * operations.\n   *\n   * The `batch` method supports both optimistic and non-optimistic updates, and\n   * provides fine-grained control over which cache layer receives the updates\n   * and when watchers are notified.\n   *\n   * For usage instructions, see [Interacting with cached data: `cache.batch`](https://www.apollographql.com/docs/react/caching/cache-interaction#using-cachebatch).\n   *\n   * @example\n   *\n   * ```js\n   * cache.batch({\n   *   update(cache) {\n   *     cache.writeQuery({\n   *       query: GET_TODOS,\n   *       data: { todos: updatedTodos },\n   *     });\n   *     cache.evict({ id: \"Todo:123\" });\n   *   },\n   * });\n   * ```\n   *\n   * @example\n   *\n   * ```js\n   * // Optimistic update with a custom layer ID\n   * cache.batch({\n   *   optimistic: \"add-todo-optimistic\",\n   *   update(cache) {\n   *     cache.modify({\n   *       fields: {\n   *         todos(existing = []) {\n   *           return [...existing, newTodoRef];\n   *         },\n   *       },\n   *     });\n   *   },\n   * });\n   * ```\n   *\n   * @returns The return value of the `update` function.\n   */\n  public batch<U>(options: Cache.BatchOptions<this, U>): U {\n    const optimisticId =\n      typeof options.optimistic === \"string\" ? options.optimistic\n      : options.optimistic === false ? null\n      : void 0;\n    let updateResult: U;\n    this.performTransaction(\n      () => (updateResult = options.update(this)),\n      optimisticId\n    );\n    return updateResult!;\n  }\n\n  public abstract performTransaction(\n    transaction: Transaction,\n    // Although subclasses may implement recordOptimisticTransaction\n    // however they choose, the default implementation simply calls\n    // performTransaction with a string as the second argument, allowing\n    // performTransaction to handle both optimistic and non-optimistic\n    // (broadcast-batching) transactions. Passing null for optimisticId is\n    // also allowed, and indicates that performTransaction should apply\n    // the transaction non-optimistically (ignoring optimistic data).\n    optimisticId?: string | null\n  ): void;\n\n  public recordOptimisticTransaction(\n    transaction: Transaction,\n    optimisticId: string\n  ) {\n    this.performTransaction(transaction, optimisticId);\n  }\n\n  // Optional API\n\n  // Called once per input document, allowing the cache to make static changes\n  // to the query, such as adding __typename fields.\n  public transformDocument(document: DocumentNode): DocumentNode {\n    return document;\n  }\n\n  // Called before each ApolloLink request, allowing the cache to make dynamic\n  // changes to the query, such as filling in missing fragment definitions.\n  public transformForLink(document: DocumentNode): DocumentNode {\n    return document;\n  }\n\n  public identify(object: StoreObject | Reference): string | undefined {\n    return;\n  }\n\n  public gc(): string[] {\n    return [];\n  }\n\n  public modify<Entity extends Record<string, any> = Record<string, any>>(\n    options: Cache.ModifyOptions<Entity>\n  ): boolean {\n    return false;\n  }\n\n  /**\n   * Read data from the cache for the specified query.\n   */\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    // spread in type definitions for discoverability in the docs\n    query,\n    variables,\n    id,\n    optimistic,\n    returnPartialData,\n  }: Cache.ReadQueryOptions<TData, TVariables>): Unmasked<TData> | null;\n  /**\n   * {@inheritDoc @apollo/client!ApolloCache#readQuery:member(1)}\n   */\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.ReadQueryOptions<TData, TVariables>,\n    /**\n     * @deprecated Pass the `optimistic` argument as part of the first argument\n     * instead of passing it as a separate option.\n     */\n    optimistic: boolean\n  ): Unmasked<TData> | null;\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.ReadQueryOptions<TData, TVariables>,\n    optimistic = !!options.optimistic\n  ): Unmasked<TData> | null {\n    return this.read({\n      ...options,\n      rootId: options.id || \"ROOT_QUERY\",\n      optimistic,\n    });\n  }\n\n  private fragmentWatches = new Trie<{\n    observable?: ApolloCache.ObservableFragment<any> & { dirty: boolean };\n  }>(true);\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<ApolloCache.FromOptionValue<TData>>;\n    }\n  ): ApolloCache.ObservableFragment<Array<Unmasked<TData>>>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<null>;\n    }\n  ): ApolloCache.ObservableFragment<Array<null>>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }\n  ): ApolloCache.ObservableFragment<Array<Unmasked<TData> | null>>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n      from: null;\n    }\n  ): ApolloCache.ObservableFragment<null>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables> & {\n      from: ApolloCache.FromOptionValue<TData>;\n    }\n  ): ApolloCache.ObservableFragment<Unmasked<TData>>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables>\n  ): ApolloCache.ObservableFragment<Unmasked<TData> | null>;\n\n  /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloCache.WatchFragmentOptions<TData, TVariables>\n  ):\n    | ApolloCache.ObservableFragment<Unmasked<TData> | null>\n    | ApolloCache.ObservableFragment<Array<Unmasked<TData> | null>> {\n    const { fragment, fragmentName, from } = options;\n    const query = this.getFragmentDoc(\n      fragment,\n      fragmentName\n    ) as TypedDocumentNode<TData, TVariables>;\n\n    const fromArray = Array.isArray(from) ? from : [from];\n\n    const ids = fromArray.map((value) => {\n      // While our TypeScript types do not allow for `undefined` as a valid\n      // `from`, its possible `useFragment` gives us an `undefined` since it\n      // calls` cache.identify` and provides that value to `from`. We are\n      // adding this fix here however to ensure those using plain JavaScript\n      // and using `cache.identify` themselves will avoid seeing the obscure\n      // warning.\n      const id = value == null ? value : this.toCacheId(value);\n\n      if (__DEV__) {\n        const actualFragmentName =\n          fragmentName || getFragmentDefinition(fragment).name.value;\n\n        if (id === undefined) {\n          invariant.warn(\n            \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n            actualFragmentName\n          );\n        }\n      }\n\n      return id as string | null;\n    });\n\n    if (!Array.isArray(from)) {\n      const observable = this.watchSingleFragment(ids[0], query, options);\n      // Unfortunately we forgot to allow for `null` on watchFragment in 4.0\n      // when `from` is a single record. As such, we need to fallback to {}\n      // when diff.result is null to maintain backwards compatibility. We\n      // should plan to change this in v5. We do however support `null` if\n      // `from` is explicitly `null`.\n      //\n      // NOTE: Using `from` with an array will maintain `null` properly\n      // without the need for a similar fallback since watchFragment with\n      // arrays is new functionality in v4.1.\n      return from === null ? observable : (\n          mapObservableFragmentMemoized(\n            observable,\n            Symbol.for(\"apollo.transform.individualResult\"),\n            (result: ApolloCache.WatchFragmentResult<any>) => ({\n              ...result,\n              data: result.data ?? ({} as any),\n            })\n          )\n        );\n    }\n\n    let currentResult: ApolloCache.WatchFragmentResult<TData>;\n    function toResult(\n      results: Array<ApolloCache.WatchFragmentResult<TData>>\n    ): ApolloCache.WatchFragmentResult<any> {\n      const result = results.reduce(\n        (memo, result, idx) => {\n          memo.data.push(result.data);\n          memo.complete &&= result.complete;\n          memo.dataState = memo.complete ? \"complete\" : \"partial\";\n\n          if (result.missing) {\n            memo.missing ||= {};\n            (memo.missing as any)[idx] = result.missing;\n          }\n\n          return memo;\n        },\n        {\n          data: [],\n          dataState: \"complete\",\n          complete: true,\n        } as ApolloCache.WatchFragmentResult<TData>\n      );\n\n      if (!equal(currentResult, result)) {\n        currentResult = result;\n      }\n\n      return currentResult;\n    }\n\n    if (ids.length === 0) {\n      return emptyArrayObservable;\n    }\n\n    let subscribed = false;\n    const observables = ids.map((id) =>\n      this.watchSingleFragment(id, query, options)\n    ) as Array<ApolloCache.ObservableFragment<TData>>;\n\n    const observable = combineLatestBatched(observables).pipe(\n      map(toResult),\n      tap({\n        subscribe: () => (subscribed = true),\n        unsubscribe: () => (subscribed = false),\n      }),\n      shareReplay({ bufferSize: 1, refCount: true })\n    );\n\n    return Object.assign(observable, {\n      getCurrentResult: () => {\n        if (subscribed && currentResult) {\n          return currentResult as any;\n        }\n\n        const results = observables.map((observable) =>\n          observable.getCurrentResult()\n        );\n\n        return toResult(results);\n      },\n    } satisfies Pick<\n      | ApolloCache.ObservableFragment<Unmasked<TData> | null>\n      | ApolloCache.ObservableFragment<Array<Unmasked<TData> | null>>,\n      \"getCurrentResult\"\n    >) as any;\n  }\n\n  /**\n   * Can be overridden by subclasses to delay calling the provided callback\n   * until after all broadcasts have been completed - e.g. in a cache scenario\n   * where many watchers are notified in parallel.\n   */\n  protected onAfterBroadcast = (cb: () => void) => cb();\n  private watchSingleFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    id: string | null,\n    fragmentQuery: TypedDocumentNode<TData, TVariables>,\n    options: Omit<\n      ApolloCache.WatchFragmentOptions<TData, TVariables>,\n      \"from\" | \"fragment\" | \"fragmentName\"\n    >\n  ): ApolloCache.ObservableFragment<Unmasked<TData> | null> & {\n    dirty: boolean;\n  } {\n    if (id === null) {\n      return nullObservable as any;\n    }\n\n    const { optimistic = true, variables } = options;\n\n    const cacheKey = [\n      fragmentQuery,\n      canonicalStringify({ id, optimistic, variables }),\n    ];\n    const cacheEntry = this.fragmentWatches.lookupArray(cacheKey);\n\n    if (!cacheEntry.observable) {\n      let subscribed = false;\n      let currentResult: ApolloCache.WatchFragmentResult<TData>;\n\n      function getNewestResult(diff: Cache.DiffResult<TData>) {\n        const data = diff.result;\n\n        if (\n          !currentResult ||\n          !equalByQuery(\n            fragmentQuery,\n            { data: currentResult.data },\n            { data },\n            options.variables\n          )\n        ) {\n          currentResult = {\n            data,\n            dataState: diff.complete ? \"complete\" : \"partial\",\n            complete: diff.complete,\n          } as ApolloCache.WatchFragmentResult<TData>;\n\n          if (diff.missing) {\n            currentResult.missing = diff.missing.missing;\n          }\n        }\n\n        return currentResult;\n      }\n\n      const observable: Observable<ApolloCache.WatchFragmentResult<TData>> & {\n        dirty?: boolean;\n      } = new Observable<ApolloCache.WatchFragmentResult<TData>>((observer) => {\n        subscribed = true;\n        const cleanup = this.watch<TData, TVariables>({\n          variables,\n          returnPartialData: true,\n          id,\n          query: fragmentQuery,\n          optimistic,\n          immediate: true,\n          callback: (diff) => {\n            observable.dirty = true;\n            this.onAfterBroadcast(() => {\n              observer.next(getNewestResult(diff));\n              observable.dirty = false;\n            });\n          },\n        });\n        return () => {\n          subscribed = false;\n          cleanup();\n          this.fragmentWatches.removeArray(cacheKey);\n        };\n      }).pipe(\n        distinctUntilChanged(),\n        share({\n          connector: () => new ReplaySubject(1),\n          // debounce so a synchronous unsubscribe+resubscribe doesn't tear down the watch and create a new one\n          resetOnRefCountZero: () => timer(0),\n        })\n      );\n\n      cacheEntry.observable = Object.assign(observable, {\n        dirty: false,\n        getCurrentResult: () => {\n          if (subscribed && currentResult) {\n            return currentResult;\n          }\n\n          return getNewestResult(\n            this.diff<TData>({\n              id,\n              query: fragmentQuery,\n              returnPartialData: true,\n              optimistic,\n              variables,\n            })\n          );\n        },\n      });\n    }\n\n    return cacheEntry.observable as ApolloCache.ObservableFragment<Unmasked<TData> | null> & {\n      dirty: boolean;\n    };\n  }\n\n  // Make sure we compute the same (===) fragment query document every\n  // time we receive the same fragment in readFragment.\n  private getFragmentDoc = wrap(getFragmentQueryDocument, {\n    max:\n      cacheSizes[\"cache.fragmentQueryDocuments\"] ||\n      defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n    cache: WeakCache,\n    makeCacheKey: bindCacheKey(this),\n  });\n\n  /**\n   * Read data from the cache for the specified fragment.\n   */\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    // spread in type definitions for discoverability in the docs\n    fragment,\n    variables,\n    fragmentName,\n    id,\n    from,\n    optimistic,\n    returnPartialData,\n  }: Cache.ReadFragmentOptions<TData, TVariables>): Unmasked<TData> | null;\n\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.ReadFragmentOptions<TData, TVariables>,\n    /**\n     * @deprecated Pass the `optimistic` argument as part of the first argument\n     * instead of passing it as a separate option.\n     */\n    optimistic: boolean\n  ): Unmasked<TData> | null;\n\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.ReadFragmentOptions<TData, TVariables>,\n    optimistic = !!options.optimistic\n  ): Unmasked<TData> | null {\n    const id =\n      options.from !== undefined ? this.toCacheId(options.from) : options.id;\n\n    return this.read({\n      ...options,\n      query: this.getFragmentDoc(options.fragment, options.fragmentName),\n      rootId: id,\n      optimistic,\n    });\n  }\n\n  /**\n   * Writes data to the root of the cache using the specified query to validate that\n   * the shape of the data you’re writing to the cache is the same as the shape of\n   * the data required by the query. Great for prepping the cache with initial data.\n   */\n  public writeQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    // spread in type definitions for discoverability in the docs\n    data,\n    query,\n    variables,\n    overwrite,\n    id,\n    broadcast,\n  }: Cache.WriteQueryOptions<TData, TVariables>): Reference | undefined;\n  public writeQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    id,\n    data,\n    ...options\n  }: Cache.WriteQueryOptions<TData, TVariables>): Reference | undefined {\n    return this.write(\n      Object.assign(options, {\n        dataId: id || \"ROOT_QUERY\",\n        result: data,\n      })\n    );\n  }\n\n  /**\n   * Similar to `writeQuery` (writes data to the cache) but uses the specified\n   * fragment to validate that the shape of the data you’re writing to the cache\n   * is the same as the shape of the data required by the fragment.\n   */\n  public writeFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    // spread in type definitions for discoverability in the docs\n    data,\n    fragment,\n    fragmentName,\n    variables,\n    overwrite,\n    id,\n    from,\n    broadcast,\n  }: Cache.WriteFragmentOptions<TData, TVariables>): Reference | undefined;\n\n  public writeFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    data,\n    fragment,\n    fragmentName,\n    ...options\n  }: Cache.WriteFragmentOptions<TData, TVariables>): Reference | undefined {\n    const id =\n      options.from !== undefined ? this.toCacheId(options.from) : options.id;\n\n    return this.write(\n      Object.assign(options, {\n        query: this.getFragmentDoc(fragment, fragmentName),\n        dataId: id,\n        result: data,\n      })\n    );\n  }\n\n  public updateQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.UpdateQueryOptions<TData, TVariables>,\n    update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void\n  ): Unmasked<TData> | null {\n    return this.batch({\n      update(cache) {\n        const value = cache.readQuery<TData, TVariables>(options);\n        const data = update(value);\n        if (data === void 0 || data === null) return value;\n        cache.writeQuery<TData, TVariables>({ ...options, data });\n        return data;\n      },\n    });\n  }\n\n  public updateFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: Cache.UpdateFragmentOptions<TData, TVariables>,\n    update: (data: Unmasked<TData> | null) => Unmasked<TData> | null | void\n  ): Unmasked<TData> | null {\n    return this.batch({\n      update(cache) {\n        const value = cache.readFragment<TData, TVariables>(options);\n        const data = update(value);\n        if (data === void 0 || data === null) return value;\n        cache.writeFragment<TData, TVariables>({ ...options, data });\n        return data;\n      },\n    });\n  }\n\n  private toCacheId(from: ApolloCache.FromOptionValue<any>) {\n    return typeof from === \"string\" ? from : this.identify(from);\n  }\n\n  /**\n   * @experimental\n   * @internal\n   * This is not a stable API - it is used in development builds to expose\n   * information to the DevTools.\n   * Use at your own risk!\n   */\n  public declare getMemoryInternals?: typeof getApolloCacheMemoryInternals;\n}\n\nif (__DEV__) {\n  ApolloCache.prototype.getMemoryInternals = getApolloCacheMemoryInternals;\n}\n\nconst nullResult = Object.freeze({\n  data: null,\n  dataState: \"complete\",\n  complete: true,\n}) as ApolloCache.WatchFragmentResult<null>;\n\nconst nullObservable = Object.assign(\n  new Observable((observer) => {\n    observer.next(nullResult);\n  }),\n  { dirty: false, getCurrentResult: () => nullResult }\n);\n\nconst emptyArrayResult = Object.freeze({\n  data: [],\n  dataState: \"complete\",\n  complete: true,\n});\n\nconst emptyArrayObservable: ApolloCache.ObservableFragment<any[]> =\n  Object.assign(\n    new Observable<ApolloCache.WatchFragmentResult<never[]>>((observer) => {\n      observer.next(emptyArrayResult);\n    }),\n    { getCurrentResult: () => emptyArrayResult }\n  );\n"
  },
  {
    "path": "src/cache/core/types/Cache.ts",
    "content": "import type {\n  DataValue,\n  DocumentNode,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport type { ExtensionsWithStreamInfo } from \"@apollo/client/utilities/internal\";\n\nimport type { ApolloCache } from \"../cache.js\";\n\nimport type {\n  AllFieldsModifier,\n  MissingFieldError,\n  Modifiers,\n} from \"./common.js\";\nexport declare namespace Cache {\n  export type WatchCallback<TData = unknown> = (\n    diff: Cache.DiffResult<TData>,\n    lastDiff?: Cache.DiffResult<TData>\n  ) => void;\n\n  export interface ReadOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /**\n     * The GraphQL query shape to be used constructed using the `gql` template\n     * string tag from `graphql-tag`. The query will be used to determine the\n     * shape of the data to be read.\n     */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * Any variables that the GraphQL query may depend on.\n     */\n    variables?: TVariables;\n\n    /**\n     * The root id to be used. Defaults to \"ROOT_QUERY\", which is the ID of the\n     * root query object. This property makes writeQuery capable of writing data\n     * to any object in the cache.\n     */\n    id?: string;\n    rootId?: string;\n    previousResult?: any;\n    optimistic: boolean;\n    returnPartialData?: boolean;\n  }\n\n  export interface WriteOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /**\n     * The GraphQL query shape to be used constructed using the `gql` template\n     * string tag from `graphql-tag`. The query will be used to determine the\n     * shape of the data to be read.\n     */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * Any variables that the GraphQL query may depend on.\n     */\n    variables?: TVariables;\n\n    dataId?: string;\n    result: Unmasked<TData>;\n\n    /**\n     * Whether to notify query watchers.\n     * @defaultValue true\n     */\n    broadcast?: boolean;\n    /**\n     * When true, ignore existing field data rather than merging it with\n     * incoming data.\n     * @defaultValue false\n     */\n    overwrite?: boolean;\n\n    /**\n     * GraphQL extensions for the write operation. Any provided `extensions`\n     * are available in `merge` functions.\n     */\n    extensions?: ExtensionsWithStreamInfo;\n  }\n\n  export interface DiffOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > extends Omit<ReadOptions<TData, TVariables>, \"rootId\"> {\n    // The DiffOptions interface is currently just an alias for\n    // ReadOptions, though DiffOptions used to be responsible for\n    // declaring the returnPartialData option.\n  }\n\n  export interface WatchOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > extends DiffOptions<TData, TVariables> {\n    watcher?: object;\n    immediate?: boolean;\n    callback: WatchCallback<TData>;\n    lastDiff?: DiffResult<TData>;\n  }\n\n  export interface EvictOptions {\n    id?: string;\n    fieldName?: string;\n    args?: Record<string, any>;\n    broadcast?: boolean;\n  }\n\n  // Although you can call cache.reset() without options, its behavior can be\n  // configured by passing a Cache.ResetOptions object.\n  export interface ResetOptions {\n    discardWatches?: boolean;\n  }\n\n  export interface ModifyOptions<\n    Entity extends Record<string, any> = Record<string, any>,\n  > {\n    id?: string;\n    fields: Modifiers<Entity> | AllFieldsModifier<Entity>;\n    optimistic?: boolean;\n    broadcast?: boolean;\n  }\n\n  export interface BatchOptions<\n    TCache extends ApolloCache,\n    TUpdateResult = void,\n  > {\n    /**\n     * A function that performs cache operations. Receives the cache instance as its argument.\n     *\n     * The return value of this function becomes the return value of `batch`.\n     */\n    update(cache: TCache): TUpdateResult;\n\n    /**\n     * Controls how optimistic data is handled:\n     *\n     * - `string`: Creates a new optimistic layer with this ID. Use `removeOptimistic` later to remove it.\n     * - `true`: Updates the current top layer of the cache (including any optimistic data).\n     * - `false`: Updates only the root (non-optimistic) cache data.\n     *\n     * @defaultValue false\n     */\n    optimistic?: string | boolean;\n\n    /**\n     * If provided, removes the optimistic layer with this ID after the batch completes.\n     *\n     * This is useful for atomically applying server data while removing a pending optimistic update, triggering at most one broadcast for both operations.\n     *\n     * Note: this option is needed because calling `cache.removeOptimistic` during the transaction function may not be safe, since any modifications to cache layers may be discarded after the transaction finishes.\n     */\n    removeOptimistic?: string;\n\n    /**\n     * Optional callback invoked for each watcher affected by the batch operation.\n     *\n     * Receives the watch options, the new diff result, and optionally the previous diff result.\n     *\n     * Return `false` to prevent broadcasting to that specific watcher.\n     */\n    onWatchUpdated?: (\n      this: TCache,\n      watch: Cache.WatchOptions,\n      diff: Cache.DiffResult<any>,\n      lastDiff?: Cache.DiffResult<any> | undefined\n    ) => any;\n  }\n\n  export interface ReadQueryOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > {\n    /**\n     * The GraphQL query shape to be used constructed using the `gql` template\n     * string tag. The query will be used to determine the\n     * shape of the data to be read.\n     */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * Any variables that the GraphQL query may depend on.\n     */\n    variables?: TVariables;\n\n    /**\n     * The root id to be used. Defaults to \"ROOT_QUERY\", which is the ID of the\n     * root query object. This property makes readQuery capable of reading data\n     * from any object in the cache.\n     */\n    id?: string;\n    /**\n     * Whether to return incomplete data rather than null.\n     * @defaultValue false\n     */\n    returnPartialData?: boolean;\n    /**\n     * Whether to read from optimistic or non-optimistic cache data. If\n     * this named option is provided, the optimistic parameter of the\n     * readQuery method can be omitted.\n     * @defaultValue false\n     */\n    optimistic?: boolean;\n  }\n\n  export type ReadFragmentOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = {\n    /**\n     * A GraphQL document created using the `gql` template string tag from\n     * `graphql-tag` with one or more fragments which will be used to determine\n     * the shape of data to read. If you provide more than one fragment in this\n     * document then you must also specify `fragmentName` to specify which\n     * fragment is the root fragment.\n     */\n    fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * The name of the fragment in your GraphQL document to be used. If you do\n     * not provide a `fragmentName` and there is only one fragment in your\n     * `fragment` document then that fragment will be used.\n     */\n    fragmentName?: string;\n\n    /**\n     * Any variables that your GraphQL fragments depend on.\n     */\n    variables?: TVariables;\n\n    /**\n     * Whether to return incomplete data rather than null.\n     * @defaultValue false\n     */\n    returnPartialData?: boolean;\n    /**\n     * Whether to read from optimistic or non-optimistic cache data. If\n     * this named option is provided, the optimistic parameter of the\n     * readFragment method can be omitted.\n     * @defaultValue false\n     */\n    optimistic?: boolean;\n  } & Cache.CacheIdentifierOption<TData>;\n\n  export interface WriteQueryOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > {\n    /**\n     * The GraphQL query shape to be used constructed using the `gql` template\n     * string tag from `graphql-tag`. The query will be used to determine the\n     * shape of the data to be read.\n     */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * Any variables that the GraphQL query may depend on.\n     */\n    variables?: TVariables;\n\n    /**\n     * The root id to be used. Defaults to \"ROOT_QUERY\", which is the ID of the\n     * root query object. This property makes writeQuery capable of writing data\n     * to any object in the cache.\n     */\n    id?: string;\n\n    /**\n     * The data to write to the store.\n     */\n    data: Unmasked<TData>;\n    /**\n     * Whether to notify query watchers.\n     * @defaultValue true\n     */\n    broadcast?: boolean;\n    /**\n     * When true, ignore existing field data rather than merging it with\n     * incoming data.\n     * @defaultValue false\n     */\n    overwrite?: boolean;\n\n    /**\n     * GraphQL extensions for the write operation. Any provided `extensions`\n     * are available in `merge` functions.\n     */\n    extensions?: ExtensionsWithStreamInfo;\n  }\n\n  export type WriteFragmentOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = {\n    /**\n     * A GraphQL document created using the `gql` template string\n     * with one or more fragments which will be used to determine\n     * the shape of data to read. If you provide more than one fragment in this\n     * document then you must also specify `fragmentName` to specify specify which\n     * fragment is the root fragment.\n     */\n    fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * The name of the fragment in your GraphQL document to be used. If you do\n     * not provide a `fragmentName` and there is only one fragment in your\n     * `fragment` document then that fragment will be used.\n     */\n    fragmentName?: string;\n\n    /**\n     * Any variables that your GraphQL fragments depend on.\n     */\n    variables?: TVariables;\n    /**\n     * The data to write to the store.\n     */\n    data: Unmasked<TData>;\n    /**\n     * Whether to notify query watchers.\n     * @defaultValue true\n     */\n    broadcast?: boolean;\n    /**\n     * When true, ignore existing field data rather than merging it with\n     * incoming data.\n     * @defaultValue false\n     */\n    overwrite?: boolean;\n  } & Cache.CacheIdentifierOption<TData>;\n\n  export interface UpdateQueryOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > extends Omit<\n      ReadQueryOptions<TData, TVariables> &\n        WriteQueryOptions<TData, TVariables>,\n      \"data\"\n    > {}\n\n  export type UpdateFragmentOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = Omit<\n    ReadFragmentOptions<TData, TVariables> &\n      WriteFragmentOptions<TData, TVariables>,\n    \"data\" | \"id\" | \"from\"\n  > &\n    Cache.CacheIdentifierOption<TData>;\n\n  export type DiffResult<TData> =\n    | {\n        result: DataValue.Complete<TData>;\n        complete: true;\n        missing?: never;\n        fromOptimisticTransaction?: boolean;\n      }\n    | {\n        result: DataValue.Partial<TData> | null;\n        complete: false;\n        missing?: MissingFieldError;\n        fromOptimisticTransaction?: boolean;\n      };\n\n  export type CacheIdentifierOption<TData> =\n    | {\n        /**\n         * The root id to be used. This id should take the same form as the\n         * value returned by the `cache.identify` function. If a value with your\n         * id does not exist in the store, `null` will be returned.\n         */\n        id?: string;\n\n        /**\n         * An object containing a `__typename` and primary key fields\n         * (such as `id`) identifying the entity object from which the fragment will\n         * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n         * (uncommon).\n         *\n         * @remarks\n         * `from` is given precedence over `id` when both are provided.\n         */\n        from?: never;\n      }\n    | {\n        /**\n         * The root id to be used. This id should take the same form as the\n         * value returned by the `cache.identify` function. If a value with your\n         * id does not exist in the store, `null` will be returned.\n         */\n        id?: never;\n\n        /**\n         * An object containing a `__typename` and primary key fields\n         * (such as `id`) identifying the entity object from which the fragment will\n         * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n         * (uncommon).\n         *\n         * @remarks\n         * `from` is given precedence over `id` when both are provided.\n         */\n        from?: ApolloCache.FromOptionValue<TData>;\n      };\n}\n"
  },
  {
    "path": "src/cache/core/types/common.ts",
    "content": "import type { DocumentNode, FieldNode } from \"graphql\";\n\nimport type {\n  AsStoreObject,\n  DeepPartial,\n  isReference,\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\n\nimport type { StorageType } from \"../../inmemory/policies.js\";\n\n// The Readonly<T> type only really works for object types, since it marks\n// all of the object's properties as readonly, but there are many cases when\n// a generic type parameter like TExisting might be a string or some other\n// primitive type, in which case we need to avoid wrapping it with Readonly.\n// SafeReadonly<string> collapses to just string, which makes string\n// assignable to SafeReadonly<any>, whereas string is not assignable to\n// Readonly<any>, somewhat surprisingly.\nexport type SafeReadonly<T> = T extends object ? Readonly<T> : T;\n\nexport type MissingTree =\n  | string\n  | {\n      readonly [key: string]: MissingTree;\n    };\n\nexport class MissingFieldError extends Error {\n  constructor(\n    public readonly message: string,\n    public readonly path: MissingTree | Array<string | number>,\n    public readonly query: DocumentNode,\n    public readonly variables?: Record<string, any>\n  ) {\n    // 'Error' breaks prototype chain here\n    super(message);\n    this.name = \"MissingFieldError\";\n\n    if (Array.isArray(this.path)) {\n      this.missing = this.message;\n      for (let i = this.path.length - 1; i >= 0; --i) {\n        this.missing = { [this.path[i]]: this.missing };\n      }\n    } else {\n      this.missing = this.path;\n    }\n\n    // We're not using `Object.setPrototypeOf` here as it isn't fully supported\n    // on Android (see issue #3236).\n    (this as any).__proto__ = MissingFieldError.prototype;\n  }\n\n  public readonly missing: MissingTree;\n}\n\nexport interface FieldSpecifier {\n  typename?: string;\n  fieldName: string;\n  field?: FieldNode;\n  args?: Record<string, any>;\n  variables?: Record<string, any>;\n}\n\nexport interface ReadFieldOptions extends FieldSpecifier {\n  from?: StoreObject | Reference;\n}\n\nexport interface ReadFieldFunction {\n  <V = StoreValue>(options: ReadFieldOptions): SafeReadonly<V> | undefined;\n  <V = StoreValue>(\n    fieldName: string,\n    from?: StoreObject | Reference\n  ): SafeReadonly<V> | undefined;\n}\n\nexport type ToReferenceFunction = (\n  objOrIdOrRef: StoreObject | string | Reference,\n  mergeIntoStore?: boolean\n) => Reference | undefined;\n\nexport type CanReadFunction = (value: StoreValue) => boolean;\n\ndeclare const _deleteModifier: unique symbol;\nexport interface DeleteModifier {\n  [_deleteModifier]: true;\n}\ndeclare const _invalidateModifier: unique symbol;\nexport interface InvalidateModifier {\n  [_invalidateModifier]: true;\n}\ndeclare const _ignoreModifier: unique symbol;\nexport interface IgnoreModifier {\n  [_ignoreModifier]: true;\n}\n\nexport type ModifierDetails = {\n  DELETE: DeleteModifier;\n  INVALIDATE: InvalidateModifier;\n  fieldName: string;\n  storeFieldName: string;\n  readField: ReadFieldFunction;\n  canRead: CanReadFunction;\n  isReference: typeof isReference;\n  toReference: ToReferenceFunction;\n  storage: StorageType;\n};\n\nexport type Modifier<T> = (\n  value: T,\n  details: ModifierDetails\n) => DeepPartial<T> | DeleteModifier | InvalidateModifier | undefined;\n\ntype StoreObjectValueMaybeReference<StoreVal> =\n  StoreVal extends ReadonlyArray<Record<string, any>> ?\n    StoreVal extends ReadonlyArray<infer Item> ?\n      [Item] extends [Record<string, any>] ?\n        ReadonlyArray<AsStoreObject<Item> | Reference>\n      : never\n    : never\n  : StoreVal extends Record<string, any> ? AsStoreObject<StoreVal> | Reference\n  : StoreVal;\n\nexport type AllFieldsModifier<Entity extends Record<string, any>> = Modifier<\n  Entity[keyof Entity] extends infer Value ?\n    StoreObjectValueMaybeReference<Exclude<Value, undefined>>\n  : never\n>;\n\nexport type Modifiers<T extends Record<string, any> = Record<string, unknown>> =\n  Partial<{\n    [FieldName in keyof T]: Modifier<\n      StoreObjectValueMaybeReference<Exclude<T[FieldName], undefined>>\n    >;\n  }>;\n"
  },
  {
    "path": "src/cache/deprecated.ts",
    "content": "import type { ApolloCache, OperationVariables } from \"@apollo/client\";\n\n/** @deprecated Use `ApolloCache.WatchFragmentOptions` instead */\nexport type WatchFragmentOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = ApolloCache.WatchFragmentOptions<TData, TVariables>;\n\n/** @deprecated Use `ApolloCache.WatchFragmentResult` instead */\nexport type WatchFragmentResult<TData> = ApolloCache.WatchFragmentResult<TData>;\n"
  },
  {
    "path": "src/cache/index.ts",
    "content": "export type { Transaction } from \"./core/cache.js\";\nexport type {\n  WatchFragmentOptions,\n  WatchFragmentResult,\n} from \"./deprecated.js\";\nexport { ApolloCache } from \"./core/cache.js\";\nexport type { Cache } from \"./core/types/Cache.js\";\nexport type {\n  IgnoreModifier,\n  MissingTree,\n  Modifier,\n  ModifierDetails,\n  Modifiers,\n  ReadFieldOptions,\n} from \"./core/types/common.js\";\nexport { MissingFieldError } from \"./core/types/common.js\";\n\nexport type { Reference } from \"@apollo/client/utilities\";\nexport { canonicalStringify, isReference } from \"@apollo/client/utilities\";\n\nexport { EntityStore } from \"./inmemory/entityStore.js\";\nexport {\n  defaultDataIdFromObject,\n  fieldNameFromStoreName,\n} from \"./inmemory/helpers.js\";\n\nexport { InMemoryCache } from \"./inmemory/inMemoryCache.js\";\n\nexport type { ReactiveVar } from \"./inmemory/reactiveVars.js\";\nexport { cacheSlot, makeVar } from \"./inmemory/reactiveVars.js\";\n\nexport type {\n  FieldFunctionOptions,\n  FieldMergeFunction,\n  FieldMergeFunctionOptions,\n  FieldPolicy,\n  FieldReadFunction,\n  FieldReadFunctionOptions,\n  PossibleTypesMap,\n  TypePolicies,\n  TypePolicy,\n} from \"./inmemory/policies.js\";\nexport { Policies } from \"./inmemory/policies.js\";\n\nexport type { FragmentRegistryAPI } from \"./inmemory/fragmentRegistry.js\";\nexport { createFragmentRegistry } from \"./inmemory/fragmentRegistry.js\";\n\nexport type {\n  ApolloReducerConfig,\n  DiffQueryAgainstStoreOptions,\n  IdGetter,\n  IdGetterObj,\n  InMemoryCacheConfig,\n  MergeInfo,\n  MergeTree,\n  NormalizedCache,\n  NormalizedCacheObject,\n  OptimisticStoreItem,\n  ReadMergeModifyContext,\n  ReadQueryOptions,\n  StoreObject,\n  StoreValue,\n} from \"./inmemory/types.js\";\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/cache.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`Cache cache.restore replaces cache.{store{Reader,Writer},maybeBroadcastWatch} 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": \"ay\",\n    \"b\": \"bee\",\n    \"c\": \"see\",\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 1`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"i\": 7,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 2`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 3`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 4`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 5`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (1/2) 6`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 1`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"i\": 7,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 2`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 3`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 4`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 5`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 7,\n    \"j\": 8,\n    \"k\": 9,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`Cache writeFragment will write some deeply nested data into the store at any id (2/2) 6`] = `\nObject {\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"bar\",\n      \"foo\",\n    ],\n  },\n  \"bar\": Object {\n    \"__typename\": \"Bar\",\n    \"i\": 10,\n    \"j\": 11,\n    \"k\": 12,\n  },\n  \"foo\": Object {\n    \"__typename\": \"Foo\",\n    \"e\": 4,\n    \"f\": 5,\n    \"g\": 6,\n    \"h\": Object {\n      \"__ref\": \"bar\",\n    },\n  },\n}\n`;\n\nexports[`InMemoryCache#modify should allow invalidation using details.INVALIDATE 1`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Maria Dahvana Headley\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Maria Dahvana Headley\",\n  },\n  \"Book:{\\\\\"isbn\\\\\":\\\\\"0374110034\\\\\"}\": Object {\n    \"__typename\": \"Book\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Maria Dahvana Headley\\\\\"}\",\n    },\n    \"isbn\": \"0374110034\",\n    \"title\": \"Beowulf: A New Translation\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"currentlyReading\": Object {\n      \"__ref\": \"Book:{\\\\\"isbn\\\\\":\\\\\"0374110034\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`TypedDocumentNode<Data, Variables> should determine Data and Variables types of {write,read}{Query,Fragment} 1`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"John C. Mitchell\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"John C. Mitchell\",\n  },\n  \"Book:{\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"}\": Object {\n    \"__typename\": \"Book\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"John C. Mitchell\\\\\"}\",\n    },\n    \"isbn\": \"0262133210\",\n    \"title\": \"Foundations for Programming Languages\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"book({\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"})\": Object {\n      \"__ref\": \"Book:{\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`TypedDocumentNode<Data, Variables> should determine Data and Variables types of {write,read}{Query,Fragment} 2`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Harold Abelson\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Harold Abelson\",\n  },\n  \"Author:{\\\\\"name\\\\\":\\\\\"John C. Mitchell\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"John C. Mitchell\",\n  },\n  \"Book:{\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"}\": Object {\n    \"__typename\": \"Book\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"John C. Mitchell\\\\\"}\",\n    },\n    \"isbn\": \"0262133210\",\n    \"title\": \"Foundations for Programming Languages\",\n  },\n  \"Book:{\\\\\"isbn\\\\\":\\\\\"0262510871\\\\\"}\": Object {\n    \"__typename\": \"Book\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Harold Abelson\\\\\"}\",\n    },\n    \"isbn\": \"0262510871\",\n    \"title\": \"Structure and Interpretation of Computer Programs\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"book({\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"})\": Object {\n      \"__ref\": \"Book:{\\\\\"isbn\\\\\":\\\\\"0262133210\\\\\"}\",\n    },\n  },\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"Book:{\\\\\"isbn\\\\\":\\\\\"0262510871\\\\\"}\",\n    ],\n  },\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/entityStore.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`EntityStore ignores retainment count for ROOT_QUERY 1`] = `\nObject {\n  \"Author:Allie Brosh\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Allie Brosh\",\n  },\n  \"Book:1982156945\": Object {\n    \"__typename\": \"Book\",\n    \"author\": Object {\n      \"__ref\": \"Author:Allie Brosh\",\n    },\n    \"title\": \"Solutions and Other Problems\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"book\": Object {\n      \"__ref\": \"Book:1982156945\",\n    },\n  },\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"Author:Allie Brosh\",\n    ],\n  },\n}\n`;\n\nexports[`EntityStore ignores retainment count for ROOT_QUERY 2`] = `\nObject {\n  \"Author:Allie Brosh\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Allie Brosh\",\n  },\n  \"__META\": Object {\n    \"extraRootIds\": Array [\n      \"Author:Allie Brosh\",\n    ],\n  },\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/fragmentMatcher.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`policies.fragmentMatches can infer fuzzy subtypes heuristically 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"objects\": Array [\n      Object {\n        \"__typename\": \"E\",\n        \"c\": \"ce\",\n      },\n      Object {\n        \"__typename\": \"F\",\n        \"c\": \"cf\",\n      },\n      Object {\n        \"__typename\": \"G\",\n        \"c\": \"cg\",\n      },\n      Object {\n        \"__typename\": \"TooLong\",\n      },\n      Object {\n        \"__typename\": \"H\",\n      },\n    ],\n  },\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/policies.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`type policies can alter the root query __typename 1`] = `\nObject {\n  \"Query:0\": Object {\n    \"__typename\": \"Query\",\n    \"id\": 0,\n  },\n  \"Query:1\": Object {\n    \"__typename\": \"Query\",\n    \"id\": 1,\n  },\n  \"Query:2\": Object {\n    \"__typename\": \"Query\",\n    \"id\": 2,\n  },\n  \"Query:3\": Object {\n    \"__typename\": \"Query\",\n    \"id\": 3,\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"RootQuery\",\n    \"items\": Array [\n      Object {\n        \"id\": 0,\n        \"query\": Object {\n          \"__ref\": \"Query:0\",\n        },\n      },\n      Object {\n        \"id\": 1,\n        \"query\": Object {\n          \"__ref\": \"Query:1\",\n        },\n      },\n      Object {\n        \"id\": 2,\n        \"query\": Object {\n          \"__ref\": \"Query:2\",\n        },\n      },\n      Object {\n        \"id\": 3,\n        \"query\": Object {\n          \"__ref\": \"Query:3\",\n        },\n      },\n    ],\n  },\n}\n`;\n\nexports[`type policies complains about missing key fields 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"title\",\n      Object {\n        \"theInformationBookData\": Object {\n          \"__typename\": \"Book\",\n          \"author\": Object {\n            \"name\": \"James Gleick\",\n          },\n          \"isbn\": \"1400096235\",\n          \"subtitle\": \"A History, a Theory, a Flood\",\n          \"title\": \"The Information\",\n        },\n        \"year\": 2011,\n      },\n    ],\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"year\",\n      Object {\n        \"__typename\": \"Book\",\n        \"author\": Object {\n          \"name\": \"James Gleick\",\n        },\n        \"isbn\": \"1400096235\",\n        \"subtitle\": \"A History, a Theory, a Flood\",\n        \"title\": \"The Information\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 1`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 2`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 3`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": true,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 4`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 5`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Brooklyn Museum Apr 3rd – Aug 23rd 2015\",\n            \"displayLabel\": \"Basquiat: The Unknown Notebooks\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 6`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, born 1943, Los Angeles, California\",\n    \"displayLabel\": \"James Turrell\",\n    \"href\": \"/artist/james-turrell\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, 1960-1988, New York, New York, based in New York, New York\",\n    \"displayLabel\": \"Jean-Michel Basquiat\",\n    \"href\": \"/artist/jean-michel-basquiat\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Brooklyn Museum Apr 3rd – Aug 23rd 2015\",\n            \"displayLabel\": \"Basquiat: The Unknown Notebooks\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n    \"search:james turrell\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 13531,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 7`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, born 1943, Los Angeles, California\",\n    \"displayLabel\": \"James Turrell\",\n    \"href\": \"/artist/james-turrell\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Brooklyn Museum Apr 3rd – Aug 23rd 2015\",\n            \"displayLabel\": \"Basquiat: The Unknown Notebooks\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n    \"search:james turrell\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 13531,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination 8`] = `\nObject {\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"American, born 1943, Los Angeles, California\",\n    \"displayLabel\": \"James Turrell\",\n    \"href\": \"/artist/james-turrell\",\n  },\n  \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\": Object {\n    \"__typename\": \"Artist\",\n    \"bio\": \"\",\n    \"displayLabel\": \"Reminiscent of Basquiat\",\n    \"href\": \"/artist/reminiscent-of-basquiat\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"search:basquiat\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/jean-michel-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjE=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Damien Hirst, James Rosenquist, David Salle, Andy Warhol, Jeff Koons, Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, David Wojnarowicz, Taylor Mead, William S. Burroughs, Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n            \"displayLabel\": \"ephemera BASQUIAT\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n            \"displayLabel\": \"Jean-Michel Basquiat | Xerox\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjM=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Banksy, SEEN, JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n            \"displayLabel\": \"STREET ART: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat, Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, Kurar, and LARS at Artrust\",\n            \"displayLabel\": \"STREET ART 2: From Basquiat to Banksy\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjU=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/reminiscent-of-basquiat\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"Past show featuring works by Jean-Michel Basquiat at Brooklyn Museum Apr 3rd – Aug 23rd 2015\",\n            \"displayLabel\": \"Basquiat: The Unknown Notebooks\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjY=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 1292,\n    },\n    \"search:james turrell\": Object {\n      \"edges\": Array [\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n          \"node\": Object {\n            \"__ref\": \"Artist:{\\\\\"href\\\\\":\\\\\"/artist/james-turrell\\\\\"}\",\n          },\n        },\n        Object {\n          \"__typename\": \"SearchableEdge\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjEx\",\n          \"node\": Object {\n            \"__typename\": \"SearchableItem\",\n            \"description\": \"<placeholder for unknown description>\",\n            \"displayLabel\": \"James Turrell: Light knows when we’re looking\",\n          },\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjEx\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjA=\",\n      },\n      \"totalCount\": 13531,\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination without args 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"todos\": Object {\n      \"__typename\": \"TodosConnection\",\n      \"edges\": Array [\n        Object {\n          \"__ref\": \"TodoEdge:edge1\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n        },\n      ],\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n      },\n      \"totalCount\": 1292,\n    },\n  },\n  \"Todo:1\": Object {\n    \"__typename\": \"Todo\",\n    \"id\": \"1\",\n    \"title\": \"Fix the tests\",\n  },\n  \"TodoEdge:edge1\": Object {\n    \"__typename\": \"TodoEdge\",\n    \"id\": \"edge1\",\n    \"node\": Object {\n      \"__ref\": \"Todo:1\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can handle Relay-style pagination without args 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"todos\": Object {\n      \"__typename\": \"TodosConnection\",\n      \"edges\": Array [\n        Object {\n          \"__ref\": \"TodoEdge:edge1\",\n          \"cursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n        },\n      ],\n      \"extraMetaData\": \"extra\",\n      \"pageInfo\": Object {\n        \"__typename\": \"PageInfo\",\n        \"endCursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n        \"hasNextPage\": true,\n        \"hasPreviousPage\": false,\n        \"startCursor\": \"YXJyYXljb25uZWN0aW9uOjI=\",\n      },\n      \"totalCount\": 1293,\n    },\n  },\n  \"Todo:1\": Object {\n    \"__typename\": \"Todo\",\n    \"id\": \"1\",\n    \"title\": \"Fix the tests\",\n  },\n  \"TodoEdge:edge1\": Object {\n    \"__typename\": \"TodoEdge\",\n    \"id\": \"edge1\",\n    \"node\": Object {\n      \"__ref\": \"Todo:1\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 1`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 2`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 3`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 4`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 5`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":3}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 6`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":3}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 7`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":3}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":4}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies can include optional arguments in field keyArgs policy 8`] = `\nObject {\n  \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\": Object {\n    \"__typename\": \"Author\",\n    \"name\": \"Nadia Eghbal\",\n    \"writings\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2,\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":1,\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"a\\\\\":3}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":2}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"b\\\\\":4}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{\\\\\"type\\\\\":\\\\\"Book\\\\\"}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n    \"writings:{}\": Array [\n      Object {\n        \"__typename\": \"Book\",\n        \"isbn\": \"0578675862\",\n        \"title\": \"Working in Public: The Making and Maintenance of Open Source Software\",\n      },\n    ],\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"author\": Object {\n      \"__ref\": \"Author:{\\\\\"name\\\\\":\\\\\"Nadia Eghbal\\\\\"}\",\n    },\n  },\n}\n`;\n\nexports[`type policies field policies read, merge, and modify functions can access options.storage 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"mergeModify\": 11,\n    \"mergeRead\": 1,\n    \"mergeReadModify\": 101,\n  },\n}\n`;\n\nexports[`type policies field policies read, merge, and modify functions can access options.storage 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"mergeModify\": 11,\n    \"mergeRead\": 1,\n    \"mergeReadModify\": 101,\n  },\n}\n`;\n\nexports[`type policies field policies readField helper function calls custom read functions 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"blockers\",\n      Object {\n        \"__typename\": \"Task\",\n        \"description\": \"grandchild task\",\n        \"id\": 4,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`type policies field policies runs nested merge functions as well as ancestors 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"time\",\n      Object {\n        \"__typename\": \"Event\",\n        \"id\": 123,\n      },\n    ],\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"time\",\n      Object {\n        \"__typename\": \"Event\",\n        \"attendees\": Array [\n          Object {\n            \"__typename\": \"Attendee\",\n            \"id\": 456,\n            \"name\": \"Inspector Beckett\",\n          },\n          Object {\n            \"__typename\": \"Attendee\",\n            \"id\": 234,\n          },\n        ],\n        \"id\": 345,\n        \"name\": \"Rooftop dog party\",\n      },\n    ],\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"name\",\n      Object {\n        \"__typename\": \"Attendee\",\n        \"id\": 234,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`type policies readField warns if explicitly passed undefined \\`from\\` option 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Undefined 'from' passed to readField with arguments %s\",\n      \"[{\\\\\"fieldName\\\\\":\\\\\"firstName\\\\\",\\\\\"from\\\\\":<undefined>}]\",\n    ],\n    Array [\n      \"Undefined 'from' passed to readField with arguments %s\",\n      \"[\\\\\"lastName\\\\\",<undefined>]\",\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`type policies support inheritance 1`] = `\nObject {\n  \"Cobra:{\\\\\"tagId\\\\\":\\\\\"Egypt30BC\\\\\"}\": Object {\n    \"__typename\": \"Cobra\",\n    \"scientificName\": \"naja haje\",\n    \"tagId\": \"Egypt30BC\",\n    \"venomous\": true,\n  },\n  \"Cottonmouth:{\\\\\"tagId\\\\\":\\\\\"CM420\\\\\"}\": Object {\n    \"__typename\": \"Cottonmouth\",\n    \"scientificName\": \"agkistrodon piscivorus\",\n    \"tagId\": \"CM420\",\n    \"venomous\": true,\n  },\n  \"Python:{\\\\\"tagId\\\\\":\\\\\"BigHug4U\\\\\"}\": Object {\n    \"__typename\": \"Python\",\n    \"scientificName\": \"malayopython reticulatus\",\n    \"tagId\": \"BigHug4U\",\n    \"venomous\": false,\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"reptiles\": Array [\n      Object {\n        \"__ref\": \"Turtle:{\\\\\"tagId\\\\\":\\\\\"RedEaredSlider42\\\\\"}\",\n      },\n      Object {\n        \"__ref\": \"Python:{\\\\\"tagId\\\\\":\\\\\"BigHug4U\\\\\"}\",\n      },\n      Object {\n        \"__ref\": \"Cobra:{\\\\\"tagId\\\\\":\\\\\"Egypt30BC\\\\\"}\",\n      },\n      Object {\n        \"__ref\": \"Cottonmouth:{\\\\\"tagId\\\\\":\\\\\"CM420\\\\\"}\",\n      },\n    ],\n  },\n  \"Turtle:{\\\\\"tagId\\\\\":\\\\\"RedEaredSlider42\\\\\"}\": Object {\n    \"__typename\": \"Turtle\",\n    \"scientificName\": \"trachemys scripta elegans\",\n    \"tagId\": \"RedEaredSlider42\",\n  },\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/roundtrip.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`roundtrip fragments should throw an error on two of the same inline fragment types 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"rank\",\n      Object {\n        \"__typename\": \"Jedi\",\n        \"name\": \"Luke Skywalker\",\n        \"side\": \"bright\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`roundtrip fragments should throw on error on two of the same spread fragment types 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"rank\",\n      Object {\n        \"__typename\": \"Jedi\",\n        \"name\": \"Luke Skywalker\",\n        \"side\": \"bright\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/__snapshots__/writeToStore.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should not warn when scalar fields are updated 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"currentTime({\\\\\"tz\\\\\":\\\\\"UTC-5\\\\\"})\": Object {\n      \"localeString\": \"9/25/2020, 1:08:33 PM\",\n    },\n    \"someJSON\": Object {\n      \"foos\": Array [\n        \"bar\",\n        \"baz\",\n      ],\n      \"oyez\": 3,\n    },\n  },\n}\n`;\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should not warn when scalar fields are updated 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"currentTime({\\\\\"tz\\\\\":\\\\\"UTC-5\\\\\"})\": Object {\n      \"msSinceEpoch\": 1601053713081,\n    },\n    \"someJSON\": Object {\n      \"asdf\": \"middle\",\n      \"qwer\": \"upper\",\n      \"zxcv\": \"lower\",\n    },\n  },\n}\n`;\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should not warn when scalar fields are updated 3`] = `[MockFunction]`;\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should warn \"Cache data may be lost...\" message 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"someJSON\": Object {\n      \"name\": \"Tom\",\n    },\n  },\n}\n`;\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should warn \"Cache data may be lost...\" message 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"someJSON\": Object {\n      \"age\": 20,\n    },\n  },\n}\n`;\n\nexports[`writing to the store \"Cache data may be lost...\" warnings should warn \"Cache data may be lost...\" message 3`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Cache data may be lost when replacing the %s field of a %s object.\n\nThis could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.\n\nTo address this problem (which is not a bug in Apollo Client), %sdefine a custom merge function for the %s field, so InMemoryCache can safely merge these objects:\n\n  existing: %o\n  incoming: %o\n\nFor more information about these options, please refer to the documentation:\n\n  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n\",\n      \"someJSON\",\n      \"Query\",\n      \"\",\n      \"Query.someJSON\",\n      Object {\n        \"name\": \"Tom\",\n      },\n      Object {\n        \"age\": 20,\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`writing to the store correctly merges fragment fields along multiple paths 1`] = `\nObject {\n  \"Item:0f47f85d-8081-466e-9121-c94069a77c3e\": Object {\n    \"__typename\": \"Item\",\n    \"id\": \"0f47f85d-8081-466e-9121-c94069a77c3e\",\n    \"value\": Object {\n      \"__typename\": \"Container\",\n      \"value\": Object {\n        \"__typename\": \"Value\",\n        \"item\": Object {\n          \"__ref\": \"Item:6dc3530b-6731-435e-b12a-0089d0ae05ac\",\n        },\n      },\n    },\n  },\n  \"Item:6dc3530b-6731-435e-b12a-0089d0ae05ac\": Object {\n    \"__typename\": \"Item\",\n    \"id\": \"6dc3530b-6731-435e-b12a-0089d0ae05ac\",\n    \"value\": Object {\n      \"__typename\": \"Container\",\n      \"text\": \"Hello World\",\n      \"value\": Object {\n        \"__typename\": \"Value\",\n      },\n    },\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"item({\\\\\"id\\\\\":\\\\\"123\\\\\"})\": Object {\n      \"__ref\": \"Item:0f47f85d-8081-466e-9121-c94069a77c3e\",\n    },\n  },\n}\n`;\n\nexports[`writing to the store should not keep reference when type of mixed inlined field changes to non-inlined field 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"id\",\n      Object {\n        \"__typename\": \"Cat\",\n        \"name\": \"cat\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`writing to the store should respect id fields added by fragments 1`] = `\nObject {\n  \"AType:a-id\": Object {\n    \"__typename\": \"AType\",\n    \"b\": Array [\n      Object {\n        \"__ref\": \"BType:b-id\",\n      },\n    ],\n    \"id\": \"a-id\",\n  },\n  \"BType:b-id\": Object {\n    \"__typename\": \"BType\",\n    \"c\": Object {\n      \"__typename\": \"CType\",\n      \"title\": \"Your experience\",\n      \"titleSize\": null,\n    },\n    \"id\": \"b-id\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"a\": Object {\n      \"__ref\": \"AType:a-id\",\n    },\n  },\n}\n`;\n\nexports[`writing to the store user objects should be able to have { __typename: \"Mutation\" } 1`] = `\nObject {\n  \"Gene:{\\\\\"id\\\\\":\\\\\"SLC45A2\\\\\"}\": Object {\n    \"__typename\": \"Gene\",\n    \"id\": \"SLC45A2\",\n  },\n  \"Gene:{\\\\\"id\\\\\":\\\\\"SNAI2\\\\\"}\": Object {\n    \"__typename\": \"Gene\",\n    \"id\": \"SNAI2\",\n  },\n  \"Mutation:{\\\\\"gene\\\\\":{\\\\\"id\\\\\":\\\\\"SLC45A2\\\\\"},\\\\\"name\\\\\":\\\\\"albinism\\\\\"}\": Object {\n    \"__typename\": \"Mutation\",\n    \"gene\": Object {\n      \"__ref\": \"Gene:{\\\\\"id\\\\\":\\\\\"SLC45A2\\\\\"}\",\n      \"id\": \"SLC45A2\",\n    },\n    \"name\": \"albinism\",\n  },\n  \"Mutation:{\\\\\"gene\\\\\":{\\\\\"id\\\\\":\\\\\"SNAI2\\\\\"},\\\\\"name\\\\\":\\\\\"piebaldism\\\\\"}\": Object {\n    \"__typename\": \"Mutation\",\n    \"gene\": Object {\n      \"__ref\": \"Gene:{\\\\\"id\\\\\":\\\\\"SNAI2\\\\\"}\",\n      \"id\": \"SNAI2\",\n    },\n    \"name\": \"piebaldism\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"mutations\": Array [\n      Object {\n        \"__ref\": \"Mutation:{\\\\\"gene\\\\\":{\\\\\"id\\\\\":\\\\\"SLC45A2\\\\\"},\\\\\"name\\\\\":\\\\\"albinism\\\\\"}\",\n      },\n      Object {\n        \"__ref\": \"Mutation:{\\\\\"gene\\\\\":{\\\\\"id\\\\\":\\\\\"SNAI2\\\\\"},\\\\\"name\\\\\":\\\\\"piebaldism\\\\\"}\",\n      },\n    ],\n  },\n}\n`;\n\nexports[`writing to the store user objects should be able to have { __typename: \"Subscription\" } 1`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"subscriptions\": Array [\n      Object {\n        \"__ref\": \"Subscription:{\\\\\"subId\\\\\":1}\",\n      },\n      Object {\n        \"__ref\": \"Subscription:{\\\\\"subId\\\\\":2}\",\n      },\n      Object {\n        \"__ref\": \"Subscription:{\\\\\"subId\\\\\":3}\",\n      },\n    ],\n  },\n  \"Subscription:{\\\\\"subId\\\\\":1}\": Object {\n    \"__typename\": \"Subscription\",\n    \"subId\": 1,\n    \"subscriber\": Object {\n      \"name\": \"Alice\",\n    },\n  },\n  \"Subscription:{\\\\\"subId\\\\\":2}\": Object {\n    \"__typename\": \"Subscription\",\n    \"subId\": 2,\n    \"subscriber\": Object {\n      \"name\": \"Bob\",\n    },\n  },\n  \"Subscription:{\\\\\"subId\\\\\":3}\": Object {\n    \"__typename\": \"Subscription\",\n    \"subId\": 3,\n    \"subscriber\": Object {\n      \"name\": \"Clytemnestra\",\n    },\n  },\n}\n`;\n\nexports[`writing to the store writeResultToStore shape checking should not warn if a field is deferred 1`] = `[MockFunction]`;\n\nexports[`writing to the store writeResultToStore shape checking should warn when it receives the wrong data inside a fragment 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"price\",\n      Object {\n        \"__typename\": \"ShoppingCartItem\",\n        \"description\": \"Description 1\",\n        \"id\": \"1\",\n        \"name\": \"Todo 1\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`writing to the store writeResultToStore shape checking should warn when it receives the wrong data with non-union fragments 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"description\",\n      Object {\n        \"id\": \"1\",\n        \"name\": \"Todo 1\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n\nexports[`writing to the store writeResultToStore shape checking should write the result data without validating its shape when a fragment matcher is not provided 1`] = `\n[MockFunction] {\n  \"calls\": Array [\n    Array [\n      \"Missing field '%s' while writing result %o\",\n      \"description\",\n      Object {\n        \"id\": \"1\",\n        \"name\": \"Todo 1\",\n      },\n    ],\n  ],\n  \"results\": Array [\n    Object {\n      \"type\": \"return\",\n      \"value\": undefined,\n    },\n  ],\n}\n`;\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/cache.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\nimport { disableFragmentWarnings, gql } from \"graphql-tag\";\n\nimport type {\n  DocumentNode,\n  Reference,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { isReference, makeVar } from \"@apollo/client\";\nimport type { Cache, InMemoryCacheConfig } from \"@apollo/client/cache\";\nimport { InMemoryCache, MissingFieldError } from \"@apollo/client/cache\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { cloneDeep, makeReference } from \"@apollo/client/utilities/internal\";\n\nimport { defaultCacheSizes } from \"../../../utilities/caching/sizes.js\";\n\ndisableFragmentWarnings();\n\ndescribe(\"Cache\", () => {\n  function itWithInitialData(\n    message: string,\n    initialDataForCaches: { [key: string]: any }[],\n    callback: (...caches: InMemoryCache[]) => any\n  ) {\n    const cachesList: InMemoryCache[][] = [\n      initialDataForCaches.map((data) =>\n        new InMemoryCache().restore(cloneDeep(data))\n      ),\n      initialDataForCaches.map((data) =>\n        new InMemoryCache({\n          resultCaching: false,\n        }).restore(cloneDeep(data))\n      ),\n    ];\n\n    cachesList.forEach((caches, i) => {\n      it(`${message} (${i + 1}/${cachesList.length})`, () =>\n        callback(...caches));\n    });\n  }\n\n  function itWithCacheConfig(\n    message: string,\n    config: InMemoryCacheConfig,\n    callback: (cache: InMemoryCache) => any\n  ) {\n    const caches = [\n      new InMemoryCache({\n        ...config,\n        resultCaching: true,\n      }),\n      new InMemoryCache({\n        ...config,\n        resultCaching: false,\n      }),\n    ];\n\n    caches.forEach((cache, i) => {\n      it(message + ` (${i + 1}/${caches.length})`, () => callback(cache));\n    });\n  }\n\n  describe(\"readQuery\", () => {\n    itWithInitialData(\n      \"will read some data from the store\",\n      [\n        {\n          ROOT_QUERY: {\n            a: 1,\n            b: 2,\n            c: 3,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                a\n              }\n            `,\n          })\n        ).toEqual({ a: 1 });\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                b\n                c\n              }\n            `,\n          })\n        ).toEqual({ b: 2, c: 3 });\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                a\n                b\n                c\n              }\n            `,\n          })\n        ).toEqual({ a: 1, b: 2, c: 3 });\n      }\n    );\n\n    itWithInitialData(\n      \"will read some deeply nested data from the store\",\n      [\n        {\n          ROOT_QUERY: {\n            a: 1,\n            b: 2,\n            c: 3,\n            d: makeReference(\"foo\"),\n          },\n          foo: {\n            e: 4,\n            f: 5,\n            g: 6,\n            h: makeReference(\"bar\"),\n          },\n          bar: {\n            i: 7,\n            j: 8,\n            k: 9,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                a\n                d {\n                  e\n                }\n              }\n            `,\n          })\n        ).toEqual({ a: 1, d: { e: 4 } });\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                a\n                d {\n                  e\n                  h {\n                    i\n                  }\n                }\n              }\n            `,\n          })\n        ).toEqual({ a: 1, d: { e: 4, h: { i: 7 } } });\n        expect(\n          proxy.readQuery({\n            query: gql`\n              {\n                a\n                b\n                c\n                d {\n                  e\n                  f\n                  g\n                  h {\n                    i\n                    j\n                    k\n                  }\n                }\n              }\n            `,\n          })\n        ).toEqual({\n          a: 1,\n          b: 2,\n          c: 3,\n          d: { e: 4, f: 5, g: 6, h: { i: 7, j: 8, k: 9 } },\n        });\n      }\n    );\n\n    itWithInitialData(\n      \"will read some data from the store with variables\",\n      [\n        {\n          ROOT_QUERY: {\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readQuery({\n            query: gql`\n              query ($literal: Boolean, $value: Int) {\n                a: field(literal: true, value: 42)\n                b: field(literal: $literal, value: $value)\n              }\n            `,\n            variables: {\n              literal: false,\n              value: 42,\n            },\n          })\n        ).toEqual({ a: 1, b: 2 });\n      }\n    );\n\n    itWithInitialData(\n      \"will read some data from the store with null variables\",\n      [\n        {\n          ROOT_QUERY: {\n            'field({\"literal\":false,\"value\":null})': 1,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readQuery({\n            query: gql`\n              query ($literal: Boolean, $value: Int) {\n                a: field(literal: $literal, value: $value)\n              }\n            `,\n            variables: {\n              literal: false,\n              value: null,\n            },\n          })\n        ).toEqual({ a: 1 });\n      }\n    );\n\n    itWithInitialData(\n      \"should not mutate arguments passed in\",\n      [\n        {\n          ROOT_QUERY: {\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        },\n      ],\n      (proxy) => {\n        const options = {\n          query: gql`\n            query ($literal: Boolean, $value: Int) {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: 42,\n          },\n        };\n\n        const preQueryCopy = cloneDeep(options);\n        expect(proxy.readQuery(options)).toEqual({ a: 1, b: 2 });\n        expect(preQueryCopy).toEqual(options);\n      }\n    );\n  });\n\n  describe(\"readFragment\", () => {\n    itWithInitialData(\n      \"will throw an error when there is no fragment\",\n      [\n        // Empty data, but still want to test with/without result caching.\n        {},\n      ],\n      (proxy) => {\n        expect(() => {\n          proxy.readFragment({\n            id: \"x\",\n            fragment: gql`\n              query {\n                a\n                b\n                c\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n        );\n        expect(() => {\n          proxy.readFragment({\n            id: \"x\",\n            fragment: gql`\n              schema {\n                query: Query\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 0 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n      }\n    );\n\n    itWithInitialData(\n      \"will throw an error when there is more than one fragment but no fragment name\",\n      [{}],\n      (proxy) => {\n        expect(() => {\n          proxy.readFragment({\n            id: \"x\",\n            fragment: gql`\n              fragment a on A {\n                a\n              }\n\n              fragment b on B {\n                b\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n        expect(() => {\n          proxy.readFragment({\n            id: \"x\",\n            fragment: gql`\n              fragment a on A {\n                a\n              }\n\n              fragment b on B {\n                b\n              }\n\n              fragment c on C {\n                c\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 3 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n      }\n    );\n\n    itWithInitialData(\n      \"will read some deeply nested data from the store at any id\",\n      [\n        {\n          ROOT_QUERY: {\n            __typename: \"Type1\",\n            a: 1,\n            b: 2,\n            c: 3,\n            d: makeReference(\"foo\"),\n          },\n          foo: {\n            __typename: \"Foo\",\n            e: 4,\n            f: 5,\n            g: 6,\n            h: makeReference(\"bar\"),\n          },\n          bar: {\n            __typename: \"Bar\",\n            i: 7,\n            j: 8,\n            k: 9,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fragmentFoo on Foo {\n                e\n                h {\n                  i\n                }\n              }\n            `,\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, h: { __typename: \"Bar\", i: 7 } });\n        expect(\n          proxy.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fragmentFoo on Foo {\n                e\n                f\n                g\n                h {\n                  i\n                  j\n                  k\n                }\n              }\n            `,\n          })\n        ).toEqual({\n          __typename: \"Foo\",\n          e: 4,\n          f: 5,\n          g: 6,\n          h: { __typename: \"Bar\", i: 7, j: 8, k: 9 },\n        });\n        expect(\n          proxy.readFragment({\n            id: \"bar\",\n            fragment: gql`\n              fragment fragmentBar on Bar {\n                i\n              }\n            `,\n          })\n        ).toEqual({ __typename: \"Bar\", i: 7 });\n        expect(\n          proxy.readFragment({\n            id: \"bar\",\n            fragment: gql`\n              fragment fragmentBar on Bar {\n                i\n                j\n                k\n              }\n            `,\n          })\n        ).toEqual({ __typename: \"Bar\", i: 7, j: 8, k: 9 });\n        expect(\n          proxy.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fragmentFoo on Foo {\n                e\n                f\n                g\n                h {\n                  i\n                  j\n                  k\n                }\n              }\n\n              fragment fragmentBar on Bar {\n                i\n                j\n                k\n              }\n            `,\n            fragmentName: \"fragmentFoo\",\n          })\n        ).toEqual({\n          __typename: \"Foo\",\n          e: 4,\n          f: 5,\n          g: 6,\n          h: { __typename: \"Bar\", i: 7, j: 8, k: 9 },\n        });\n        expect(\n          proxy.readFragment({\n            id: \"bar\",\n            fragment: gql`\n              fragment fragmentFoo on Foo {\n                e\n                f\n                g\n                h {\n                  i\n                  j\n                  k\n                }\n              }\n\n              fragment fragmentBar on Bar {\n                i\n                j\n                k\n              }\n            `,\n            fragmentName: \"fragmentBar\",\n          })\n        ).toEqual({ __typename: \"Bar\", i: 7, j: 8, k: 9 });\n      }\n    );\n\n    itWithInitialData(\n      \"will read some data from the store with `from`\",\n      [\n        {\n          \"Foo:1\": {\n            __typename: \"Foo\",\n            id: 1,\n            e: 4,\n            f: 5,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            from: { __typename: \"Foo\", id: 1 },\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n\n        expect(\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            from: { __ref: \"Foo:1\" },\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n\n        expect(\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            from: \"Foo:1\",\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n      }\n    );\n\n    itWithInitialData(\n      \"prefers `from` over `id`\",\n      [\n        {\n          \"Foo:1\": {\n            __typename: \"Foo\",\n            id: 1,\n            e: 4,\n            f: 5,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          // @ts-expect-error types don't allow `id` and `from`\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            id: \"unknown\",\n            from: { __typename: \"Foo\", id: 1 },\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n\n        expect(\n          // @ts-expect-error types don't allow `id` and `from`\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            id: \"unknown\",\n            from: { __ref: \"Foo:1\" },\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n\n        expect(\n          // @ts-expect-error types don't allow `id` and `from`\n          proxy.readFragment({\n            fragment: gql`\n              fragment foo on Foo {\n                e\n                f\n              }\n            `,\n            id: \"unknown\",\n            from: \"Foo:1\",\n          })\n        ).toEqual({ __typename: \"Foo\", e: 4, f: 5 });\n      }\n    );\n\n    itWithInitialData(\n      \"will read some data from the store with variables\",\n      [\n        {\n          foo: {\n            __typename: \"Foo\",\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        },\n      ],\n      (proxy) => {\n        expect(\n          proxy.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment foo on Foo {\n                a: field(literal: true, value: 42)\n                b: field(literal: $literal, value: $value)\n              }\n            `,\n            variables: {\n              literal: false,\n              value: 42,\n            },\n          })\n        ).toEqual({ __typename: \"Foo\", a: 1, b: 2 });\n      }\n    );\n\n    itWithInitialData(\n      \"will return null when an id that can’t be found is provided\",\n      [\n        // client1\n        {},\n        // client2\n        {\n          bar: { __typename: \"Bar\", a: 1, b: 2, c: 3 },\n        },\n        // client3\n        {\n          foo: { __typename: \"Foo\", a: 1, b: 2, c: 3 },\n        },\n      ],\n      (client1, client2, client3) => {\n        expect(\n          client1.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fooFragment on Foo {\n                a\n                b\n                c\n              }\n            `,\n          })\n        ).toEqual(null);\n        expect(\n          client2.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fooFragment on Foo {\n                a\n                b\n                c\n              }\n            `,\n          })\n        ).toEqual(null);\n        expect(\n          client3.readFragment({\n            id: \"foo\",\n            fragment: gql`\n              fragment fooFragment on Foo {\n                a\n                b\n                c\n              }\n            `,\n          })\n        ).toEqual({ __typename: \"Foo\", a: 1, b: 2, c: 3 });\n      }\n    );\n\n    it(\"should not accidentally depend on unrelated entity fields\", () => {\n      const cache = new InMemoryCache({\n        resultCaching: true,\n      });\n\n      const bothNamesData = {\n        __typename: \"Person\",\n        id: 123,\n        firstName: \"Ben\",\n        lastName: \"Newman\",\n      };\n\n      const firstNameQuery = gql`\n        {\n          firstName\n        }\n      `;\n      const lastNameQuery = gql`\n        {\n          lastName\n        }\n      `;\n\n      const id = cache.identify(bothNamesData);\n\n      cache.writeQuery({\n        id,\n        query: firstNameQuery,\n        data: bothNamesData,\n      });\n\n      const meta123 = {\n        extraRootIds: [\"Person:123\"],\n      };\n\n      expect(cache.extract()).toEqual({\n        __META: meta123,\n        \"Person:123\": {\n          __typename: \"Person\",\n          id: 123,\n          firstName: \"Ben\",\n        },\n      });\n\n      const firstNameResult = cache.readQuery({\n        id,\n        query: firstNameQuery,\n      });\n\n      expect(firstNameResult).toEqual({\n        __typename: \"Person\",\n        firstName: \"Ben\",\n      });\n\n      cache.writeQuery({\n        id,\n        query: lastNameQuery,\n        data: bothNamesData,\n      });\n\n      expect(cache.extract()).toEqual({\n        __META: meta123,\n        \"Person:123\": {\n          __typename: \"Person\",\n          id: 123,\n          firstName: \"Ben\",\n          lastName: \"Newman\",\n        },\n      });\n\n      // This is the crucial test: modifying the lastName field should not\n      // invalidate results that did not depend on the lastName field.\n      expect(\n        cache.readQuery({\n          id,\n          query: firstNameQuery,\n        })\n      ).toBe(firstNameResult);\n\n      const lastNameResult = cache.readQuery({\n        id,\n        query: lastNameQuery,\n      });\n\n      expect(lastNameResult).toEqual({\n        __typename: \"Person\",\n        lastName: \"Newman\",\n      });\n\n      cache.writeQuery({\n        id,\n        query: firstNameQuery,\n        data: {\n          ...bothNamesData,\n          firstName: \"Benjamin\",\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        __META: meta123,\n        \"Person:123\": {\n          __typename: \"Person\",\n          id: 123,\n          firstName: \"Benjamin\",\n          lastName: \"Newman\",\n        },\n      });\n\n      const benjaminResult = cache.readQuery({\n        id,\n        query: firstNameQuery,\n      });\n\n      expect(benjaminResult).toEqual({\n        __typename: \"Person\",\n        firstName: \"Benjamin\",\n      });\n\n      // Still the same as it was?\n      expect(firstNameResult).toEqual({\n        __typename: \"Person\",\n        firstName: \"Ben\",\n      });\n\n      // Updating the firstName should not have invalidated the\n      // previously-read lastNameResult.\n      expect(\n        cache.readQuery({\n          id,\n          query: lastNameQuery,\n        })\n      ).toBe(lastNameResult);\n    });\n\n    it(\"should not return null when ID found in optimistic layer\", () => {\n      const cache = new InMemoryCache();\n\n      const fragment = gql`\n        fragment NameFragment on Person {\n          firstName\n          lastName\n        }\n      `;\n\n      const data = {\n        __typename: \"Person\",\n        id: 321,\n        firstName: \"Hugh\",\n        lastName: \"Willson\",\n      };\n\n      const id = cache.identify(data)!;\n\n      cache.recordOptimisticTransaction((proxy) => {\n        proxy.writeFragment({ id, fragment, data });\n      }, \"optimistic Hugh\");\n\n      expect(cache.extract(false)).toEqual({});\n      expect(cache.extract(true)).toEqual({\n        __META: {\n          extraRootIds: [\"Person:321\"],\n        },\n        \"Person:321\": {\n          __typename: \"Person\",\n          id: 321,\n          firstName: \"Hugh\",\n          lastName: \"Willson\",\n        },\n      });\n\n      expect(\n        cache.readFragment(\n          { id, fragment },\n          false // not optimistic\n        )\n      ).toBe(null);\n\n      expect(\n        cache.readFragment(\n          { id, fragment },\n          true // optimistic\n        )\n      ).toEqual({\n        __typename: \"Person\",\n        firstName: \"Hugh\",\n        lastName: \"Willson\",\n      });\n\n      cache.writeFragment({\n        id,\n        fragment,\n        data: {\n          ...data,\n          firstName: \"HUGH\",\n          lastName: \"WILLSON\",\n        },\n      });\n\n      expect(\n        cache.readFragment(\n          { id, fragment },\n          false // not optimistic\n        )\n      ).toEqual({\n        __typename: \"Person\",\n        firstName: \"HUGH\",\n        lastName: \"WILLSON\",\n      });\n\n      expect(\n        cache.readFragment(\n          { id, fragment },\n          true // optimistic\n        )\n      ).toEqual({\n        __typename: \"Person\",\n        firstName: \"Hugh\",\n        lastName: \"Willson\",\n      });\n\n      cache.removeOptimistic(\"optimistic Hugh\");\n\n      expect(\n        cache.readFragment(\n          { id, fragment },\n          true // optimistic\n        )\n      ).toEqual({\n        __typename: \"Person\",\n        firstName: \"HUGH\",\n        lastName: \"WILLSON\",\n      });\n    });\n  });\n\n  describe(\"writeQuery\", () => {\n    itWithInitialData(\"will write some data to the store\", [{}], (proxy) => {\n      proxy.writeQuery({\n        data: { a: 1 },\n        query: gql`\n          {\n            a\n          }\n        `,\n      });\n\n      expect((proxy as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n        },\n      });\n\n      proxy.writeQuery({\n        data: { b: 2, c: 3 },\n        query: gql`\n          {\n            b\n            c\n          }\n        `,\n      });\n\n      expect((proxy as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          c: 3,\n        },\n      });\n\n      proxy.writeQuery({\n        data: { a: 4, b: 5, c: 6 },\n        query: gql`\n          {\n            a\n            b\n            c\n          }\n        `,\n      });\n\n      expect((proxy as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 4,\n          b: 5,\n          c: 6,\n        },\n      });\n    });\n\n    it(\"will write some deeply nested data to the store\", () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              d: {\n                // Deliberately silence \"Cache data may be lost...\"\n                // warnings by unconditionally favoring the incoming data.\n                merge: false,\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        data: { a: 1, d: { e: 4 } },\n        query: gql`\n          {\n            a\n            d {\n              e\n            }\n          }\n        `,\n      });\n\n      expect((cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          d: {\n            e: 4,\n          },\n        },\n      });\n\n      cache.writeQuery({\n        data: { a: 1, d: { h: { i: 7 } } },\n        query: gql`\n          {\n            a\n            d {\n              h {\n                i\n              }\n            }\n          }\n        `,\n      });\n\n      expect((cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          // The new value for d overwrites the old value, since there\n          // is no custom merge function defined for Query.d.\n          d: {\n            h: {\n              i: 7,\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        data: {\n          a: 1,\n          b: 2,\n          c: 3,\n          d: { e: 4, f: 5, g: 6, h: { i: 7, j: 8, k: 9 } },\n        },\n        query: gql`\n          {\n            a\n            b\n            c\n            d {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n          }\n        `,\n      });\n\n      expect((cache as InMemoryCache).extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          a: 1,\n          b: 2,\n          c: 3,\n          d: {\n            e: 4,\n            f: 5,\n            g: 6,\n            h: {\n              i: 7,\n              j: 8,\n              k: 9,\n            },\n          },\n        },\n      });\n    });\n\n    itWithInitialData(\n      \"will write some data to the store with variables\",\n      [{}],\n      (proxy) => {\n        proxy.writeQuery({\n          data: {\n            a: 1,\n            b: 2,\n          },\n          query: gql`\n            query ($literal: Boolean, $value: Int) {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: 42,\n          },\n        });\n\n        expect((proxy as InMemoryCache).extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        });\n      }\n    );\n\n    itWithInitialData(\n      \"will write some data to the store with variables where some are null\",\n      [{}],\n      (proxy) => {\n        proxy.writeQuery({\n          data: {\n            a: 1,\n            b: 2,\n          },\n          query: gql`\n            query ($literal: Boolean, $value: Int) {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: null,\n          },\n        });\n\n        expect((proxy as InMemoryCache).extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":null})': 2,\n          },\n        });\n      }\n    );\n\n    it(\"does not write @stream directive as part of the cache key\", () => {\n      const cache = new InMemoryCache();\n\n      cache.writeQuery({\n        data: {\n          list: [{ __typename: \"Item\", id: \"1\", value: 1 }],\n        },\n        query: gql`\n          query {\n            list @stream(initialCount: 1) {\n              id\n              value\n            }\n          }\n        `,\n      });\n\n      expect(cache.extract()).toStrictEqualTyped({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          list: [{ __ref: \"Item:1\" }],\n        },\n        \"Item:1\": { __typename: \"Item\", id: \"1\", value: 1 },\n      });\n\n      // We should be able to read the list without the `@stream` directive and\n      // get back results\n      expect(\n        cache.readQuery({\n          query: gql`\n            query {\n              list {\n                id\n                value\n              }\n            }\n          `,\n        })\n      ).toStrictEqualTyped({\n        list: [{ __typename: \"Item\", id: \"1\", value: 1 }],\n      });\n    });\n  });\n\n  describe(\"writeFragment\", () => {\n    itWithInitialData(\n      \"will throw an error when there is no fragment\",\n      [{}],\n      (proxy) => {\n        expect(() => {\n          proxy.writeFragment({\n            data: {},\n            id: \"x\",\n            fragment: gql`\n              query {\n                a\n                b\n                c\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n        );\n        expect(() => {\n          proxy.writeFragment({\n            data: {},\n            id: \"x\",\n            fragment: gql`\n              schema {\n                query: Query\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 0 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n      }\n    );\n\n    itWithInitialData(\n      \"will throw an error when there is more than one fragment but no fragment name\",\n      [{}],\n      (proxy) => {\n        expect(() => {\n          proxy.writeFragment({\n            data: {},\n            id: \"x\",\n            fragment: gql`\n              fragment a on A {\n                a\n              }\n\n              fragment b on B {\n                b\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n        expect(() => {\n          proxy.writeFragment({\n            data: {},\n            id: \"x\",\n            fragment: gql`\n              fragment a on A {\n                a\n              }\n\n              fragment b on B {\n                b\n              }\n\n              fragment c on C {\n                c\n              }\n            `,\n          });\n        }).toThrow(\n          \"Found 3 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n        );\n      }\n    );\n\n    itWithCacheConfig(\n      \"will write some deeply nested data into the store at any id\",\n      {\n        dataIdFromObject: (o: any) => o.id,\n      },\n      (proxy) => {\n        proxy.writeFragment({\n          data: { __typename: \"Foo\", e: 4, h: { id: \"bar\", i: 7 } },\n          id: \"foo\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              e\n              h {\n                i\n              }\n            }\n          `,\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n        proxy.writeFragment({\n          data: { __typename: \"Foo\", f: 5, g: 6, h: { id: \"bar\", j: 8, k: 9 } },\n          id: \"foo\",\n          fragment: gql`\n            fragment fragmentFoo on Foo {\n              f\n              g\n              h {\n                j\n                k\n              }\n            }\n          `,\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n\n        proxy.writeFragment({\n          data: { i: 10, __typename: \"Bar\" },\n          id: \"bar\",\n          fragment: gql`\n            fragment fragmentBar on Bar {\n              i\n            }\n          `,\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n\n        proxy.writeFragment({\n          data: { j: 11, k: 12, __typename: \"Bar\" },\n          id: \"bar\",\n          fragment: gql`\n            fragment fragmentBar on Bar {\n              j\n              k\n            }\n          `,\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n\n        proxy.writeFragment({\n          data: {\n            __typename: \"Foo\",\n            e: 4,\n            f: 5,\n            g: 6,\n            h: { __typename: \"Bar\", id: \"bar\", i: 7, j: 8, k: 9 },\n          },\n          id: \"foo\",\n          fragment: gql`\n            fragment fooFragment on Foo {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n\n            fragment barFragment on Bar {\n              i\n              j\n              k\n            }\n          `,\n          fragmentName: \"fooFragment\",\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n\n        proxy.writeFragment({\n          data: { __typename: \"Bar\", i: 10, j: 11, k: 12 },\n          id: \"bar\",\n          fragment: gql`\n            fragment fooFragment on Foo {\n              e\n              f\n              g\n              h {\n                i\n                j\n                k\n              }\n            }\n\n            fragment barFragment on Bar {\n              i\n              j\n              k\n            }\n          `,\n          fragmentName: \"barFragment\",\n        });\n\n        expect((proxy as InMemoryCache).extract()).toMatchSnapshot();\n      }\n    );\n\n    itWithCacheConfig(\"writes data that can be read back\", {}, (proxy) => {\n      const readWriteFragment = gql`\n        fragment aFragment on query {\n          getSomething {\n            id\n          }\n        }\n      `;\n      const data = {\n        __typename: \"query\",\n        getSomething: { id: \"123\", __typename: \"Something\" },\n      };\n      proxy.writeFragment({\n        data,\n        id: \"query\",\n        fragment: readWriteFragment,\n      });\n\n      const result = proxy.readFragment({\n        fragment: readWriteFragment,\n        id: \"query\",\n      });\n      expect(result).toEqual(data);\n    });\n\n    itWithCacheConfig(\n      \"will write some data to the store with variables\",\n      {},\n      (proxy) => {\n        proxy.writeFragment({\n          data: {\n            a: 1,\n            b: 2,\n            __typename: \"Foo\",\n          },\n          id: \"foo\",\n          fragment: gql`\n            fragment foo on Foo {\n              a: field(literal: true, value: 42)\n              b: field(literal: $literal, value: $value)\n            }\n          `,\n          variables: {\n            literal: false,\n            value: 42,\n          },\n        });\n\n        expect((proxy as InMemoryCache).extract()).toEqual({\n          __META: {\n            extraRootIds: [\"foo\"],\n          },\n          foo: {\n            __typename: \"Foo\",\n            'field({\"literal\":true,\"value\":42})': 1,\n            'field({\"literal\":false,\"value\":42})': 2,\n          },\n        });\n      }\n    );\n\n    itWithCacheConfig(\"can use the `from` option\", {}, (proxy) => {\n      proxy.writeFragment({\n        data: {\n          id: 1,\n          a: 1,\n          b: 2,\n          __typename: \"Foo\",\n        },\n        from: { __typename: \"Foo\", id: 1 },\n        fragment: gql`\n          fragment foo on Foo {\n            id\n            a\n            b\n          }\n        `,\n      });\n\n      expect(proxy.extract()).toEqual({\n        __META: {\n          extraRootIds: [\"Foo:1\"],\n        },\n        \"Foo:1\": {\n          __typename: \"Foo\",\n          id: 1,\n          a: 1,\n          b: 2,\n        },\n      });\n\n      proxy.writeFragment({\n        data: {\n          c: 3,\n          d: 4,\n          __typename: \"Foo\",\n        },\n        from: { __ref: \"Foo:1\" },\n        fragment: gql`\n          fragment foo on Foo {\n            c\n            d\n          }\n        `,\n      });\n\n      expect(proxy.extract()).toEqual({\n        __META: {\n          extraRootIds: [\"Foo:1\"],\n        },\n        \"Foo:1\": {\n          __typename: \"Foo\",\n          id: 1,\n          a: 1,\n          b: 2,\n          c: 3,\n          d: 4,\n        },\n      });\n\n      proxy.writeFragment({\n        data: {\n          e: 5,\n          f: 6,\n          __typename: \"Foo\",\n        },\n        from: \"Foo:1\",\n        fragment: gql`\n          fragment foo on Foo {\n            e\n            f\n          }\n        `,\n      });\n\n      expect(proxy.extract()).toEqual({\n        __META: {\n          extraRootIds: [\"Foo:1\"],\n        },\n        \"Foo:1\": {\n          __typename: \"Foo\",\n          id: 1,\n          a: 1,\n          b: 2,\n          c: 3,\n          d: 4,\n          e: 5,\n          f: 6,\n        },\n      });\n    });\n  });\n\n  describe(\"cache.updateQuery and cache.updateFragment\", () => {\n    it(\"should be batched\", () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Person: {\n            keyFields: [\"name\"],\n          },\n        },\n      });\n\n      type QueryData = {\n        me: {\n          __typename: string;\n          name: string;\n        };\n      };\n\n      const query: TypedDocumentNode<QueryData> = gql`\n        query {\n          me {\n            name\n          }\n        }\n      `;\n      const results: QueryData[] = [];\n\n      const cancel = cache.watch({\n        query,\n        optimistic: true,\n        callback(diff) {\n          if (diff.complete) {\n            results.push(diff.result);\n          }\n        },\n      });\n\n      cache.updateQuery({ query }, (data) => {\n        expect(data).toBe(null);\n\n        cache.writeQuery({\n          query,\n          data: {\n            me: {\n              __typename: \"Person\",\n              name: \"Ben\",\n            },\n          },\n        });\n\n        return {\n          me: {\n            __typename: \"Person\",\n            name: \"Ben Newman\",\n          },\n        };\n      });\n\n      expect(results).toEqual([\n        { me: { __typename: \"Person\", name: \"Ben Newman\" } },\n      ]);\n\n      expect(cache.extract()).toEqual({\n        'Person:{\"name\":\"Ben Newman\"}': {\n          __typename: \"Person\",\n          name: \"Ben Newman\",\n        },\n        'Person:{\"name\":\"Ben\"}': {\n          __typename: \"Person\",\n          name: \"Ben\",\n        },\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __ref: 'Person:{\"name\":\"Ben Newman\"}',\n          },\n        },\n      });\n\n      const usernameFragment = gql`\n        fragment UsernameFragment on Person {\n          username\n        }\n      `;\n\n      const bnId = cache.identify({\n        __typename: \"Person\",\n        name: \"Ben Newman\",\n      });\n\n      cache.updateFragment<any>(\n        {\n          id: bnId,\n          fragment: usernameFragment,\n          returnPartialData: true,\n        },\n        (data) => {\n          expect(data).toEqual({\n            __typename: \"Person\",\n          });\n\n          cache.writeQuery({\n            query,\n            data: {\n              me: {\n                __typename: \"Person\",\n                name: \"Brian Kim\",\n              },\n            },\n          });\n\n          cache.writeFragment({\n            id: cache.identify({\n              __typename: \"Person\",\n              name: \"Brian Kim\",\n            }),\n            fragment: usernameFragment,\n            data: {\n              username: \"brainkim\",\n            },\n          });\n\n          expect(results.length).toBe(1);\n\n          return {\n            ...data,\n            name: \"Ben Newman\",\n            username: \"benjamn\",\n          };\n        }\n      );\n\n      // Still just two results, thanks to cache.update{Query,Fragment} using\n      // cache.batch behind the scenes.\n      expect(results).toEqual([\n        { me: { __typename: \"Person\", name: \"Ben Newman\" } },\n        { me: { __typename: \"Person\", name: \"Brian Kim\" } },\n      ]);\n\n      expect(cache.extract()).toEqual({\n        'Person:{\"name\":\"Ben\"}': {\n          __typename: \"Person\",\n          name: \"Ben\",\n        },\n        'Person:{\"name\":\"Ben Newman\"}': {\n          __typename: \"Person\",\n          name: \"Ben Newman\",\n          username: \"benjamn\",\n        },\n        'Person:{\"name\":\"Brian Kim\"}': {\n          __typename: \"Person\",\n          name: \"Brian Kim\",\n          username: \"brainkim\",\n        },\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __ref: 'Person:{\"name\":\"Brian Kim\"}',\n          },\n        },\n        __META: {\n          extraRootIds: [\n            'Person:{\"name\":\"Ben Newman\"}',\n            'Person:{\"name\":\"Brian Kim\"}',\n          ],\n        },\n      });\n\n      cancel();\n    });\n\n    it(\"can use `from` with `updateFragment`\", async () => {\n      type Data = { a: number; b: number; __typename: \"Foo\" };\n\n      const cache = new InMemoryCache();\n      const fragment: TypedDocumentNode<Data, Record<string, never>> = gql`\n        fragment foo on Foo {\n          a\n          b\n        }\n      `;\n\n      function update(data: Data | null): Data {\n        if (!data) {\n          return { a: 1, b: 2, __typename: \"Foo\" };\n        }\n\n        return { a: data.a + 1, b: data.b + 1, __typename: \"Foo\" };\n      }\n\n      expect(\n        cache.updateFragment(\n          { fragment, from: { __typename: \"Foo\", id: 1 } },\n          update\n        )\n      ).toStrictEqualTyped({ __typename: \"Foo\", a: 1, b: 2 });\n\n      expect(\n        cache.updateFragment({ fragment, from: { __ref: \"Foo:1\" } }, update)\n      ).toStrictEqualTyped({ __typename: \"Foo\", a: 2, b: 3 });\n\n      expect(\n        cache.updateFragment({ fragment, from: \"Foo:1\" }, update)\n      ).toStrictEqualTyped({ __typename: \"Foo\", a: 3, b: 4 });\n    });\n  });\n\n  describe(\"cache.restore\", () => {\n    it(\"replaces cache.{store{Reader,Writer},maybeBroadcastWatch}\", () => {\n      const cache = new InMemoryCache();\n      const query = gql`\n        query {\n          a\n          b\n          c\n        }\n      `;\n\n      const originalReader = cache[\"storeReader\"];\n      const originalWriter = cache[\"storeWriter\"];\n\n      const originalMBW = cache[\"maybeBroadcastWatch\"];\n      expect(typeof originalMBW).toBe(\"function\");\n\n      cache.writeQuery({\n        query,\n        data: {\n          a: \"ay\",\n          b: \"bee\",\n          c: \"see\",\n        },\n      });\n\n      const snapshot = cache.extract();\n      expect(snapshot).toMatchSnapshot();\n\n      cache.restore({});\n      expect(cache.extract()).toEqual({});\n      expect(cache.readQuery({ query })).toBe(null);\n\n      cache.restore(snapshot);\n      expect(cache.extract()).toEqual(snapshot);\n      expect(cache.readQuery({ query })).toEqual({\n        a: \"ay\",\n        b: \"bee\",\n        c: \"see\",\n      });\n\n      expect(originalReader).not.toBe(cache[\"storeReader\"]);\n      expect(originalWriter).not.toBe(cache[\"storeWriter\"]);\n      expect(originalMBW).not.toBe(cache[\"maybeBroadcastWatch\"]);\n    });\n  });\n\n  describe(\"cache.batch\", () => {\n    const last = <E>(array: E[]) => array[array.length - 1];\n\n    function watch(cache: InMemoryCache, query: DocumentNode) {\n      const options: Cache.WatchOptions = {\n        query,\n        optimistic: true,\n        immediate: true,\n        callback(diff) {\n          diffs.push(diff);\n        },\n      };\n      const diffs: Cache.DiffResult<any>[] = [];\n      const cancel = cache.watch(options);\n      diffs.shift(); // Discard the immediate diff\n      return { diffs, watch: options, cancel };\n    }\n\n    it(\"calls onWatchUpdated for each invalidated watch\", () => {\n      const cache = new InMemoryCache();\n\n      const aQuery = gql`\n        query {\n          a\n        }\n      `;\n      const abQuery = gql`\n        query {\n          a\n          b\n        }\n      `;\n      const bQuery = gql`\n        query {\n          b\n        }\n      `;\n\n      const aInfo = watch(cache, aQuery);\n      const abInfo = watch(cache, abQuery);\n      const bInfo = watch(cache, bQuery);\n\n      const dirtied = new Map<Cache.WatchOptions, Cache.DiffResult<any>>();\n\n      const aUpdateResult = cache.batch({\n        update(cache) {\n          cache.writeQuery({\n            query: aQuery,\n            data: {\n              a: \"ay\",\n            },\n          });\n          return \"aQuery updated\";\n        },\n        optimistic: true,\n        onWatchUpdated(w, diff) {\n          dirtied.set(w, diff);\n        },\n      });\n      expect(aUpdateResult).toBe(\"aQuery updated\");\n\n      expect(dirtied.size).toBe(2);\n      expect(dirtied.has(aInfo.watch)).toBe(true);\n      expect(dirtied.has(abInfo.watch)).toBe(true);\n      expect(dirtied.has(bInfo.watch)).toBe(false);\n\n      expect(aInfo.diffs.length).toBe(1);\n      expect(last(aInfo.diffs)).toEqual({\n        complete: true,\n        result: {\n          a: \"ay\",\n        },\n      });\n\n      expect(abInfo.diffs.length).toBe(1);\n      expect(last(abInfo.diffs)).toEqual({\n        complete: false,\n        missing: expect.any(MissingFieldError),\n        result: {\n          a: \"ay\",\n        },\n      });\n\n      expect(bInfo.diffs.length).toBe(0);\n\n      dirtied.clear();\n\n      const bUpdateResult = cache.batch({\n        update(cache) {\n          cache.writeQuery({\n            query: bQuery,\n            data: {\n              b: \"bee\",\n            },\n          });\n          // Not returning anything, so beUpdateResult will be undefined.\n        },\n        optimistic: true,\n        onWatchUpdated(w, diff) {\n          dirtied.set(w, diff);\n        },\n      });\n      expect(bUpdateResult).toBeUndefined();\n\n      expect(dirtied.size).toBe(2);\n      expect(dirtied.has(aInfo.watch)).toBe(false);\n      expect(dirtied.has(abInfo.watch)).toBe(true);\n      expect(dirtied.has(bInfo.watch)).toBe(true);\n\n      expect(aInfo.diffs.length).toBe(1);\n      expect(last(aInfo.diffs)).toEqual({\n        complete: true,\n        result: {\n          a: \"ay\",\n        },\n      });\n\n      expect(abInfo.diffs.length).toBe(2);\n      expect(last(abInfo.diffs)).toEqual({\n        complete: true,\n        result: {\n          a: \"ay\",\n          b: \"bee\",\n        },\n      });\n\n      expect(bInfo.diffs.length).toBe(1);\n      expect(last(bInfo.diffs)).toEqual({\n        complete: true,\n        result: {\n          b: \"bee\",\n        },\n      });\n\n      aInfo.cancel();\n      abInfo.cancel();\n      bInfo.cancel();\n    });\n\n    it(\"works with cache.modify and INVALIDATE\", () => {\n      const cache = new InMemoryCache();\n\n      const aQuery = gql`\n        query {\n          a\n        }\n      `;\n      const abQuery = gql`\n        query {\n          a\n          b\n        }\n      `;\n      const bQuery = gql`\n        query {\n          b\n        }\n      `;\n\n      cache.writeQuery({\n        query: abQuery,\n        data: {\n          a: \"ay\",\n          b: \"bee\",\n        },\n      });\n\n      const aInfo = watch(cache, aQuery);\n      const abInfo = watch(cache, abQuery);\n      const bInfo = watch(cache, bQuery);\n\n      const dirtied = new Map<Cache.WatchOptions, Cache.DiffResult<any>>();\n\n      cache.batch({\n        update(cache) {\n          cache.modify({\n            fields: {\n              a(value, { INVALIDATE }) {\n                expect(value).toBe(\"ay\");\n                return INVALIDATE;\n              },\n            },\n          });\n        },\n        optimistic: true,\n        onWatchUpdated(w, diff) {\n          dirtied.set(w, diff);\n        },\n      });\n\n      expect(dirtied.size).toBe(2);\n      expect(dirtied.has(aInfo.watch)).toBe(true);\n      expect(dirtied.has(abInfo.watch)).toBe(true);\n      expect(dirtied.has(bInfo.watch)).toBe(false);\n\n      // No new diffs should have been generated, since we only invalidated\n      // fields using cache.modify, and did not change any field values.\n      expect(aInfo.diffs).toEqual([]);\n      expect(abInfo.diffs).toEqual([]);\n      expect(bInfo.diffs).toEqual([]);\n\n      aInfo.cancel();\n      abInfo.cancel();\n      bInfo.cancel();\n    });\n\n    it(\"does not pass previously invalidated queries to onWatchUpdated\", () => {\n      const cache = new InMemoryCache();\n\n      const aQuery = gql`\n        query {\n          a\n        }\n      `;\n      const abQuery = gql`\n        query {\n          a\n          b\n        }\n      `;\n      const bQuery = gql`\n        query {\n          b\n        }\n      `;\n\n      cache.writeQuery({\n        query: abQuery,\n        data: {\n          a: \"ay\",\n          b: \"bee\",\n        },\n      });\n\n      const aInfo = watch(cache, aQuery);\n      const abInfo = watch(cache, abQuery);\n      const bInfo = watch(cache, bQuery);\n\n      cache.writeQuery({\n        query: bQuery,\n        // Writing this data with broadcast:false queues this update for\n        // the next broadcast, whenever it happens. If that next broadcast\n        // is the one triggered by cache.batch, the bQuery broadcast could\n        // be accidentally intercepted by onWatchUpdated, even though the\n        // transaction does not touch the Query.b field. To solve this\n        // problem, the batch method calls cache.broadcastWatches() before\n        // the transaction, when options.onWatchUpdated is provided.\n        broadcast: false,\n        data: {\n          b: \"beeeee\",\n        },\n      });\n\n      // No diffs reported so far, thanks to broadcast: false.\n      expect(aInfo.diffs).toEqual([]);\n      expect(abInfo.diffs).toEqual([]);\n      expect(bInfo.diffs).toEqual([]);\n\n      const dirtied = new Map<Cache.WatchOptions, Cache.DiffResult<any>>();\n\n      cache.batch({\n        update(cache) {\n          cache.modify({\n            fields: {\n              a(value) {\n                expect(value).toBe(\"ay\");\n                return \"ayyyy\";\n              },\n            },\n          });\n        },\n        optimistic: true,\n        onWatchUpdated(watch, diff) {\n          dirtied.set(watch, diff);\n        },\n      });\n\n      expect(dirtied.size).toBe(2);\n      expect(dirtied.has(aInfo.watch)).toBe(true);\n      expect(dirtied.has(abInfo.watch)).toBe(true);\n      expect(dirtied.has(bInfo.watch)).toBe(false);\n\n      expect(aInfo.diffs).toEqual([\n        // This diff resulted from the cache.modify call in the cache.batch\n        // update function.\n        {\n          complete: true,\n          result: {\n            a: \"ayyyy\",\n          },\n        },\n      ]);\n\n      expect(abInfo.diffs).toEqual([\n        // This diff resulted from the cache.modify call in the cache.batch\n        // update function.\n        {\n          complete: true,\n          result: {\n            a: \"ayyyy\",\n            b: \"beeeee\",\n          },\n        },\n      ]);\n\n      // No diffs so far for bQuery.\n      expect(bInfo.diffs).toEqual([]);\n\n      // Trigger broadcast of watchers that were dirty before the cache.batch\n      // transaction.\n      cache[\"broadcastWatches\"]();\n\n      expect(aInfo.diffs).toEqual([\n        // Same array of diffs as before.\n        {\n          complete: true,\n          result: {\n            a: \"ayyyy\",\n          },\n        },\n      ]);\n\n      expect(abInfo.diffs).toEqual([\n        // The abQuery watcher was dirty before the cache.batch transaction,\n        // but it got picked up in the post-transaction broadcast, which is why\n        // we do not see another (duplicate) diff here.\n        {\n          complete: true,\n          result: {\n            a: \"ayyyy\",\n            b: \"beeeee\",\n          },\n        },\n      ]);\n\n      expect(bInfo.diffs).toEqual([\n        // This diff is caused by the data written by cache.writeQuery before\n        // the cache.batch transaction, but gets broadcast only after the batch\n        // transaction, by cache[\"broadcastWatches\"]() above.\n        {\n          complete: true,\n          result: {\n            b: \"beeeee\",\n          },\n        },\n      ]);\n\n      aInfo.cancel();\n      abInfo.cancel();\n      bInfo.cancel();\n    });\n\n    it(\"returns options.update result for optimistic and non-optimistic batches\", () => {\n      const cache = new InMemoryCache();\n      const expected = Symbol.for(\"expected\");\n\n      expect(\n        cache.batch({\n          optimistic: false,\n          update(c) {\n            c.writeQuery({\n              query: gql`\n                query {\n                  value\n                }\n              `,\n              data: { value: 12345 },\n            });\n            return expected;\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          optimistic: false,\n          update(c) {\n            c.reset();\n            return expected;\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          optimistic: false,\n          update(c) {\n            c.writeQuery({\n              query: gql`\n                query {\n                  optimistic\n                }\n              `,\n              data: { optimistic: false },\n            });\n            return expected;\n          },\n          onWatchUpdated() {\n            throw new Error(\"onWatchUpdated should not have been called\");\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          optimistic: true,\n          update(c) {\n            return expected;\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          optimistic: true,\n          update(c) {\n            c.writeQuery({\n              query: gql`\n                query {\n                  optimistic\n                }\n              `,\n              data: { optimistic: true },\n            });\n            return expected;\n          },\n          onWatchUpdated() {\n            throw new Error(\"onWatchUpdated should not have been called\");\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          // The optimistic option defaults to true.\n          // optimistic: true,\n          update(c) {\n            return expected;\n          },\n        })\n      ).toBe(expected);\n\n      expect(\n        cache.batch({\n          optimistic: \"some optimistic ID\",\n          update(c) {\n            expect(\n              c.readQuery({\n                query: gql`\n                  query {\n                    __typename\n                  }\n                `,\n              })\n            ).toEqual({ __typename: \"Query\" });\n            return expected;\n          },\n        })\n      ).toBe(expected);\n\n      const optimisticId = \"some optimistic ID\";\n      expect(\n        cache.batch({\n          optimistic: optimisticId,\n          update(c) {\n            c.writeQuery({\n              query: gql`\n                query {\n                  optimistic\n                }\n              `,\n              data: { optimistic: optimisticId },\n            });\n            return expected;\n          },\n          onWatchUpdated() {\n            throw new Error(\"onWatchUpdated should not have been called\");\n          },\n        })\n      ).toBe(expected);\n    });\n  });\n\n  describe(\"performTransaction\", () => {\n    itWithInitialData(\"will not broadcast mid-transaction\", [{}], (cache) => {\n      let numBroadcasts = 0;\n\n      const query = gql`\n        {\n          a\n        }\n      `;\n\n      cache.watch({\n        query,\n        optimistic: false,\n        callback: () => {\n          numBroadcasts++;\n        },\n      });\n\n      expect(numBroadcasts).toEqual(0);\n\n      cache.performTransaction((proxy) => {\n        proxy.writeQuery({\n          data: { a: 1 },\n          query,\n        });\n\n        expect(numBroadcasts).toEqual(0);\n\n        proxy.writeQuery({\n          data: { a: 4, b: 5, c: 6 },\n          query: gql`\n            {\n              a\n              b\n              c\n            }\n          `,\n        });\n\n        expect(numBroadcasts).toEqual(0);\n      });\n\n      expect(numBroadcasts).toEqual(1);\n    });\n  });\n\n  describe(\"recordOptimisticTransaction\", () => {\n    itWithInitialData(\"will only broadcast once\", [{}], (cache) => {\n      let numBroadcasts = 0;\n\n      const query = gql`\n        {\n          a\n        }\n      `;\n\n      cache.watch({\n        query,\n        optimistic: true,\n        callback: () => {\n          numBroadcasts++;\n        },\n      });\n\n      expect(numBroadcasts).toEqual(0);\n\n      cache.recordOptimisticTransaction((proxy) => {\n        proxy.writeQuery({\n          data: { a: 1 },\n          query,\n        });\n\n        expect(numBroadcasts).toEqual(0);\n\n        proxy.writeQuery({\n          data: { a: 4, b: 5, c: 6 },\n          query: gql`\n            {\n              a\n              b\n              c\n            }\n          `,\n        });\n\n        expect(numBroadcasts).toEqual(0);\n      }, 1 as any);\n\n      expect(numBroadcasts).toEqual(1);\n    });\n  });\n});\n\ndescribe(\"resultCacheMaxSize\", () => {\n  it(\"uses default max size on caches\", () => {\n    const cache = new InMemoryCache();\n    expect(cache[\"maybeBroadcastWatch\"].options.max).toBe(\n      defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"]\n    );\n    expect(cache[\"storeReader\"][\"executeSelectionSet\"].options.max).toBe(\n      defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"]\n    );\n    expect(cache[\"getFragmentDoc\"].options.max).toBe(\n      defaultCacheSizes[\"cache.fragmentQueryDocuments\"]\n    );\n  });\n});\n\ndescribe(\"InMemoryCache#broadcastWatches\", function () {\n  it(\"should keep distinct consumers distinct (issue #5733)\", function () {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        value(arg: $arg) {\n          name\n        }\n      }\n    `;\n\n    const receivedCallbackResults: [string, number, any][] = [];\n\n    let nextWatchId = 1;\n    function watch(arg: number) {\n      const watchId = `id${nextWatchId++}`;\n      cache.watch({\n        query,\n        variables: { arg },\n        optimistic: false,\n        callback(result) {\n          receivedCallbackResults.push([watchId, arg, result]);\n        },\n      });\n      return watchId;\n    }\n\n    const id1 = watch(1);\n    expect(receivedCallbackResults).toEqual([]);\n\n    function write(arg: number, name: string) {\n      cache.writeQuery({\n        query,\n        variables: { arg },\n        data: {\n          value: { name },\n        },\n      });\n    }\n\n    write(1, \"one\");\n\n    const received1 = [\n      id1,\n      1,\n      {\n        result: {\n          value: {\n            name: \"one\",\n          },\n        },\n        complete: true,\n      },\n    ];\n\n    expect(receivedCallbackResults).toEqual([received1]);\n\n    const id2 = watch(2);\n\n    expect(receivedCallbackResults).toEqual([received1]);\n\n    write(2, \"two\");\n\n    const received2 = [\n      id2,\n      2,\n      {\n        result: {\n          value: {\n            name: \"two\",\n          },\n        },\n        complete: true,\n      },\n    ];\n\n    expect(receivedCallbackResults).toEqual([\n      received1,\n      // New results:\n      received2,\n    ]);\n\n    const id3 = watch(1);\n    const id4 = watch(1);\n\n    write(1, \"one\");\n\n    const received3 = [\n      id3,\n      1,\n      {\n        result: {\n          value: {\n            name: \"one\",\n          },\n        },\n        complete: true,\n      },\n    ];\n\n    const received4 = [\n      id4,\n      1,\n      {\n        result: {\n          value: {\n            name: \"one\",\n          },\n        },\n        complete: true,\n      },\n    ];\n\n    expect(receivedCallbackResults).toEqual([\n      received1,\n      received2,\n      // New results:\n      received3,\n      received4,\n    ]);\n\n    write(2, \"TWO\");\n\n    const received2AllCaps = [\n      id2,\n      2,\n      {\n        result: {\n          value: {\n            name: \"TWO\",\n          },\n        },\n        complete: true,\n      },\n    ];\n\n    expect(receivedCallbackResults).toEqual([\n      received1,\n      received2,\n      received3,\n      received4,\n      // New results:\n      received2AllCaps,\n    ]);\n  });\n});\n\ndescribe(\"InMemoryCache#modify\", () => {\n  it(\"should work with single modifier function\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        a\n        b\n        c\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        a: 0,\n        b: 0,\n        c: 0,\n      },\n    });\n\n    const resultBeforeModify = cache.readQuery({ query });\n    expect(resultBeforeModify).toEqual({ a: 0, b: 0, c: 0 });\n\n    cache.modify({\n      // Passing a function for options.fields is equivalent to invoking\n      // that function for all fields within the object.\n      fields(value, { fieldName }) {\n        switch (fieldName) {\n          case \"a\":\n            return value + 1;\n          case \"b\":\n            return value - 1;\n          default:\n            return value;\n        }\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: 1,\n        b: -1,\n        c: 0,\n      },\n    });\n\n    const resultAfterModify = cache.readQuery({ query });\n    expect(resultAfterModify).toEqual({ a: 1, b: -1, c: 0 });\n  });\n\n  it(\"should work with multiple modifier functions\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        a\n        b\n        c\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        a: 0,\n        b: 0,\n        c: 0,\n      },\n    });\n\n    const resultBeforeModify = cache.readQuery({ query });\n    expect(resultBeforeModify).toEqual({ a: 0, b: 0, c: 0 });\n\n    let checkedTypename = false;\n    cache.modify({\n      fields: {\n        a(value) {\n          return value + 1;\n        },\n        b(value) {\n          return value - 1;\n        },\n        __typename(t: string, { readField }) {\n          expect(t).toBe(\"Query\");\n          expect(readField(\"c\")).toBe(0);\n          checkedTypename = true;\n          return t;\n        },\n      },\n    });\n    expect(checkedTypename).toBe(true);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: 1,\n        b: -1,\n        c: 0,\n      },\n    });\n\n    const resultAfterModify = cache.readQuery({ query });\n    expect(resultAfterModify).toEqual({ a: 1, b: -1, c: 0 });\n  });\n\n  it(\"should allow invalidation using details.INVALIDATE\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n        Author: {\n          keyFields: [\"name\"],\n        },\n      },\n    });\n\n    const query: TypedDocumentNode<{\n      currentlyReading: {\n        title: string;\n        isbn: string;\n        author: {\n          name: string;\n        };\n      };\n    }> = gql`\n      query {\n        currentlyReading {\n          title\n          isbn\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    const currentlyReading = {\n      __typename: \"Book\",\n      isbn: \"0374110034\",\n      title: \"Beowulf: A New Translation\",\n      author: {\n        __typename: \"Author\",\n        name: \"Maria Dahvana Headley\",\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        currentlyReading,\n      },\n    });\n\n    function read() {\n      return cache.readQuery({ query })!;\n    }\n\n    const initialResult = read();\n\n    expect(cache.extract()).toMatchSnapshot();\n\n    expect(\n      cache.modify({\n        id: cache.identify({\n          __typename: \"Author\",\n          name: \"Maria Dahvana Headley\",\n        }),\n        fields: {\n          name(_, { INVALIDATE }) {\n            return INVALIDATE;\n          },\n        },\n      })\n    ).toBe(false); // Nothing actually modified.\n\n    const resultAfterAuthorInvalidation = read();\n    expect(resultAfterAuthorInvalidation).toEqual(initialResult);\n    expect(resultAfterAuthorInvalidation).not.toBe(initialResult);\n\n    expect(\n      cache.modify({\n        id: cache.identify({\n          __typename: \"Book\",\n          isbn: \"0374110034\",\n        }),\n        // Invalidate all fields of the Book entity.\n        fields(_, { INVALIDATE }) {\n          return INVALIDATE;\n        },\n      })\n    ).toBe(false); // Nothing actually modified.\n\n    const resultAfterBookInvalidation = read();\n    expect(resultAfterBookInvalidation).toEqual(resultAfterAuthorInvalidation);\n    expect(resultAfterBookInvalidation).not.toBe(resultAfterAuthorInvalidation);\n    expect(resultAfterBookInvalidation.currentlyReading.author).toEqual({\n      __typename: \"Author\",\n      name: \"Maria Dahvana Headley\",\n    });\n    expect(resultAfterBookInvalidation.currentlyReading.author).toBe(\n      resultAfterAuthorInvalidation.currentlyReading.author\n    );\n  });\n\n  it(\"should allow deletion using details.DELETE\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n        Author: {\n          keyFields: [\"name\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        currentlyReading {\n          title\n          isbn\n          author {\n            name\n            yearOfBirth\n          }\n        }\n      }\n    `;\n\n    const currentlyReading = {\n      __typename: \"Book\",\n      isbn: \"147670032X\",\n      title: \"Why We're Polarized\",\n      author: {\n        __typename: \"Author\",\n        name: \"Ezra Klein\",\n        yearOfBirth: 1983,\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        currentlyReading,\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        currentlyReading: {\n          __ref: 'Book:{\"isbn\":\"147670032X\"}',\n        },\n      },\n      'Book:{\"isbn\":\"147670032X\"}': {\n        __typename: \"Book\",\n        isbn: \"147670032X\",\n        author: {\n          __ref: 'Author:{\"name\":\"Ezra Klein\"}',\n        },\n        title: \"Why We're Polarized\",\n      },\n      'Author:{\"name\":\"Ezra Klein\"}': {\n        __typename: \"Author\",\n        name: \"Ezra Klein\",\n        yearOfBirth: 1983,\n      },\n    });\n\n    const authorId = cache.identify(currentlyReading.author)!;\n    expect(authorId).toBe('Author:{\"name\":\"Ezra Klein\"}');\n\n    cache.modify({\n      id: authorId,\n      fields: {\n        yearOfBirth(yob) {\n          return yob + 1;\n        },\n      },\n    });\n\n    const yobResult = cache.readFragment({\n      id: authorId,\n      fragment: gql`\n        fragment YOB on Author {\n          yearOfBirth\n        }\n      `,\n    });\n\n    expect(yobResult).toEqual({\n      __typename: \"Author\",\n      yearOfBirth: 1984,\n    });\n\n    const bookId = cache.identify(currentlyReading)!;\n\n    // Modifying the Book in order to modify the Author is fancier than\n    // necessary, but we want fancy use cases to work, too.\n    cache.modify({\n      id: bookId,\n      fields: {\n        author(author: Reference, { readField }) {\n          expect(readField(\"title\")).toBe(\"Why We're Polarized\");\n          expect(readField(\"name\", author)).toBe(\"Ezra Klein\");\n          cache.modify({\n            fields: {\n              yearOfBirth(yob, { DELETE }) {\n                expect(yob).toBe(1984);\n                return DELETE;\n              },\n            },\n            id: cache.identify({\n              __typename: readField(\"__typename\", author),\n              name: readField(\"name\", author),\n            }),\n          });\n          return author;\n        },\n      },\n    });\n\n    const snapshotWithoutYOB = cache.extract();\n    expect(snapshotWithoutYOB[authorId]!.yearOfBirth).toBeUndefined();\n    expect(\"yearOfBirth\" in snapshotWithoutYOB[authorId]!).toBe(false);\n    expect(snapshotWithoutYOB).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        currentlyReading: {\n          __ref: 'Book:{\"isbn\":\"147670032X\"}',\n        },\n      },\n      'Book:{\"isbn\":\"147670032X\"}': {\n        __typename: \"Book\",\n        isbn: \"147670032X\",\n        author: {\n          __ref: 'Author:{\"name\":\"Ezra Klein\"}',\n        },\n        title: \"Why We're Polarized\",\n      },\n      'Author:{\"name\":\"Ezra Klein\"}': {\n        __typename: \"Author\",\n        name: \"Ezra Klein\",\n        // yearOfBirth is gone now\n      },\n    });\n\n    // Delete the whole Book.\n    cache.modify({\n      id: bookId,\n      fields: (_, { DELETE }) => DELETE,\n    });\n\n    const snapshotWithoutBook = cache.extract();\n    expect(snapshotWithoutBook[bookId]).toBeUndefined();\n    expect(bookId in snapshotWithoutBook).toBe(false);\n    expect(snapshotWithoutBook).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        currentlyReading: {\n          __ref: 'Book:{\"isbn\":\"147670032X\"}',\n        },\n      },\n      'Author:{\"name\":\"Ezra Klein\"}': {\n        __typename: \"Author\",\n        name: \"Ezra Klein\",\n      },\n    });\n\n    // Delete all fields of the Author, which also removes the object.\n    cache.modify({\n      id: authorId,\n      fields: {\n        __typename(_, { DELETE }) {\n          return DELETE;\n        },\n        name(_, { DELETE }) {\n          return DELETE;\n        },\n      },\n    });\n\n    const snapshotWithoutAuthor = cache.extract();\n    expect(snapshotWithoutAuthor[authorId]).toBeUndefined();\n    expect(authorId in snapshotWithoutAuthor).toBe(false);\n    expect(snapshotWithoutAuthor).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        currentlyReading: {\n          __ref: 'Book:{\"isbn\":\"147670032X\"}',\n        },\n      },\n    });\n\n    cache.modify({\n      fields: (_, { DELETE }) => DELETE,\n    });\n\n    expect(cache.extract()).toEqual({});\n  });\n\n  it(\"can remove specific items from paginated lists\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Thread: {\n          keyFields: [\"tid\"],\n\n          fields: {\n            comments: {\n              merge(\n                existing: Reference[],\n                incoming: Reference[],\n                { args, mergeObjects }\n              ) {\n                const merged = existing ? existing.slice(0) : [];\n                const end =\n                  args!.offset + Math.min(args!.limit, incoming.length);\n                for (let i = args!.offset; i < end; ++i) {\n                  merged[i] = mergeObjects(\n                    merged[i],\n                    incoming[i - args!.offset]\n                  ) as Reference;\n                }\n                return merged;\n              },\n\n              read(existing: Reference[], { args }) {\n                const page =\n                  existing &&\n                  existing.slice(args!.offset, args!.offset + args!.limit);\n                if (page && page.length > 0) {\n                  return page;\n                }\n              },\n            },\n          },\n        },\n\n        Comment: {\n          keyFields: [\"id\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query GetThread($offset: Int, $limit: Int) {\n        thread {\n          tid\n          comments(offset: $offset, limit: $limit) {\n            id\n            text\n          }\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        thread: {\n          __typename: \"Thread\",\n          tid: 123,\n          comments: [\n            {\n              __typename: \"Comment\",\n              id: \"c1\",\n              text: \"first post\",\n            },\n            {\n              __typename: \"Comment\",\n              id: \"c2\",\n              text: \"I have thoughts\",\n            },\n            {\n              __typename: \"Comment\",\n              id: \"c3\",\n              text: \"friendly ping\",\n            },\n          ],\n        },\n      },\n      variables: {\n        offset: 0,\n        limit: 3,\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        thread: {\n          __ref: 'Thread:{\"tid\":123}',\n        },\n      },\n      'Thread:{\"tid\":123}': {\n        __typename: \"Thread\",\n        tid: 123,\n        comments: [\n          { __ref: 'Comment:{\"id\":\"c1\"}' },\n          { __ref: 'Comment:{\"id\":\"c2\"}' },\n          { __ref: 'Comment:{\"id\":\"c3\"}' },\n        ],\n      },\n      'Comment:{\"id\":\"c1\"}': {\n        __typename: \"Comment\",\n        id: \"c1\",\n        text: \"first post\",\n      },\n      'Comment:{\"id\":\"c2\"}': {\n        __typename: \"Comment\",\n        id: \"c2\",\n        text: \"I have thoughts\",\n      },\n      'Comment:{\"id\":\"c3\"}': {\n        __typename: \"Comment\",\n        id: \"c3\",\n        text: \"friendly ping\",\n      },\n    });\n\n    cache.modify({\n      fields: {\n        comments(comments: readonly Reference[], { readField }) {\n          expect(Object.isFrozen(comments)).toBe(true);\n          expect(comments.length).toBe(3);\n          const filtered = comments.filter((comment) => {\n            return readField(\"id\", comment) !== \"c1\";\n          });\n          expect(filtered.length).toBe(2);\n          return filtered;\n        },\n      },\n\n      id: cache.identify({\n        __typename: \"Thread\",\n        tid: 123,\n      }),\n    });\n\n    expect(cache.gc()).toEqual(['Comment:{\"id\":\"c1\"}']);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        thread: {\n          __ref: 'Thread:{\"tid\":123}',\n        },\n      },\n      'Thread:{\"tid\":123}': {\n        __typename: \"Thread\",\n        tid: 123,\n        comments: [\n          { __ref: 'Comment:{\"id\":\"c2\"}' },\n          { __ref: 'Comment:{\"id\":\"c3\"}' },\n        ],\n      },\n      'Comment:{\"id\":\"c2\"}': {\n        __typename: \"Comment\",\n        id: \"c2\",\n        text: \"I have thoughts\",\n      },\n      'Comment:{\"id\":\"c3\"}': {\n        __typename: \"Comment\",\n        id: \"c3\",\n        text: \"friendly ping\",\n      },\n    });\n  });\n\n  it(\"should not revisit deleted fields\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        a\n        b\n        c\n      }\n    `;\n\n    cache.recordOptimisticTransaction((cache) => {\n      cache.writeQuery({\n        query,\n        data: {\n          a: 1,\n          b: 2,\n          c: 3,\n        },\n      });\n    }, \"transaction\");\n\n    cache.modify({\n      fields: {\n        b(value, { DELETE }) {\n          expect(value).toBe(2);\n          return DELETE;\n        },\n      },\n      optimistic: true,\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: 1,\n        c: 3,\n      },\n    });\n\n    cache.modify({\n      fields(value, { fieldName }) {\n        expect(fieldName).not.toBe(\"b\");\n        if (fieldName === \"a\") expect(value).toBe(1);\n        if (fieldName === \"c\") expect(value).toBe(3);\n        return value;\n      },\n      optimistic: true,\n    });\n\n    cache.removeOptimistic(\"transaction\");\n\n    expect(cache.extract(true)).toEqual({});\n  });\n\n  it(\"should broadcast watches for queries with changed fields\", () => {\n    const cache = new InMemoryCache();\n    const queryA = gql`\n      {\n        a {\n          value\n        }\n      }\n    `;\n    const queryB = gql`\n      {\n        b {\n          value\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query: queryA,\n      data: {\n        a: {\n          __typename: \"A\",\n          id: 1,\n          value: 123,\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: queryB,\n      data: {\n        b: {\n          __typename: \"B\",\n          id: 1,\n          value: 321,\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        a: { __ref: \"A:1\" },\n        b: { __ref: \"B:1\" },\n      },\n      \"A:1\": {\n        __typename: \"A\",\n        id: 1,\n        value: 123,\n      },\n      \"B:1\": {\n        __typename: \"B\",\n        id: 1,\n        value: 321,\n      },\n    });\n\n    let aResults: any[] = [];\n    cache.watch({\n      query: queryA,\n      optimistic: true,\n      immediate: true,\n      callback(data) {\n        aResults.push(data);\n      },\n    });\n\n    let bResults: any[] = [];\n    cache.watch({\n      query: queryB,\n      optimistic: true,\n      immediate: true,\n      callback(data) {\n        bResults.push(data);\n      },\n    });\n\n    function makeResult(\n      __typename: string,\n      value: number,\n      complete: boolean = true\n    ) {\n      return {\n        complete,\n        result: {\n          [__typename.toLowerCase()]: {\n            __typename,\n            value,\n          },\n        },\n      };\n    }\n\n    const a123 = makeResult(\"A\", 123);\n    const b321 = makeResult(\"B\", 321);\n\n    expect(aResults).toEqual([a123]);\n    expect(bResults).toEqual([b321]);\n\n    const aId = cache.identify({ __typename: \"A\", id: 1 });\n    const bId = cache.identify({ __typename: \"B\", id: 1 });\n\n    cache.modify({\n      id: aId,\n      fields: {\n        value(x: number) {\n          return x + 1;\n        },\n      },\n    });\n\n    const a124 = makeResult(\"A\", 124);\n\n    expect(aResults).toEqual([a123, a124]);\n    expect(bResults).toEqual([b321]);\n\n    cache.modify({\n      id: bId,\n      fields: {\n        value(x: number) {\n          return x + 1;\n        },\n      },\n    });\n\n    const b322 = makeResult(\"B\", 322);\n\n    expect(aResults).toEqual([a123, a124]);\n    expect(bResults).toEqual([b321, b322]);\n\n    // Check that resetting the result cache does not trigger additional watch\n    // notifications.\n    expect(\n      cache.gc({\n        resetResultCache: true,\n      })\n    ).toEqual([]);\n    expect(aResults).toEqual([a123, a124]);\n    expect(bResults).toEqual([b321, b322]);\n    cache[\"broadcastWatches\"]();\n    expect(aResults).toEqual([a123, a124]);\n    expect(bResults).toEqual([b321, b322]);\n  });\n\n  it(\"should handle argument-determined field identities\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            book: {\n              keyArgs: [\"isbn\"],\n            },\n          },\n        },\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    function addBook(isbn: string, title: string) {\n      cache.writeQuery({\n        query: gql`\n          query {\n            book(isbn: $isbn) {\n              isbn\n              title\n            }\n          }\n        `,\n        data: {\n          book: {\n            __typename: \"Book\",\n            isbn,\n            title,\n          },\n        },\n        variables: {\n          isbn,\n        },\n      });\n    }\n\n    addBook(\"147670032X\", \"Why We're Polarized\");\n    addBook(\"1760641790\", \"How To Do Nothing\");\n    addBook(\"0735211280\", \"Spineless\");\n\n    const fullSnapshot = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'book:{\"isbn\":\"0735211280\"}': {\n          __ref: 'Book:{\"isbn\":\"0735211280\"}',\n        },\n        'book:{\"isbn\":\"147670032X\"}': {\n          __ref: 'Book:{\"isbn\":\"147670032X\"}',\n        },\n        'book:{\"isbn\":\"1760641790\"}': {\n          __ref: 'Book:{\"isbn\":\"1760641790\"}',\n        },\n      },\n      'Book:{\"isbn\":\"147670032X\"}': {\n        __typename: \"Book\",\n        isbn: \"147670032X\",\n        title: \"Why We're Polarized\",\n      },\n      'Book:{\"isbn\":\"1760641790\"}': {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n      'Book:{\"isbn\":\"0735211280\"}': {\n        __typename: \"Book\",\n        isbn: \"0735211280\",\n        title: \"Spineless\",\n      },\n    };\n\n    expect(cache.extract()).toEqual(fullSnapshot);\n\n    function check(isbnToDelete?: string) {\n      let bookCount = 0;\n\n      cache.modify({\n        fields: {\n          book(\n            book: Reference,\n            { fieldName, storeFieldName, isReference, readField, DELETE }\n          ) {\n            expect(fieldName).toBe(\"book\");\n            expect(isReference(book)).toBe(true);\n            expect(typeof readField(\"title\", book)).toBe(\"string\");\n            expect(readField(\"__typename\", book)).toBe(\"Book\");\n            expect(\n              readField({\n                fieldName: \"__typename\",\n                from: book,\n              })\n            ).toBe(\"Book\");\n\n            const parts = storeFieldName.split(\":\");\n            expect(parts.shift()).toBe(\"book\");\n            const keyArgs = JSON.parse(parts.join(\":\"));\n            expect(typeof keyArgs.isbn).toBe(\"string\");\n            expect(Object.keys(keyArgs)).toEqual([\"isbn\"]);\n\n            expect(readField(\"isbn\", book)).toBe(keyArgs.isbn);\n\n            if (isbnToDelete === keyArgs.isbn) {\n              return DELETE;\n            }\n\n            ++bookCount;\n\n            return book;\n          },\n        },\n      });\n\n      return bookCount;\n    }\n\n    // No change from repeatedly calling check().\n    expect(check()).toBe(3);\n    expect(check()).toBe(3);\n\n    expect(check(\"0735211280\")).toBe(2);\n    expect(check(\"147670032X\")).toBe(1);\n\n    // No change from re-deleting already-deleted ISBNs.\n    expect(check(\"0735211280\")).toBe(1);\n    expect(check(\"147670032X\")).toBe(1);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'book:{\"isbn\":\"1760641790\"}': {\n          __ref: 'Book:{\"isbn\":\"1760641790\"}',\n        },\n      },\n      'Book:{\"isbn\":\"147670032X\"}': {\n        __typename: \"Book\",\n        isbn: \"147670032X\",\n        title: \"Why We're Polarized\",\n      },\n      'Book:{\"isbn\":\"1760641790\"}': {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n      'Book:{\"isbn\":\"0735211280\"}': {\n        __typename: \"Book\",\n        isbn: \"0735211280\",\n        title: \"Spineless\",\n      },\n    });\n\n    expect(cache.gc().sort()).toEqual([\n      'Book:{\"isbn\":\"0735211280\"}',\n      'Book:{\"isbn\":\"147670032X\"}',\n    ]);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'book:{\"isbn\":\"1760641790\"}': {\n          __ref: 'Book:{\"isbn\":\"1760641790\"}',\n        },\n      },\n      'Book:{\"isbn\":\"1760641790\"}': {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n    });\n\n    expect(check(\"1760641790\")).toBe(0);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n      },\n      'Book:{\"isbn\":\"1760641790\"}': {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n    });\n\n    expect(cache.gc()).toEqual(['Book:{\"isbn\":\"1760641790\"}']);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n      },\n    });\n  });\n\n  it(\"should modify ROOT_QUERY only when options.id absent\", function () {\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          field\n        }\n      `,\n      data: {\n        field: \"oyez\",\n      },\n    });\n\n    const snapshot = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        field: \"oyez\",\n      },\n    };\n\n    expect(cache.extract()).toEqual(snapshot);\n\n    function check(id: any) {\n      expect(\n        cache.modify({\n          id,\n          fields(value) {\n            throw new Error(`unexpected value: ${value}`);\n          },\n        })\n      ).toBe(false);\n    }\n\n    check(void 0);\n    check(false);\n    check(null);\n    check(\"\");\n    check(\"bogus:id\");\n\n    expect(cache.extract()).toEqual(snapshot);\n  });\n\n  it(\"warns if `modify` returns a mixed array of objects and references\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        me {\n          id\n          books {\n            id\n            title\n          }\n        }\n      }\n    `;\n\n    interface Book {\n      __typename: \"Book\";\n      id: string;\n      title: string;\n    }\n\n    const book1: Book = { __typename: \"Book\", id: \"1\", title: \"1984\" };\n    const book2: Book = { __typename: \"Book\", id: \"2\", title: \"The Odyssey\" };\n    const book3: Book = { __typename: \"Book\", id: \"3\", title: \"The Hobbit\" };\n    const book4: Book = { __typename: \"Book\", id: \"4\", title: \"The Swarm\" };\n\n    cache.writeQuery({\n      query,\n      data: {\n        me: {\n          __typename: \"User\",\n          id: \"42\",\n          books: [book1, book2, book3],\n        },\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"User\",\n        books: [book1, book2, book3],\n        id: \"42\",\n      },\n    });\n\n    {\n      using consoleSpy = spyOnConsole(\"warn\");\n      cache.modify<{ books: Book[] }>({\n        id: cache.identify({ __typename: \"User\", id: \"42\" }),\n        fields: {\n          books(existingBooks, { toReference }) {\n            return [toReference(existingBooks[2])!, book4];\n          },\n        },\n      });\n      expect(consoleSpy.warn).toHaveBeenLastCalledWith(\n        \"cache.modify: Writing an array with a mix of both References and Objects will not result in the Objects being normalized correctly.\\n\" +\n          \"Please convert the object instance %o to a Reference before writing it to the cache by calling `toReference(object, true)`.\",\n        book4\n      );\n    }\n  });\n\n  it(\"warns if `modify` returns a Reference that is not part of the store as part of an array\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        me {\n          id\n          books {\n            id\n            title\n          }\n        }\n      }\n    `;\n\n    type Book = {\n      __typename: \"Book\";\n      id: string;\n      title: string;\n    };\n\n    const book1: Book = { __typename: \"Book\", id: \"1\", title: \"1984\" };\n    const book2: Book = { __typename: \"Book\", id: \"2\", title: \"The Odyssey\" };\n    const book3: Book = { __typename: \"Book\", id: \"3\", title: \"The Hobbit\" };\n    const book4: Book = { __typename: \"Book\", id: \"4\", title: \"The Swarm\" };\n\n    cache.writeQuery({\n      query,\n      data: {\n        me: {\n          __typename: \"User\",\n          id: \"42\",\n          books: [book1, book2, book3],\n        },\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"User\",\n        books: [book1, book2, book3],\n        id: \"42\",\n      },\n    });\n\n    {\n      using consoleSpy = spyOnConsole(\"warn\");\n      cache.modify<{ books: Book[] }>({\n        id: cache.identify({ __typename: \"User\", id: \"42\" }),\n        fields: {\n          books(existingBooks, { toReference }) {\n            return [...existingBooks, toReference(book4)!];\n          },\n        },\n      });\n      expect(consoleSpy.warn).toHaveBeenLastCalledWith(\n        \"cache.modify: You are trying to write a Reference that is not part of the store: %o\\n\" +\n          \"Please make sure to set the `mergeIntoStore` parameter to `true` when creating a Reference that is not part of the store yet:\\n\" +\n          \"`toReference(object, true)`\",\n        { __ref: \"Book:4\" }\n      );\n    }\n\n    // reading the cache *looks* good to the user\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"User\",\n        // this is what we're warning about - book 4 is not in the store\n        books: [book1, book2, book3],\n        id: \"42\",\n      },\n    });\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: { __typename: \"Query\", me: { __ref: \"User:42\" } },\n      \"Book:1\": book1,\n      \"Book:2\": book2,\n      \"Book:3\": book3,\n      // no Book:4\n      \"User:42\": {\n        __typename: \"User\",\n        id: \"42\",\n        // Book:4 here is a dead ref\n        books: [\n          { __ref: \"Book:1\" },\n          { __ref: \"Book:2\" },\n          { __ref: \"Book:3\" },\n          { __ref: \"Book:4\" },\n        ],\n      },\n    });\n  });\n\n  it(\"warns if `modify` returns a Reference that is not part of the store\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        me {\n          id\n        }\n      }\n    `;\n\n    type User = {\n      __typename: string;\n      id: string;\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        me: {\n          __typename: \"User\",\n          id: \"42\",\n        },\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"User\",\n        id: \"42\",\n      },\n    });\n\n    {\n      using consoleSpy = spyOnConsole(\"warn\");\n      cache.modify<{ me: User }>({\n        id: \"ROOT_QUERY\",\n        fields: {\n          me(existingUser, { toReference }) {\n            return toReference({\n              __typename: \"User\",\n              id: \"43\",\n            })!;\n          },\n        },\n      });\n      expect(consoleSpy.warn).toHaveBeenLastCalledWith(\n        \"cache.modify: You are trying to write a Reference that is not part of the store: %o\\n\" +\n          \"Please make sure to set the `mergeIntoStore` parameter to `true` when creating a Reference that is not part of the store yet:\\n\" +\n          \"`toReference(object, true)`\",\n        { __ref: \"User:43\" }\n      );\n    }\n\n    // reading the cache returns `null`\n    expect(cache.readQuery({ query })).toEqual(null);\n    expect(cache.extract()).toEqual({\n      // User:43 is a dead ref\n      ROOT_QUERY: { __typename: \"Query\", me: { __ref: \"User:43\" } },\n      \"User:42\": {\n        __typename: \"User\",\n        id: \"42\",\n      },\n      // no User:43\n    });\n  });\n});\n\ndescribe(\"ReactiveVar and makeVar\", () => {\n  function makeCacheAndVar(resultCaching: boolean) {\n    const nameVar = makeVar(\"Ben\");\n    const cache: InMemoryCache = new InMemoryCache({\n      resultCaching,\n      typePolicies: {\n        Person: {\n          fields: {\n            name() {\n              return nameVar();\n            },\n          },\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        onCall @client {\n          name\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        onCall: {\n          __typename: \"Person\",\n        },\n      },\n    });\n\n    return {\n      cache,\n      nameVar,\n      query,\n    };\n  }\n\n  it(\"should work with resultCaching enabled (default)\", () => {\n    const { cache, nameVar, query } = makeCacheAndVar(true);\n\n    const result1 = cache.readQuery({ query });\n    expect(result1).toEqual({\n      onCall: {\n        __typename: \"Person\",\n        name: \"Ben\",\n      },\n    });\n\n    // No change before updating the nameVar.\n    expect(cache.readQuery({ query })).toBe(result1);\n\n    expect(nameVar()).toBe(\"Ben\");\n    expect(nameVar(\"Hugh\")).toBe(\"Hugh\");\n\n    const result2 = cache.readQuery({ query });\n    expect(result2).not.toBe(result1);\n    expect(result2).toEqual({\n      onCall: {\n        __typename: \"Person\",\n        name: \"Hugh\",\n      },\n    });\n\n    expect(nameVar()).toBe(\"Hugh\");\n    expect(nameVar(\"James\")).toBe(\"James\");\n\n    expect(cache.readQuery({ query })).toEqual({\n      onCall: {\n        __typename: \"Person\",\n        name: \"James\",\n      },\n    });\n  });\n\n  it(\"should work with resultCaching disabled (unusual)\", () => {\n    const { cache, nameVar, query } = makeCacheAndVar(false);\n\n    const result1 = cache.readQuery({ query });\n    expect(result1).toEqual({\n      onCall: {\n        __typename: \"Person\",\n        name: \"Ben\",\n      },\n    });\n\n    const result2 = cache.readQuery({ query });\n    expect(result2).toEqual(result1);\n    expect(result2).not.toBe(result1);\n\n    expect(nameVar()).toBe(\"Ben\");\n    expect(nameVar(\"Hugh\")).toBe(\"Hugh\");\n\n    const result3 = cache.readQuery({ query });\n    expect(result3).toEqual({\n      onCall: {\n        __typename: \"Person\",\n        name: \"Hugh\",\n      },\n    });\n  });\n\n  it(\"should forget cache once all watches are cancelled\", () => {\n    const { cache, nameVar, query } = makeCacheAndVar(false);\n    const spy = jest.spyOn(nameVar, \"forgetCache\");\n\n    const diffs: Cache.DiffResult<any>[] = [];\n    const watch = () =>\n      cache.watch({\n        query,\n        optimistic: true,\n        immediate: true,\n        callback(diff) {\n          diffs.push(diff);\n        },\n      });\n\n    const unwatchers = [watch(), watch(), watch(), watch(), watch()];\n\n    expect(diffs.length).toBe(5);\n\n    expect(cache[\"watches\"].size).toBe(5);\n    expect(spy).not.toHaveBeenCalled();\n\n    unwatchers.pop()!();\n    expect(cache[\"watches\"].size).toBe(4);\n    expect(spy).not.toHaveBeenCalled();\n\n    unwatchers.shift()!();\n    expect(cache[\"watches\"].size).toBe(3);\n    expect(spy).not.toHaveBeenCalled();\n\n    unwatchers.pop()!();\n    expect(cache[\"watches\"].size).toBe(2);\n    expect(spy).not.toHaveBeenCalled();\n\n    expect(diffs.length).toBe(5);\n    unwatchers.push(watch());\n    expect(diffs.length).toBe(6);\n\n    expect(unwatchers.length).toBe(3);\n    unwatchers.forEach((unwatch) => unwatch());\n\n    expect(cache[\"watches\"].size).toBe(0);\n    expect(spy).toHaveBeenCalledTimes(1);\n    expect(spy).toHaveBeenCalledWith(cache);\n  });\n\n  it(\"should remove all watchers when cache.reset() called\", () => {\n    const { cache, query, nameVar } = makeCacheAndVar(false);\n    const unwatchers: Record<string, Array<() => void>> = {};\n    const diffCounts: Record<string, number> = {};\n\n    function watch(id: string) {\n      const fns = unwatchers[id] || (unwatchers[id] = []);\n      fns.push(\n        cache.watch({\n          query,\n          optimistic: true,\n          immediate: true,\n          callback() {\n            diffCounts[id] = (diffCounts[id] || 0) + 1;\n          },\n        })\n      );\n    }\n\n    watch(\"a\");\n    watch(\"b\");\n    watch(\"c\");\n    watch(\"a\");\n    watch(\"d\");\n\n    expect(cache[\"watches\"].size).toBe(5);\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 1,\n      c: 1,\n      d: 1,\n    });\n\n    unwatchers.a.forEach((unwatch) => unwatch());\n    unwatchers.a.length = 0;\n    expect(cache[\"watches\"].size).toBe(3);\n\n    nameVar(\"Hugh\");\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n    });\n\n    cache.reset({ discardWatches: true });\n    expect(cache[\"watches\"].size).toBe(0);\n\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n    });\n\n    nameVar(\"Brian\");\n    // No change because cache.reset() called.\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        onCall: {\n          __typename: \"Person\",\n        },\n      },\n    });\n\n    watch(\"e\");\n    watch(\"f\");\n\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n      e: 1,\n      f: 1,\n    });\n\n    nameVar(\"Trevor\");\n    expect(cache[\"watches\"].size).toBe(2);\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n      e: 2,\n      f: 2,\n    });\n\n    cache.reset({ discardWatches: true });\n    expect(cache[\"watches\"].size).toBe(0);\n\n    nameVar(\"Danielle\");\n    expect(diffCounts).toEqual({\n      a: 2,\n      b: 2,\n      c: 2,\n      d: 2,\n      e: 2,\n      f: 2,\n    });\n\n    expect(cache[\"watches\"].size).toBe(0);\n  });\n\n  it(\"should recall forgotten vars once cache has watches again\", () => {\n    const { cache, nameVar, query } = makeCacheAndVar(false);\n    const spy = jest.spyOn(nameVar, \"forgetCache\");\n\n    const diffs: Cache.DiffResult<any>[] = [];\n    const watch = (immediate = true) =>\n      cache.watch({\n        query,\n        optimistic: true,\n        immediate,\n        callback(diff) {\n          diffs.push(diff);\n        },\n      });\n\n    const unwatchers = [watch(), watch(), watch()];\n\n    const names = () => diffs.map((diff) => diff.result.onCall.name);\n\n    expect(diffs.length).toBe(3);\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\"]);\n\n    expect(cache[\"watches\"].size).toBe(3);\n    expect(spy).not.toHaveBeenCalled();\n\n    unwatchers.pop()!();\n    expect(cache[\"watches\"].size).toBe(2);\n    expect(spy).not.toHaveBeenCalled();\n\n    unwatchers.shift()!();\n    expect(cache[\"watches\"].size).toBe(1);\n    expect(spy).not.toHaveBeenCalled();\n\n    nameVar(\"Hugh\");\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\", \"Hugh\"]);\n\n    unwatchers.pop()!();\n    expect(cache[\"watches\"].size).toBe(0);\n    expect(spy).toHaveBeenCalledTimes(1);\n    expect(spy).toHaveBeenCalledWith(cache);\n\n    // This update is ignored because the cache no longer has any watchers.\n    nameVar(\"ignored\");\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\", \"Hugh\"]);\n\n    // Call watch(false) to avoid immediate delivery of the \"ignored\" name.\n    unwatchers.push(watch(false));\n    expect(cache[\"watches\"].size).toBe(1);\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\", \"Hugh\"]);\n\n    // This is the test that would fail if cache.watch did not call\n    // recallCache(cache) upon re-adding the first watcher.\n    nameVar(\"Jenn\");\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\", \"Hugh\", \"Jenn\"]);\n\n    unwatchers.forEach((cancel) => cancel());\n    expect(spy).toHaveBeenCalledTimes(2);\n    expect(spy).toHaveBeenCalledWith(cache);\n\n    // Ignored again because all watchers have been cancelled.\n    nameVar(\"also ignored\");\n    expect(names()).toEqual([\"Ben\", \"Ben\", \"Ben\", \"Hugh\", \"Jenn\"]);\n  });\n\n  it(\"should broadcast only once for multiple reads of same variable\", () => {\n    const nameVar = makeVar(\"Ben\");\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            name() {\n              return nameVar();\n            },\n          },\n        },\n      },\n    });\n\n    // TODO This should not be necessary, but cache.readQuery currently\n    // returns null if we read a query before writing any queries.\n    cache.restore({\n      ROOT_QUERY: {},\n    });\n\n    const broadcast = cache[\"broadcastWatches\"];\n    let broadcastCount = 0;\n    cache[\"broadcastWatches\"] = function () {\n      ++broadcastCount;\n      // @ts-expect-error\n      return broadcast.apply(this, arguments);\n    };\n\n    const query = gql`\n      query {\n        name1: name\n        name2: name\n      }\n    `;\n\n    const watchDiffs: Cache.DiffResult<any>[] = [];\n    cache.watch({\n      query,\n      optimistic: true,\n      callback(diff) {\n        watchDiffs.push(diff);\n      },\n    });\n\n    const benResult = cache.readQuery({ query });\n    expect(benResult).toEqual({\n      name1: \"Ben\",\n      name2: \"Ben\",\n    });\n\n    expect(watchDiffs).toEqual([]);\n\n    expect(broadcastCount).toBe(0);\n    nameVar(\"Jenn\");\n    expect(broadcastCount).toBe(1);\n\n    const jennResult = cache.readQuery({ query });\n    expect(jennResult).toEqual({\n      name1: \"Jenn\",\n      name2: \"Jenn\",\n    });\n\n    expect(watchDiffs).toEqual([\n      {\n        complete: true,\n        result: {\n          name1: \"Jenn\",\n          name2: \"Jenn\",\n        },\n      },\n    ]);\n\n    expect(broadcastCount).toBe(1);\n    nameVar(\"Hugh\");\n    expect(broadcastCount).toBe(2);\n\n    const hughResult = cache.readQuery({ query });\n    expect(hughResult).toEqual({\n      name1: \"Hugh\",\n      name2: \"Hugh\",\n    });\n\n    expect(watchDiffs).toEqual([\n      {\n        complete: true,\n        result: {\n          name1: \"Jenn\",\n          name2: \"Jenn\",\n        },\n      },\n      {\n        complete: true,\n        result: {\n          name1: \"Hugh\",\n          name2: \"Hugh\",\n        },\n      },\n    ]);\n  });\n\n  it(\"should broadcast to manually added caches\", () => {\n    const rv = makeVar(0);\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        value\n      }\n    `;\n    const diffs: Cache.DiffResult<any>[] = [];\n    const watch: Cache.WatchOptions = {\n      query,\n      optimistic: true,\n      callback(diff) {\n        diffs.push(diff);\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        value: \"oyez\",\n      },\n    });\n\n    const cancel = cache.watch(watch);\n\n    // This should not trigger a broadcast, since we haven't associated\n    // this cache with rv yet.\n    rv(rv() + 1);\n    expect(diffs).toEqual([]);\n\n    // The rv.attachCache method returns rv, for chaining.\n    rv.attachCache(cache)(rv() + 1);\n\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: {\n          value: \"oyez\",\n        },\n      },\n    ]);\n\n    cache.writeQuery({\n      query,\n      broadcast: false,\n      data: {\n        value: \"oyez, oyez\",\n      },\n    });\n\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: {\n          value: \"oyez\",\n        },\n      },\n    ]);\n\n    rv(rv() + 1);\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: {\n          value: \"oyez\",\n        },\n      },\n      {\n        complete: true,\n        result: {\n          value: \"oyez, oyez\",\n        },\n      },\n    ]);\n\n    expect(rv.forgetCache(cache)).toBe(true);\n\n    cache.writeQuery({\n      query,\n      broadcast: false,\n      data: {\n        value: \"oyez, oyez, oyez\",\n      },\n    });\n\n    // Since we called rv.forgetCache(cache) above, updating rv here\n    // should not trigger a broadcast.\n    rv(rv() + 1);\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: {\n          value: \"oyez\",\n        },\n      },\n      {\n        complete: true,\n        result: {\n          value: \"oyez, oyez\",\n        },\n      },\n    ]);\n\n    cache[\"broadcastWatches\"]();\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: {\n          value: \"oyez\",\n        },\n      },\n      {\n        complete: true,\n        result: {\n          value: \"oyez, oyez\",\n        },\n      },\n      {\n        complete: true,\n        result: {\n          value: \"oyez, oyez, oyez\",\n        },\n      },\n    ]);\n\n    cancel();\n\n    expect(rv()).toBe(4);\n  });\n});\n\ndescribe(\"TypedDocumentNode<Data, Variables>\", () => {\n  type Book = {\n    isbn?: string;\n    title: string;\n    author: {\n      name: string;\n    };\n  };\n\n  const query: TypedDocumentNode<{ book: Book }, { isbn: string }> = gql`\n    query GetBook($isbn: String!) {\n      book(isbn: $isbn) {\n        title\n        author {\n          name\n        }\n      }\n    }\n  `;\n\n  const fragment: TypedDocumentNode<Book> = gql`\n    fragment TitleAndAuthor on Book {\n      title\n      isbn\n      author {\n        name\n      }\n    }\n  `;\n\n  // We need to define these objects separately from calling writeQuery,\n  // because passing them directly to writeQuery will trigger excess property\n  // warnings due to the extra __typename and isbn fields. Internally, we\n  // almost never pass object literals to writeQuery or writeFragment, so\n  // excess property checks should not be a problem in practice.\n  const jcmAuthor = {\n    __typename: \"Author\",\n    name: \"John C. Mitchell\",\n  };\n\n  const ffplBook = {\n    __typename: \"Book\",\n    isbn: \"0262133210\",\n    title: \"Foundations for Programming Languages\",\n    author: jcmAuthor,\n  };\n\n  const ffplVariables = {\n    isbn: \"0262133210\",\n  };\n\n  function getBookCache() {\n    return new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            book(existing, { args, toReference }) {\n              return (\n                existing ??\n                (args &&\n                  toReference({\n                    __typename: \"Book\",\n                    isbn: args.isbn,\n                  }))\n              );\n            },\n          },\n        },\n\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n\n        Author: {\n          keyFields: [\"name\"],\n        },\n      },\n    });\n  }\n\n  it(\"should determine Data and Variables types of {write,read}{Query,Fragment}\", () => {\n    const cache = getBookCache();\n\n    cache.writeQuery({\n      query,\n      variables: ffplVariables,\n      data: {\n        book: ffplBook,\n      },\n    });\n\n    expect(cache.extract()).toMatchSnapshot();\n\n    const ffplQueryResult = cache.readQuery({\n      query,\n      variables: ffplVariables,\n    });\n\n    if (ffplQueryResult === null) throw new Error(\"null result\");\n    expect(ffplQueryResult.book.isbn).toBeUndefined();\n    expect(ffplQueryResult.book.author.name).toBe(jcmAuthor.name);\n    expect(ffplQueryResult).toEqual({\n      book: {\n        __typename: \"Book\",\n        title: \"Foundations for Programming Languages\",\n        author: {\n          __typename: \"Author\",\n          name: \"John C. Mitchell\",\n        },\n      },\n    });\n\n    const sicpBook = {\n      __typename: \"Book\",\n      isbn: \"0262510871\",\n      title: \"Structure and Interpretation of Computer Programs\",\n      author: {\n        __typename: \"Author\",\n        name: \"Harold Abelson\",\n      },\n    };\n\n    const sicpRef = cache.writeFragment({\n      fragment,\n      data: sicpBook,\n    });\n\n    expect(isReference(sicpRef)).toBe(true);\n    expect(cache.extract()).toMatchSnapshot();\n\n    const ffplFragmentResult = cache.readFragment({\n      fragment,\n      id: cache.identify(ffplBook),\n    });\n    if (ffplFragmentResult === null) throw new Error(\"null result\");\n    expect(ffplFragmentResult.title).toBe(ffplBook.title);\n    expect(ffplFragmentResult.author.name).toBe(ffplBook.author.name);\n    expect(ffplFragmentResult).toEqual(ffplBook);\n\n    // This uses the read function for the Query.book field.\n    const sicpReadResult = cache.readQuery({\n      query,\n      variables: {\n        isbn: sicpBook.isbn,\n      },\n    });\n    if (sicpReadResult === null) throw new Error(\"null result\");\n    expect(sicpReadResult.book.isbn).toBeUndefined();\n    expect(sicpReadResult.book.title).toBe(sicpBook.title);\n    expect(sicpReadResult.book.author.name).toBe(sicpBook.author.name);\n    expect(sicpReadResult).toEqual({\n      book: {\n        __typename: \"Book\",\n        title: \"Structure and Interpretation of Computer Programs\",\n        author: {\n          __typename: \"Author\",\n          name: \"Harold Abelson\",\n        },\n      },\n    });\n  });\n\n  it.skip(\"should infer the types of modifier fields\", () => {\n    const cache = getBookCache();\n\n    cache.writeQuery({\n      query,\n      variables: ffplVariables,\n      data: {\n        book: ffplBook,\n      },\n    });\n\n    cache.modify<Book>({\n      id: cache.identify(ffplBook),\n      fields: {\n        isbn: (value) => {\n          expectTypeOf(value).toEqualTypeOf<string>();\n          return value;\n        },\n        title: (value, { INVALIDATE }) => {\n          expectTypeOf(value).toEqualTypeOf<string>();\n          return INVALIDATE;\n        },\n        author: (value, { DELETE, isReference }) => {\n          expectTypeOf(value).toEqualTypeOf<Reference | Book[\"author\"]>();\n          if (isReference(value)) {\n            expectTypeOf(value).toEqualTypeOf<Reference>();\n          } else {\n            expectTypeOf(value).toEqualTypeOf<Book[\"author\"]>();\n          }\n\n          return DELETE;\n        },\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/cache.writeQuery/extensions.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\n\ntest(\"extensions are available in merge functions\", () => {\n  const extensions = {\n    customField: \"customValue\",\n    metadata: { version: 1 },\n  };\n\n  const merge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  cache.writeQuery({\n    query: gql`\n      query {\n        book {\n          title\n        }\n      }\n    `,\n    data: {\n      book: {\n        __typename: \"Book\",\n        title: \"Test Book\",\n      },\n    },\n    extensions,\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    undefined,\n    { __typename: \"Book\", title: \"Test Book\" },\n    expect.objectContaining({ extensions })\n  );\n});\n\ntest(\"extensions are undefined when not provided\", () => {\n  const merge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  cache.writeQuery({\n    query: gql`\n      query {\n        book {\n          title\n        }\n      }\n    `,\n    data: {\n      book: {\n        __typename: \"Book\",\n        title: \"Test Book\",\n      },\n    },\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    undefined,\n    { __typename: \"Book\", title: \"Test Book\" },\n    expect.objectContaining({ extensions: undefined })\n  );\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/diffAgainstStore.ts",
    "content": "import { disableFragmentWarnings, gql } from \"graphql-tag\";\n\nimport { MissingFieldError } from \"@apollo/client\";\nimport { defaultDataIdFromObject, InMemoryCache } from \"@apollo/client/cache\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreReader } from \"../readFromStore.js\";\nimport type { NormalizedCache, Reference } from \"../types.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreWriter } from \"../writeToStore.js\";\n\nimport {\n  defaultNormalizedCacheFactory,\n  withError,\n  writeQueryToStore,\n} from \"./helpers.js\";\n\ndisableFragmentWarnings();\n\ndescribe(\"diffing queries against the store\", () => {\n  const cache = new InMemoryCache({\n    dataIdFromObject: defaultDataIdFromObject,\n  });\n  const reader = new StoreReader({ cache });\n  const writer = new StoreWriter(cache);\n\n  it(\n    \"expects named fragments to return complete as false when diffd against \" +\n      \"the store\",\n    () => {\n      const store = defaultNormalizedCacheFactory({});\n\n      const queryResult = reader.diffQueryAgainstStore({\n        store,\n        query: gql`\n          query foo {\n            ...root\n          }\n\n          fragment root on Query {\n            nestedObj {\n              innerArray {\n                id\n                someField\n              }\n            }\n          }\n        `,\n      });\n\n      expect(queryResult.complete).toEqual(false);\n      expect(queryResult.result).toEqual(null);\n    }\n  );\n\n  it(\n    \"expects inline fragments to return complete as false when diffd against \" +\n      \"the store\",\n    () => {\n      const store = defaultNormalizedCacheFactory();\n\n      const queryResult = reader.diffQueryAgainstStore({\n        store,\n        query: gql`\n          {\n            ... on DummyQuery {\n              nestedObj {\n                innerArray {\n                  id\n                  otherField\n                }\n              }\n            }\n            ... on Query {\n              nestedObj {\n                innerArray {\n                  id\n                  someField\n                }\n              }\n            }\n            ... on DummyQuery2 {\n              nestedObj {\n                innerArray {\n                  id\n                  otherField2\n                }\n              }\n            }\n          }\n        `,\n      });\n\n      expect(queryResult.complete).toEqual(false);\n      expect(queryResult.result).toEqual(null);\n    }\n  );\n\n  // TODO: Determine what this means. `complete` is `true` and the result is the\n  // written result, so I'm not sure what the \"nothing\" is referring to or what\n  // it means for the store to be \"enough\".\n  it(\"returns nothing when the store is enough\", () => {\n    const query = gql`\n      {\n        people_one(id: \"1\") {\n          name\n        }\n      }\n    `;\n\n    const result = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const store = writeQueryToStore({\n      writer,\n      result,\n      query,\n    });\n\n    const queryResult = reader.diffQueryAgainstStore({\n      store,\n      query,\n    });\n\n    expect(queryResult.complete).toBe(true);\n    expect(queryResult.result).toEqual(result);\n  });\n\n  it(\"correctly returns a complete result with an empty object if all fields are non-included or skipped\", () => {\n    const query = gql`\n      query {\n        firstName @include(if: false)\n        lastName @skip(if: true)\n      }\n    `;\n\n    const store = writeQueryToStore({\n      writer,\n      result: {},\n      query,\n    });\n\n    const queryResult = reader.diffQueryAgainstStore({\n      store,\n      query,\n    });\n\n    expect(queryResult).toStrictEqualTyped({\n      complete: true,\n      result: {},\n      missing: undefined,\n    });\n  });\n\n  it(\"caches root queries both under the ID of the node and the query name\", () => {\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        typePolicies: {\n          Person: {\n            keyFields: [\"id\"],\n          },\n        },\n      })\n    );\n\n    const store = writeQueryToStore({\n      writer,\n      query: gql`\n        {\n          people_one(id: \"1\") {\n            __typename\n            idAlias: id\n            name\n          }\n        }\n      `,\n      result: {\n        people_one: {\n          __typename: \"Person\",\n          idAlias: \"1\",\n          name: \"Luke Skywalker\",\n        },\n      },\n    });\n\n    const secondQuery = gql`\n      {\n        people_one(id: \"1\") {\n          __typename\n          id\n          name\n        }\n      }\n    `;\n\n    const { result, complete } = reader.diffQueryAgainstStore({\n      store,\n      query: secondQuery,\n    });\n\n    expect(complete).toBe(true);\n    expect(result).toEqual({\n      people_one: { __typename: \"Person\", id: \"1\", name: \"Luke Skywalker\" },\n    });\n    expect((store as any).lookup('Person:{\"id\":\"1\"}')).toEqual({\n      __typename: \"Person\",\n      id: \"1\",\n      name: \"Luke Skywalker\",\n    });\n  });\n\n  it(\"does not swallow errors other than field errors\", () => {\n    const firstQuery = gql`\n      query {\n        person {\n          powers\n        }\n      }\n    `;\n    const firstResult = {\n      person: {\n        powers: \"the force\",\n      },\n    };\n    const store = writeQueryToStore({\n      writer,\n      result: firstResult,\n      query: firstQuery,\n    });\n    const unionQuery = gql`\n      query {\n        ...notARealFragment\n      }\n    `;\n    return expect(() => {\n      reader.diffQueryAgainstStore({\n        store,\n        query: unionQuery,\n      });\n    }).toThrow(/No fragment/);\n  });\n\n  it(\"does not error on a correct query with union typed fragments\", () => {\n    return withError(() => {\n      const firstQuery = gql`\n        query {\n          person {\n            __typename\n            firstName\n            lastName\n          }\n        }\n      `;\n      const firstResult = {\n        person: {\n          __typename: \"Author\",\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const store = writeQueryToStore({\n        writer,\n        result: firstResult,\n        query: firstQuery,\n      });\n      const unionQuery = gql`\n        query {\n          person {\n            __typename\n            ... on Author {\n              firstName\n              lastName\n            }\n            ... on Jedi {\n              powers\n            }\n          }\n        }\n      `;\n      const { complete, result } = reader.diffQueryAgainstStore({\n        store,\n        query: unionQuery,\n        returnPartialData: false,\n      });\n\n      expect(complete).toBe(true);\n      expect(result).toEqual(firstResult);\n    });\n  });\n\n  it(\"does not error on a query with fields missing from all but one named fragment\", () => {\n    const firstQuery = gql`\n      query {\n        person {\n          __typename\n          firstName\n          lastName\n        }\n      }\n    `;\n    const firstResult = {\n      person: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const store = writeQueryToStore({\n      writer,\n      result: firstResult,\n      query: firstQuery,\n    });\n    const unionQuery = gql`\n      query {\n        person {\n          __typename\n          ...authorInfo\n          ...jediInfo\n        }\n      }\n\n      fragment authorInfo on Author {\n        firstName\n      }\n\n      fragment jediInfo on Jedi {\n        powers\n      }\n    `;\n\n    const { complete, result } = reader.diffQueryAgainstStore({\n      store,\n      query: unionQuery,\n    });\n\n    expect(complete).toBe(true);\n    expect(result).toEqual({\n      person: { __typename: \"Author\", firstName: \"John\" },\n    });\n  });\n\n  it(\"returns null result on a query with fields missing from matching named fragments\", () => {\n    const firstQuery = gql`\n      query {\n        person {\n          __typename\n          firstName\n          lastName\n        }\n      }\n    `;\n    const firstResult = {\n      person: {\n        __typename: \"Author\",\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const store = writeQueryToStore({\n      writer,\n      result: firstResult,\n      query: firstQuery,\n    });\n    const unionQuery = gql`\n      query {\n        person {\n          __typename\n          ...authorInfo2\n          ...jediInfo2\n        }\n      }\n\n      fragment authorInfo2 on Author {\n        firstName\n        address\n      }\n\n      fragment jediInfo2 on Jedi {\n        jedi\n      }\n    `;\n\n    const { complete, result, missing } = reader.diffQueryAgainstStore({\n      store,\n      query: unionQuery,\n      returnPartialData: false,\n    });\n\n    const missingFieldErrorMessage = `Can't find field 'address' on object ${JSON.stringify(\n      firstResult.person,\n      null,\n      2\n    )}`;\n\n    expect(complete).toBe(false);\n    expect(result).toBe(null);\n    expect(missing).toEqual(\n      new MissingFieldError(\n        missingFieldErrorMessage,\n        {\n          person: {\n            address: missingFieldErrorMessage,\n          },\n        },\n        unionQuery,\n        {}\n      )\n    );\n  });\n\n  it(\"returns available fields if returnPartialData is true\", () => {\n    const firstQuery = gql`\n      {\n        people_one(id: \"1\") {\n          __typename\n          id\n          name\n        }\n      }\n    `;\n\n    const firstResult = {\n      people_one: {\n        __typename: \"Person\",\n        id: \"lukeId\",\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const store = writeQueryToStore({\n      writer,\n      result: firstResult,\n      query: firstQuery,\n    });\n\n    // Variants on a simple query with a missing field.\n\n    const simpleQuery = gql`\n      {\n        people_one(id: \"1\") {\n          name\n          age\n        }\n      }\n    `;\n\n    const inlineFragmentQuery = gql`\n      {\n        people_one(id: \"1\") {\n          ... on Person {\n            name\n            age\n          }\n        }\n      }\n    `;\n\n    const namedFragmentQuery = gql`\n      query {\n        people_one(id: \"1\") {\n          ...personInfo\n        }\n      }\n\n      fragment personInfo on Person {\n        name\n        age\n      }\n    `;\n\n    const simpleDiff = reader.diffQueryAgainstStore({\n      store,\n      query: simpleQuery,\n    });\n\n    expect(simpleDiff.complete).toBe(false);\n    expect(simpleDiff.result).toEqual({\n      people_one: {\n        __typename: \"Person\",\n        name: \"Luke Skywalker\",\n      },\n    });\n\n    const inlineDiff = reader.diffQueryAgainstStore({\n      store,\n      query: inlineFragmentQuery,\n    });\n\n    expect(inlineDiff.complete).toBe(false);\n    expect(inlineDiff.result).toEqual({\n      people_one: {\n        __typename: \"Person\",\n        name: \"Luke Skywalker\",\n      },\n    });\n\n    const namedDiff = reader.diffQueryAgainstStore({\n      store,\n      query: namedFragmentQuery,\n    });\n\n    expect(namedDiff.complete).toBe(false);\n    expect(namedDiff.result).toEqual({\n      people_one: {\n        __typename: \"Person\",\n        name: \"Luke Skywalker\",\n      },\n    });\n\n    const { complete, result, missing } = reader.diffQueryAgainstStore({\n      store,\n      query: simpleQuery,\n      returnPartialData: false,\n    });\n\n    const missingFieldErrorMessage = `Can't find field 'age' on Person:lukeId object`;\n\n    expect(complete).toBe(false);\n    expect(result).toBeNull();\n    expect(missing).toEqual(\n      new MissingFieldError(\n        missingFieldErrorMessage,\n        { people_one: { age: missingFieldErrorMessage } },\n        simpleQuery,\n        {}\n      )\n    );\n  });\n\n  it(\"will add a private id property\", () => {\n    const query = gql`\n      query {\n        a {\n          id\n          b\n        }\n        c {\n          d\n          e {\n            id\n            f\n          }\n          g {\n            h\n          }\n        }\n      }\n    `;\n\n    const queryResult = {\n      a: [\n        { id: \"a:1\", b: 1.1 },\n        { id: \"a:2\", b: 1.2 },\n        { id: \"a:3\", b: 1.3 },\n      ],\n      c: {\n        d: 2,\n        e: [\n          { id: \"e:1\", f: 3.1 },\n          { id: \"e:2\", f: 3.2 },\n          { id: \"e:3\", f: 3.3 },\n          { id: \"e:4\", f: 3.4 },\n          { id: \"e:5\", f: 3.5 },\n        ],\n        g: { h: 4 },\n      },\n    };\n\n    const cache = new InMemoryCache({\n      dataIdFromObject(obj: any) {\n        return obj.id;\n      },\n    });\n\n    const writer = new StoreWriter(cache);\n\n    const store = writeQueryToStore({\n      writer,\n      query,\n      result: queryResult,\n    });\n\n    const { result } = reader.diffQueryAgainstStore<any>({\n      store,\n      query,\n    });\n\n    expect(result).toEqual(queryResult);\n    expect(cache.identify(result.a[0])).toEqual(\"a:1\");\n    expect(cache.identify(result.a[1])).toEqual(\"a:2\");\n    expect(cache.identify(result.a[2])).toEqual(\"a:3\");\n    expect(cache.identify(result.c.e[0])).toEqual(\"e:1\");\n    expect(cache.identify(result.c.e[1])).toEqual(\"e:2\");\n    expect(cache.identify(result.c.e[2])).toEqual(\"e:3\");\n    expect(cache.identify(result.c.e[3])).toEqual(\"e:4\");\n    expect(cache.identify(result.c.e[4])).toEqual(\"e:5\");\n  });\n\n  // TODO: Remove these tests on the 4.0 branch. Support for the\n  // `previousResult` option was removed in https://github.com/apollographql/apollo-client/pull/5644\n  // so there is no referential equality in the way these tests are making them.\n  // We should remove support for `previousResult` entirely from the TypeScript\n  // types and eliminate any use in the codebase since this option is completely\n  // ignored within `diffQueryAgainstStore`.\n  describe(\"referential equality preservation\", () => {\n    it(\"will return the previous result if there are no changes\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n          c {\n            d\n            e {\n              f\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: { b: 1 },\n        c: { d: 2, e: { f: 3 } },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: { b: 1 },\n        c: { d: 2, e: { f: 3 } },\n      };\n\n      const { result } = reader.diffQueryAgainstStore({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).not.toBe(queryResult);\n      expect(result).not.toBe(previousResult);\n      expect(result).toEqual(queryResult);\n      expect(result).toEqual(previousResult);\n    });\n\n    it(\"will return parts of the previous result that changed\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n          c {\n            d\n            e {\n              f\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: { b: 1 },\n        c: { d: 2, e: { f: 3 } },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: { b: 1 },\n        c: { d: 20, e: { f: 3 } },\n      };\n\n      const { result } = reader.diffQueryAgainstStore<any>({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).not.toEqual(previousResult);\n      expect(result.a).toEqual(previousResult.a);\n      expect(result.c).not.toEqual(previousResult.c);\n      expect(result.c.e).toEqual(previousResult.c.e);\n    });\n\n    it(\"will return the previous result if there are no changes in child arrays\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n          c {\n            d\n            e {\n              f\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: [{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }],\n        c: {\n          d: 2,\n          e: [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }, { f: 3.4 }, { f: 3.5 }],\n        },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: [{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }],\n        c: {\n          d: 2,\n          e: [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }, { f: 3.4 }, { f: 3.5 }],\n        },\n      };\n\n      const { result } = reader.diffQueryAgainstStore({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).toEqual(previousResult);\n    });\n\n    it(\"will not add zombie items when previousResult starts with the same items\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: [{ b: 1.1 }, { b: 1.2 }],\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: [{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }],\n      };\n\n      const { result } = reader.diffQueryAgainstStore<any>({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result.a[0]).toEqual(previousResult.a[0]);\n      expect(result.a[1]).toEqual(previousResult.a[1]);\n    });\n\n    it(\"will return the previous result if there are no changes in nested child arrays\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n          c {\n            d\n            e {\n              f\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: [[[[[{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }]]]]],\n        c: {\n          d: 2,\n          e: [\n            [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }],\n            [{ f: 3.4 }, { f: 3.5 }],\n          ],\n        },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: [[[[[{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }]]]]],\n        c: {\n          d: 2,\n          e: [\n            [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }],\n            [{ f: 3.4 }, { f: 3.5 }],\n          ],\n        },\n      };\n\n      const { result } = reader.diffQueryAgainstStore({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).toEqual(previousResult);\n    });\n\n    it(\"will return parts of the previous result if there are changes in child arrays\", () => {\n      const query = gql`\n        query {\n          a {\n            b\n          }\n          c {\n            d\n            e {\n              f\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: [{ b: 1.1 }, { b: 1.2 }, { b: 1.3 }],\n        c: {\n          d: 2,\n          e: [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }, { f: 3.4 }, { f: 3.5 }],\n        },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: [{ b: 1.1 }, { b: -1.2 }, { b: 1.3 }],\n        c: {\n          d: 20,\n          e: [{ f: 3.1 }, { f: 3.2 }, { f: 3.3 }, { f: 3.4 }, { f: 3.5 }],\n        },\n      };\n\n      const { result } = reader.diffQueryAgainstStore<any>({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).not.toEqual(previousResult);\n      expect(result.a).not.toEqual(previousResult.a);\n      expect(result.a[0]).toEqual(previousResult.a[0]);\n      expect(result.a[1]).not.toEqual(previousResult.a[1]);\n      expect(result.a[2]).toEqual(previousResult.a[2]);\n      expect(result.c).not.toEqual(previousResult.c);\n      expect(result.c.e).toEqual(previousResult.c.e);\n      expect(result.c.e[0]).toEqual(previousResult.c.e[0]);\n      expect(result.c.e[1]).toEqual(previousResult.c.e[1]);\n      expect(result.c.e[2]).toEqual(previousResult.c.e[2]);\n      expect(result.c.e[3]).toEqual(previousResult.c.e[3]);\n      expect(result.c.e[4]).toEqual(previousResult.c.e[4]);\n    });\n\n    it(\"will return the same items in a different order with `dataIdFromObject`\", () => {\n      const query = gql`\n        query {\n          a {\n            id\n            b\n          }\n          c {\n            d\n            e {\n              id\n              f\n            }\n            g {\n              h\n            }\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: [\n          { id: \"a:1\", b: 1.1 },\n          { id: \"a:2\", b: 1.2 },\n          { id: \"a:3\", b: 1.3 },\n        ],\n        c: {\n          d: 2,\n          e: [\n            { id: \"e:1\", f: 3.1 },\n            { id: \"e:2\", f: 3.2 },\n            { id: \"e:3\", f: 3.3 },\n            { id: \"e:4\", f: 3.4 },\n            { id: \"e:5\", f: 3.5 },\n          ],\n          g: { h: 4 },\n        },\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: (obj: any) => obj.id,\n        })\n      );\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: [\n          { id: \"a:3\", b: 1.3 },\n          { id: \"a:2\", b: 1.2 },\n          { id: \"a:1\", b: 1.1 },\n        ],\n        c: {\n          d: 2,\n          e: [\n            { id: \"e:4\", f: 3.4 },\n            { id: \"e:2\", f: 3.2 },\n            { id: \"e:5\", f: 3.5 },\n            { id: \"e:3\", f: 3.3 },\n            { id: \"e:1\", f: 3.1 },\n          ],\n          g: { h: 4 },\n        },\n      };\n\n      const { result } = reader.diffQueryAgainstStore<any>({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).not.toEqual(previousResult);\n      expect(result.a).not.toEqual(previousResult.a);\n      expect(result.a[0]).toEqual(previousResult.a[2]);\n      expect(result.a[1]).toEqual(previousResult.a[1]);\n      expect(result.a[2]).toEqual(previousResult.a[0]);\n      expect(result.c).not.toEqual(previousResult.c);\n      expect(result.c.e).not.toEqual(previousResult.c.e);\n      expect(result.c.e[0]).toEqual(previousResult.c.e[4]);\n      expect(result.c.e[1]).toEqual(previousResult.c.e[1]);\n      expect(result.c.e[2]).toEqual(previousResult.c.e[3]);\n      expect(result.c.e[3]).toEqual(previousResult.c.e[0]);\n      expect(result.c.e[4]).toEqual(previousResult.c.e[2]);\n      expect(result.c.g).toEqual(previousResult.c.g);\n    });\n\n    it(\"will return the same JSON scalar field object\", () => {\n      const query = gql`\n        {\n          a {\n            b\n            c\n          }\n          d {\n            e\n            f\n          }\n        }\n      `;\n\n      const queryResult = {\n        a: { b: 1, c: { x: 2, y: 3, z: 4 } },\n        d: { e: 5, f: { x: 6, y: 7, z: 8 } },\n      };\n\n      const store = writeQueryToStore({\n        writer,\n        query,\n        result: queryResult,\n      });\n\n      const previousResult = {\n        a: { b: 1, c: { x: 2, y: 3, z: 4 } },\n        d: { e: 50, f: { x: 6, y: 7, z: 8 } },\n      };\n\n      const { result } = reader.diffQueryAgainstStore<any>({\n        store,\n        query,\n        previousResult,\n      });\n\n      expect(result).toEqual(queryResult);\n      expect(result).not.toEqual(previousResult);\n      expect(result.a).toEqual(previousResult.a);\n      expect(result.d).not.toEqual(previousResult.d);\n      expect(result.d.f).toEqual(previousResult.d.f);\n    });\n\n    it(\"will preserve equality with custom resolvers\", () => {\n      const listQuery = gql`\n        {\n          people {\n            id\n            name\n            __typename\n          }\n        }\n      `;\n\n      const listResult = {\n        people: [\n          {\n            id: 4,\n            name: \"Luke Skywalker\",\n            __typename: \"Person\",\n          },\n        ],\n      };\n\n      const itemQuery = gql`\n        {\n          person(id: 4) {\n            id\n            name\n            __typename\n          }\n        }\n      `;\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              person(_, { args, isReference, toReference, readField }) {\n                expect(typeof args!.id).toBe(\"number\");\n                const ref = toReference({ __typename: \"Person\", id: args!.id });\n                expect(isReference(ref)).toBe(true);\n                expect(ref).toEqual({\n                  __ref: `Person:${JSON.stringify({ id: args!.id })}`,\n                });\n                const found = readField<Reference[]>(\"people\")!.find(\n                  (person) => ref && person.__ref === ref.__ref\n                );\n                expect(found).toBeTruthy();\n                return found;\n              },\n            },\n          },\n          Person: {\n            keyFields: [\"id\"],\n          },\n        },\n      });\n\n      const reader = new StoreReader({ cache });\n      const writer = new StoreWriter(cache, reader);\n\n      const store = writeQueryToStore({\n        writer,\n        query: listQuery,\n        result: listResult,\n      });\n\n      const previousResult = {\n        person: listResult.people[0],\n      };\n\n      const { result } = reader.diffQueryAgainstStore({\n        store,\n        query: itemQuery,\n        previousResult,\n      });\n\n      expect(result).toEqual(previousResult);\n    });\n  });\n\n  describe(\"malformed queries\", () => {\n    it(\"throws for non-scalar query fields without selection sets\", () => {\n      // Issue #4025, fixed by PR #4038.\n\n      const validQuery = gql`\n        query getMessageList {\n          messageList {\n            id\n            __typename\n            message\n          }\n        }\n      `;\n\n      const invalidQuery = gql`\n        query getMessageList {\n          # This field needs a selection set because its value is an array\n          # of non-scalar objects.\n          messageList\n        }\n      `;\n\n      const store = writeQueryToStore({\n        writer,\n        query: validQuery,\n        result: {\n          messageList: [\n            {\n              id: 1,\n              __typename: \"Message\",\n              message: \"hi\",\n            },\n            {\n              id: 2,\n              __typename: \"Message\",\n              message: \"hello\",\n            },\n            {\n              id: 3,\n              __typename: \"Message\",\n              message: \"hey\",\n            },\n          ],\n        },\n      });\n\n      expect(() => {\n        reader.diffQueryAgainstStore({\n          store,\n          query: invalidQuery,\n        });\n      }).toThrow(\n        \"Missing selection set for object of type Message returned for query field messageList\"\n      );\n    });\n  });\n\n  describe(\"issue #4081\", () => {\n    it(\"should not return results containing cycles\", () => {\n      const company = {\n        __typename: \"Company\",\n        id: 1,\n        name: \"Apollo\",\n        users: [],\n      } as any;\n\n      company.users.push(\n        {\n          __typename: \"User\",\n          id: 1,\n          name: \"Ben\",\n          company,\n        },\n        {\n          __typename: \"User\",\n          id: 2,\n          name: \"James\",\n          company,\n        }\n      );\n\n      const query = gql`\n        query Query {\n          user {\n            ...UserFragment\n            company {\n              users {\n                ...UserFragment\n              }\n            }\n          }\n        }\n\n        fragment UserFragment on User {\n          id\n          name\n          company {\n            id\n            name\n          }\n        }\n      `;\n\n      function check(store: NormalizedCache) {\n        const { result } = reader.diffQueryAgainstStore({ store, query });\n\n        // This JSON.stringify call has the side benefit of verifying that the\n        // result does not have any cycles.\n        const json = JSON.stringify(result);\n\n        company.users.forEach((user: any) => {\n          expect(json).toContain(JSON.stringify(user.name));\n        });\n\n        expect(result).toEqual({\n          user: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Ben\",\n            company: {\n              __typename: \"Company\",\n              id: 1,\n              name: \"Apollo\",\n              users: [\n                {\n                  __typename: \"User\",\n                  id: 1,\n                  name: \"Ben\",\n                  company: {\n                    __typename: \"Company\",\n                    id: 1,\n                    name: \"Apollo\",\n                  },\n                },\n                {\n                  __typename: \"User\",\n                  id: 2,\n                  name: \"James\",\n                  company: {\n                    __typename: \"Company\",\n                    id: 1,\n                    name: \"Apollo\",\n                  },\n                },\n              ],\n            },\n          },\n        });\n      }\n\n      // Check first using generated IDs.\n      check(\n        writeQueryToStore({\n          writer: new StoreWriter(\n            new InMemoryCache({\n              dataIdFromObject: void 0,\n            })\n          ),\n          query,\n          result: {\n            user: company.users[0],\n          },\n        })\n      );\n\n      // Now check with __typename-specific IDs.\n      check(\n        writeQueryToStore({\n          writer: new StoreWriter(\n            new InMemoryCache({\n              dataIdFromObject: defaultDataIdFromObject,\n            })\n          ),\n          query,\n          result: {\n            user: company.users[0],\n          },\n        })\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/entityStore.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport type { ApolloCache } from \"@apollo/client/cache\";\nimport {\n  EntityStore,\n  InMemoryCache,\n  MissingFieldError,\n} from \"@apollo/client/cache\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { isReference } from \"@apollo/client/utilities\";\nimport {\n  makeReference,\n  stringifyForDisplay,\n} from \"@apollo/client/utilities/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport type {\n  Reference,\n  StoreValue,\n} from \"../../../utilities/graphql/storeUtils.js\";\nimport type { Cache } from \"../../core/types/Cache.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { supportsResultCaching } from \"../entityStore.js\";\nimport type { StoreObject } from \"../types.js\";\n\ndescribe(\"EntityStore\", () => {\n  it(\"should support result caching if so configured\", () => {\n    const cache = new InMemoryCache();\n\n    const storeWithResultCaching = new EntityStore.Root({\n      policies: cache.policies,\n      resultCaching: true,\n    });\n\n    const storeWithoutResultCaching = new EntityStore.Root({\n      policies: cache.policies,\n      resultCaching: false,\n    });\n\n    expect(supportsResultCaching({ some: \"arbitrary object \" })).toBe(false);\n    expect(supportsResultCaching(storeWithResultCaching)).toBe(true);\n    expect(supportsResultCaching(storeWithoutResultCaching)).toBe(false);\n\n    const layerWithCaching = storeWithResultCaching.addLayer(\n      \"with caching\",\n      () => {}\n    );\n    expect(supportsResultCaching(layerWithCaching)).toBe(true);\n    const anotherLayer = layerWithCaching.addLayer(\"another layer\", () => {});\n    expect(supportsResultCaching(anotherLayer)).toBe(true);\n    expect(\n      anotherLayer.removeLayer(\"with caching\").removeLayer(\"another layer\")\n    ).toBe(storeWithResultCaching.stump);\n    expect(supportsResultCaching(storeWithResultCaching)).toBe(true);\n\n    const layerWithoutCaching = storeWithoutResultCaching.addLayer(\n      \"with caching\",\n      () => {}\n    );\n    expect(supportsResultCaching(layerWithoutCaching)).toBe(false);\n    expect(layerWithoutCaching.removeLayer(\"with caching\")).toBe(\n      storeWithoutResultCaching.stump\n    );\n    expect(supportsResultCaching(storeWithoutResultCaching)).toBe(false);\n  });\n\n  function newBookAuthorCache() {\n    const cache = new InMemoryCache({\n      resultCaching: true,\n      dataIdFromObject(value: any) {\n        switch (value && value.__typename) {\n          case \"Book\":\n            return \"Book:\" + value.isbn;\n          case \"Author\":\n            return \"Author:\" + value.name;\n        }\n      },\n    });\n\n    const query: TypedDocumentNode<{\n      book: {\n        __typename: string;\n        title: string;\n        isbn: string;\n        author: {\n          __typename: string;\n          name: string;\n        };\n      };\n    }> = gql`\n      query {\n        book {\n          title\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    return {\n      cache,\n      query,\n    };\n  }\n\n  it(\"should respect optimistic updates, when active\", () => {\n    const { cache, query } = newBookAuthorCache();\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"9781451673319\",\n          title: \"Fahrenheit 451\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ray Bradbury\",\n          },\n        },\n      },\n    });\n\n    expect(cache.gc()).toEqual([]);\n\n    // Orphan the F451 / Ray Bradbury data, but avoid collecting garbage yet.\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"1980719802\",\n          title: \"1984\",\n          author: {\n            __typename: \"Author\",\n            name: \"George Orwell\",\n          },\n        },\n      },\n    });\n\n    cache.recordOptimisticTransaction((proxy) => {\n      proxy.writeFragment({\n        id: \"Author:Ray Bradbury\",\n        fragment: gql`\n          fragment AuthorBooks on Author {\n            books {\n              title\n            }\n          }\n        `,\n        data: {\n          books: [\n            {\n              __typename: \"Book\",\n              isbn: \"9781451673319\",\n              title: \"Fahrenheit 451\",\n            },\n          ],\n        },\n      });\n    }, \"ray books\");\n\n    const rayMeta = {\n      extraRootIds: [\"Author:Ray Bradbury\"],\n    };\n\n    expect(cache.extract(true)).toEqual({\n      __META: rayMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:1980719802\",\n        },\n      },\n      \"Author:Ray Bradbury\": {\n        __typename: \"Author\",\n        name: \"Ray Bradbury\",\n        books: [\n          {\n            __ref: \"Book:9781451673319\",\n          },\n        ],\n      },\n      \"Book:9781451673319\": {\n        __typename: \"Book\",\n        title: \"Fahrenheit 451\",\n        author: {\n          __ref: \"Author:Ray Bradbury\",\n        },\n      },\n      \"Author:George Orwell\": {\n        __typename: \"Author\",\n        name: \"George Orwell\",\n      },\n      \"Book:1980719802\": {\n        __typename: \"Book\",\n        title: \"1984\",\n        author: {\n          __ref: \"Author:George Orwell\",\n        },\n      },\n    });\n\n    // Nothing can be reclaimed while the optimistic update is retaining\n    // Fahrenheit 451.\n    expect(cache.gc()).toEqual([]);\n\n    cache.removeOptimistic(\"ray books\");\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:1980719802\",\n        },\n      },\n      \"Author:Ray Bradbury\": {\n        __typename: \"Author\",\n        name: \"Ray Bradbury\",\n        // Note that the optimistic books field has disappeared, as expected.\n      },\n      \"Book:9781451673319\": {\n        __typename: \"Book\",\n        title: \"Fahrenheit 451\",\n        author: {\n          __ref: \"Author:Ray Bradbury\",\n        },\n      },\n      \"Author:George Orwell\": {\n        __typename: \"Author\",\n        name: \"George Orwell\",\n      },\n      \"Book:1980719802\": {\n        __typename: \"Book\",\n        title: \"1984\",\n        author: {\n          __ref: \"Author:George Orwell\",\n        },\n      },\n    });\n\n    expect(cache.gc().sort()).toEqual([\n      \"Author:Ray Bradbury\",\n      \"Book:9781451673319\",\n    ]);\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:1980719802\",\n        },\n      },\n      \"Author:George Orwell\": {\n        __typename: \"Author\",\n        name: \"George Orwell\",\n      },\n      \"Book:1980719802\": {\n        __typename: \"Book\",\n        title: \"1984\",\n        author: {\n          __ref: \"Author:George Orwell\",\n        },\n      },\n    });\n\n    expect(cache.gc()).toEqual([]);\n  });\n\n  it(\"should respect retain/release methods\", () => {\n    const { query, cache } = newBookAuthorCache();\n\n    const eagerBookData = {\n      __typename: \"Book\",\n      isbn: \"1603589082\",\n      title: \"Eager\",\n      subtitle: \"The Surprising, Secret Life of Beavers and Why They Matter\",\n      author: {\n        __typename: \"Author\",\n        name: \"Ben Goldfarb\",\n      },\n    };\n\n    const spinelessBookData = {\n      __typename: \"Book\",\n      isbn: \"0735211280\",\n      title: \"Spineless\",\n      subtitle: \"The Science of Jellyfish and the Art of Growing a Backbone\",\n      author: {\n        __typename: \"Author\",\n        name: \"Juli Berwald\",\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: spinelessBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:0735211280\",\n        },\n      },\n      \"Book:0735211280\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Juli Berwald\",\n        },\n        title: \"Spineless\",\n      },\n      \"Author:Juli Berwald\": {\n        __typename: \"Author\",\n        name: \"Juli Berwald\",\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: eagerBookData,\n      },\n    });\n\n    const snapshotWithBothBooksAndAuthors = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:1603589082\",\n        },\n      },\n      \"Book:0735211280\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Juli Berwald\",\n        },\n        title: \"Spineless\",\n      },\n      \"Author:Juli Berwald\": {\n        __typename: \"Author\",\n        name: \"Juli Berwald\",\n      },\n      \"Book:1603589082\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Ben Goldfarb\",\n        },\n        title: \"Eager\",\n      },\n      \"Author:Ben Goldfarb\": {\n        __typename: \"Author\",\n        name: \"Ben Goldfarb\",\n      },\n    };\n\n    expect(cache.extract(true)).toEqual(snapshotWithBothBooksAndAuthors);\n\n    expect(cache.retain(\"Book:0735211280\")).toBe(1);\n\n    expect(cache.gc()).toEqual([]);\n\n    expect(cache.retain(\"Author:Juli Berwald\")).toBe(1);\n\n    cache.recordOptimisticTransaction((proxy) => {\n      proxy.writeFragment({\n        id: \"Author:Juli Berwald\",\n        fragment: gql`\n          fragment AuthorBooks on Author {\n            books {\n              title\n            }\n          }\n        `,\n        data: {\n          books: [\n            {\n              __typename: \"Book\",\n              isbn: \"0735211280\",\n              title: \"Spineless\",\n            },\n          ],\n        },\n      });\n    }, \"juli books\");\n\n    // Retain the Spineless book on the optimistic layer (for the first time)\n    // but release it on the root layer.\n    expect(cache.retain(\"Book:0735211280\", true)).toBe(1);\n    expect(cache.release(\"Book:0735211280\")).toBe(0);\n\n    // The Spineless book is still protected by the reference from author Juli\n    // Berwald's optimistically-added author.books field.\n    expect(cache.gc()).toEqual([]);\n\n    const juliBookMeta = {\n      extraRootIds: [\"Author:Juli Berwald\", \"Book:0735211280\"],\n    };\n\n    expect(cache.extract(true)).toEqual({\n      __META: juliBookMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:1603589082\",\n        },\n      },\n      \"Book:0735211280\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Juli Berwald\",\n        },\n        title: \"Spineless\",\n      },\n      \"Author:Juli Berwald\": {\n        __typename: \"Author\",\n        name: \"Juli Berwald\",\n        // Note this extra optimistic field.\n        books: [\n          {\n            __ref: \"Book:0735211280\",\n          },\n        ],\n      },\n      \"Book:1603589082\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Ben Goldfarb\",\n        },\n        title: \"Eager\",\n      },\n      \"Author:Ben Goldfarb\": {\n        __typename: \"Author\",\n        name: \"Ben Goldfarb\",\n      },\n    });\n\n    const juliMeta = {\n      extraRootIds: [\"Author:Juli Berwald\"],\n    };\n\n    // A non-optimistic snapshot will not have the extra books field.\n    expect(cache.extract(false)).toEqual({\n      ...snapshotWithBothBooksAndAuthors,\n      __META: juliMeta,\n    });\n\n    cache.removeOptimistic(\"juli books\");\n\n    // The optimistic books field is gone now that we've removed the optimistic\n    // layer that added it.\n    expect(cache.extract(true)).toEqual({\n      ...snapshotWithBothBooksAndAuthors,\n      __META: juliMeta,\n    });\n\n    // The Spineless book is no longer retained or kept alive by any other root\n    // IDs, so it can finally be collected.\n    expect(cache.gc()).toEqual([\"Book:0735211280\"]);\n\n    expect(cache.release(\"Author:Juli Berwald\")).toBe(0);\n\n    // Now that Juli Berwald's author entity is no longer retained, garbage\n    // collection cometh for her. Look out, Juli!\n    expect(cache.gc()).toEqual([\"Author:Juli Berwald\"]);\n\n    expect(cache.gc()).toEqual([]);\n  });\n\n  it(\"allows cache eviction\", () => {\n    const { cache, query } = newBookAuthorCache();\n\n    const cuckoosCallingBook = {\n      __typename: \"Book\",\n      isbn: \"031648637X\",\n      title: \"The Cuckoo's Calling\",\n      author: {\n        __typename: \"Author\",\n        name: \"Robert Galbraith\",\n      },\n    };\n\n    expect(cache.identify(cuckoosCallingBook)).toBe(\"Book:031648637X\");\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: cuckoosCallingBook,\n      },\n    });\n\n    expect(cache.evict({ id: \"Author:J.K. Rowling\" })).toBe(false);\n\n    const bookAuthorFragment = gql`\n      fragment BookAuthor on Book {\n        author {\n          name\n        }\n      }\n    `;\n\n    const fragmentResult = cache.readFragment<StoreObject>({\n      id: cache.identify(cuckoosCallingBook)!,\n      fragment: bookAuthorFragment,\n    });\n\n    expect(fragmentResult).toEqual({\n      __typename: \"Book\",\n      author: {\n        __typename: \"Author\",\n        name: \"Robert Galbraith\",\n      },\n    });\n\n    cache.recordOptimisticTransaction((proxy) => {\n      proxy.writeFragment({\n        id: cache.identify(cuckoosCallingBook)!,\n        fragment: bookAuthorFragment,\n        data: {\n          ...fragmentResult,\n          author: {\n            __typename: \"Author\",\n            name: \"J.K. Rowling\",\n          },\n        },\n      });\n    }, \"real name\");\n\n    const snapshotWithBothNames = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:031648637X\",\n        },\n      },\n      \"Book:031648637X\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:J.K. Rowling\",\n        },\n        title: \"The Cuckoo's Calling\",\n      },\n      \"Author:Robert Galbraith\": {\n        __typename: \"Author\",\n        name: \"Robert Galbraith\",\n      },\n      \"Author:J.K. Rowling\": {\n        __typename: \"Author\",\n        name: \"J.K. Rowling\",\n      },\n    };\n\n    const cuckooMeta = {\n      extraRootIds: [\"Book:031648637X\"],\n    };\n\n    expect(cache.extract(true)).toEqual({\n      ...snapshotWithBothNames,\n      __META: cuckooMeta,\n    });\n\n    expect(cache.gc()).toEqual([]);\n\n    expect(cache.retain(\"Author:Robert Galbraith\")).toBe(1);\n\n    expect(cache.gc()).toEqual([]);\n\n    expect(cache.evict({ id: \"Author:Robert Galbraith\" })).toBe(true);\n\n    expect(cache.gc()).toEqual([]);\n\n    cache.removeOptimistic(\"real name\");\n\n    const robertMeta = {\n      extraRootIds: [\"Author:Robert Galbraith\"],\n    };\n\n    expect(cache.extract(true)).toEqual({\n      __META: robertMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:031648637X\",\n        },\n      },\n      \"Book:031648637X\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:Robert Galbraith\",\n        },\n        title: \"The Cuckoo's Calling\",\n      },\n      // The Robert Galbraith Author record is no longer here because\n      // cache.evict evicts data from all EntityStore layers.\n    });\n\n    cache.writeFragment({\n      id: cache.identify(cuckoosCallingBook)!,\n      fragment: bookAuthorFragment,\n      data: {\n        ...fragmentResult,\n        author: {\n          __typename: \"Author\",\n          name: \"J.K. Rowling\",\n        },\n      },\n    });\n\n    const cuckooRobertMeta = {\n      ...cuckooMeta,\n      ...robertMeta,\n      extraRootIds: [\n        ...cuckooMeta.extraRootIds,\n        ...robertMeta.extraRootIds,\n      ].sort(),\n    };\n\n    expect(cache.extract(true)).toEqual({\n      __META: cuckooRobertMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: \"Book:031648637X\",\n        },\n      },\n      \"Book:031648637X\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:J.K. Rowling\",\n        },\n        title: \"The Cuckoo's Calling\",\n      },\n      \"Author:J.K. Rowling\": {\n        __typename: \"Author\",\n        name: \"J.K. Rowling\",\n      },\n    });\n\n    expect(cache.retain(\"Author:Robert Galbraith\")).toBe(2);\n\n    expect(cache.gc()).toEqual([]);\n\n    expect(cache.release(\"Author:Robert Galbraith\")).toBe(1);\n    expect(cache.release(\"Author:Robert Galbraith\")).toBe(0);\n\n    expect(cache.gc()).toEqual([]);\n\n    function checkFalsyEvictId(id: any) {\n      expect(id).toBeFalsy();\n      expect(\n        cache.evict({\n          // Accidentally passing a falsy/undefined options.id to\n          // cache.evict (perhaps because cache.identify failed) should\n          // *not* cause the ROOT_QUERY object to be evicted! In order for\n          // cache.evict to default to ROOT_QUERY, the options.id property\n          // must be *absent* (not just undefined).\n          id,\n        })\n      ).toBe(false);\n    }\n    checkFalsyEvictId(void 0);\n    checkFalsyEvictId(null);\n    checkFalsyEvictId(false);\n    checkFalsyEvictId(0);\n    checkFalsyEvictId(\"\");\n\n    // In other words, this is how you evict the entire ROOT_QUERY\n    // object. If you're ever tempted to do this, you probably want to use\n    // cache.clear() instead, but evicting the ROOT_QUERY should work.\n    expect(cache.evict({})).toBe(true);\n\n    expect(cache.extract(true)).toEqual({\n      __META: cuckooMeta,\n      \"Book:031648637X\": {\n        __typename: \"Book\",\n        author: {\n          __ref: \"Author:J.K. Rowling\",\n        },\n        title: \"The Cuckoo's Calling\",\n      },\n      \"Author:J.K. Rowling\": {\n        __typename: \"Author\",\n        name: \"J.K. Rowling\",\n      },\n    });\n\n    const ccId = cache.identify(cuckoosCallingBook)!;\n    expect(cache.retain(ccId)).toBe(2);\n    expect(cache.release(ccId)).toBe(1);\n    expect(cache.release(ccId)).toBe(0);\n\n    expect(cache.gc().sort()).toEqual([\"Author:J.K. Rowling\", ccId]);\n  });\n\n  it(\"ignores retainment count for ROOT_QUERY\", () => {\n    const { cache, query } = newBookAuthorCache();\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"1982156945\",\n          title: \"Solutions and Other Problems\",\n          author: {\n            __typename: \"Author\",\n            name: \"Allie Brosh\",\n          },\n        },\n      },\n    });\n\n    const allieId = cache.identify({\n      __typename: \"Author\",\n      name: \"Allie Brosh\",\n    })!;\n    expect(allieId).toBe(\"Author:Allie Brosh\");\n    expect(cache.retain(allieId)).toBe(1);\n\n    const snapshot = cache.extract();\n    expect(snapshot).toMatchSnapshot();\n\n    expect(cache.gc()).toEqual([]);\n\n    const cache2 = newBookAuthorCache().cache;\n    cache2.restore(snapshot);\n\n    expect(cache2.extract()).toEqual(snapshot);\n\n    expect(cache2.gc()).toEqual([]);\n\n    // Evicting the whole ROOT_QUERY object is probably a terrible idea in\n    // any real application, but it's worthwhile to test that eviction is\n    // stronger than retainment.\n    expect(\n      cache2.evict({\n        id: \"ROOT_QUERY\",\n      })\n    ).toBe(true);\n\n    expect(cache2.gc().sort()).toEqual([\"Book:1982156945\"]);\n\n    expect(cache2.extract()).toMatchSnapshot();\n\n    expect(cache2.release(allieId)).toBe(0);\n\n    expect(cache2.gc().sort()).toEqual([\"Author:Allie Brosh\"]);\n\n    expect(cache2.extract()).toEqual({});\n  });\n\n  it(\"cache.gc is not confused by StoreObjects with stray __ref fields\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Person: {\n          keyFields: [\"name\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        parent {\n          name\n          child {\n            name\n          }\n        }\n      }\n    `;\n\n    const data = {\n      parent: {\n        __typename: \"Person\",\n        name: \"Will Smith\",\n        child: {\n          __typename: \"Person\",\n          name: \"Jaden Smith\",\n        },\n      },\n    };\n\n    cache.writeQuery({ query, data });\n\n    expect(cache.gc()).toEqual([]);\n\n    const willId = cache.identify(data.parent)!;\n    const store = cache[\"data\"];\n    const storeRootData = store[\"data\"];\n    // Hacky way of injecting a stray __ref field into the Will Smith Person\n    // object, clearing store.refs (which was populated by the previous GC).\n    storeRootData[willId]!.__ref = willId;\n    store[\"refs\"] = {};\n\n    expect(cache.extract()).toEqual({\n      'Person:{\"name\":\"Jaden Smith\"}': {\n        __typename: \"Person\",\n        name: \"Jaden Smith\",\n      },\n      'Person:{\"name\":\"Will Smith\"}': {\n        __typename: \"Person\",\n        name: \"Will Smith\",\n        child: {\n          __ref: 'Person:{\"name\":\"Jaden Smith\"}',\n        },\n        // This is the bogus line that makes this Person object look like a\n        // Reference object to the garbage collector.\n        __ref: 'Person:{\"name\":\"Will Smith\"}',\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        parent: {\n          __ref: 'Person:{\"name\":\"Will Smith\"}',\n        },\n      },\n    });\n\n    // Ensure the garbage collector is not confused by the stray __ref.\n    expect(cache.gc()).toEqual([]);\n  });\n\n  it(\"allows evicting specific fields\", () => {\n    const query: DocumentNode = gql`\n      query {\n        authorOfBook(isbn: $isbn) {\n          name\n          hobby\n        }\n        publisherOfBook(isbn: $isbn) {\n          name\n          yearOfFounding\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            authorOfBook: {\n              keyArgs: [\"isbn\"],\n            },\n          },\n        },\n        Author: {\n          keyFields: [\"name\"],\n        },\n        Publisher: {\n          keyFields: [\"name\"],\n        },\n      },\n    });\n\n    const TedChiangData = {\n      __typename: \"Author\",\n      name: \"Ted Chiang\",\n      hobby: \"video games\",\n    };\n\n    const KnopfData = {\n      __typename: \"Publisher\",\n      name: \"Alfred A. Knopf\",\n      yearOfFounding: 1915,\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: TedChiangData,\n        publisherOfBook: KnopfData,\n      },\n      variables: {\n        isbn: \"1529014514\",\n      },\n    });\n\n    const justTedRootQueryData = {\n      __typename: \"Query\",\n      'authorOfBook:{\"isbn\":\"1529014514\"}': {\n        __ref: 'Author:{\"name\":\"Ted Chiang\"}',\n      },\n      // This storeFieldName format differs slightly from that of\n      // authorOfBook because we did not define keyArgs for the\n      // publisherOfBook field, so the legacy storeKeyNameFromField\n      // function was used instead.\n      'publisherOfBook({\"isbn\":\"1529014514\"})': {\n        __ref: 'Publisher:{\"name\":\"Alfred A. Knopf\"}',\n      },\n    };\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: justTedRootQueryData,\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Publisher:{\"name\":\"Alfred A. Knopf\"}': KnopfData,\n    });\n\n    const JennyOdellData = {\n      __typename: \"Author\",\n      name: \"Jenny Odell\",\n      hobby: \"birding\",\n    };\n\n    const MelvilleData = {\n      __typename: \"Publisher\",\n      name: \"Melville House\",\n      yearOfFounding: 2001,\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: JennyOdellData,\n        publisherOfBook: MelvilleData,\n      },\n      variables: {\n        isbn: \"1760641790\",\n      },\n    });\n\n    const justJennyRootQueryData = {\n      __typename: \"Query\",\n      'authorOfBook:{\"isbn\":\"1760641790\"}': {\n        __ref: 'Author:{\"name\":\"Jenny Odell\"}',\n      },\n      'publisherOfBook({\"isbn\":\"1760641790\"})': {\n        __ref: 'Publisher:{\"name\":\"Melville House\"}',\n      },\n    };\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        ...justTedRootQueryData,\n        ...justJennyRootQueryData,\n      },\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Publisher:{\"name\":\"Alfred A. Knopf\"}': KnopfData,\n      'Author:{\"name\":\"Jenny Odell\"}': JennyOdellData,\n      'Publisher:{\"name\":\"Melville House\"}': MelvilleData,\n    });\n\n    const fullTedResult = cache.readQuery<any>({\n      query,\n      variables: {\n        isbn: \"1529014514\",\n      },\n    });\n\n    expect(fullTedResult).toEqual({\n      authorOfBook: TedChiangData,\n      publisherOfBook: KnopfData,\n    });\n\n    const fullJennyResult = cache.readQuery<any>({\n      query,\n      variables: {\n        isbn: \"1760641790\",\n      },\n    });\n\n    expect(fullJennyResult).toEqual({\n      authorOfBook: JennyOdellData,\n      publisherOfBook: MelvilleData,\n    });\n\n    cache.evict({\n      id: cache.identify({\n        __typename: \"Publisher\",\n        name: \"Alfred A. Knopf\",\n      })!,\n      fieldName: \"yearOfFounding\",\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        ...justTedRootQueryData,\n        ...justJennyRootQueryData,\n      },\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Publisher:{\"name\":\"Alfred A. Knopf\"}': {\n        __typename: \"Publisher\",\n        name: \"Alfred A. Knopf\",\n        // yearOfFounding has been removed\n      },\n      'Author:{\"name\":\"Jenny Odell\"}': JennyOdellData,\n      'Publisher:{\"name\":\"Melville House\"}': MelvilleData,\n    });\n\n    // Nothing to garbage collect yet.\n    expect(cache.gc()).toEqual([]);\n\n    cache.evict({\n      id: cache.identify({\n        __typename: \"Publisher\",\n        name: \"Melville House\",\n      })!,\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        ...justTedRootQueryData,\n        ...justJennyRootQueryData,\n      },\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Publisher:{\"name\":\"Alfred A. Knopf\"}': {\n        __typename: \"Publisher\",\n        name: \"Alfred A. Knopf\",\n      },\n      'Author:{\"name\":\"Jenny Odell\"}': JennyOdellData,\n      // Melville House has been removed\n    });\n\n    cache.evict({ id: \"ROOT_QUERY\", fieldName: \"publisherOfBook\" });\n\n    function withoutPublisherOfBook(obj: Record<string, any>) {\n      const clean = { ...obj };\n      Object.keys(obj).forEach((key) => {\n        if (key.startsWith(\"publisherOfBook\")) {\n          delete clean[key];\n        }\n      });\n      return clean;\n    }\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        ...withoutPublisherOfBook(justTedRootQueryData),\n        ...withoutPublisherOfBook(justJennyRootQueryData),\n      },\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Publisher:{\"name\":\"Alfred A. Knopf\"}': {\n        __typename: \"Publisher\",\n        name: \"Alfred A. Knopf\",\n      },\n      'Author:{\"name\":\"Jenny Odell\"}': JennyOdellData,\n    });\n\n    expect(cache.gc()).toEqual(['Publisher:{\"name\":\"Alfred A. Knopf\"}']);\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        ...withoutPublisherOfBook(justTedRootQueryData),\n        ...withoutPublisherOfBook(justJennyRootQueryData),\n      },\n      'Author:{\"name\":\"Ted Chiang\"}': TedChiangData,\n      'Author:{\"name\":\"Jenny Odell\"}': JennyOdellData,\n    });\n\n    const partialTedResult = cache.diff<any>({\n      query,\n      returnPartialData: true,\n      optimistic: false, // required but not important\n      variables: {\n        isbn: \"1529014514\",\n      },\n    });\n    expect(partialTedResult.complete).toBe(false);\n    expect(partialTedResult.result).toEqual({\n      authorOfBook: TedChiangData,\n    });\n    // The result caching system preserves the referential identity of\n    // unchanged nested result objects.\n    expect(partialTedResult.result.authorOfBook).toBe(\n      fullTedResult.authorOfBook\n    );\n\n    const partialJennyResult = cache.diff<any>({\n      query,\n      returnPartialData: true,\n      optimistic: false, // required but not important\n      variables: {\n        isbn: \"1760641790\",\n      },\n    });\n    expect(partialJennyResult.complete).toBe(false);\n    expect(partialJennyResult.result).toEqual({\n      authorOfBook: JennyOdellData,\n    });\n    // The result caching system preserves the referential identity of\n    // unchanged nested result objects.\n    expect(partialJennyResult.result.authorOfBook).toBe(\n      fullJennyResult.authorOfBook\n    );\n\n    const tedWithoutHobby = {\n      __typename: \"Author\",\n      name: \"Ted Chiang\",\n    };\n\n    cache.evict({\n      id: cache.identify(tedWithoutHobby)!,\n      fieldName: \"hobby\",\n    });\n\n    expect(\n      cache.diff<any>({\n        query,\n        returnPartialData: true,\n        optimistic: false, // required but not important\n        variables: {\n          isbn: \"1529014514\",\n        },\n      })\n    ).toEqual({\n      complete: false,\n      result: {\n        authorOfBook: tedWithoutHobby,\n      },\n      missing: new MissingFieldError(\n        'Can\\'t find field \\'hobby\\' on Author:{\"name\":\"Ted Chiang\"} object',\n        {\n          publisherOfBook:\n            \"Can't find field 'publisherOfBook' on ROOT_QUERY object\",\n          authorOfBook: {\n            hobby:\n              'Can\\'t find field \\'hobby\\' on Author:{\"name\":\"Ted Chiang\"} object',\n          },\n        },\n        expect.anything(), // query\n        expect.anything() // variables\n      ),\n    });\n\n    cache.evict({ id: \"ROOT_QUERY\", fieldName: \"authorOfBook\" });\n    expect(cache.gc().sort()).toEqual([\n      'Author:{\"name\":\"Jenny Odell\"}',\n      'Author:{\"name\":\"Ted Chiang\"}',\n    ]);\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        // Everything else has been removed.\n        __typename: \"Query\",\n      },\n    });\n  });\n\n  it(\"allows evicting specific fields with specific arguments\", () => {\n    const query: DocumentNode = gql`\n      query {\n        authorOfBook(isbn: $isbn) {\n          name\n          hobby\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    const TedChiangData = {\n      __typename: \"Author\",\n      name: \"Ted Chiang\",\n      hobby: \"video games\",\n    };\n\n    const IsaacAsimovData = {\n      __typename: \"Author\",\n      name: \"Isaac Asimov\",\n      hobby: \"chemistry\",\n    };\n\n    const JamesCoreyData = {\n      __typename: \"Author\",\n      name: \"James S.A. Corey\",\n      hobby: \"tabletop games\",\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: TedChiangData,\n      },\n      variables: {\n        isbn: \"1\",\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: IsaacAsimovData,\n      },\n      variables: {\n        isbn: \"2\",\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: JamesCoreyData,\n      },\n      variables: {},\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"1\"})': {\n          __typename: \"Author\",\n          name: \"Ted Chiang\",\n          hobby: \"video games\",\n        },\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      fieldName: \"authorOfBook\",\n      args: { isbn: \"1\" },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      fieldName: \"authorOfBook\",\n      args: { isbn: \"3\" },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      fieldName: \"authorOfBook\",\n      args: {},\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n      },\n    });\n\n    cache.evict({\n      fieldName: \"authorOfBook\",\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n      },\n    });\n  });\n\n  it(\"allows evicting specific fields with specific arguments using EvictOptions\", () => {\n    const query: DocumentNode = gql`\n      query {\n        authorOfBook(isbn: $isbn) {\n          name\n          hobby\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    const TedChiangData = {\n      __typename: \"Author\",\n      name: \"Ted Chiang\",\n      hobby: \"video games\",\n    };\n\n    const IsaacAsimovData = {\n      __typename: \"Author\",\n      name: \"Isaac Asimov\",\n      hobby: \"chemistry\",\n    };\n\n    const JamesCoreyData = {\n      __typename: \"Author\",\n      name: \"James S.A. Corey\",\n      hobby: \"tabletop games\",\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: TedChiangData,\n      },\n      variables: {\n        isbn: \"1\",\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: IsaacAsimovData,\n      },\n      variables: {\n        isbn: \"2\",\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        authorOfBook: JamesCoreyData,\n      },\n      variables: {},\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"1\"})': {\n          __typename: \"Author\",\n          name: \"Ted Chiang\",\n          hobby: \"video games\",\n        },\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      id: \"ROOT_QUERY\",\n      fieldName: \"authorOfBook\",\n      args: { isbn: \"1\" },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      id: \"ROOT_QUERY\",\n      fieldName: \"authorOfBook\",\n      args: { isbn: \"3\" },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n        authorOfBook: {\n          __typename: \"Author\",\n          name: \"James S.A. Corey\",\n          hobby: \"tabletop games\",\n        },\n      },\n    });\n\n    cache.evict({\n      id: \"ROOT_QUERY\",\n      fieldName: \"authorOfBook\",\n      args: {},\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'authorOfBook({\"isbn\":\"2\"})': {\n          __typename: \"Author\",\n          name: \"Isaac Asimov\",\n          hobby: \"chemistry\",\n        },\n      },\n    });\n\n    cache.evict({\n      id: \"ROOT_QUERY\",\n      fieldName: \"authorOfBook\",\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n      },\n    });\n  });\n\n  it(\"supports cache.identify(reference)\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Task: {\n          keyFields: [\"uuid\"],\n        },\n      },\n    });\n\n    expect(cache.identify(makeReference(\"oyez\"))).toBe(\"oyez\");\n\n    const todoRef = cache.writeFragment({\n      fragment: gql`\n        fragment TodoId on Todo {\n          id\n        }\n      `,\n      data: {\n        __typename: \"Todo\",\n        id: 123,\n      },\n    });\n    expect(isReference(todoRef)).toBe(true);\n    expect(cache.identify(todoRef!)).toBe(\"Todo:123\");\n\n    const taskRef = cache.writeFragment({\n      fragment: gql`\n        fragment TaskId on Task {\n          uuid\n        }\n      `,\n      data: {\n        __typename: \"Task\",\n        uuid: \"eb8cffcc-7a9e-4d8b-a517-7d987bf42138\",\n      },\n    });\n    expect(isReference(taskRef)).toBe(true);\n    expect(cache.identify(taskRef!)).toBe(\n      'Task:{\"uuid\":\"eb8cffcc-7a9e-4d8b-a517-7d987bf42138\"}'\n    );\n  });\n\n  it(\"supports cache.identify(object)\", () => {\n    const queryWithAliases: DocumentNode = gql`\n      query {\n        abcs {\n          first: a\n          second: b\n          ...Rest\n        }\n      }\n      fragment Rest on ABCs {\n        third: c\n      }\n    `;\n\n    const queryWithoutAliases: DocumentNode = gql`\n      query {\n        abcs {\n          a\n          b\n          ...Rest\n        }\n      }\n      fragment Rest on ABCs {\n        c\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        ABCs: {\n          keyFields: [\"b\", \"a\", \"c\"],\n        },\n      },\n    });\n\n    const ABCs = {\n      __typename: \"ABCs\",\n      first: \"ay\",\n      second: \"bee\",\n      third: \"see\",\n    };\n\n    cache.writeQuery({\n      query: queryWithAliases,\n      data: {\n        abcs: ABCs,\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        abcs: {\n          __ref: 'ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"}',\n        },\n      },\n      'ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"}': {\n        __typename: \"ABCs\",\n        a: \"ay\",\n        b: \"bee\",\n        c: \"see\",\n      },\n    });\n\n    const resultWithAliases = cache.readQuery({\n      query: queryWithAliases,\n    });\n\n    expect(resultWithAliases).toEqual({ abcs: ABCs });\n\n    const resultWithoutAliases = cache.readQuery({\n      query: queryWithoutAliases,\n    });\n\n    expect(resultWithoutAliases).toEqual({\n      abcs: {\n        __typename: \"ABCs\",\n        a: \"ay\",\n        b: \"bee\",\n        c: \"see\",\n      },\n    });\n\n    expect(\n      cache.identify({\n        __typename: \"ABCs\",\n        a: 1,\n        b: 2,\n        c: 3,\n      })\n    ).toBe('ABCs:{\"b\":2,\"a\":1,\"c\":3}');\n\n    {\n      using consoleSpies = spyOnConsole(\"warn\");\n      expect(cache.identify(ABCs)).toBeUndefined();\n      expect(consoleSpies.warn).toHaveBeenCalledTimes(1);\n      expect(consoleSpies.warn).toHaveBeenCalledWith(\n        new InvariantError(\n          `Missing field 'b' while extracting keyFields from ${stringifyForDisplay(\n            ABCs,\n            2\n          )}`\n        )\n      );\n    }\n\n    expect(\n      cache.readFragment({\n        id: cache.identify({\n          __typename: \"ABCs\",\n          a: \"ay\",\n          b: \"bee\",\n          c: \"see\",\n        })!,\n        fragment: gql`\n          fragment JustB on ABCs {\n            b\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"ABCs\",\n      b: \"bee\",\n    });\n\n    expect(\n      cache.readQuery({\n        query: queryWithAliases,\n      })\n    ).toBe(resultWithAliases);\n\n    expect(\n      cache.readQuery({\n        query: queryWithoutAliases,\n      })\n    ).toBe(resultWithoutAliases);\n\n    cache.evict({\n      id: cache.identify({\n        __typename: \"ABCs\",\n        a: \"ay\",\n        b: \"bee\",\n        c: \"see\",\n      }),\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        abcs: {\n          __ref: 'ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"}',\n        },\n      },\n    });\n\n    function diff(query: DocumentNode) {\n      return cache.diff({\n        query,\n        optimistic: true,\n        returnPartialData: false,\n      });\n    }\n\n    expect(\n      cache.readQuery({\n        query: queryWithAliases,\n      })\n    ).toBe(null);\n\n    expect(diff(queryWithAliases)).toEqual({\n      result: null,\n      complete: false,\n      missing: new MissingFieldError(\n        'Dangling reference to missing ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"} object',\n        {\n          abcs: 'Dangling reference to missing ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"} object',\n        },\n        queryWithAliases,\n        {}\n      ),\n    });\n\n    expect(\n      cache.readQuery({\n        query: queryWithoutAliases,\n      })\n    ).toBe(null);\n\n    expect(diff(queryWithoutAliases)).toEqual({\n      result: null,\n      complete: false,\n      missing: new MissingFieldError(\n        'Dangling reference to missing ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"} object',\n        {\n          abcs: 'Dangling reference to missing ABCs:{\"b\":\"bee\",\"a\":\"ay\",\"c\":\"see\"} object',\n        },\n        queryWithoutAliases,\n        {}\n      ),\n    });\n  });\n\n  it(\"gracefully handles eviction amid optimistic updates\", () => {\n    const cache = new InMemoryCache();\n    const query = gql`\n      query {\n        book {\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    function writeInitialData(cache: ApolloCache) {\n      cache.writeQuery({\n        query,\n        data: {\n          book: {\n            __typename: \"Book\",\n            id: 1,\n            author: {\n              __typename: \"Author\",\n              id: 2,\n              name: \"Geoffrey Chaucer\",\n            },\n          },\n        },\n      });\n    }\n\n    writeInitialData(cache);\n\n    // Writing data in an optimistic transaction to exercise the\n    // interaction between eviction and optimistic layers.\n    cache.recordOptimisticTransaction((proxy) => {\n      writeInitialData(proxy);\n    }, \"initial transaction\");\n\n    expect(cache.extract(true)).toEqual({\n      \"Author:2\": {\n        __typename: \"Author\",\n        id: 2,\n        name: \"Geoffrey Chaucer\",\n      },\n      \"Book:1\": {\n        __typename: \"Book\",\n        id: 1,\n        author: { __ref: \"Author:2\" },\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: { __ref: \"Book:1\" },\n      },\n    });\n\n    const authorId = cache.identify({\n      __typename: \"Author\",\n      id: 2,\n    })!;\n\n    expect(cache.evict({ id: authorId })).toBe(true);\n\n    expect(cache.extract(true)).toEqual({\n      \"Book:1\": {\n        __typename: \"Book\",\n        id: 1,\n        author: { __ref: \"Author:2\" },\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: { __ref: \"Book:1\" },\n      },\n    });\n\n    expect(cache.evict({ id: authorId })).toBe(false);\n\n    const missing = new MissingFieldError(\n      \"Dangling reference to missing Author:2 object\",\n      {\n        book: {\n          author: \"Dangling reference to missing Author:2 object\",\n        },\n      },\n      expect.anything(), // query\n      expect.anything() // variables\n    );\n\n    expect(\n      cache.diff({\n        query,\n        optimistic: true,\n        returnPartialData: true,\n      })\n    ).toEqual({\n      complete: false,\n      missing,\n      result: {\n        book: {\n          __typename: \"Book\",\n          author: {},\n        },\n      },\n    });\n\n    cache.removeOptimistic(\"initial transaction\");\n\n    // The root layer is exposed again once the optimistic layer is\n    // removed, but the Author:2 entity has been evicted from all layers.\n    expect(cache.extract(true)).toEqual({\n      \"Book:1\": {\n        __typename: \"Book\",\n        id: 1,\n        author: { __ref: \"Author:2\" },\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: { __ref: \"Book:1\" },\n      },\n    });\n\n    expect(\n      cache.diff({\n        query,\n        optimistic: true,\n        returnPartialData: true,\n      })\n    ).toEqual({\n      complete: false,\n      missing,\n      result: {\n        book: {\n          __typename: \"Book\",\n          author: {},\n        },\n      },\n    });\n\n    writeInitialData(cache);\n\n    expect(\n      cache.diff({\n        query,\n        optimistic: true,\n        returnPartialData: true,\n      })\n    ).toEqual({\n      complete: true,\n      result: {\n        book: {\n          __typename: \"Book\",\n          author: {\n            __typename: \"Author\",\n            name: \"Geoffrey Chaucer\",\n          },\n        },\n      },\n    });\n  });\n\n  it(\"supports toReference(obj, true) to persist obj\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            book(_, { args, toReference, readField }) {\n              const ref = toReference(\n                {\n                  __typename: \"Book\",\n                  isbn: args!.isbn,\n                },\n                true\n              ) as Reference;\n\n              expect(readField(\"__typename\", ref)).toEqual(\"Book\");\n              const isbn = readField<string>(\"isbn\", ref);\n              expect(isbn).toEqual(args!.isbn);\n              expect(readField(\"title\", ref)).toBe(titlesByISBN.get(isbn!));\n\n              return ref;\n            },\n\n            books: {\n              merge(\n                existing: Reference[] = [],\n                incoming: any[],\n                { isReference, toReference, readField }\n              ) {\n                incoming.forEach((book) => {\n                  expect(isReference(book)).toBe(false);\n                  expect(book.__typename).toBeUndefined();\n                });\n\n                const refs = incoming.map(\n                  (book) =>\n                    toReference(\n                      {\n                        __typename: \"Book\",\n                        title: titlesByISBN.get(book.isbn),\n                        ...book,\n                      },\n                      true\n                    ) as Reference\n                );\n\n                refs.forEach((ref, i) => {\n                  expect(isReference(ref)).toBe(true);\n                  expect(readField(\"__typename\", ref)).toBe(\"Book\");\n                  const isbn = readField<string>(\"isbn\", ref);\n                  expect(typeof isbn).toBe(\"string\");\n                  expect(isbn).toBe(readField(\"isbn\", incoming[i]));\n                });\n\n                return [...existing, ...refs];\n              },\n            },\n          },\n        },\n\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    const booksQuery = gql`\n      query {\n        books {\n          isbn\n        }\n      }\n    `;\n\n    const bookQuery = gql`\n      query {\n        book(isbn: $isbn) {\n          isbn\n          title\n        }\n      }\n    `;\n\n    const titlesByISBN = new Map<string, string>([\n      [\"9781451673319\", \"Fahrenheit 451\"],\n      [\"1603589082\", \"Eager\"],\n      [\"1760641790\", \"How To Do Nothing\"],\n    ]);\n\n    cache.writeQuery({\n      query: booksQuery,\n      data: {\n        books: [\n          {\n            // Note: intentionally omitting __typename:\"Book\" here.\n            isbn: \"9781451673319\",\n          },\n          {\n            isbn: \"1603589082\",\n          },\n        ],\n      },\n    });\n\n    const twoBookSnapshot = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        books: [\n          { __ref: 'Book:{\"isbn\":\"9781451673319\"}' },\n          { __ref: 'Book:{\"isbn\":\"1603589082\"}' },\n        ],\n      },\n      'Book:{\"isbn\":\"9781451673319\"}': {\n        __typename: \"Book\",\n        isbn: \"9781451673319\",\n        title: \"Fahrenheit 451\",\n      },\n      'Book:{\"isbn\":\"1603589082\"}': {\n        __typename: \"Book\",\n        isbn: \"1603589082\",\n        title: \"Eager\",\n      },\n    };\n\n    // Check that the __typenames were appropriately added.\n    expect(cache.extract()).toEqual(twoBookSnapshot);\n\n    cache.writeQuery({\n      query: booksQuery,\n      data: {\n        books: [\n          {\n            isbn: \"1760641790\",\n          },\n        ],\n      },\n    });\n\n    const threeBookSnapshot = {\n      ...twoBookSnapshot,\n      ROOT_QUERY: {\n        ...twoBookSnapshot.ROOT_QUERY,\n        books: [\n          ...twoBookSnapshot.ROOT_QUERY.books,\n          { __ref: 'Book:{\"isbn\":\"1760641790\"}' },\n        ],\n      },\n      'Book:{\"isbn\":\"1760641790\"}': {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n    };\n\n    expect(cache.extract()).toEqual(threeBookSnapshot);\n\n    const howToDoNothingResult = cache.readQuery({\n      query: bookQuery,\n      variables: {\n        isbn: \"1760641790\",\n      },\n    });\n\n    expect(howToDoNothingResult).toEqual({\n      book: {\n        __typename: \"Book\",\n        isbn: \"1760641790\",\n        title: \"How To Do Nothing\",\n      },\n    });\n\n    // Check that reading the query didn't change anything.\n    expect(cache.extract()).toEqual(threeBookSnapshot);\n\n    const f451Result = cache.readQuery({\n      query: bookQuery,\n      variables: {\n        isbn: \"9781451673319\",\n      },\n    });\n\n    expect(f451Result).toEqual({\n      book: {\n        __typename: \"Book\",\n        isbn: \"9781451673319\",\n        title: \"Fahrenheit 451\",\n      },\n    });\n\n    const cuckoosCallingDiffResult = cache.diff({\n      query: bookQuery,\n      optimistic: true,\n      variables: {\n        isbn: \"031648637X\",\n      },\n    });\n\n    expect(cuckoosCallingDiffResult).toEqual({\n      complete: false,\n      result: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"031648637X\",\n        },\n      },\n      missing: new MissingFieldError(\n        'Can\\'t find field \\'title\\' on Book:{\"isbn\":\"031648637X\"} object',\n        {\n          book: {\n            title:\n              'Can\\'t find field \\'title\\' on Book:{\"isbn\":\"031648637X\"} object',\n          },\n        },\n        expect.anything(), // query\n        expect.anything() // variables\n      ),\n    });\n\n    expect(cache.extract()).toEqual({\n      ...threeBookSnapshot,\n      // This book was added as a side effect of the read function.\n      'Book:{\"isbn\":\"031648637X\"}': {\n        __typename: \"Book\",\n        isbn: \"031648637X\",\n      },\n    });\n\n    const cuckoosCallingId = cache.identify({\n      __typename: \"Book\",\n      isbn: \"031648637X\",\n    })!;\n\n    expect(cuckoosCallingId).toBe('Book:{\"isbn\":\"031648637X\"}');\n\n    cache.writeQuery({\n      id: cuckoosCallingId,\n      query: gql`\n        {\n          title\n        }\n      `,\n      data: {\n        title: \"The Cuckoo's Calling\",\n      },\n    });\n\n    const cuckooMeta = {\n      extraRootIds: ['Book:{\"isbn\":\"031648637X\"}'],\n    };\n\n    expect(cache.extract()).toEqual({\n      ...threeBookSnapshot,\n      __META: cuckooMeta,\n      // This book was added as a side effect of the read function.\n      'Book:{\"isbn\":\"031648637X\"}': {\n        __typename: \"Book\",\n        isbn: \"031648637X\",\n        title: \"The Cuckoo's Calling\",\n      },\n    });\n\n    cache.modify({\n      id: cuckoosCallingId,\n      fields: {\n        title(title: string, { isReference, toReference, readField }) {\n          const book = {\n            __typename: \"Book\",\n            isbn: readField(\"isbn\"),\n            author: \"J.K. Rowling\",\n          };\n\n          // By not passing true as the second argument to toReference, we\n          // get back a Reference object, but the book.author field is not\n          // persisted into the store.\n          const refWithoutAuthor = toReference(book);\n          expect(isReference(refWithoutAuthor)).toBe(true);\n          expect(\n            readField(\"author\", refWithoutAuthor as Reference)\n          ).toBeUndefined();\n\n          // Update this very Book entity before we modify its title.\n          // Passing true for the second argument causes the extra\n          // book.author field to be persisted into the store.\n          const ref = toReference(book, true);\n          expect(isReference(ref)).toBe(true);\n          expect(readField(\"author\", ref as Reference)).toBe(\"J.K. Rowling\");\n\n          // In fact, readField doesn't need the ref if we're reading from\n          // the same entity that we're modifying.\n          expect(readField(\"author\")).toBe(\"J.K. Rowling\");\n\n          // Typography matters!\n          return title.split(\"'\").join(\"’\");\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ...threeBookSnapshot,\n      __META: cuckooMeta,\n      // This book was added as a side effect of the read function.\n      'Book:{\"isbn\":\"031648637X\"}': {\n        __typename: \"Book\",\n        isbn: \"031648637X\",\n        title: \"The Cuckoo’s Calling\",\n        author: \"J.K. Rowling\",\n      },\n    });\n  });\n\n  it(\"supports toReference(id)\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          fields: {\n            favorited(_, { readField, toReference }) {\n              const rootQueryRef = toReference(\"ROOT_QUERY\");\n              expect(rootQueryRef).toEqual(makeReference(\"ROOT_QUERY\"));\n              const favoritedBooks = readField<Reference[]>(\n                \"favoritedBooks\",\n                rootQueryRef\n              );\n              return favoritedBooks!.some((bookRef) => {\n                return readField(\"isbn\") === readField(\"isbn\", bookRef);\n              });\n            },\n          },\n          keyFields: [\"isbn\"],\n        },\n        Query: {\n          fields: {\n            book(_, { args, toReference }) {\n              const ref = toReference(\n                {\n                  __typename: \"Book\",\n                  isbn: args!.isbn,\n                  title: titlesByISBN.get(args!.isbn),\n                },\n                true\n              );\n\n              return ref;\n            },\n          },\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: gql`\n        {\n          favoritedBooks {\n            isbn\n            title\n          }\n        }\n      `,\n      data: {\n        favoritedBooks: [\n          {\n            __typename: \"Book\",\n            isbn: \"9781784295547\",\n            title: \"Shrill\",\n            author: \"Lindy West\",\n          },\n        ],\n      },\n    });\n\n    const titlesByISBN = new Map<string, string>([\n      [\"9780062569714\", \"Hunger\"],\n      [\"9781784295547\", \"Shrill\"],\n      [\"9780807083109\", \"Kindred\"],\n    ]);\n\n    const bookQuery = gql`\n      query {\n        book(isbn: $isbn) {\n          isbn\n          title\n          favorited @client\n        }\n      }\n    `;\n\n    const shrillResult = cache.readQuery({\n      query: bookQuery,\n      variables: {\n        isbn: \"9781784295547\",\n      },\n    });\n\n    expect(shrillResult).toEqual({\n      book: {\n        __typename: \"Book\",\n        isbn: \"9781784295547\",\n        title: \"Shrill\",\n        favorited: true,\n      },\n    });\n\n    const kindredResult = cache.readQuery({\n      query: bookQuery,\n      variables: {\n        isbn: \"9780807083109\",\n      },\n    });\n\n    expect(kindredResult).toEqual({\n      book: {\n        __typename: \"Book\",\n        isbn: \"9780807083109\",\n        title: \"Kindred\",\n        favorited: false,\n      },\n    });\n  });\n\n  it(\"should not over-invalidate fields with keyArgs\", () => {\n    const isbnsWeHaveRead: string[] = [];\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            book: {\n              // The presence of this keyArgs configuration permits the\n              // cache to track result caching dependencies at the level\n              // of individual Books, so writing one Book does not\n              // invalidate other Books with different ISBNs. If the cache\n              // doesn't know which arguments are \"important,\" it can't\n              // make any assumptions about the relationships between\n              // field values with the same field name but different\n              // arguments, so it has to err on the side of invalidating\n              // all Query.book data whenever any Book is written.\n              keyArgs: [\"isbn\"],\n\n              read(book, { args, toReference }) {\n                isbnsWeHaveRead.push(args!.isbn);\n                return (\n                  book ||\n                  toReference({\n                    __typename: \"Book\",\n                    isbn: args!.isbn,\n                  })\n                );\n              },\n            },\n          },\n        },\n\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query Book($isbn: string) {\n        book(isbn: $isbn) {\n          title\n          isbn\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    const diffs: Cache.DiffResult<any>[] = [];\n    cache.watch({\n      query,\n      optimistic: true,\n      variables: {\n        isbn: \"1449373321\",\n      },\n      callback(diff) {\n        diffs.push(diff);\n      },\n    });\n\n    const ddiaData = {\n      book: {\n        __typename: \"Book\",\n        isbn: \"1449373321\",\n        title: \"Designing Data-Intensive Applications\",\n        author: {\n          __typename: \"Author\",\n          name: \"Martin Kleppmann\",\n        },\n      },\n    };\n\n    expect(isbnsWeHaveRead).toEqual([]);\n\n    cache.writeQuery({\n      query,\n      variables: {\n        isbn: \"1449373321\",\n      },\n      data: ddiaData,\n    });\n\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\"]);\n\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: ddiaData,\n      },\n    ]);\n\n    const theEndData = {\n      book: {\n        __typename: \"Book\",\n        isbn: \"1982103558\",\n        title: \"The End of Everything\",\n        author: {\n          __typename: \"Author\",\n          name: \"Katie Mack\",\n        },\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      variables: {\n        isbn: \"1982103558\",\n      },\n      data: theEndData,\n    });\n\n    // This list does not include the book we just wrote, because the\n    // cache.watch we started above only depends on the Query.book field\n    // value corresponding to the 1449373321 ISBN.\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: ddiaData,\n      },\n    ]);\n\n    // Likewise, this list is unchanged, because we did not need to read\n    // the 1449373321 Book again after writing the 1982103558 data.\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\"]);\n\n    const theEndResult = cache.readQuery({\n      query,\n      variables: {\n        isbn: \"1982103558\",\n      },\n      // TODO It's a regrettable accident of history that cache.readQuery is\n      // non-optimistic by default. Perhaps the default can be swapped to true\n      // in the next major version of Apollo Client.\n      optimistic: true,\n    });\n\n    expect(theEndResult).toEqual(theEndData);\n\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\", \"1982103558\"]);\n\n    expect(\n      cache.readQuery({\n        query,\n        variables: {\n          isbn: \"1449373321\",\n        },\n        optimistic: true,\n      })\n    ).toBe(diffs[0].result);\n\n    expect(\n      cache.readQuery({\n        query,\n        variables: {\n          isbn: \"1982103558\",\n        },\n        optimistic: true,\n      })\n    ).toBe(theEndResult);\n\n    // Still no additional reads, because both books are cached.\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\", \"1982103558\"]);\n\n    // Evicting the 1982103558 Book should not invalidate the 1449373321\n    // Book, so diffs and isbnsWeHaveRead should remain unchanged.\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Book\",\n          isbn: \"1982103558\",\n        }),\n      })\n    ).toBe(true);\n\n    expect(diffs).toEqual([\n      {\n        complete: true,\n        result: ddiaData,\n      },\n    ]);\n\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\", \"1982103558\"]);\n\n    expect(\n      cache.readQuery({\n        query,\n        variables: {\n          isbn: \"1449373321\",\n        },\n        // Read this query non-optimistically, to test that the read function\n        // runs again, adding \"1449373321\" again to isbnsWeHaveRead.\n        optimistic: false,\n      })\n    ).toEqual(diffs[0].result);\n\n    expect(isbnsWeHaveRead).toEqual([\"1449373321\", \"1982103558\", \"1449373321\"]);\n  });\n\n  it(\"Refuses to merge { __ref } objects as StoreObjects\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            book: {\n              keyArgs: [\"isbn\"],\n            },\n          },\n        },\n\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    const store = cache[\"data\"];\n\n    const query = gql`\n      query Book($isbn: string) {\n        book(isbn: $isbn) {\n          title\n        }\n      }\n    `;\n\n    const data = {\n      book: {\n        __typename: \"Book\",\n        isbn: \"1449373321\",\n        title: \"Designing Data-Intensive Applications\",\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data,\n      variables: {\n        isbn: data.book.isbn,\n      },\n    });\n\n    const bookId = cache.identify(data.book)!;\n\n    store.merge(bookId, makeReference(bookId) as StoreValue as StoreObject);\n\n    const snapshot = cache.extract();\n    expect(snapshot).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'book:{\"isbn\":\"1449373321\"}': {\n          __ref: 'Book:{\"isbn\":\"1449373321\"}',\n        },\n      },\n      'Book:{\"isbn\":\"1449373321\"}': {\n        __typename: \"Book\",\n        isbn: \"1449373321\",\n        title: \"Designing Data-Intensive Applications\",\n      },\n    });\n\n    store.merge(makeReference(bookId) as StoreValue as StoreObject, bookId);\n\n    expect(cache.extract()).toEqual(snapshot);\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/fragmentMatcher.ts",
    "content": "import type { FragmentDefinitionNode } from \"graphql\";\nimport { visit } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport { InMemoryCache } from \"@apollo/client/cache\";\n\ndescribe(\"fragment matching\", () => {\n  it(\"can match exact types with or without possibleTypes\", () => {\n    const cacheWithoutPossibleTypes = new InMemoryCache();\n\n    const cacheWithPossibleTypes = new InMemoryCache({\n      possibleTypes: {\n        Animal: [\"Cat\", \"Dog\"],\n      },\n    });\n\n    const query = gql`\n      query AnimalNames {\n        animals {\n          id\n          name\n          ...CatDetails\n        }\n      }\n      fragment CatDetails on Cat {\n        livesLeft\n        killsToday\n      }\n    `;\n\n    const data = {\n      animals: [\n        {\n          __typename: \"Cat\",\n          id: 1,\n          name: \"Felix\",\n          livesLeft: 8,\n          killsToday: 2,\n        },\n        {\n          __typename: \"Dog\",\n          id: 2,\n          name: \"Baxter\",\n        },\n      ],\n    };\n\n    cacheWithoutPossibleTypes.writeQuery({ query, data });\n    expect(cacheWithoutPossibleTypes.readQuery({ query })).toEqual(data);\n\n    cacheWithPossibleTypes.writeQuery({ query, data });\n    expect(cacheWithPossibleTypes.readQuery({ query })).toEqual(data);\n  });\n\n  it(\"can match interface subtypes\", () => {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        Animal: [\"Cat\", \"Dog\"],\n      },\n    });\n\n    const query = gql`\n      query BestFriend {\n        bestFriend {\n          id\n          ...AnimalName\n        }\n      }\n      fragment AnimalName on Animal {\n        name\n      }\n    `;\n\n    const data = {\n      bestFriend: {\n        __typename: \"Dog\",\n        id: 2,\n        name: \"Beckett\",\n      },\n    };\n\n    cache.writeQuery({ query, data });\n    expect(cache.readQuery({ query })).toEqual(data);\n  });\n\n  it(\"can match union member types\", () => {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        Status: [\"PASSING\", \"FAILING\", \"SKIPPED\"],\n      },\n    });\n\n    const query = gql`\n      query {\n        testResults {\n          id\n          output {\n            ... on Status {\n              stdout\n            }\n            ... on FAILING {\n              stderr\n            }\n          }\n        }\n      }\n    `;\n\n    const data = {\n      testResults: [\n        {\n          __typename: \"TestResult\",\n          id: 123,\n          output: {\n            __typename: \"PASSING\",\n            stdout: \"ok!\",\n          },\n        },\n        {\n          __typename: \"TestResult\",\n          id: 456,\n          output: {\n            __typename: \"FAILING\",\n            stdout: \"\",\n            stderr: \"oh no\",\n          },\n        },\n      ],\n    };\n\n    cache.writeQuery({ query, data });\n    expect(cache.readQuery({ query })).toEqual(data);\n  });\n\n  it(\"can match indirect subtypes while avoiding cycles\", () => {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        Animal: [\"Animal\", \"Bug\", \"Mammal\"],\n        Bug: [\"Ant\", \"Spider\", \"RolyPoly\"],\n        Mammal: [\"Dog\", \"Cat\", \"Human\"],\n        Cat: [\"Calico\", \"Siamese\", \"Sphynx\", \"Tabby\"],\n      },\n    });\n\n    const query = gql`\n      query {\n        animals {\n          ... on Mammal {\n            hasFur\n            bodyTemperature\n          }\n          ... on Bug {\n            isVenomous\n          }\n        }\n      }\n    `;\n\n    const data = {\n      animals: [\n        {\n          __typename: \"Sphynx\",\n          hasFur: false,\n          bodyTemperature: 99,\n        },\n        {\n          __typename: \"Dog\",\n          hasFur: true,\n          bodyTemperature: 102,\n        },\n        {\n          __typename: \"Spider\",\n          isVenomous: \"maybe\",\n        },\n      ],\n    };\n\n    cache.writeQuery({ query, data });\n    expect(cache.readQuery({ query })).toEqual(data);\n  });\n\n  it(\"can match against the root Query\", () => {\n    const cache = new InMemoryCache();\n\n    const query = gql`\n      query AllPeople {\n        people {\n          id\n          name\n        }\n        ...PeopleTypes\n      }\n      fragment PeopleTypes on Query {\n        __type(name: \"Person\") {\n          name\n          kind\n        }\n      }\n    `;\n\n    const data = {\n      people: [\n        {\n          __typename: \"Person\",\n          id: 123,\n          name: \"Ben\",\n        },\n      ],\n      __type: {\n        __typename: \"__Type\",\n        name: \"Person\",\n        kind: \"OBJECT\",\n      },\n    };\n\n    cache.writeQuery({ query, data });\n    expect(cache.readQuery({ query })).toEqual(data);\n  });\n});\n\ndescribe(\"policies.fragmentMatches\", () => {\n  const warnings: any[] = [];\n  const { warn } = console;\n\n  beforeEach(() => {\n    warnings.length = 0;\n    console.warn = function (...args: any) {\n      warnings.push(args);\n    };\n  });\n\n  afterEach(() => {\n    console.warn = warn;\n  });\n\n  it(\"can infer fuzzy subtypes heuristically\", async () => {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        A: [\"B\", \"C\"],\n        B: [\"D\"],\n        C: [\"[E-Z]\"],\n      },\n    });\n\n    const fragments = gql`\n      fragment FragA on A {\n        a\n      }\n      fragment FragB on B {\n        b\n      }\n      fragment FragC on C {\n        c\n      }\n      fragment FragD on D {\n        d\n      }\n      fragment FragE on E {\n        e\n      }\n      fragment FragF on F {\n        f\n      }\n    `;\n\n    function checkTypes(expected: Record<string, Record<string, boolean>>) {\n      const checked = new Set<FragmentDefinitionNode>();\n\n      visit(fragments, {\n        FragmentDefinition(frag) {\n          function check(typename: string, result: boolean) {\n            if (result !== cache.policies.fragmentMatches(frag, typename)) {\n              throw new Error(\n                `fragment ${frag.name.value} should${\n                  result ? \"\" : \" not\"\n                } have matched typename ${typename}`\n              );\n            }\n          }\n\n          const supertype = frag.typeCondition.name.value;\n          expect(\"ABCDEF\".split(\"\")).toContain(supertype);\n\n          if (expected.hasOwnProperty(supertype)) {\n            Object.keys(expected[supertype]).forEach((subtype) => {\n              check(subtype, expected[supertype][subtype]);\n            });\n\n            checked.add(frag);\n          }\n        },\n      });\n\n      return checked;\n    }\n\n    expect(\n      checkTypes({\n        A: {\n          A: true,\n          B: true,\n          C: true,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n        },\n        B: {\n          A: false,\n          B: true,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n        },\n        C: {\n          A: false,\n          B: false,\n          C: true,\n          D: false,\n          E: false,\n          F: false,\n          G: false,\n        },\n        D: {\n          A: false,\n          B: false,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n        },\n        E: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: true,\n          F: false,\n          G: false,\n        },\n        F: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: true,\n          G: false,\n        },\n        G: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: false,\n          G: true,\n        },\n      }).size\n    ).toBe(\"ABCDEF\".length);\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          objects {\n            ...FragC\n          }\n        }\n        ${fragments}\n      `,\n      data: {\n        objects: [\n          { __typename: \"E\", c: \"ce\" },\n          { __typename: \"F\", c: \"cf\" },\n          { __typename: \"G\", c: \"cg\" },\n          // The /[E-Z]/ subtype pattern specified for the C supertype\n          // must match the entire subtype string.\n          { __typename: \"TooLong\", c: \"nope\" },\n          // The H typename matches the regular expression for C, but it\n          // does not pass the heuristic test of having all the fields\n          // expected if FragC matched.\n          { __typename: \"H\", h: \"not c\" },\n        ],\n      },\n    });\n\n    expect(warnings).toEqual([\n      [\"Inferring subtype %s of supertype %s\", \"E\", \"C\"],\n      [\"Inferring subtype %s of supertype %s\", \"F\", \"C\"],\n      [\"Inferring subtype %s of supertype %s\", \"G\", \"C\"],\n      // Note that TooLong is not inferred here.\n    ]);\n\n    expect(\n      checkTypes({\n        A: {\n          A: true,\n          B: true,\n          C: true,\n          D: true,\n          E: true,\n          F: true,\n          G: true,\n          H: false,\n        },\n        B: {\n          A: false,\n          B: true,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n          H: false,\n        },\n        C: {\n          A: false,\n          B: false,\n          C: true,\n          D: false,\n          E: true,\n          F: true,\n          G: true,\n          H: false,\n        },\n        D: {\n          A: false,\n          B: false,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n          H: false,\n        },\n        E: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: true,\n          F: false,\n          G: false,\n          H: false,\n        },\n        F: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: true,\n          G: false,\n          H: false,\n        },\n        G: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: true,\n          G: true,\n          H: false,\n        },\n      }).size\n    ).toBe(\"ABCDEF\".length);\n\n    expect(cache.extract()).toMatchSnapshot();\n\n    // Now add the TooLong subtype of C explicitly.\n    cache.policies.addPossibleTypes({\n      C: [\"TooLong\"],\n    });\n\n    expect(\n      checkTypes({\n        A: {\n          A: true,\n          B: true,\n          C: true,\n          D: true,\n          E: true,\n          F: true,\n          G: true,\n          TooLong: true,\n          H: false,\n        },\n        B: {\n          A: false,\n          B: true,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n          TooLong: false,\n          H: false,\n        },\n        C: {\n          A: false,\n          B: false,\n          C: true,\n          D: false,\n          E: true,\n          F: true,\n          G: true,\n          TooLong: true,\n          H: false,\n        },\n        D: {\n          A: false,\n          B: false,\n          C: false,\n          D: true,\n          E: false,\n          F: false,\n          G: false,\n          TooLong: false,\n          H: false,\n        },\n        E: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: true,\n          F: false,\n          G: false,\n          TooLong: false,\n          H: false,\n        },\n        F: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: true,\n          G: false,\n          TooLong: false,\n          H: false,\n        },\n        G: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: true,\n          G: true,\n          TooLong: false,\n          H: false,\n        },\n        H: {\n          A: false,\n          B: false,\n          C: false,\n          D: false,\n          E: false,\n          F: false,\n          G: false,\n          TooLong: false,\n          H: true,\n        },\n      }).size\n    ).toBe(\"ABCDEF\".length);\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/fragmentRegistry.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport { ApolloClient, ApolloLink, gql, NetworkStatus } from \"@apollo/client\";\nimport { createFragmentRegistry, InMemoryCache } from \"@apollo/client/cache\";\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\nimport { getFragmentDefinitions } from \"@apollo/client/utilities/internal\";\n\ndescribe(\"FragmentRegistry\", () => {\n  it(\"can be passed to InMemoryCache\", () => {\n    const cache = new InMemoryCache({\n      fragments: createFragmentRegistry(gql`\n        fragment BasicFragment on Query {\n          basic\n        }\n      `),\n    });\n\n    // TODO Allow writeFragment to just use fragmentName:\"BasicFragment\"?\n    cache.writeQuery({\n      query: gql`\n        query {\n          ...BasicFragment\n        }\n      `,\n      data: {\n        basic: true,\n      },\n    });\n\n    const result = cache.readQuery({\n      query: gql`\n        query {\n          ...BasicFragment\n        }\n      `,\n    });\n\n    expect(result).toEqual({\n      basic: true,\n    });\n  });\n\n  it(\"influences ApolloClient and ApolloLink\", async () => {\n    const cache = new InMemoryCache({\n      fragments: createFragmentRegistry(gql`\n        fragment SourceFragment on Query {\n          source\n        }\n      `),\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            expect(\n              getFragmentDefinitions(operation.query)\n                .map((def) => def.name.value)\n                .sort()\n            ).toEqual([\n              // Proof that the missing SourceFragment definition was appended to\n              // operation.query before it was passed into the link.\n              \"SourceFragment\",\n            ]);\n\n            // Emit value async so we can observe the loading state\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  source: \"link\",\n                },\n              });\n\n              observer.complete();\n            });\n          })\n      ),\n    });\n\n    const query = gql`\n      query SourceQuery {\n        ...SourceFragment\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        source: \"local\",\n      },\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, fetchPolicy: \"cache-and-network\" })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: {\n        __typename: \"Query\",\n        source: \"local\",\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        __typename: \"Query\",\n        source: \"link\",\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      source: \"link\",\n    });\n  });\n\n  it(\"throws an error when not all used fragments are defined\", () => {\n    const cache = new InMemoryCache({\n      fragments: createFragmentRegistry(gql`\n        fragment IncompleteFragment on Person {\n          __typename\n          id\n          ...MustBeDefinedByQuery\n        }\n      `),\n    });\n\n    const queryWithoutFragment = gql`\n      query WithoutFragment {\n        me {\n          ...IncompleteFragment\n        }\n      }\n    `;\n\n    const queryWithFragment = gql`\n      query WithFragment {\n        me {\n          ...IncompleteFragment\n        }\n      }\n\n      fragment MustBeDefinedByQuery on Person {\n        name\n      }\n    `;\n\n    expect(() => {\n      cache.writeQuery({\n        query: queryWithoutFragment,\n        data: {\n          me: {\n            __typename: \"Person\",\n            id: 12345,\n            name: \"Ben\",\n          },\n        },\n      });\n    }).toThrow(/No fragment named MustBeDefinedByQuery/);\n\n    expect(cache.extract()).toEqual({\n      // Nothing written because the cache.writeQuery failed above.\n    });\n\n    cache.writeQuery({\n      query: queryWithFragment,\n      data: {\n        me: {\n          __typename: \"Person\",\n          id: 12345,\n          name: \"Ben Newman\",\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        me: { __ref: \"Person:12345\" },\n      },\n      \"Person:12345\": {\n        __typename: \"Person\",\n        id: 12345,\n        name: \"Ben Newman\",\n      },\n    });\n\n    expect(() => {\n      cache.diff({\n        query: queryWithoutFragment,\n        returnPartialData: true,\n        optimistic: true,\n      });\n    }).toThrow(/No fragment named MustBeDefinedByQuery/);\n\n    expect(() => {\n      cache.readQuery({\n        query: queryWithoutFragment,\n      });\n    }).toThrow(/No fragment named MustBeDefinedByQuery/);\n\n    expect(\n      cache.readQuery({\n        query: queryWithFragment,\n      })\n    ).toEqual({\n      me: {\n        __typename: \"Person\",\n        id: 12345,\n        name: \"Ben Newman\",\n      },\n    });\n  });\n\n  it(\"can register fragments with unbound ...spreads\", () => {\n    const cache = new InMemoryCache({\n      fragments: createFragmentRegistry(gql`\n        fragment NeedsExtra on Person {\n          __typename\n          id\n          # This fragment spread has a default definition below, but can be\n          # selectively overridden by queries.\n          ...ExtraFields\n        }\n\n        fragment ExtraFields on Person {\n          __typename\n        }\n      `),\n    });\n\n    const query = gql`\n      query GetMe {\n        me {\n          ...NeedsExtra\n        }\n      }\n\n      # This version of the ExtraFields fragment will be used instead of the one\n      # registered in the FragmentRegistry, because explicit definitions take\n      # precedence over registered fragments.\n      fragment ExtraFields on Person {\n        name\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        me: {\n          __typename: \"Person\",\n          id: 12345,\n          name: \"Alice\",\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        me: { __ref: \"Person:12345\" },\n      },\n      \"Person:12345\": {\n        __typename: \"Person\",\n        id: 12345,\n        name: \"Alice\",\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"Person\",\n        id: 12345,\n        name: \"Alice\",\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/helpers.ts",
    "content": "import type { Cache } from \"@apollo/client\";\nimport { EntityStore, InMemoryCache } from \"@apollo/client/cache\";\n\nimport type { StoreReader } from \"../readFromStore.js\";\nimport type {\n  DiffQueryAgainstStoreOptions,\n  NormalizedCache,\n  NormalizedCacheObject,\n} from \"../types.js\";\nimport type { StoreWriter } from \"../writeToStore.js\";\n\nexport function defaultNormalizedCacheFactory(\n  seed?: NormalizedCacheObject\n): NormalizedCache {\n  const cache = new InMemoryCache();\n  return new EntityStore.Root({\n    policies: cache.policies,\n    resultCaching: true,\n    seed,\n  });\n}\n\ninterface WriteQueryToStoreOptions extends Cache.WriteOptions {\n  writer: StoreWriter;\n  store?: NormalizedCache;\n}\n\nexport function readQueryFromStore<T = any>(\n  reader: StoreReader,\n  options: DiffQueryAgainstStoreOptions\n) {\n  return reader.diffQueryAgainstStore<T>({\n    ...options,\n    returnPartialData: false,\n  }).result;\n}\n\nexport function writeQueryToStore(\n  options: WriteQueryToStoreOptions\n): NormalizedCache {\n  const {\n    dataId = \"ROOT_QUERY\",\n    store = new EntityStore.Root({\n      policies: options.writer.cache.policies,\n    }),\n    ...writeOptions\n  } = options;\n  options.writer.writeToStore(store, {\n    ...writeOptions,\n    dataId,\n  });\n  return store;\n}\n\nexport function withError(func: Function, regex?: RegExp) {\n  let message: string = null as never;\n  const { error } = console;\n  console.error = (m: any) => {\n    message = m;\n  };\n\n  try {\n    const result = func();\n    if (regex) {\n      expect(message).toMatch(regex);\n    }\n    return result;\n  } finally {\n    console.error = error;\n  }\n}\n\ndescribe(\"defaultNormalizedCacheFactory\", function () {\n  it(\"should return an EntityStore\", function () {\n    const store = defaultNormalizedCacheFactory();\n    expect(store).toBeInstanceOf(EntityStore);\n    expect(store).toBeInstanceOf(EntityStore.Root);\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/key-extractor.ts",
    "content": "import { canonicalStringify } from \"@apollo/client/utilities\";\n\nimport {\n  collectSpecifierPaths,\n  extractKeyPath,\n  getSpecifierPaths,\n  // not exported\n  // eslint-disable-next-line local-rules/no-relative-imports\n} from \"../key-extractor.js\";\nimport type { KeySpecifier } from \"../policies.js\";\n\ndescribe(\"keyFields and keyArgs extraction\", () => {\n  it(\"getSpecifierPaths should work for various specifiers\", () => {\n    function check(specifier: KeySpecifier, expected: string[][]) {\n      const actualPaths = getSpecifierPaths(specifier);\n      expect(actualPaths).toEqual(expected);\n      // Make sure paths lookup is cached.\n      expect(getSpecifierPaths(specifier)).toBe(actualPaths);\n    }\n\n    check([], []);\n    check([\"a\"], [[\"a\"]]);\n\n    // prettier-ignore\n    check([\"a\", \"b\", \"c\"], [\n      [\"a\"],\n      [\"b\"],\n      [\"c\"]\n    ]);\n\n    // prettier-ignore\n    check([\"a\", [\"b\", \"c\"], \"d\"], [\n      [\"a\", \"b\"],\n      [\"a\", \"c\"],\n      [\"d\"],\n    ]);\n\n    // prettier-ignore\n    check([\"a\", \"b\", [\"c\"], \"d\"], [\n      [\"a\"],\n      [\"b\", \"c\"],\n      [\"d\"],\n    ]);\n\n    // prettier-ignore\n    check([\"a\", \"b\", [\"c\", [\"d\", [\"e\", \"f\"], \"g\"]]], [\n      [\"a\"],\n      [\"b\", \"c\", \"d\", \"e\"],\n      [\"b\", \"c\", \"d\", \"f\"],\n      [\"b\", \"c\", \"g\"],\n    ]);\n  });\n\n  it(\"collectSpecifierPaths should work for various specifiers\", () => {\n    const object = {\n      a: 123,\n      b: {\n        d: {\n          f: 567,\n          e: 456,\n        },\n        c: 234,\n        g: 678,\n      },\n      h: 789,\n    };\n\n    function collect(specifier: KeySpecifier) {\n      return collectSpecifierPaths(specifier, (path) =>\n        extractKeyPath(object, path)\n      );\n    }\n\n    function check(specifier: KeySpecifier, expected: Record<string, any>) {\n      const actual = collect(specifier);\n      expect(actual).toEqual(expected);\n      // Not only must actual and expected be equal, but their key orderings\n      // must also be the same.\n      expect(JSON.stringify(actual)).toBe(JSON.stringify(expected));\n    }\n\n    check([], {});\n\n    check([\"a\", \"h\"], {\n      a: 123,\n      h: 789,\n    });\n\n    check([\"h\", \"a\", \"bogus\"], {\n      h: 789,\n      a: 123,\n    });\n\n    check([\"b\", [\"d\", [\"e\"]]], {\n      b: { d: { e: 456 } },\n    });\n\n    check([\"b\", [\"d\", [\"e\"]], \"a\"], {\n      b: { d: { e: 456 } },\n      a: 123,\n    });\n\n    check([\"b\", [\"g\", \"d\"], \"a\"], {\n      b: {\n        g: 678,\n        d: {\n          e: 456,\n          f: 567,\n        },\n      },\n      a: 123,\n    });\n\n    check([\"b\", \"a\"], {\n      b: {\n        // Notice that the keys of each nested object are sorted, despite being\n        // out of order in the original object.\n        c: 234,\n        d: {\n          e: 456,\n          f: 567,\n        },\n        g: 678,\n      },\n      // This a key comes after the b key, however, because we requested that\n      // ordering with the [\"b\", \"a\"] specifier array.\n      a: 123,\n    });\n  });\n\n  it(\"extractKeyPath can handle arrays\", () => {\n    const object = {\n      extra: \"read about it elsewhere\",\n      array: [\n        { value: 1, a: \"should be first\" },\n        { value: 2, x: \"should come after value\" },\n        { z: \"should come last\", value: 3 },\n      ],\n      more: \"another word for extra\",\n    };\n\n    expect(extractKeyPath(object, [\"array\", \"value\"])).toEqual([1, 2, 3]);\n\n    expect(\n      collectSpecifierPaths([\"array\", [\"value\", \"a\", \"x\", \"z\"]], (path) => {\n        expect(path.length).toBe(2);\n        expect(path[0]).toBe(\"array\");\n        expect([\"value\", \"a\", \"x\", \"z\"]).toContain(path[1]);\n        return extractKeyPath(object, path);\n      })\n    ).toEqual({\n      array: {\n        value: object.array.map((item) => item.value),\n        a: [\"should be first\", void 0, void 0],\n        x: [void 0, \"should come after value\", void 0],\n        z: [void 0, void 0, \"should come last\"],\n      },\n    });\n\n    // This test case is \"underspecified\" because the specifier array [\"array\"]\n    // does not name any nested fields to pull from each array element.\n    const underspecified = extractKeyPath(object, [\"array\"]);\n    expect(underspecified).toEqual(object.array);\n    const understringified = JSON.stringify(underspecified);\n    // Although the objects are structurally equal, they do not stringify the\n    // same, since the underspecified keys have been stably sorted.\n    expect(understringified).not.toEqual(JSON.stringify(object.array));\n\n    expect(understringified).toBe(\n      JSON.stringify([\n        // Note that a: object.array[0].a has become the first key, because \"a\"\n        // precedes \"value\" alphabetically.\n        { a: object.array[0].a, value: 1 },\n        { value: 2, x: object.array[1].x },\n        { value: 3, z: object.array[2].z },\n      ])\n    );\n\n    // This new ordering also happens to be the canonical/stable ordering,\n    // according to canonicalStringify.\n    expect(understringified).toBe(canonicalStringify(object.array));\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/optimistic.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport { InMemoryCache } from \"@apollo/client/cache\";\n\ndescribe(\"optimistic cache layers\", () => {\n  it(\"return === results for repeated reads\", () => {\n    const cache = new InMemoryCache({\n      resultCaching: true,\n      dataIdFromObject(value: any) {\n        switch (value && value.__typename) {\n          case \"Book\":\n            return \"Book:\" + value.isbn;\n          case \"Author\":\n            return \"Author:\" + value.name;\n        }\n      },\n    });\n\n    const query = gql`\n      {\n        book {\n          title\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    function readOptimistic(cache: InMemoryCache) {\n      return cache.readQuery<{ book: any }>({ query }, true);\n    }\n\n    function readRealistic(cache: InMemoryCache) {\n      return cache.readQuery<{ book: any }>({ query }, false);\n    }\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"1980719802\",\n          title: \"1984\",\n          author: {\n            __typename: \"Author\",\n            name: \"George Orwell\",\n          },\n        },\n      },\n    });\n\n    const result1984 = readOptimistic(cache);\n    expect(result1984).toEqual({\n      book: {\n        __typename: \"Book\",\n        title: \"1984\",\n        author: {\n          __typename: \"Author\",\n          name: \"George Orwell\",\n        },\n      },\n    });\n\n    expect(result1984).toBe(readOptimistic(cache));\n    expect(result1984).toEqual(readRealistic(cache));\n\n    let result2666InTransaction: ReturnType<typeof readOptimistic> | null =\n      null;\n    cache.performTransaction((proxy) => {\n      expect(readOptimistic(cache)).toEqual(result1984);\n\n      proxy.writeQuery({\n        query,\n        data: {\n          book: {\n            __typename: \"Book\",\n            isbn: \"0312429215\",\n            title: \"2666\",\n            author: {\n              __typename: \"Author\",\n              name: \"Roberto Bolaño\",\n            },\n          },\n        },\n      });\n\n      result2666InTransaction = readOptimistic(proxy);\n      expect(result2666InTransaction).toEqual({\n        book: {\n          __typename: \"Book\",\n          title: \"2666\",\n          author: {\n            __typename: \"Author\",\n            name: \"Roberto Bolaño\",\n          },\n        },\n      });\n    }, \"first\");\n\n    expect(readOptimistic(cache)).toBe(result2666InTransaction);\n\n    expect(result1984).toEqual(readRealistic(cache));\n    expect(result1984).not.toBe(readRealistic(cache));\n\n    let resultCatch22: ReturnType<typeof readOptimistic> | null = null;\n    cache.performTransaction((proxy) => {\n      proxy.writeQuery({\n        query,\n        data: {\n          book: {\n            __typename: \"Book\",\n            isbn: \"1451626657\",\n            title: \"Catch-22\",\n            author: {\n              __typename: \"Author\",\n              name: \"Joseph Heller\",\n            },\n          },\n        },\n      });\n\n      resultCatch22 = readOptimistic(proxy);\n      expect(resultCatch22).toEqual({\n        book: {\n          __typename: \"Book\",\n          title: \"Catch-22\",\n          author: {\n            __typename: \"Author\",\n            name: \"Joseph Heller\",\n          },\n        },\n      });\n    }, \"second\");\n\n    expect(readOptimistic(cache)).toBe(resultCatch22);\n\n    expect(result1984).toEqual(readRealistic(cache));\n\n    cache.removeOptimistic(\"first\");\n\n    expect(readOptimistic(cache)).toBe(resultCatch22);\n\n    // Write a new book to the root Query.book field, which should not affect\n    // the 'second' optimistic layer that is still applied.\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          isbn: \"9781451673319\",\n          title: \"Fahrenheit 451\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ray Bradbury\",\n          },\n        },\n      },\n    });\n\n    expect(readOptimistic(cache)).toEqual(resultCatch22);\n\n    const resultF451 = readRealistic(cache);\n    expect(resultF451).toEqual({\n      book: {\n        __typename: \"Book\",\n        title: \"Fahrenheit 451\",\n        author: {\n          __typename: \"Author\",\n          name: \"Ray Bradbury\",\n        },\n      },\n    });\n\n    cache.removeOptimistic(\"second\");\n\n    expect(resultF451).toBe(readRealistic(cache));\n    expect(resultF451).toEqual(readOptimistic(cache));\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: { __ref: \"Book:9781451673319\" },\n      },\n      \"Book:1980719802\": {\n        title: \"1984\",\n        author: { __ref: \"Author:George Orwell\" },\n        __typename: \"Book\",\n      },\n      \"Book:9781451673319\": {\n        title: \"Fahrenheit 451\",\n        author: { __ref: \"Author:Ray Bradbury\" },\n        __typename: \"Book\",\n      },\n      \"Author:George Orwell\": {\n        __typename: \"Author\",\n        name: \"George Orwell\",\n      },\n      \"Author:Ray Bradbury\": {\n        __typename: \"Author\",\n        name: \"Ray Bradbury\",\n      },\n    });\n  });\n\n  it(\"dirties appropriate IDs when optimistic layers are removed\", () => {\n    const cache = new InMemoryCache({\n      resultCaching: true,\n      dataIdFromObject(value: any) {\n        switch (value && value.__typename) {\n          case \"Book\":\n            return \"Book:\" + value.isbn;\n          case \"Author\":\n            return \"Author:\" + value.name;\n        }\n      },\n    });\n\n    type Q = {\n      books: any[];\n    };\n\n    const query = gql`\n      {\n        books {\n          title\n          subtitle\n        }\n      }\n    `;\n\n    const eagerBookData = {\n      __typename: \"Book\",\n      isbn: \"1603589082\",\n      title: \"Eager\",\n      subtitle: \"The Surprising, Secret Life of Beavers and Why They Matter\",\n      author: {\n        __typename: \"Author\",\n        name: \"Ben Goldfarb\",\n      },\n    };\n\n    const spinelessBookData = {\n      __typename: \"Book\",\n      isbn: \"0735211280\",\n      title: \"Spineless\",\n      subtitle: \"The Science of Jellyfish and the Art of Growing a Backbone\",\n      author: {\n        __typename: \"Author\",\n        name: \"Juli Berwald\",\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data: {\n        books: [eagerBookData, spinelessBookData],\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        books: [{ __ref: \"Book:1603589082\" }, { __ref: \"Book:0735211280\" }],\n      },\n      \"Book:1603589082\": {\n        title: \"Eager\",\n        subtitle: eagerBookData.subtitle,\n        __typename: \"Book\",\n      },\n      \"Book:0735211280\": {\n        title: \"Spineless\",\n        subtitle: spinelessBookData.subtitle,\n        __typename: \"Book\",\n      },\n    });\n\n    function read() {\n      return cache.readQuery<Q>({ query }, true)!;\n    }\n\n    const result = read();\n    expect(result).toEqual({\n      books: [\n        {\n          __typename: \"Book\",\n          title: \"Eager\",\n          subtitle:\n            \"The Surprising, Secret Life of Beavers and Why They Matter\",\n        },\n        {\n          __typename: \"Book\",\n          title: \"Spineless\",\n          subtitle:\n            \"The Science of Jellyfish and the Art of Growing a Backbone\",\n        },\n      ],\n    });\n    expect(read()).toBe(result);\n\n    const bookAuthorNameFragment = gql`\n      fragment BookAuthorName on Book {\n        author {\n          name\n        }\n      }\n    `;\n\n    cache.writeFragment({\n      id: \"Book:0735211280\",\n      fragment: bookAuthorNameFragment,\n      data: {\n        author: spinelessBookData.author,\n      },\n    });\n\n    // Adding an author doesn't change the structure of the original result,\n    // because the original query did not ask for author information.\n    const resultWithSpinlessAuthor = read();\n    expect(resultWithSpinlessAuthor).toEqual(result);\n    expect(resultWithSpinlessAuthor).toBe(result);\n    expect(resultWithSpinlessAuthor.books[0]).toBe(result.books[0]);\n    expect(resultWithSpinlessAuthor.books[1]).toBe(result.books[1]);\n\n    cache.recordOptimisticTransaction((proxy) => {\n      proxy.writeFragment({\n        id: \"Book:1603589082\",\n        fragment: bookAuthorNameFragment,\n        data: {\n          author: eagerBookData.author,\n        },\n      });\n    }, \"eager author\");\n\n    expect(read()).toEqual(result);\n\n    const queryWithAuthors = gql`\n      {\n        books {\n          title\n          subtitle\n          author {\n            name\n          }\n        }\n      }\n    `;\n\n    function readWithAuthors(optimistic = true) {\n      return cache.readQuery<Q>(\n        {\n          query: queryWithAuthors,\n        },\n        optimistic\n      )!;\n    }\n\n    function withoutISBN(data: any) {\n      return JSON.parse(\n        JSON.stringify(data, (key, value) => {\n          if (key === \"isbn\") return;\n          return value;\n        })\n      );\n    }\n\n    const resultWithTwoAuthors = readWithAuthors();\n    expect(resultWithTwoAuthors).toEqual({\n      books: [withoutISBN(eagerBookData), withoutISBN(spinelessBookData)],\n    });\n\n    const buzzBookData = {\n      __typename: \"Book\",\n      isbn: \"0465052614\",\n      title: \"Buzz\",\n      subtitle: \"The Nature and Necessity of Bees\",\n      author: {\n        __typename: \"Author\",\n        name: \"Thor Hanson\",\n      },\n    };\n\n    cache.recordOptimisticTransaction((proxy) => {\n      proxy.writeQuery({\n        query: queryWithAuthors,\n        data: {\n          books: [eagerBookData, spinelessBookData, buzzBookData],\n        },\n      });\n    }, \"buzz book\");\n\n    const resultWithBuzz = readWithAuthors();\n\n    expect(resultWithBuzz).toEqual({\n      books: [\n        withoutISBN(eagerBookData),\n        withoutISBN(spinelessBookData),\n        withoutISBN(buzzBookData),\n      ],\n    });\n    expect(resultWithBuzz.books[0]).toEqual(resultWithTwoAuthors.books[0]);\n    expect(resultWithBuzz.books[1]).toEqual(resultWithTwoAuthors.books[1]);\n\n    // Before removing the Buzz optimistic layer from the cache, write the same\n    // data to the root layer of the cache.\n    cache.writeQuery({\n      query: queryWithAuthors,\n      data: {\n        books: [eagerBookData, spinelessBookData, buzzBookData],\n      },\n    });\n\n    expect(readWithAuthors()).toEqual(resultWithBuzz);\n\n    function readSpinelessFragment() {\n      return cache.readFragment<{ author: any }>(\n        {\n          id: \"Book:\" + spinelessBookData.isbn,\n          fragment: bookAuthorNameFragment,\n        },\n        true\n      );\n    }\n\n    const spinelessBeforeRemovingBuzz = readSpinelessFragment();\n    cache.removeOptimistic(\"buzz book\");\n    const spinelessAfterRemovingBuzz = readSpinelessFragment();\n    expect(spinelessBeforeRemovingBuzz).toEqual(spinelessAfterRemovingBuzz);\n    expect(spinelessBeforeRemovingBuzz).toBe(spinelessAfterRemovingBuzz);\n\n    const resultAfterRemovingBuzzLayer = readWithAuthors();\n    expect(resultAfterRemovingBuzzLayer).toEqual(resultWithBuzz);\n    resultWithTwoAuthors.books.forEach((book, i) => {\n      expect(book).toEqual(resultAfterRemovingBuzzLayer.books[i]);\n    });\n\n    const nonOptimisticResult = readWithAuthors(false);\n    expect(nonOptimisticResult).toEqual(resultWithBuzz);\n    cache.removeOptimistic(\"eager author\");\n    const resultWithoutOptimisticLayers = readWithAuthors();\n    expect(resultWithoutOptimisticLayers).toEqual(nonOptimisticResult);\n  });\n\n  describe(\"eviction during optimistic updates\", function () {\n    it(\"should not evict from lower layers\", function () {\n      const cache = new InMemoryCache();\n\n      const query = gql`\n        query {\n          counter {\n            value\n          }\n        }\n      `;\n\n      function write(value: number) {\n        cache.writeQuery({\n          query,\n          data: {\n            counter: {\n              value,\n            },\n          },\n        });\n      }\n\n      function expectOptimisticCount(value: number) {\n        expect(\n          cache.readQuery({\n            query,\n            optimistic: true,\n          })\n        ).toEqual({\n          counter: {\n            value,\n          },\n        });\n\n        expect(cache.extract(true)).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            counter: {\n              value,\n            },\n          },\n        });\n      }\n\n      function expectNonOptimisticCount(value: number) {\n        // Reading non-optimistically returns the original non-optimistic data.\n        expect(\n          cache.readQuery({\n            query,\n            optimistic: false,\n          })\n        ).toEqual({\n          counter: {\n            value,\n          },\n        });\n\n        // Extracting non-optimistically shows Query.counter === 0 again.\n        expect(cache.extract(false)).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            counter: {\n              value,\n            },\n          },\n        });\n      }\n\n      write(0);\n      expectOptimisticCount(0);\n      expectNonOptimisticCount(0);\n\n      cache.batch({\n        optimistic: \"layer 1\",\n        update() {\n          write(1);\n          expectOptimisticCount(1);\n          // Within the update function, non-optimistic cache reads come from\n          // the current optimistic layer, so we read 1 here instead of 0.\n          expectNonOptimisticCount(1);\n        },\n      });\n      expectOptimisticCount(1);\n      // Now that we're out of the update function, the non-optimistic data is\n      // back to looking as it always did.\n      expectNonOptimisticCount(0);\n\n      cache.batch({\n        optimistic: \"layer 2\",\n        update() {\n          write(2);\n          expectOptimisticCount(2);\n        },\n      });\n      expectOptimisticCount(2);\n\n      cache.batch({\n        optimistic: \"layer 3\",\n        update() {\n          write(3);\n          expectOptimisticCount(3);\n\n          expect(\n            cache.evict({\n              fieldName: \"counter\",\n            })\n          ).toBe(true);\n\n          expectOptimisticEviction();\n        },\n      });\n\n      function expectOptimisticEviction() {\n        // Reading optimistically fails because the data have been evicted,\n        // though only optimistically.\n        expect(\n          cache.readQuery({\n            query,\n            optimistic: true,\n          })\n        ).toBe(null);\n\n        // Extracting optimistically shows Query.counter undefined.\n        expect(cache.extract(true)).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            counter: void 0,\n          },\n        });\n      }\n\n      expectOptimisticEviction();\n\n      cache.removeOptimistic(\"layer 2\");\n\n      // Nothing changes because \"layer 2\" was not the top layer.\n      expectOptimisticEviction();\n\n      // Original data still intact, of course.\n      expectNonOptimisticCount(0);\n\n      cache.removeOptimistic(\"layer 3\");\n\n      // Since we removed layers 2 and then 3, only layer 1 is left.\n      expectOptimisticCount(1);\n      expectNonOptimisticCount(0);\n\n      // Since this eviction is not happening inside an optimistic update\n      // function, it evicts the Query.counter field from both the optimistic\n      // layer (1) and the root layer.\n      expect(\n        cache.evict({\n          fieldName: \"counter\",\n        })\n      ).toBe(true);\n\n      expectOptimisticEviction();\n\n      cache.removeOptimistic(\"layer 1\");\n\n      // There are no optimistic layers now, but the root/non-optimistic layer\n      // also exhibits the eviction.\n      expectOptimisticEviction();\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/policies.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport type {\n  DocumentNode,\n  OperationVariables,\n  Reference,\n  StoreObject,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport {\n  InMemoryCache,\n  makeVar,\n  MissingFieldError,\n} from \"@apollo/client/cache\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { relayStylePagination } from \"@apollo/client/utilities\";\nimport { stringifyForDisplay } from \"@apollo/client/utilities/internal\";\n\nimport type { FieldPolicy, StorageType } from \"../policies.js\";\nimport type { ReactiveVar } from \"../reactiveVars.js\";\n\nfunction reverse(s: string) {\n  return s.split(\"\").reverse().join(\"\");\n}\n\ndescribe(\"type policies\", function () {\n  const bookQuery = gql`\n    query {\n      book {\n        title\n        author {\n          name\n        }\n      }\n    }\n  `;\n\n  const theInformationBookData = {\n    __typename: \"Book\",\n    isbn: \"1400096235\",\n    title: \"The Information\",\n    subtitle: \"A History, a Theory, a Flood\",\n    author: {\n      name: \"James Gleick\",\n    },\n  };\n\n  function checkAuthorName(cache: InMemoryCache) {\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            book {\n              author {\n                name\n              }\n            }\n          }\n        `,\n      })\n    ).toEqual({\n      book: {\n        __typename: \"Book\",\n        author: {\n          name: theInformationBookData.author.name,\n        },\n      },\n    });\n  }\n\n  it(\"can specify basic keyFields\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: bookQuery,\n      data: {\n        book: theInformationBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: 'Book:{\"isbn\":\"1400096235\"}',\n        },\n      },\n      'Book:{\"isbn\":\"1400096235\"}': {\n        __typename: \"Book\",\n        isbn: \"1400096235\",\n        title: \"The Information\",\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"can specify composite keyFields\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"title\", \"author\", [\"name\"]],\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: bookQuery,\n      data: {\n        book: theInformationBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref:\n            'Book:{\"title\":\"The Information\",\"author\":{\"name\":\"James Gleick\"}}',\n        },\n      },\n      'Book:{\"title\":\"The Information\",\"author\":{\"name\":\"James Gleick\"}}': {\n        __typename: \"Book\",\n        title: \"The Information\",\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"can specify nested keyFields with alias\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"title\", \"author\", [\"name\"]],\n        },\n      },\n    });\n\n    const aliasQuery = gql`\n      query {\n        book {\n          title\n          writer: author {\n            alias: name\n          }\n        }\n      }\n    `;\n\n    const { author, ...rest } = theInformationBookData;\n    const aliasBookData = {\n      ...rest,\n      writer: {\n        alias: author.name,\n      },\n    };\n\n    cache.writeQuery({\n      query: aliasQuery,\n      data: {\n        book: aliasBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref:\n            'Book:{\"title\":\"The Information\",\"author\":{\"name\":\"James Gleick\"}}',\n        },\n      },\n      'Book:{\"title\":\"The Information\",\"author\":{\"name\":\"James Gleick\"}}': {\n        __typename: \"Book\",\n        title: \"The Information\",\n        // Note that \"author\" and \"name\" are stored internally, since they are\n        // the true names of their fields (according to the schema), despite the\n        // writer:author and alias:name aliases.\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"keeps keyFields in specified order\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"author\", [\"name\"], \"title\"],\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: bookQuery,\n      data: {\n        book: theInformationBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref:\n            'Book:{\"author\":{\"name\":\"James Gleick\"},\"title\":\"The Information\"}',\n        },\n      },\n      'Book:{\"author\":{\"name\":\"James Gleick\"},\"title\":\"The Information\"}': {\n        __typename: \"Book\",\n        title: \"The Information\",\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"serializes nested keyFields objects in stable order\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          // If you explicitly specify the order of author sub-fields, there\n          // will be no ambiguity about how the author object should be\n          // serialized. However, cache IDs should at least be stably\n          // stringified if the child property names are omitted, as below.\n          // keyFields: [\"title\", \"author\", [\"firstName\", \"lastName\"]],\n          keyFields: [\"title\", \"author\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        book {\n          title\n          writer: author {\n            first: firstName\n            lastName\n          }\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          writer: {\n            // The order of fields shouldn't matter here, since cache\n            // identification will stringify them in a stable order.\n            first: \"Rebecca\",\n            lastName: \"Schwarzlose\",\n            __typename: \"Person\",\n          },\n          title: \"Brainscapes\",\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          __typename: \"Book\",\n          title: \"The Science of Can and Can't\",\n          writer: {\n            // The order of fields shouldn't matter here, since cache\n            // identification will stringify them in a stable order.\n            lastName: \"Marletto\",\n            __typename: \"Person\",\n            first: \"Chiarra\",\n          },\n        },\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      // The order of the author object's __typename, firstName, and lastName\n      // fields has been determined by our keyFields configuration and stable\n      // stringification.\n      'Book:{\"title\":\"Brainscapes\",\"author\":{\"__typename\":\"Person\",\"firstName\":\"Rebecca\",\"lastName\":\"Schwarzlose\"}}':\n        {\n          __typename: \"Book\",\n          title: \"Brainscapes\",\n          author: {\n            __typename: \"Person\",\n            firstName: \"Rebecca\",\n            lastName: \"Schwarzlose\",\n          },\n        },\n      // Again, __typename, firstName, and then lastName, despite the different\n      // order of keys in the data we wrote.\n      'Book:{\"title\":\"The Science of Can and Can\\'t\",\"author\":{\"__typename\":\"Person\",\"firstName\":\"Chiarra\",\"lastName\":\"Marletto\"}}':\n        {\n          __typename: \"Book\",\n          title: \"The Science of Can and Can't\",\n          author: {\n            __typename: \"Person\",\n            firstName: \"Chiarra\",\n            lastName: \"Marletto\",\n          },\n        },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref:\n            'Book:{\"title\":\"The Science of Can and Can\\'t\",\"author\":{\"__typename\":\"Person\",\"firstName\":\"Chiarra\",\"lastName\":\"Marletto\"}}',\n        },\n      },\n    });\n  });\n\n  it(\"accepts keyFields functions\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields(book, context) {\n            expect(context.typename).toBe(\"Book\");\n            expect(context.selectionSet!.kind).toBe(\"SelectionSet\");\n            expect(context.fragmentMap).toEqual({});\n            return [\"isbn\"];\n          },\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: bookQuery,\n      data: {\n        book: theInformationBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: 'Book:{\"isbn\":\"1400096235\"}',\n        },\n      },\n      'Book:{\"isbn\":\"1400096235\"}': {\n        __typename: \"Book\",\n        isbn: \"1400096235\",\n        title: \"The Information\",\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"works with fragments that contain aliased key fields\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"ISBN\", \"title\"],\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          book {\n            ...BookFragment\n            author {\n              name\n            }\n          }\n        }\n        fragment BookFragment on Book {\n          isbn: ISBN\n          title\n        }\n      `,\n      data: {\n        book: theInformationBookData,\n      },\n    });\n\n    expect(cache.extract(true)).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        book: {\n          __ref: 'Book:{\"ISBN\":\"1400096235\",\"title\":\"The Information\"}',\n        },\n      },\n      'Book:{\"ISBN\":\"1400096235\",\"title\":\"The Information\"}': {\n        __typename: \"Book\",\n        ISBN: \"1400096235\",\n        title: \"The Information\",\n        author: {\n          name: \"James Gleick\",\n        },\n      },\n    });\n\n    checkAuthorName(cache);\n  });\n\n  it(\"complains about missing key fields\", function () {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"title\", \"year\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        book {\n          title\n          year\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        book: {\n          year: 2011,\n          theInformationBookData,\n        },\n      },\n    });\n\n    expect(() => {\n      cache.writeQuery({\n        query,\n        data: {\n          book: theInformationBookData,\n        },\n      });\n    }).toThrow(\n      `Missing field 'year' while extracting keyFields from ${stringifyForDisplay(\n        theInformationBookData,\n        2\n      )}`\n    );\n  });\n\n  it(\"does not clobber previous keyFields with undefined\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Movie: {\n          keyFields(incoming) {\n            return `MotionPicture::${incoming.id}`;\n          },\n        },\n      },\n    });\n\n    cache.policies.addTypePolicies({\n      Movie: {\n        fields: {\n          isPurchased() {\n            return false;\n          },\n        },\n      },\n    });\n\n    expect(\n      cache.identify({\n        __typename: \"Movie\",\n        id: \"3993d4118143\",\n      })\n    ).toBe(\"MotionPicture::3993d4118143\");\n  });\n\n  it(\"does not remove previous typePolicies\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            foo: () => \"foo\",\n          },\n        },\n      },\n    });\n\n    cache.policies.addTypePolicies({\n      Query: {\n        fields: {\n          bar: () => \"bar\",\n        },\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          {\n            foo\n          }\n        `,\n      })\n    ).toEqual({ foo: \"foo\" });\n    expect(\n      cache.readQuery({\n        query: gql`\n          {\n            bar\n          }\n        `,\n      })\n    ).toEqual({ bar: \"bar\" });\n  });\n\n  it(\"support inheritance\", function () {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        Reptile: [\"Snake\", \"Turtle\"],\n        Snake: [\"Python\", \"Viper\", \"Cobra\"],\n        Viper: [\"Cottonmouth\"],\n      },\n\n      typePolicies: {\n        Reptile: {\n          keyFields: [\"tagId\"],\n\n          fields: {\n            scientificName: {\n              merge(_, incoming) {\n                // Normalize all scientific names to lower case.\n                return incoming.toLowerCase();\n              },\n            },\n          },\n        },\n\n        Snake: {\n          fields: {\n            // Default to a truthy non-boolean value if we don't know\n            // whether this snake is venomous.\n            venomous(status = \"unknown\") {\n              return status;\n            },\n          },\n        },\n      },\n    });\n\n    const query: TypedDocumentNode<{\n      reptiles: Record<string, any>[];\n    }> = gql`\n      query {\n        reptiles {\n          tagId\n          scientificName\n          ... on Snake {\n            venomous\n          }\n        }\n      }\n    `;\n\n    const reptiles = [\n      {\n        __typename: \"Turtle\",\n        tagId: \"RedEaredSlider42\",\n        scientificName: \"Trachemys scripta elegans\",\n      },\n      {\n        __typename: \"Python\",\n        tagId: \"BigHug4U\",\n        scientificName: \"Malayopython reticulatus\",\n        venomous: false,\n      },\n      {\n        __typename: \"Cobra\",\n        tagId: \"Egypt30BC\",\n        scientificName: \"Naja haje\",\n        venomous: true,\n      },\n      {\n        __typename: \"Cottonmouth\",\n        tagId: \"CM420\",\n        scientificName: \"Agkistrodon piscivorus\",\n        venomous: true,\n      },\n    ];\n\n    cache.writeQuery({\n      query,\n      data: { reptiles },\n    });\n\n    expect(cache.extract()).toMatchSnapshot();\n\n    const result1 = cache.readQuery({ query })!;\n    expect(result1).toEqual({\n      reptiles: reptiles.map((reptile) => ({\n        ...reptile,\n        scientificName: reptile.scientificName.toLowerCase(),\n      })),\n    });\n\n    const cmId = cache.identify({\n      __typename: \"Cottonmouth\",\n      tagId: \"CM420\",\n    });\n\n    expect(\n      cache.evict({\n        id: cmId,\n        fieldName: \"venomous\",\n      })\n    ).toBe(true);\n\n    const result2 = cache.readQuery({ query })!;\n\n    result2.reptiles.forEach((reptile, i) => {\n      if (reptile.__typename === \"Cottonmouth\") {\n        expect(reptile).not.toBe(result1.reptiles[i]);\n        expect(reptile).not.toEqual(result1.reptiles[i]);\n        expect(reptile).toEqual({\n          __typename: \"Cottonmouth\",\n          tagId: \"CM420\",\n          // This name has been normalized to lower case.\n          scientificName: \"agkistrodon piscivorus\",\n          // Venomosity status has been set to a default value.\n          venomous: \"unknown\",\n        });\n      } else {\n        expect(reptile).toBe(result1.reptiles[i]);\n      }\n    });\n\n    cache.policies.addPossibleTypes({\n      Viper: [\"DeathAdder\"],\n    });\n\n    expect(\n      cache.identify({\n        __typename: \"DeathAdder\",\n        tagId: \"LethalAbacus666\",\n      })\n    ).toBe('DeathAdder:{\"tagId\":\"LethalAbacus666\"}');\n  });\n\n  it(\"specific field policies will not override supertype policies\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Named: {\n          fields: Object.freeze({\n            name: Object.freeze({\n              read(existing: any) {\n                return existing + \" (Named)\";\n              },\n            }),\n          }),\n        },\n        Person: {\n          fields: {\n            name: {\n              read(existing) {\n                return existing + \" (Person)\";\n              },\n            },\n          },\n        },\n      },\n      possibleTypes: {\n        Named: [\"Person\", \"Pet\"],\n      },\n    });\n    const query = gql`\n      {\n        me {\n          __typename\n          id\n          name\n          pets {\n            __typename\n            id\n            name\n          }\n        }\n      }\n    `;\n    cache.writeQuery({\n      query,\n      data: {\n        me: {\n          __typename: \"Person\",\n          id: 23,\n          name: \"John Doe\",\n          pets: [\n            {\n              __typename: \"Pet\",\n              id: 1,\n              name: \"Fido\",\n            },\n            {\n              __typename: \"Pet\",\n              id: 2,\n              name: \"Whiskers\",\n            },\n          ],\n        },\n      },\n    });\n    expect(cache.readQuery({ query })).toEqual({\n      me: {\n        __typename: \"Person\",\n        id: 23,\n        name: \"John Doe (Person)\",\n        pets: [\n          { __typename: \"Pet\", id: 1, name: \"Fido (Named)\" },\n          { __typename: \"Pet\", id: 2, name: \"Whiskers (Named)\" },\n        ],\n      },\n    });\n  });\n\n  it(\"typePolicies can be inherited from supertypes with fuzzy possibleTypes\", () => {\n    const cache = new InMemoryCache({\n      possibleTypes: {\n        EntitySupertype: [\".*Entity\"],\n      },\n      typePolicies: {\n        Query: {\n          fields: {\n            coworkers: {\n              merge(existing, incoming) {\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n\n        // The point of this test is to ensure keyFields: [\"uid\"] can be\n        // registered for all __typename strings matching the RegExp /.*Entity/,\n        // without manually enumerating all of them.\n        EntitySupertype: {\n          keyFields: [\"uid\"],\n        },\n      },\n    });\n\n    type Coworker = {\n      __typename: \"CoworkerEntity\" | \"ManagerEntity\";\n      uid: string;\n      name: string;\n    };\n\n    const query: TypedDocumentNode<{\n      coworkers: Coworker[];\n    }> = gql`\n      query {\n        coworkers {\n          uid\n          name\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        coworkers: [\n          { __typename: \"CoworkerEntity\", uid: \"qwer\", name: \"Alessia\" },\n          { __typename: \"CoworkerEntity\", uid: \"asdf\", name: \"Jerel\" },\n          { __typename: \"CoworkerEntity\", uid: \"zxcv\", name: \"Lenz\" },\n          { __typename: \"ManagerEntity\", uid: \"uiop\", name: \"Jeff\" },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        coworkers: [\n          { __ref: 'CoworkerEntity:{\"uid\":\"qwer\"}' },\n          { __ref: 'CoworkerEntity:{\"uid\":\"asdf\"}' },\n          { __ref: 'CoworkerEntity:{\"uid\":\"zxcv\"}' },\n          { __ref: 'ManagerEntity:{\"uid\":\"uiop\"}' },\n        ],\n      },\n      'CoworkerEntity:{\"uid\":\"qwer\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"qwer\",\n        name: \"Alessia\",\n      },\n      'CoworkerEntity:{\"uid\":\"asdf\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"asdf\",\n        name: \"Jerel\",\n      },\n      'CoworkerEntity:{\"uid\":\"zxcv\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"zxcv\",\n        name: \"Lenz\",\n      },\n      'ManagerEntity:{\"uid\":\"uiop\"}': {\n        __typename: \"ManagerEntity\",\n        uid: \"uiop\",\n        name: \"Jeff\",\n      },\n    });\n\n    interface CoworkerWithAlias extends Omit<Coworker, \"uid\"> {\n      idAlias: string;\n    }\n\n    const queryWithAlias: TypedDocumentNode<{\n      coworkers: CoworkerWithAlias[];\n    }> = gql`\n      query {\n        coworkers {\n          idAlias: uid\n          name\n        }\n      }\n    `;\n\n    expect(cache.readQuery({ query: queryWithAlias })).toEqual({\n      coworkers: [\n        { __typename: \"CoworkerEntity\", idAlias: \"qwer\", name: \"Alessia\" },\n        { __typename: \"CoworkerEntity\", idAlias: \"asdf\", name: \"Jerel\" },\n        { __typename: \"CoworkerEntity\", idAlias: \"zxcv\", name: \"Lenz\" },\n        { __typename: \"ManagerEntity\", idAlias: \"uiop\", name: \"Jeff\" },\n      ],\n    });\n\n    cache.writeQuery({\n      query: queryWithAlias,\n      data: {\n        coworkers: [\n          { __typename: \"CoworkerEntity\", idAlias: \"hjkl\", name: \"Martijn\" },\n          { __typename: \"ManagerEntity\", idAlias: \"vbnm\", name: \"Hugh\" },\n        ],\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      coworkers: [\n        { __typename: \"CoworkerEntity\", uid: \"qwer\", name: \"Alessia\" },\n        { __typename: \"CoworkerEntity\", uid: \"asdf\", name: \"Jerel\" },\n        { __typename: \"CoworkerEntity\", uid: \"zxcv\", name: \"Lenz\" },\n        { __typename: \"ManagerEntity\", uid: \"uiop\", name: \"Jeff\" },\n        { __typename: \"CoworkerEntity\", uid: \"hjkl\", name: \"Martijn\" },\n        { __typename: \"ManagerEntity\", uid: \"vbnm\", name: \"Hugh\" },\n      ],\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        coworkers: [\n          { __ref: 'CoworkerEntity:{\"uid\":\"qwer\"}' },\n          { __ref: 'CoworkerEntity:{\"uid\":\"asdf\"}' },\n          { __ref: 'CoworkerEntity:{\"uid\":\"zxcv\"}' },\n          { __ref: 'ManagerEntity:{\"uid\":\"uiop\"}' },\n          { __ref: 'CoworkerEntity:{\"uid\":\"hjkl\"}' },\n          { __ref: 'ManagerEntity:{\"uid\":\"vbnm\"}' },\n        ],\n      },\n      'CoworkerEntity:{\"uid\":\"qwer\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"qwer\",\n        name: \"Alessia\",\n      },\n      'CoworkerEntity:{\"uid\":\"asdf\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"asdf\",\n        name: \"Jerel\",\n      },\n      'CoworkerEntity:{\"uid\":\"zxcv\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"zxcv\",\n        name: \"Lenz\",\n      },\n      'ManagerEntity:{\"uid\":\"uiop\"}': {\n        __typename: \"ManagerEntity\",\n        uid: \"uiop\",\n        name: \"Jeff\",\n      },\n      'CoworkerEntity:{\"uid\":\"hjkl\"}': {\n        __typename: \"CoworkerEntity\",\n        uid: \"hjkl\",\n        name: \"Martijn\",\n      },\n      'ManagerEntity:{\"uid\":\"vbnm\"}': {\n        __typename: \"ManagerEntity\",\n        uid: \"vbnm\",\n        name: \"Hugh\",\n      },\n    });\n  });\n\n  describe(\"field policies\", function () {\n    it(`can filter arguments using keyArgs`, function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              book: {\n                keyArgs: [\"isbn\"],\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            book(junk: \"ignored\", isbn: \"0465030793\") {\n              title\n            }\n          }\n        `,\n        data: {\n          book: {\n            __typename: \"Book\",\n            isbn: \"0465030793\",\n            title: \"I Am a Strange Loop\",\n          },\n        },\n      });\n\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'book:{\"isbn\":\"0465030793\"}': {\n            __typename: \"Book\",\n            title: \"I Am a Strange Loop\",\n          },\n        },\n      });\n    });\n\n    it(`can filter arguments using keyArgs in non-Query fields`, function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n            fields: {\n              author: {\n                keyArgs: [\"firstName\", \"lastName\"],\n              },\n            },\n          },\n          Author: {\n            keyFields: [\"name\"],\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          book {\n            isbn\n            title\n            author(\n              firstName: \"Douglas\"\n              middleName: \"Richard\"\n              lastName: \"Hofstadter\"\n            ) {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = {\n        book: {\n          __typename: \"Book\",\n          isbn: \"0465030793\",\n          title: \"I Am a Strange Loop\",\n          author: {\n            __typename: \"Author\",\n            name: \"Douglas Hofstadter\",\n          },\n        },\n      };\n\n      cache.writeQuery({ query, data });\n\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          book: {\n            __ref: 'Book:{\"isbn\":\"0465030793\"}',\n          },\n        },\n        'Book:{\"isbn\":\"0465030793\"}': {\n          __typename: \"Book\",\n          isbn: \"0465030793\",\n          title: \"I Am a Strange Loop\",\n          'author:{\"firstName\":\"Douglas\",\"lastName\":\"Hofstadter\"}': {\n            __ref: 'Author:{\"name\":\"Douglas Hofstadter\"}',\n          },\n        },\n        'Author:{\"name\":\"Douglas Hofstadter\"}': {\n          __typename: \"Author\",\n          name: \"Douglas Hofstadter\",\n        },\n      });\n\n      const result = cache.readQuery({ query });\n      expect(result).toEqual(data);\n    });\n\n    it(\"assumes keyArgs:false when read and merge function present\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          TypeA: {\n            fields: {\n              a() {\n                return \"a\";\n              },\n            },\n          },\n\n          TypeB: {\n            fields: {\n              b: {\n                keyArgs: [\"x\"],\n                read() {\n                  return \"b\";\n                },\n              },\n            },\n          },\n\n          TypeC: {\n            fields: {\n              c: {\n                keyArgs: false,\n                merge(existing, incoming: string) {\n                  return reverse(incoming);\n                },\n              },\n            },\n          },\n\n          TypeD: {\n            fields: {\n              d: {\n                keyArgs() {\n                  return \"d\";\n                },\n                read(existing: string) {\n                  return existing.toLowerCase();\n                },\n                merge(existing: string, incoming: string) {\n                  return incoming.toUpperCase();\n                },\n              },\n            },\n          },\n\n          TypeE: {\n            fields: {\n              e: {\n                read(existing: string) {\n                  return existing.slice(1);\n                },\n                merge(existing: string, incoming: string) {\n                  return \"*\" + incoming;\n                },\n              },\n            },\n          },\n\n          TypeF: {\n            fields: {\n              f: {\n                // nothing\n              },\n            },\n          },\n\n          Query: {\n            fields: {\n              types(existing: any[], { args }) {\n                const fromCode = args!.from.charCodeAt(0);\n                const toCode = args!.to.charCodeAt(0);\n                let e = 0;\n                for (let code = fromCode; code <= toCode; ++code) {\n                  const upper = String.fromCharCode(code).toUpperCase();\n                  const obj = existing[e++];\n                  expect(obj.__typename).toBe(\"Type\" + upper);\n                }\n                return existing;\n              },\n            },\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          types(from: \"A\", to: \"F\") {\n            ... on TypeA {\n              a\n            }\n            ... on TypeB {\n              b(x: 1, y: 2, z: 3)\n            }\n            ... on TypeC {\n              c(see: \"si\")\n            }\n            ... on TypeD {\n              d\n            }\n            ... on TypeE {\n              e(eee: \"ee\")\n            }\n            ... on TypeF {\n              f(g: \"h\")\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          types: [\n            {\n              __typename: \"TypeA\",\n            },\n            {\n              __typename: \"TypeB\",\n              b: \"x1\",\n            },\n            {\n              __typename: \"TypeC\",\n              c: \"naive\",\n            },\n            {\n              __typename: \"TypeD\",\n              d: \"quiet\",\n            },\n            {\n              __typename: \"TypeE\",\n              e: \"asterisk\",\n            },\n            {\n              __typename: \"TypeF\",\n              f: \"effigy\",\n            },\n          ],\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'types({\"from\":\"A\",\"to\":\"F\"})': [\n            {\n              __typename: \"TypeA\",\n            },\n            {\n              __typename: \"TypeB\",\n              'b:{\"x\":1}': \"x1\",\n            },\n            {\n              __typename: \"TypeC\",\n              c: \"evian\",\n            },\n            {\n              __typename: \"TypeD\",\n              d: \"QUIET\",\n            },\n            {\n              __typename: \"TypeE\",\n              e: \"*asterisk\",\n            },\n            {\n              __typename: \"TypeF\",\n              'f({\"g\":\"h\"})': \"effigy\",\n            },\n          ],\n        },\n      });\n\n      const result = cache.readQuery({ query });\n      expect(result).toEqual({\n        types: [\n          {\n            __typename: \"TypeA\",\n            a: \"a\",\n          },\n          {\n            __typename: \"TypeB\",\n            b: \"b\",\n          },\n          {\n            __typename: \"TypeC\",\n            c: \"evian\",\n          },\n          {\n            __typename: \"TypeD\",\n            d: \"quiet\",\n          },\n          {\n            __typename: \"TypeE\",\n            e: \"asterisk\",\n          },\n          {\n            __typename: \"TypeF\",\n            f: \"effigy\",\n          },\n        ],\n      });\n    });\n\n    it(`can include optional arguments in field keyArgs policy`, function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Author: {\n            keyFields: [\"name\"],\n            fields: {\n              writings: {\n                keyArgs: [\"a\", \"b\", \"type\"],\n              },\n            },\n          },\n        },\n      });\n\n      const data = {\n        author: {\n          __typename: \"Author\",\n          name: \"Nadia Eghbal\",\n          writings: [\n            {\n              __typename: \"Book\",\n              isbn: \"0578675862\",\n              title:\n                \"Working in Public: The Making and Maintenance of \" +\n                \"Open Source Software\",\n            },\n          ],\n        },\n      };\n\n      function check<\n        TData extends typeof data,\n        TVariables extends OperationVariables,\n      >(\n        query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n        variables?: TVariables\n      ) {\n        cache.writeQuery<typeof data>({ query, variables, data });\n        expect(cache.readQuery({ query, variables })).toEqual(data);\n      }\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(type: \"Book\") {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(type: \"Book\", b: 2, a: 1) {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(b: 2, a: 1) {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(b: 2) {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(a: 3) {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings(unrelated: \"oyez\") {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(\n        gql`\n          query AuthorWritings($type: String) {\n            author {\n              name\n              writings(b: 4, type: $type, unrelated: \"oyez\") {\n                ... on Book {\n                  title\n                  isbn\n                }\n              }\n            }\n          }\n        `,\n        { type: void 0 as any }\n      );\n      expect(cache.extract()).toMatchSnapshot();\n\n      check(gql`\n        query {\n          author {\n            name\n            writings {\n              ... on Book {\n                title\n                isbn\n              }\n            }\n          }\n        }\n      `);\n      expect(cache.extract()).toMatchSnapshot();\n\n      const storeFieldNames: string[] = [];\n\n      cache.modify({\n        id: cache.identify({\n          __typename: \"Author\",\n          name: \"Nadia Eghbal\",\n        }),\n\n        fields: {\n          writings(value, { storeFieldName }) {\n            storeFieldNames.push(storeFieldName);\n            expect(value).toEqual(data.author.writings);\n            return value;\n          },\n        },\n      });\n\n      expect(storeFieldNames.sort()).toEqual([\n        \"writings\",\n        'writings:{\"a\":1,\"b\":2,\"type\":\"Book\"}',\n        'writings:{\"a\":1,\"b\":2}',\n        'writings:{\"a\":3}',\n        'writings:{\"b\":2}',\n        'writings:{\"b\":4}',\n        'writings:{\"type\":\"Book\"}',\n        \"writings:{}\",\n      ]);\n    });\n\n    it(`can return KeySpecifier arrays from keyArgs functions`, function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Thread: {\n            keyFields: [\"tid\"],\n            fields: {\n              comments: {\n                keyArgs(args, context) {\n                  expect(context.typename).toBe(\"Thread\");\n                  expect(context.fieldName).toBe(\"comments\");\n                  expect(context.field!.name.value).toBe(\"comments\");\n                  expect(context.variables).toEqual({\n                    unused: \"check me\",\n                  });\n\n                  if (typeof args!.limit === \"number\") {\n                    if (typeof args!.offset === \"number\") {\n                      expect(args).toEqual({ offset: 0, limit: 2 });\n                      return [\"offset\", \"limit\"];\n                    }\n                    if (args!.beforeId) {\n                      expect(args).toEqual({ beforeId: \"asdf\", limit: 2 });\n                      return [\"beforeId\", \"limit\"];\n                    }\n                  }\n                },\n              },\n            },\n          },\n\n          Comment: {\n            keyFields: [\"author\", [\"name\"]],\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          thread {\n            tid\n            offsetComments: comments(offset: 0, limit: 2) {\n              author {\n                name\n              }\n            }\n            beforeIdComments: comments(beforeId: \"asdf\", limit: 2) {\n              author {\n                name\n              }\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          thread: {\n            __typename: \"Thread\",\n            tid: \"12345\",\n            offsetComments: [\n              {\n                __typename: \"Comment\",\n                author: { name: \"Alice\" },\n              },\n              {\n                __typename: \"Comment\",\n                author: { name: \"Bobby\" },\n              },\n            ],\n            beforeIdComments: [\n              {\n                __typename: \"Comment\",\n                author: { name: \"Calvin\" },\n              },\n              {\n                __typename: \"Comment\",\n                author: { name: \"Hobbes\" },\n              },\n            ],\n          },\n        },\n        variables: {\n          unused: \"check me\",\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          thread: {\n            __ref: 'Thread:{\"tid\":\"12345\"}',\n          },\n        },\n        'Thread:{\"tid\":\"12345\"}': {\n          __typename: \"Thread\",\n          tid: \"12345\",\n          'comments:{\"beforeId\":\"asdf\",\"limit\":2}': [\n            { __ref: 'Comment:{\"author\":{\"name\":\"Calvin\"}}' },\n            { __ref: 'Comment:{\"author\":{\"name\":\"Hobbes\"}}' },\n          ],\n          'comments:{\"offset\":0,\"limit\":2}': [\n            { __ref: 'Comment:{\"author\":{\"name\":\"Alice\"}}' },\n            { __ref: 'Comment:{\"author\":{\"name\":\"Bobby\"}}' },\n          ],\n        },\n        'Comment:{\"author\":{\"name\":\"Alice\"}}': {\n          __typename: \"Comment\",\n          author: {\n            name: \"Alice\",\n          },\n        },\n        'Comment:{\"author\":{\"name\":\"Bobby\"}}': {\n          __typename: \"Comment\",\n          author: {\n            name: \"Bobby\",\n          },\n        },\n        'Comment:{\"author\":{\"name\":\"Calvin\"}}': {\n          __typename: \"Comment\",\n          author: {\n            name: \"Calvin\",\n          },\n        },\n        'Comment:{\"author\":{\"name\":\"Hobbes\"}}': {\n          __typename: \"Comment\",\n          author: {\n            name: \"Hobbes\",\n          },\n        },\n      });\n    });\n\n    // Use several different directives to prove we're not hard-coding support\n    // for the @connection directive.\n    [\"connection\", \"directive\", \"misdirective\"].forEach((directiveName) =>\n      it(`can refer to directive @${directiveName} in field key shorthand array`, function () {\n        const cache = new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                feed: {\n                  keyArgs: [\"@\" + directiveName, [\"key\"], \"arg\"],\n                },\n              },\n            },\n          },\n        });\n\n        const helloTokens = [\n          { __typename: \"Token\", text: \"Hello\" },\n          { __typename: \"Token\", text: \"World\" },\n          { __typename: \"Token\", text: \"!\" },\n        ];\n\n        cache.writeQuery({\n          query: gql`\n          query FeedQuery($num: Int) {\n            feed(arg: $num) @${directiveName}(key: \"asdf\", ignored: \"boo\") {\n              text\n            }\n          }\n        `,\n          variables: {\n            num: 1234,\n          },\n          data: {\n            feed: helloTokens,\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            [`feed:{\"@${directiveName}\":{\"key\":\"asdf\"},\"arg\":1234}`]:\n              helloTokens,\n          },\n        });\n\n        const farewellTokens = [\n          { __typename: \"Token\", text: \"farewell\" },\n          { __typename: \"Token\", text: \"cruel\" },\n          { __typename: \"Token\", text: \"world\" },\n        ];\n\n        cache.writeQuery({\n          query: gql`\n            query FeedQuery($num: Int) {\n              feed(arg: $num) {\n                text\n              }\n            }\n          `,\n          variables: {\n            num: 2345,\n          },\n          data: {\n            feed: farewellTokens,\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            [`feed:{\"@${directiveName}\":{\"key\":\"asdf\"},\"arg\":1234}`]:\n              helloTokens,\n            'feed:{\"arg\":2345}': farewellTokens,\n          },\n        });\n\n        const directivesTokens = [\n          { __typename: \"Token\", text: \"directives\" },\n          { __typename: \"Token\", text: \"consuming\" },\n          { __typename: \"Token\", text: \"variables\" },\n        ];\n\n        cache.writeQuery({\n          query: gql`\n          query FeedQuery($num: Int) {\n            feed @${directiveName}(key: $num, ignored: \"boo\") {\n              text\n            }\n          }\n        `,\n          variables: {\n            num: 3456,\n          },\n          data: {\n            feed: directivesTokens,\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            [`feed:{\"@${directiveName}\":{\"key\":\"asdf\"},\"arg\":1234}`]:\n              helloTokens,\n            'feed:{\"arg\":2345}': farewellTokens,\n            [`feed:{\"@${directiveName}\":{\"key\":3456}}`]: directivesTokens,\n          },\n        });\n      })\n    );\n\n    it(\"can refer to variables in field key shorthand array\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              defaultToNumVariable: {\n                keyArgs: [\"input\", \"$num\"],\n                read(existing, { args, variables }) {\n                  return existing ?? args?.input ?? variables?.num;\n                },\n              },\n            },\n          },\n        },\n      });\n\n      const queryWithInputArg = gql`\n        query WithInputArg($num: Int) {\n          defaultToNumVariable(input: 1234)\n        }\n      `;\n\n      cache.writeQuery({\n        query: queryWithInputArg,\n        data: {\n          defaultToNumVariable: \"forced with input and $num\",\n        },\n        variables: {\n          num: 1234,\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'defaultToNumVariable:{\"input\":1234,\"$num\":1234}':\n            \"forced with input and $num\",\n        },\n      });\n\n      const queryWithNoArgs = gql`\n        query WithInputArg($num: Int) {\n          defaultToNumVariable\n        }\n      `;\n\n      cache.writeQuery({\n        query: queryWithNoArgs,\n        data: {\n          defaultToNumVariable: \"forced with only $num\",\n        },\n        variables: {\n          num: 2345,\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'defaultToNumVariable:{\"input\":1234,\"$num\":1234}':\n            \"forced with input and $num\",\n          'defaultToNumVariable:{\"$num\":2345}': \"forced with only $num\",\n        },\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithInputArg,\n          variables: {\n            num: 1234,\n          },\n        })\n      ).toEqual({\n        defaultToNumVariable: \"forced with input and $num\",\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithNoArgs,\n          variables: {\n            num: 2345,\n          },\n        })\n      ).toEqual({\n        defaultToNumVariable: \"forced with only $num\",\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithInputArg,\n          variables: {\n            num: 3456,\n          },\n        })\n      ).toEqual({\n        defaultToNumVariable: 1234,\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithNoArgs,\n          variables: {\n            num: 4567,\n          },\n        })\n      ).toEqual({\n        defaultToNumVariable: 4567,\n      });\n    });\n\n    it(\"can use options.storage in read functions\", function () {\n      const storageSet = new Set<Record<string, any>>();\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Task: {\n            fields: {\n              result(existing, { args, storage }) {\n                storageSet.add(storage);\n                if (storage.result) return storage.result;\n                return (storage.result = compute());\n              },\n            },\n          },\n        },\n      });\n\n      let computeCount = 0;\n      function compute() {\n        return `expensive result ${++computeCount}`;\n      }\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            tasks {\n              id\n            }\n          }\n        `,\n        data: {\n          tasks: [\n            {\n              __typename: \"Task\",\n              id: 1,\n            },\n            {\n              __typename: \"Task\",\n              id: 2,\n            },\n          ],\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          tasks: [{ __ref: \"Task:1\" }, { __ref: \"Task:2\" }],\n        },\n        \"Task:1\": {\n          __typename: \"Task\",\n          id: 1,\n        },\n        \"Task:2\": {\n          __typename: \"Task\",\n          id: 2,\n        },\n      });\n\n      const result1 = cache.readQuery({\n        query: gql`\n          query {\n            tasks {\n              result\n            }\n          }\n        `,\n      });\n\n      expect(result1).toEqual({\n        tasks: [\n          {\n            __typename: \"Task\",\n            result: \"expensive result 1\",\n          },\n          {\n            __typename: \"Task\",\n            result: \"expensive result 2\",\n          },\n        ],\n      });\n\n      const result2 = cache.readQuery({\n        query: gql`\n          query {\n            tasks {\n              id\n              result\n            }\n          }\n        `,\n      });\n\n      expect(result2).toEqual({\n        tasks: [\n          {\n            __typename: \"Task\",\n            id: 1,\n            result: \"expensive result 1\",\n          },\n          {\n            __typename: \"Task\",\n            id: 2,\n            result: \"expensive result 2\",\n          },\n        ],\n      });\n\n      // Clear the cached results.\n      storageSet.forEach((storage) => {\n        delete storage.result;\n      });\n\n      const result3 = cache.readQuery({\n        query: gql`\n          query {\n            tasks {\n              __typename\n              result\n            }\n          }\n        `,\n      });\n\n      expect(result3).toEqual({\n        tasks: [\n          {\n            __typename: \"Task\",\n            result: \"expensive result 3\",\n          },\n          {\n            __typename: \"Task\",\n            result: \"expensive result 4\",\n          },\n        ],\n      });\n    });\n\n    it(\"can use read function to implement synthetic/computed keys\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Person: {\n            keyFields: [\"firstName\", \"lastName\"],\n            fields: {\n              fullName(_, { readField }) {\n                const firstName = readField(\"firstName\");\n                const lastName = readField(\"lastName\");\n                return `${firstName} ${lastName}`;\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            me {\n              firstName\n              lastName\n            }\n          }\n        `,\n        data: {\n          me: {\n            __typename: \"Person\",\n            firstName: \"Ben\",\n            lastName: \"Newman\",\n          },\n        },\n      });\n\n      const expectedExtraction = {\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __ref: 'Person:{\"firstName\":\"Ben\",\"lastName\":\"Newman\"}',\n          },\n        },\n        'Person:{\"firstName\":\"Ben\",\"lastName\":\"Newman\"}': {\n          __typename: \"Person\",\n          firstName: \"Ben\",\n          lastName: \"Newman\",\n        },\n      };\n\n      expect(cache.extract(true)).toEqual(expectedExtraction);\n\n      const expectedResult = {\n        me: {\n          __typename: \"Person\",\n          fullName: \"Ben Newman\",\n        },\n      };\n\n      expect(\n        cache.readQuery({\n          query: gql`\n            query {\n              me {\n                fullName\n              }\n            }\n          `,\n        })\n      ).toEqual(expectedResult);\n\n      expect(\n        cache.readQuery({\n          query: gql`\n            query {\n              me {\n                fullName @client\n              }\n            }\n          `,\n        })\n      ).toEqual(expectedResult);\n\n      expect(cache.extract(true)).toEqual(expectedExtraction);\n    });\n\n    it(\"should return correct variables in read function\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Country: {\n            fields: {\n              isCanada: {\n                read(_, { readField }) {\n                  return readField(\"name\") === \"CA\";\n                },\n              },\n              name: {\n                read(_, { variables }) {\n                  return variables?.code;\n                },\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query Countries($code: ID!) {\n            country(code: $code) {\n              name\n            }\n          }\n        `,\n        data: {\n          country: {\n            __typename: \"Country\",\n            name: \"CA\",\n          },\n        },\n        variables: {\n          code: \"CA\",\n        },\n      });\n\n      const expectedExtraction = {\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'country({\"code\":\"CA\"})': {\n            __typename: \"Country\",\n            name: \"CA\",\n          },\n        },\n      };\n\n      expect(cache.extract(true)).toEqual(expectedExtraction);\n\n      const expectedResult = {\n        country: {\n          __typename: \"Country\",\n          name: \"CA\",\n          isCanada: true,\n        },\n      };\n\n      expect(\n        cache.readQuery({\n          query: gql`\n            query Countries($code: ID!) {\n              country(code: $code) {\n                name\n                isCanada @client\n              }\n            }\n          `,\n          variables: {\n            code: \"CA\",\n          },\n        })\n      ).toEqual(expectedResult);\n    });\n\n    it(\"read and merge can cooperate through options.storage\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              jobs: {\n                merge(existing: any[] = [], incoming: any[]) {\n                  return [...existing, ...incoming];\n                },\n              },\n            },\n          },\n\n          Job: {\n            keyFields: [\"name\"],\n            fields: {\n              result: {\n                read(_, { storage }) {\n                  if (!storage.jobName) {\n                    storage.jobName = makeVar(undefined);\n                  }\n                  return storage.jobName();\n                },\n                merge(_, incoming: string, { storage }) {\n                  if (storage.jobName) {\n                    storage.jobName(incoming);\n                  } else {\n                    storage.jobName = makeVar(incoming);\n                  }\n                },\n              },\n            },\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          jobs {\n            name\n            result\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #1\",\n              // intentionally omitting the result field\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #2\",\n              // intentionally omitting the result field\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #3\",\n              // intentionally omitting the result field\n            },\n          ],\n        },\n      });\n\n      const snapshot1 = {\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          jobs: [\n            { __ref: 'Job:{\"name\":\"Job #1\"}' },\n            { __ref: 'Job:{\"name\":\"Job #2\"}' },\n            { __ref: 'Job:{\"name\":\"Job #3\"}' },\n          ],\n        },\n        'Job:{\"name\":\"Job #1\"}': {\n          __typename: \"Job\",\n          name: \"Job #1\",\n        },\n        'Job:{\"name\":\"Job #2\"}': {\n          __typename: \"Job\",\n          name: \"Job #2\",\n        },\n        'Job:{\"name\":\"Job #3\"}': {\n          __typename: \"Job\",\n          name: \"Job #3\",\n        },\n      };\n\n      expect(cache.extract()).toEqual(snapshot1);\n\n      expect(\n        cache.diff({\n          query,\n          optimistic: false,\n          returnPartialData: true,\n        })\n      ).toEqual({\n        result: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #1\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #2\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #3\",\n            },\n          ],\n        },\n        complete: false,\n        missing: new MissingFieldError(\n          `Can't find field 'result' on Job:{\"name\":\"Job #${1}\"} object`,\n          {\n            jobs: {\n              0: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #1\"} object',\n              },\n              1: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #2\"} object',\n              },\n              2: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #3\"} object',\n              },\n            },\n          },\n          expect.anything(), // query\n          expect.anything() // variables\n        ),\n      });\n\n      function setResult(jobNum: number) {\n        cache.writeFragment({\n          id: cache.identify({\n            __typename: \"Job\",\n            name: `Job #${jobNum}`,\n          })!,\n          fragment: gql`\n            fragment JobResult on Job {\n              result\n            }\n          `,\n          data: {\n            __typename: \"Job\",\n            name: `Job #${jobNum}`,\n            result: `result for job ${jobNum}`,\n          },\n        });\n      }\n\n      setResult(2);\n\n      // Nothing should have changed in the cache itself as a result of\n      // writing a result for job #2.\n      expect(cache.extract()).toEqual({\n        ...snapshot1,\n        __META: {\n          extraRootIds: ['Job:{\"name\":\"Job #2\"}'],\n        },\n      });\n\n      expect(\n        cache.diff({\n          query,\n          optimistic: false,\n          returnPartialData: true,\n        })\n      ).toEqual({\n        result: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #1\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #2\",\n              result: \"result for job 2\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #3\",\n            },\n          ],\n        },\n        complete: false,\n        missing: new MissingFieldError(\n          `Can't find field 'result' on Job:{\"name\":\"Job #${1}\"} object`,\n          {\n            jobs: {\n              0: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #1\"} object',\n              },\n              2: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #3\"} object',\n              },\n            },\n          },\n          expect.anything(), // query\n          expect.anything() // variables\n        ),\n      });\n\n      cache.writeQuery({\n        query,\n        data: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #4\",\n              result: \"result for job 4\",\n            },\n          ],\n        },\n      });\n\n      const snapshot2 = {\n        ...snapshot1,\n        ROOT_QUERY: {\n          ...snapshot1.ROOT_QUERY,\n          jobs: [\n            ...snapshot1.ROOT_QUERY.jobs,\n            { __ref: 'Job:{\"name\":\"Job #4\"}' },\n          ],\n        },\n        'Job:{\"name\":\"Job #4\"}': {\n          __typename: \"Job\",\n          name: \"Job #4\",\n        },\n      };\n\n      expect(cache.extract()).toEqual({\n        ...snapshot2,\n        __META: {\n          extraRootIds: ['Job:{\"name\":\"Job #2\"}'],\n        },\n      });\n\n      expect(\n        cache.diff({\n          query,\n          optimistic: false,\n          returnPartialData: true,\n        })\n      ).toEqual({\n        result: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #1\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #2\",\n              result: \"result for job 2\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #3\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #4\",\n              result: \"result for job 4\",\n            },\n          ],\n        },\n        complete: false,\n        missing: new MissingFieldError(\n          `Can't find field 'result' on Job:{\"name\":\"Job #${1}\"} object`,\n          {\n            jobs: {\n              0: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #1\"} object',\n              },\n              2: {\n                result:\n                  'Can\\'t find field \\'result\\' on Job:{\"name\":\"Job #3\"} object',\n              },\n            },\n          },\n          expect.anything(), // query\n          expect.anything() // variables\n        ),\n      });\n\n      setResult(1);\n      setResult(3);\n\n      expect(\n        cache.diff({\n          query,\n          optimistic: false,\n          returnPartialData: true,\n        })\n      ).toEqual({\n        result: {\n          jobs: [\n            {\n              __typename: \"Job\",\n              name: \"Job #1\",\n              result: \"result for job 1\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #2\",\n              result: \"result for job 2\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #3\",\n              result: \"result for job 3\",\n            },\n            {\n              __typename: \"Job\",\n              name: \"Job #4\",\n              result: \"result for job 4\",\n            },\n          ],\n        },\n        complete: true,\n      });\n\n      expect(cache.readQuery({ query })).toEqual({\n        jobs: [\n          {\n            __typename: \"Job\",\n            name: \"Job #1\",\n            result: \"result for job 1\",\n          },\n          {\n            __typename: \"Job\",\n            name: \"Job #2\",\n            result: \"result for job 2\",\n          },\n          {\n            __typename: \"Job\",\n            name: \"Job #3\",\n            result: \"result for job 3\",\n          },\n          {\n            __typename: \"Job\",\n            name: \"Job #4\",\n            result: \"result for job 4\",\n          },\n        ],\n      });\n    });\n\n    it(\"read, merge, and modify functions can access options.storage\", function () {\n      const storageByFieldName = new Map<string, StorageType>();\n\n      function recordStorageOnce(fieldName: string, storage: StorageType) {\n        if (storageByFieldName.has(fieldName)) {\n          expect(storageByFieldName.get(fieldName)).toBe(storage);\n        } else {\n          storageByFieldName.set(fieldName, storage);\n        }\n      }\n\n      function makeFieldPolicy(): FieldPolicy<number> {\n        return {\n          read(existing = 0, { fieldName, storage }) {\n            storage.readCount = (storage.readCount | 0) + 1;\n            recordStorageOnce(fieldName, storage);\n            return existing;\n          },\n          merge(existing = 0, incoming, { fieldName, storage }) {\n            storage.mergeCount = (storage.mergeCount | 0) + 1;\n            recordStorageOnce(fieldName, storage);\n            return existing + incoming;\n          },\n        };\n      }\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              mergeRead: makeFieldPolicy(),\n              mergeModify: makeFieldPolicy(),\n              mergeReadModify: makeFieldPolicy(),\n            },\n          },\n        },\n      });\n\n      const query: TypedDocumentNode<{\n        mergeRead: number;\n        mergeModify: number;\n        mergeReadModify: number;\n      }> = gql`\n        query {\n          mergeRead\n          mergeModify\n          mergeReadModify\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          mergeRead: 1,\n          mergeModify: 10,\n          mergeReadModify: 100,\n        },\n      });\n\n      expect(storageByFieldName.get(\"mergeRead\")).toEqual({\n        mergeCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeModify\")).toEqual({\n        mergeCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeReadModify\")).toEqual({\n        mergeCount: 1,\n      });\n\n      expect(\n        cache.readQuery({\n          query: gql`\n            query {\n              mergeRead\n              mergeReadModify\n            }\n          `,\n        })\n      ).toEqual({\n        mergeRead: 1,\n        mergeReadModify: 100,\n      });\n\n      expect(storageByFieldName.get(\"mergeRead\")).toEqual({\n        mergeCount: 1,\n        readCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeModify\")).toEqual({\n        mergeCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeReadModify\")).toEqual({\n        mergeCount: 1,\n        readCount: 1,\n      });\n\n      expect(\n        cache.modify({\n          fields: {\n            mergeModify(value, { fieldName, storage }) {\n              storage.modifyCount = (storage.modifyCount | 0) + 1;\n              recordStorageOnce(fieldName, storage);\n              return value + 1;\n            },\n            mergeReadModify(value, { fieldName, storage }) {\n              storage.modifyCount = (storage.modifyCount | 0) + 1;\n              recordStorageOnce(fieldName, storage);\n              return value + 1;\n            },\n          },\n        })\n      ).toBe(true);\n\n      expect(cache.extract()).toMatchSnapshot();\n\n      expect(storageByFieldName.get(\"mergeRead\")).toEqual({\n        mergeCount: 1,\n        readCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeModify\")).toEqual({\n        mergeCount: 1,\n        modifyCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeReadModify\")).toEqual({\n        mergeCount: 1,\n        readCount: 1,\n        modifyCount: 1,\n      });\n\n      expect(cache.readQuery({ query })).toEqual({\n        mergeRead: 1,\n        mergeModify: 11,\n        mergeReadModify: 101,\n      });\n\n      expect(storageByFieldName.get(\"mergeRead\")).toEqual({\n        mergeCount: 1,\n        readCount: 2,\n      });\n\n      expect(storageByFieldName.get(\"mergeModify\")).toEqual({\n        mergeCount: 1,\n        modifyCount: 1,\n        readCount: 1,\n      });\n\n      expect(storageByFieldName.get(\"mergeReadModify\")).toEqual({\n        mergeCount: 1,\n        readCount: 2,\n        modifyCount: 1,\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n    });\n\n    it(\"merge functions can deduplicate items using readField\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              books: {\n                merge(existing: any[] = [], incoming: any[], { readField }) {\n                  if (existing) {\n                    const merged = existing.slice(0);\n                    const existingIsbnSet = new Set(\n                      merged.map((book) => readField(\"isbn\", book))\n                    );\n                    incoming.forEach((book) => {\n                      const isbn = readField(\"isbn\", book);\n                      if (!existingIsbnSet.has(isbn)) {\n                        existingIsbnSet.add(isbn);\n                        merged.push(book);\n                      }\n                    });\n                    return merged;\n                  }\n                  return incoming;\n                },\n\n                // Returns the books array, sorted by title.\n                read(existing: any[], { readField }) {\n                  if (existing) {\n                    return existing.slice(0).sort((a, b) => {\n                      const aTitle = readField<string>(\"title\", a);\n                      const bTitle = readField<string>(\"title\", b);\n                      if (aTitle === bTitle) return 0;\n                      if (aTitle! < bTitle!) return -1;\n                      return 1;\n                    });\n                  }\n                  return [];\n                },\n              },\n            },\n          },\n\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          books {\n            isbn\n            title\n          }\n        }\n      `;\n\n      const programmingRustBook = {\n        __typename: \"Book\",\n        isbn: \"9781491927281\",\n        title: \"Programming Rust: Fast, Safe Systems Development\",\n      };\n\n      const officialRustBook = {\n        __typename: \"Book\",\n        isbn: \"1593278284\",\n        title: \"The Rust Programming Language\",\n      };\n\n      const handsOnConcurrencyBook = {\n        __typename: \"Book\",\n        isbn: \"1788399978\",\n        title: \"Hands-On Concurrency with Rust\",\n      };\n\n      const wasmWithRustBook = {\n        __typename: \"Book\",\n        isbn: \"1680506366\",\n        title: \"Programming WebAssembly with Rust\",\n      };\n\n      function addBooks(...books: (typeof programmingRustBook)[]) {\n        cache.writeQuery({\n          query,\n          data: {\n            books,\n          },\n        });\n      }\n\n      addBooks(officialRustBook);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          books: [{ __ref: 'Book:{\"isbn\":\"1593278284\"}' }],\n        },\n        'Book:{\"isbn\":\"1593278284\"}': {\n          __typename: \"Book\",\n          isbn: \"1593278284\",\n          title: \"The Rust Programming Language\",\n        },\n      });\n\n      addBooks(programmingRustBook, officialRustBook);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          books: [\n            { __ref: 'Book:{\"isbn\":\"1593278284\"}' },\n            { __ref: 'Book:{\"isbn\":\"9781491927281\"}' },\n          ],\n        },\n        'Book:{\"isbn\":\"1593278284\"}': officialRustBook,\n        'Book:{\"isbn\":\"9781491927281\"}': programmingRustBook,\n      });\n\n      addBooks(\n        wasmWithRustBook,\n        wasmWithRustBook,\n        programmingRustBook,\n        wasmWithRustBook\n      );\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          books: [\n            { __ref: 'Book:{\"isbn\":\"1593278284\"}' },\n            { __ref: 'Book:{\"isbn\":\"9781491927281\"}' },\n            { __ref: 'Book:{\"isbn\":\"1680506366\"}' },\n          ],\n        },\n        'Book:{\"isbn\":\"1593278284\"}': officialRustBook,\n        'Book:{\"isbn\":\"9781491927281\"}': programmingRustBook,\n        'Book:{\"isbn\":\"1680506366\"}': wasmWithRustBook,\n      });\n\n      addBooks(\n        programmingRustBook,\n        officialRustBook,\n        handsOnConcurrencyBook,\n        wasmWithRustBook\n      );\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          books: [\n            { __ref: 'Book:{\"isbn\":\"1593278284\"}' },\n            { __ref: 'Book:{\"isbn\":\"9781491927281\"}' },\n            { __ref: 'Book:{\"isbn\":\"1680506366\"}' },\n            { __ref: 'Book:{\"isbn\":\"1788399978\"}' },\n          ],\n        },\n        'Book:{\"isbn\":\"1593278284\"}': officialRustBook,\n        'Book:{\"isbn\":\"9781491927281\"}': programmingRustBook,\n        'Book:{\"isbn\":\"1680506366\"}': wasmWithRustBook,\n        'Book:{\"isbn\":\"1788399978\"}': handsOnConcurrencyBook,\n      });\n\n      expect(cache.readQuery({ query })).toEqual({\n        // Note that these books have been sorted by title, thanks to the\n        // custom read function we defined above.\n        books: [\n          {\n            __typename: \"Book\",\n            isbn: \"1788399978\",\n            title: \"Hands-On Concurrency with Rust\",\n          },\n          {\n            __typename: \"Book\",\n            isbn: \"9781491927281\",\n            title: \"Programming Rust: Fast, Safe Systems Development\",\n          },\n          {\n            __typename: \"Book\",\n            isbn: \"1680506366\",\n            title: \"Programming WebAssembly with Rust\",\n          },\n          {\n            __typename: \"Book\",\n            isbn: \"1593278284\",\n            title: \"The Rust Programming Language\",\n          },\n        ],\n      });\n    });\n\n    it(\"readField helper function calls custom read functions\", function () {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      // Rather than writing ownTime data into the cache, we maintain it\n      // externally in this object:\n      const ownTimes: Record<string, ReactiveVar<number>> = {\n        \"parent task\": makeVar(2),\n        \"child task 1\": makeVar(3),\n        \"child task 2\": makeVar(4),\n        \"grandchild task\": makeVar(5),\n        \"independent task\": makeVar(11),\n      };\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Agenda: {\n            fields: {\n              taskCount(_, { readField }) {\n                return readField<Reference[]>(\"tasks\")!.length;\n              },\n\n              tasks: {\n                // Thanks to this read function, the readField(\"tasks\")\n                // call above will always return an array, so we don't\n                // have to guard against the possibility that the tasks\n                // data is undefined above.\n                read(existing = []) {\n                  return existing;\n                },\n\n                merge(existing: Reference[], incoming: Reference[]) {\n                  const merged = existing ? existing.slice(0) : [];\n                  merged.push(...incoming);\n                  return merged;\n                },\n              },\n            },\n          },\n\n          Task: {\n            fields: {\n              ownTime(_, { readField }) {\n                const description = readField<string>(\"description\");\n                return ownTimes[description!]() || 0;\n              },\n\n              totalTime(_, { readField, toReference }) {\n                function total(\n                  blockers: Readonly<Reference[]> = [],\n                  seen = new Set<string>()\n                ) {\n                  let time = 0;\n                  blockers.forEach((blocker) => {\n                    if (!seen.has(blocker.__ref)) {\n                      seen.add(blocker.__ref);\n                      time += readField<number>(\"ownTime\", blocker)!;\n                      time += total(\n                        readField<Reference[]>(\"blockers\", blocker),\n                        seen\n                      );\n                    }\n                  });\n                  return time;\n                }\n                return total([\n                  toReference({\n                    __typename: \"Task\",\n                    id: readField(\"id\"),\n                  }) as Reference,\n                ]);\n              },\n\n              blockers: {\n                merge(existing: Reference[] = [], incoming: Reference[]) {\n                  const seenIDs = new Set(existing.map((ref) => ref.__ref));\n                  const merged = existing.slice(0);\n                  incoming.forEach((ref) => {\n                    if (!seenIDs.has(ref.__ref)) {\n                      seenIDs.add(ref.__ref);\n                      merged.push(ref);\n                    }\n                  });\n                  return merged;\n                },\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            agenda {\n              id\n              tasks {\n                id\n                description\n                blockers {\n                  id\n                }\n              }\n            }\n          }\n        `,\n        data: {\n          agenda: {\n            __typename: \"Agenda\",\n            id: 1,\n            tasks: [\n              {\n                __typename: \"Task\",\n                id: 1,\n                description: \"parent task\",\n                blockers: [\n                  {\n                    __typename: \"Task\",\n                    id: 2,\n                  },\n                  {\n                    __typename: \"Task\",\n                    id: 3,\n                  },\n                ],\n              },\n              {\n                __typename: \"Task\",\n                id: 2,\n                description: \"child task 1\",\n                blockers: [\n                  {\n                    __typename: \"Task\",\n                    id: 4,\n                  },\n                ],\n              },\n              {\n                __typename: \"Task\",\n                id: 3,\n                description: \"child task 2\",\n                blockers: [\n                  {\n                    __typename: \"Task\",\n                    id: 4,\n                  },\n                ],\n              },\n              {\n                __typename: \"Task\",\n                id: 4,\n                description: \"grandchild task\",\n              },\n            ],\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          agenda: { __ref: \"Agenda:1\" },\n        },\n        \"Agenda:1\": {\n          __typename: \"Agenda\",\n          id: 1,\n          tasks: [\n            { __ref: \"Task:1\" },\n            { __ref: \"Task:2\" },\n            { __ref: \"Task:3\" },\n            { __ref: \"Task:4\" },\n          ],\n        },\n        \"Task:1\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:2\" }, { __ref: \"Task:3\" }],\n          description: \"parent task\",\n          id: 1,\n        },\n        \"Task:2\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:4\" }],\n          description: \"child task 1\",\n          id: 2,\n        },\n        \"Task:3\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:4\" }],\n          description: \"child task 2\",\n          id: 3,\n        },\n        \"Task:4\": {\n          __typename: \"Task\",\n          description: \"grandchild task\",\n          id: 4,\n        },\n      });\n\n      const query = gql`\n        query {\n          agenda {\n            taskCount\n            tasks {\n              description\n              ownTime\n              totalTime\n            }\n          }\n        }\n      `;\n\n      function read(): { agenda: any } | null {\n        return cache.readQuery({ query });\n      }\n\n      const firstResult = read();\n\n      expect(firstResult).toEqual({\n        agenda: {\n          __typename: \"Agenda\",\n          taskCount: 4,\n          tasks: [\n            {\n              __typename: \"Task\",\n              description: \"parent task\",\n              ownTime: 2,\n              totalTime: 2 + 3 + 4 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 1\",\n              ownTime: 3,\n              totalTime: 3 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 2\",\n              ownTime: 4,\n              totalTime: 4 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"grandchild task\",\n              ownTime: 5,\n              totalTime: 5,\n            },\n          ],\n        },\n      });\n\n      expect(read()).toBe(firstResult);\n\n      ownTimes[\"child task 2\"](6);\n\n      const secondResult = read();\n      expect(secondResult).not.toBe(firstResult);\n      expect(secondResult).toEqual({\n        agenda: {\n          __typename: \"Agenda\",\n          taskCount: 4,\n          tasks: [\n            {\n              __typename: \"Task\",\n              description: \"parent task\",\n              ownTime: 2,\n              totalTime: 2 + 3 + 6 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 1\",\n              ownTime: 3,\n              totalTime: 3 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 2\",\n              ownTime: 6,\n              totalTime: 6 + 5,\n            },\n            {\n              __typename: \"Task\",\n              description: \"grandchild task\",\n              ownTime: 5,\n              totalTime: 5,\n            },\n          ],\n        },\n      });\n      expect(secondResult!.agenda.tasks[0]).not.toBe(\n        firstResult!.agenda.tasks[0]\n      );\n      expect(secondResult!.agenda.tasks[1]).toBe(firstResult!.agenda.tasks[1]);\n      expect(secondResult!.agenda.tasks[2]).not.toBe(\n        firstResult!.agenda.tasks[2]\n      );\n      expect(secondResult!.agenda.tasks[3]).toBe(firstResult!.agenda.tasks[3]);\n\n      ownTimes[\"grandchild task\"](7);\n\n      const thirdResult = read();\n      expect(thirdResult).not.toBe(secondResult);\n      expect(thirdResult).toEqual({\n        agenda: {\n          __typename: \"Agenda\",\n          taskCount: 4,\n          tasks: [\n            {\n              __typename: \"Task\",\n              description: \"parent task\",\n              ownTime: 2,\n              totalTime: 2 + 3 + 6 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 1\",\n              ownTime: 3,\n              totalTime: 3 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 2\",\n              ownTime: 6,\n              totalTime: 6 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"grandchild task\",\n              ownTime: 7,\n              totalTime: 7,\n            },\n          ],\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            agenda {\n              id\n              tasks {\n                id\n                description\n              }\n            }\n          }\n        `,\n        data: {\n          agenda: {\n            __typename: \"Agenda\",\n            id: 1,\n            tasks: [\n              {\n                __typename: \"Task\",\n                id: 5,\n                description: \"independent task\",\n              },\n            ],\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          agenda: { __ref: \"Agenda:1\" },\n        },\n        \"Agenda:1\": {\n          __typename: \"Agenda\",\n          id: 1,\n          tasks: [\n            { __ref: \"Task:1\" },\n            { __ref: \"Task:2\" },\n            { __ref: \"Task:3\" },\n            { __ref: \"Task:4\" },\n            { __ref: \"Task:5\" },\n          ],\n        },\n        \"Task:1\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:2\" }, { __ref: \"Task:3\" }],\n          description: \"parent task\",\n          id: 1,\n        },\n        \"Task:2\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:4\" }],\n          description: \"child task 1\",\n          id: 2,\n        },\n        \"Task:3\": {\n          __typename: \"Task\",\n          blockers: [{ __ref: \"Task:4\" }],\n          description: \"child task 2\",\n          id: 3,\n        },\n        \"Task:4\": {\n          __typename: \"Task\",\n          description: \"grandchild task\",\n          id: 4,\n        },\n        \"Task:5\": {\n          __typename: \"Task\",\n          description: \"independent task\",\n          id: 5,\n        },\n      });\n\n      const fourthResult = read();\n      expect(fourthResult).not.toBe(thirdResult);\n      expect(fourthResult).toEqual({\n        agenda: {\n          __typename: \"Agenda\",\n          taskCount: 5,\n          tasks: [\n            {\n              __typename: \"Task\",\n              description: \"parent task\",\n              ownTime: 2,\n              totalTime: 2 + 3 + 6 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 1\",\n              ownTime: 3,\n              totalTime: 3 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"child task 2\",\n              ownTime: 6,\n              totalTime: 6 + 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"grandchild task\",\n              ownTime: 7,\n              totalTime: 7,\n            },\n            {\n              __typename: \"Task\",\n              description: \"independent task\",\n              ownTime: 11,\n              totalTime: 11,\n            },\n          ],\n        },\n      });\n\n      function checkFirstFourIdentical(result: ReturnType<typeof read>) {\n        for (let i = 0; i < 4; ++i) {\n          expect(result!.agenda.tasks[i]).toBe(thirdResult!.agenda.tasks[i]);\n        }\n      }\n      // The four original task results should not have been altered by\n      // the addition of a fifth independent task.\n      checkFirstFourIdentical(fourthResult);\n\n      const indVar = ownTimes[\"independent task\"];\n      indVar(indVar() + 1);\n\n      const fifthResult = read();\n      expect(fifthResult).not.toBe(fourthResult);\n      expect(fifthResult).toEqual({\n        agenda: {\n          __typename: \"Agenda\",\n          taskCount: 5,\n          tasks: [\n            fourthResult!.agenda.tasks[0],\n            fourthResult!.agenda.tasks[1],\n            fourthResult!.agenda.tasks[2],\n            fourthResult!.agenda.tasks[3],\n            {\n              __typename: \"Task\",\n              description: \"independent task\",\n              ownTime: 12,\n              totalTime: 12,\n            },\n          ],\n        },\n      });\n      checkFirstFourIdentical(fifthResult);\n    });\n\n    it(\"can return void to indicate missing field\", function () {\n      let secretReadAttempted = false;\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Person: {\n            fields: {\n              secret() {\n                secretReadAttempted = true;\n                // Return nothing to signal field is missing.\n              },\n            },\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          me {\n            name\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          me: {\n            __typename: \"Person\",\n            name: \"Ben Newman\",\n          },\n        },\n      });\n\n      expect(secretReadAttempted).toBe(false);\n\n      expect(\n        cache.readQuery({\n          query: gql`\n            query {\n              me {\n                secret\n              }\n            }\n          `,\n        })\n      ).toBe(null);\n\n      const diff = cache.diff({\n        optimistic: true,\n        returnPartialData: false,\n        query: gql`\n          query {\n            me {\n              secret\n            }\n          }\n        `,\n      });\n\n      const missingFieldErrorMessage = `Can't find field 'secret' on object ${JSON.stringify(\n        {\n          __typename: \"Person\",\n          name: \"Ben Newman\",\n        },\n        null,\n        2\n      )}`;\n\n      expect(diff.complete).toBe(false);\n      expect(diff.result).toBeNull();\n      expect(diff.missing).toEqual(\n        new MissingFieldError(\n          missingFieldErrorMessage,\n          {\n            me: { secret: missingFieldErrorMessage },\n          },\n          gql`\n            query {\n              me {\n                secret\n              }\n            }\n          `,\n          {}\n        )\n      );\n\n      expect(secretReadAttempted).toBe(true);\n    });\n\n    it(`can define custom merge functions and keyArgs simultaneously`, function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Person: {\n            // Disables normalization for the Person type, which means the\n            // todos field will be nested inside a non-normalized object\n            // (with __typename \"Person\") directly under the ROOT_QUERY.me\n            // field, which exercises what happens when mergeOverrides\n            // becomes nested (see writeToStore.ts).\n            keyFields: false,\n\n            fields: {\n              todos: {\n                keyArgs: [],\n\n                read(existing: any[], { args, toReference, isReference }) {\n                  expect(!existing || Object.isFrozen(existing)).toBe(true);\n                  expect(typeof toReference).toBe(\"function\");\n                  const slice = existing.slice(\n                    args!.offset,\n                    args!.offset + args!.limit\n                  );\n                  slice.forEach((ref) => expect(isReference(ref)).toBe(true));\n                  return slice;\n                },\n\n                merge(\n                  existing: any[],\n                  incoming: any[],\n                  { args, toReference, isReference }\n                ) {\n                  expect(!existing || Object.isFrozen(existing)).toBe(true);\n                  expect(typeof toReference).toBe(\"function\");\n                  const copy = existing ? existing.slice(0) : [];\n                  const limit = args!.offset + args!.limit;\n                  for (let i = args!.offset; i < limit; ++i) {\n                    copy[i] = incoming[i - args!.offset];\n                  }\n                  copy.forEach((todo) => expect(isReference(todo)).toBe(true));\n                  return copy;\n                },\n              },\n            },\n          },\n\n          Todo: {\n            keyFields: [\"id\"],\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          me {\n            todos(offset: $offset, limit: $limit) {\n              text\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          me: {\n            __typename: \"Person\",\n            id: \"ignored\",\n            todos: [\n              { __typename: \"Todo\", id: 1, text: \"Write more merge tests\" },\n              { __typename: \"Todo\", id: 2, text: \"Write pagination tests\" },\n            ],\n          },\n        },\n        variables: {\n          offset: 0,\n          limit: 2,\n        },\n      });\n\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __typename: \"Person\",\n            \"todos:{}\": [\n              { __ref: 'Todo:{\"id\":1}' },\n              { __ref: 'Todo:{\"id\":2}' },\n            ],\n          },\n        },\n        'Todo:{\"id\":1}': {\n          __typename: \"Todo\",\n          id: 1,\n          text: \"Write more merge tests\",\n        },\n        'Todo:{\"id\":2}': {\n          __typename: \"Todo\",\n          id: 2,\n          text: \"Write pagination tests\",\n        },\n      });\n\n      cache.writeQuery({\n        query,\n        data: {\n          me: {\n            __typename: \"Person\",\n            todos: [\n              { __typename: \"Todo\", id: 5, text: \"Submit pull request\" },\n              { __typename: \"Todo\", id: 6, text: \"Merge pull request\" },\n            ],\n          },\n        },\n        variables: {\n          offset: 4,\n          limit: 2,\n        },\n      });\n\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __typename: \"Person\",\n            \"todos:{}\": [\n              { __ref: 'Todo:{\"id\":1}' },\n              { __ref: 'Todo:{\"id\":2}' },\n              void 0,\n              void 0,\n              { __ref: 'Todo:{\"id\":5}' },\n              { __ref: 'Todo:{\"id\":6}' },\n            ],\n          },\n        },\n        'Todo:{\"id\":1}': {\n          __typename: \"Todo\",\n          id: 1,\n          text: \"Write more merge tests\",\n        },\n        'Todo:{\"id\":2}': {\n          __typename: \"Todo\",\n          id: 2,\n          text: \"Write pagination tests\",\n        },\n        'Todo:{\"id\":5}': {\n          __typename: \"Todo\",\n          id: 5,\n          text: \"Submit pull request\",\n        },\n        'Todo:{\"id\":6}': {\n          __typename: \"Todo\",\n          id: 6,\n          text: \"Merge pull request\",\n        },\n      });\n\n      cache.writeQuery({\n        query,\n        data: {\n          me: {\n            __typename: \"Person\",\n            todos: [\n              { __typename: \"Todo\", id: 3, text: \"Iron out merge API\" },\n              { __typename: \"Todo\", id: 4, text: \"Take a nap\" },\n            ],\n          },\n        },\n        variables: {\n          offset: 2,\n          limit: 2,\n        },\n      });\n\n      expect(cache.extract(true)).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          me: {\n            __typename: \"Person\",\n            \"todos:{}\": [\n              { __ref: 'Todo:{\"id\":1}' },\n              { __ref: 'Todo:{\"id\":2}' },\n              { __ref: 'Todo:{\"id\":3}' },\n              { __ref: 'Todo:{\"id\":4}' },\n              { __ref: 'Todo:{\"id\":5}' },\n              { __ref: 'Todo:{\"id\":6}' },\n            ],\n          },\n        },\n        'Todo:{\"id\":1}': {\n          __typename: \"Todo\",\n          id: 1,\n          text: \"Write more merge tests\",\n        },\n        'Todo:{\"id\":2}': {\n          __typename: \"Todo\",\n          id: 2,\n          text: \"Write pagination tests\",\n        },\n        'Todo:{\"id\":3}': {\n          __typename: \"Todo\",\n          id: 3,\n          text: \"Iron out merge API\",\n        },\n        'Todo:{\"id\":4}': {\n          __typename: \"Todo\",\n          id: 4,\n          text: \"Take a nap\",\n        },\n        'Todo:{\"id\":5}': {\n          __typename: \"Todo\",\n          id: 5,\n          text: \"Submit pull request\",\n        },\n        'Todo:{\"id\":6}': {\n          __typename: \"Todo\",\n          id: 6,\n          text: \"Merge pull request\",\n        },\n      });\n\n      expect(cache.gc()).toEqual([]);\n\n      // The moment of truth!\n      expect(\n        cache.readQuery({\n          query,\n          variables: {\n            offset: 1,\n            limit: 4,\n          },\n        })\n      ).toEqual({\n        me: {\n          __typename: \"Person\",\n          todos: [\n            { __typename: \"Todo\", text: \"Write pagination tests\" },\n            { __typename: \"Todo\", text: \"Iron out merge API\" },\n            { __typename: \"Todo\", text: \"Take a nap\" },\n            { __typename: \"Todo\", text: \"Submit pull request\" },\n          ],\n        },\n      });\n    });\n\n    it(\"can handle Relay-style pagination without args\", async () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              todos: relayStylePagination(),\n            },\n          },\n        },\n      });\n\n      const firstQuery = gql`\n        query TodoQuery {\n          todos {\n            totalCount\n          }\n        }\n      `;\n\n      const secondQuery = gql`\n        query TodoQuery {\n          todos(after: $after, first: $first) {\n            pageInfo {\n              __typename\n              hasNextPage\n              endCursor\n            }\n            totalCount\n            edges {\n              __typename\n              id\n              node {\n                __typename\n                id\n                title\n              }\n            }\n          }\n        }\n      `;\n\n      const thirdQuery = gql`\n        query TodoQuery {\n          todos {\n            totalCount\n            extraMetaData\n          }\n        }\n      `;\n\n      const secondVariables = {\n        first: 1,\n      };\n\n      const secondEdges = [\n        {\n          __typename: \"TodoEdge\",\n          id: \"edge1\",\n          node: {\n            __typename: \"Todo\",\n            id: \"1\",\n            title: \"Fix the tests\",\n          },\n        },\n      ];\n\n      const secondPageInfo = {\n        __typename: \"PageInfo\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjI=\",\n        hasNextPage: true,\n      };\n\n      const link = new MockLink([\n        {\n          request: {\n            query: firstQuery,\n          },\n          result: {\n            data: {\n              todos: {\n                __typename: \"TodosConnection\",\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query: secondQuery,\n            variables: secondVariables,\n          },\n          result: {\n            data: {\n              todos: {\n                __typename: \"TodosConnection\",\n                edges: secondEdges,\n                pageInfo: secondPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query: thirdQuery,\n          },\n          result: {\n            data: {\n              todos: {\n                __typename: \"TodosConnection\",\n                totalCount: 1293,\n                extraMetaData: \"extra\",\n              },\n            },\n          },\n        },\n      ]);\n\n      const client = new ApolloClient({ link, cache });\n\n      let result = await client.query({ query: firstQuery });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          todos: {\n            __typename: \"TodosConnection\",\n            totalCount: 1292,\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          todos: {\n            __typename: \"TodosConnection\",\n            edges: [],\n            pageInfo: {\n              endCursor: \"\",\n              hasNextPage: true,\n              hasPreviousPage: false,\n              startCursor: \"\",\n            },\n            totalCount: 1292,\n          },\n        },\n      });\n\n      result = await client.query({\n        query: secondQuery,\n        variables: secondVariables,\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          todos: {\n            __typename: \"TodosConnection\",\n            edges: secondEdges,\n            pageInfo: secondPageInfo,\n            totalCount: 1292,\n          },\n        },\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n\n      result = await client.query({ query: thirdQuery });\n      expect(result).toStrictEqualTyped({\n        data: {\n          todos: {\n            __typename: \"TodosConnection\",\n            totalCount: 1293,\n            extraMetaData: \"extra\",\n          },\n        },\n      });\n      expect(cache.extract()).toMatchSnapshot();\n    });\n\n    it(\"can handle Relay-style pagination\", async () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              search: relayStylePagination((args, { fieldName }) => {\n                expect(typeof args!.query).toBe(\"string\");\n                expect(fieldName).toBe(\"search\");\n                // Normalize the search query by lower-casing it.\n                return args!.query.toLowerCase();\n              }),\n            },\n          },\n\n          Artist: {\n            keyFields: [\"href\"],\n          },\n        },\n      });\n\n      const query = gql`\n        query ArtsySearch(\n          $query: String!\n          $after: String\n          $first: Int\n          $before: String\n          $last: Int\n        ) {\n          search(\n            query: $query\n            after: $after\n            first: $first\n            before: $before\n            last: $last\n          ) {\n            edges {\n              __typename\n              node {\n                __typename\n                displayLabel\n                ... on Artist {\n                  __typename\n                  href\n                  bio\n                }\n                ... on SearchableItem {\n                  __typename\n                  description\n                }\n              }\n            }\n            pageInfo {\n              __typename\n              startCursor\n              endCursor\n              hasPreviousPage\n              hasNextPage\n            }\n            totalCount\n          }\n        }\n      `;\n\n      const firstVariables = {\n        query: \"Basquiat\",\n        first: 3,\n      };\n\n      const firstEdges = [\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"Artist\",\n            href: \"/artist/jean-michel-basquiat\",\n            displayLabel: \"Jean-Michel Basquiat\",\n            bio: \"American, 1960-1988, New York, New York, based in New York, New York\",\n          },\n        },\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            displayLabel: \"ephemera BASQUIAT\",\n            __typename: \"SearchableItem\",\n            description:\n              \"Past show featuring works by Damien Hirst, \" +\n              \"James Rosenquist, David Salle, Andy Warhol, Jeff Koons, \" +\n              \"Jean-Michel Basquiat, Keith Haring, Kiki Smith, Sandro Chia, \" +\n              \"Kenny Scharf, Mike Bidlo, Jon Schueler, William Wegman, \" +\n              \"David Wojnarowicz, Taylor Mead, William S. Burroughs, \" +\n              \"Michael Halsband, Rene Ricard, and Chris DAZE Ellis\",\n          },\n        },\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            displayLabel: \"Jean-Michel Basquiat | Xerox\",\n            __typename: \"SearchableItem\",\n            description:\n              \"Past show featuring works by Jean-Michel \" +\n              \"Basquiat at Nahmad Contemporary Mar 12th – May 31st 2019\",\n          },\n        },\n      ];\n\n      const firstPageInfo = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjI=\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      };\n\n      const secondVariables = {\n        query: \"Basquiat\",\n        after: firstPageInfo.endCursor,\n        first: 3,\n      };\n\n      const secondEdges = [\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            displayLabel: \"STREET ART: From Basquiat to Banksy\",\n            __typename: \"SearchableItem\",\n            description:\n              \"Past show featuring works by Banksy, SEEN, \" +\n              \"JonOne and QUIK at Artrust Oct 8th – Dec 16th 2017\",\n          },\n        },\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"SearchableItem\",\n            displayLabel: \"STREET ART 2: From Basquiat to Banksy\",\n            description:\n              \"Past show featuring works by Jean-Michel Basquiat, \" +\n              \"Shepard Fairey, COPE2, Pure Evil, Sickboy, Blade, \" +\n              \"Kurar, and LARS at Artrust\",\n          },\n        },\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"Artist\",\n            href: \"/artist/reminiscent-of-basquiat\",\n            displayLabel: \"Reminiscent of Basquiat\",\n            bio: \"\",\n          },\n        },\n      ];\n\n      const secondPageInfo = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjM=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjU=\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      };\n\n      const thirdVariables = {\n        // Intentionally lower-case Basquiat here to make sure the results\n        // end up merged with other capitalized results.\n        query: \"basquiat\",\n        before: secondPageInfo.startCursor,\n        last: 2,\n        // Make sure these variables are not inherited.\n        after: void 0,\n        first: void 0,\n      };\n\n      const thirdEdges = firstEdges.slice(1);\n\n      const thirdPageInfo = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjE=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjM=\",\n        hasPreviousPage: true,\n        hasNextPage: true,\n      };\n\n      const fourthVariables = {\n        query: \"basquiat\",\n        before: thirdPageInfo.startCursor,\n        last: 1,\n        // Make sure these variables are not inherited.\n        after: void 0,\n        first: void 0,\n      };\n\n      // Just the initial Basquiat Artist edge.\n      const fourthEdges = firstEdges.slice(0, 1);\n\n      const fourthPageInfo = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      };\n\n      const fifthVariables = {\n        query: \"Basquiat\",\n        after: secondPageInfo.endCursor,\n        first: 1,\n      };\n\n      const fifthEdges = [\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"SearchableItem\",\n            displayLabel: \"Basquiat: The Unknown Notebooks\",\n            description:\n              \"Past show featuring works by Jean-Michel Basquiat \" +\n              \"at Brooklyn Museum Apr 3rd – Aug 23rd 2015\",\n          },\n        },\n      ];\n\n      const fifthPageInfo = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjY=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjY=\",\n        hasPreviousPage: true,\n        hasNextPage: true,\n      };\n\n      const turrellVariables1 = {\n        query: \"James Turrell\",\n        first: 1,\n      };\n\n      const turrellVariables2 = {\n        query: \"James Turrell\",\n        first: 2,\n      };\n\n      const turrellEdges = [\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"Artist\",\n            href: \"/artist/james-turrell\",\n            displayLabel: \"James Turrell\",\n            bio: \"American, born 1943, Los Angeles, California\",\n          },\n        },\n        {\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"SearchableItem\",\n            displayLabel: \"James Turrell: Light knows when we’re looking\",\n            description: \"<placeholder for unknown description>\",\n          },\n        },\n      ];\n\n      const turrellPageInfo1 = {\n        __typename: \"PageInfo\",\n        startCursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      };\n\n      const turrellPageInfo2 = {\n        ...turrellPageInfo1,\n        endCursor: \"YXJyYXljb25uZWN0aW9uOjEx\",\n      };\n\n      const link = new MockLink([\n        {\n          request: {\n            query,\n            variables: firstVariables,\n          },\n          result: {\n            data: {\n              search: {\n                edges: firstEdges,\n                pageInfo: firstPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: secondVariables,\n          },\n          result: {\n            data: {\n              search: {\n                edges: secondEdges,\n                pageInfo: secondPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: thirdVariables,\n          },\n          result: {\n            data: {\n              search: {\n                edges: thirdEdges,\n                pageInfo: thirdPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: fourthVariables,\n          },\n          result: {\n            data: {\n              search: {\n                edges: fourthEdges,\n                pageInfo: fourthPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: fifthVariables,\n          },\n          result: {\n            data: {\n              search: {\n                edges: fifthEdges,\n                pageInfo: fifthPageInfo,\n                totalCount: 1292,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: turrellVariables1,\n          },\n          result: {\n            data: {\n              search: {\n                edges: turrellEdges.slice(0, 1),\n                pageInfo: turrellPageInfo1,\n                totalCount: 13531,\n              },\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: turrellVariables2,\n          },\n          result: {\n            data: {\n              search: {\n                edges: turrellEdges,\n                pageInfo: turrellPageInfo2,\n                totalCount: 13531,\n              },\n            },\n          },\n        },\n      ]);\n\n      const client = new ApolloClient({ link, cache });\n\n      const observable = client.watchQuery<\n        any,\n        {\n          query: string;\n          after?: string;\n          first?: number;\n          before?: string;\n          last?: number;\n        }\n      >({\n        query,\n        notifyOnNetworkStatusChange: false,\n        variables: {\n          query: \"Basquiat\",\n          first: 3,\n        },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        data: {\n          search: {\n            edges: firstEdges,\n            pageInfo: firstPageInfo,\n            totalCount: 1292,\n          },\n        },\n        dataState: \"complete\",\n        partial: false,\n      });\n      expect(cache.extract()).toMatchSnapshot();\n\n      await observable.fetchMore({ variables: secondVariables });\n\n      {\n        const result = await stream.takeNext();\n\n        expect(result).toStrictEqualTyped({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          data: {\n            search: {\n              edges: [...firstEdges, ...secondEdges],\n              pageInfo: {\n                __typename: \"PageInfo\",\n                startCursor: firstPageInfo.startCursor,\n                endCursor: secondPageInfo.endCursor,\n                hasPreviousPage: false,\n                hasNextPage: true,\n              },\n              totalCount: 1292,\n            },\n          },\n          dataState: \"complete\",\n          partial: false,\n        });\n        expect(cache.extract()).toMatchSnapshot();\n      }\n\n      await observable.fetchMore({ variables: thirdVariables });\n\n      {\n        const result = await stream.takeNext();\n\n        expect(result.data.search.edges.length).toBe(5);\n\n        expect(result).toStrictEqualTyped({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          data: {\n            search: {\n              edges: [...thirdEdges, ...secondEdges],\n              pageInfo: {\n                __typename: \"PageInfo\",\n                startCursor: thirdPageInfo.startCursor,\n                endCursor: secondPageInfo.endCursor,\n                hasPreviousPage: true,\n                hasNextPage: true,\n              },\n              totalCount: 1292,\n            },\n          },\n          dataState: \"complete\",\n          partial: false,\n        });\n\n        expect(cache.extract()).toMatchSnapshot();\n      }\n\n      await observable.fetchMore({ variables: fourthVariables });\n\n      {\n        const result = await stream.takeNext();\n\n        expect(result).toStrictEqualTyped({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          data: {\n            search: {\n              edges: [...fourthEdges, ...thirdEdges, ...secondEdges],\n              pageInfo: {\n                __typename: \"PageInfo\",\n                startCursor: firstPageInfo.startCursor,\n                endCursor: secondPageInfo.endCursor,\n                hasPreviousPage: false,\n                hasNextPage: true,\n              },\n              totalCount: 1292,\n            },\n          },\n          dataState: \"complete\",\n          partial: false,\n        });\n\n        expect(result.data.search.edges).toEqual([\n          ...firstEdges,\n          ...secondEdges,\n        ]);\n\n        expect(cache.extract()).toMatchSnapshot();\n      }\n\n      await observable.fetchMore({ variables: fifthVariables });\n\n      {\n        const result = await stream.takeNext();\n\n        expect(result.data.search.edges.length).toBe(7);\n\n        expect(result).toStrictEqualTyped({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          data: {\n            search: {\n              edges: [...firstEdges, ...secondEdges, ...fifthEdges],\n              pageInfo: {\n                __typename: \"PageInfo\",\n                startCursor: firstPageInfo.startCursor,\n                endCursor: fifthPageInfo.endCursor,\n                hasPreviousPage: false,\n                hasNextPage: true,\n              },\n              totalCount: 1292,\n            },\n          },\n          dataState: \"complete\",\n          partial: false,\n        });\n\n        expect(cache.extract()).toMatchSnapshot();\n      }\n\n      // Now search for a different artist to verify that they keyArgs\n      // function we passed to relayStylePagination above keeps\n      // different search queries separate in the cache.\n      {\n        const result = await client.query({\n          query,\n          variables: {\n            query: \"James Turrell\",\n            first: 1,\n          },\n        });\n        const snapshot = cache.extract();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            search: {\n              edges: turrellEdges.slice(0, 1),\n              pageInfo: turrellPageInfo1,\n              totalCount: 13531,\n            },\n          },\n        });\n\n        expect(snapshot).toMatchSnapshot();\n        expect(\n          // Note that Turrell's name has been lower-cased.\n          snapshot.ROOT_QUERY![\"search:james turrell\"]\n        ).toEqual({\n          edges: turrellEdges.slice(0, 1).map((edge) => ({\n            ...edge,\n            // The relayStylePagination merge function updates the\n            // edge.cursor field of the first and last edge, even if\n            // the query did not request the edge.cursor field, if\n            // pageInfo.{start,end}Cursor are defined.\n            cursor: turrellPageInfo1.startCursor,\n            // Artist objects are normalized by HREF:\n            node: { __ref: 'Artist:{\"href\":\"/artist/james-turrell\"}' },\n          })),\n          pageInfo: turrellPageInfo1,\n          totalCount: 13531,\n        });\n      }\n\n      // Evict the Basquiat entity to verify that the dangling\n      // edge.node Reference gets automatically elided from the\n      // Basquiat search results, thanks to the read function\n      // generated by the relayStylePagination helper.\n      expect(\n        cache.evict({\n          id: cache.identify({\n            __typename: \"Artist\",\n            href: \"/artist/jean-michel-basquiat\",\n          }),\n        })\n      ).toBe(true);\n\n      {\n        const result = await stream.takeNext();\n\n        // Same full list of edges that we saw in the previous case.\n        const edges = [...firstEdges, ...secondEdges, ...fifthEdges];\n\n        // Remove the Basquiat edge, which we know to be first.\n        expect(edges.shift()).toEqual({\n          __typename: \"SearchableEdge\",\n          node: {\n            __typename: \"Artist\",\n            href: \"/artist/jean-michel-basquiat\",\n            displayLabel: \"Jean-Michel Basquiat\",\n            bio: \"American, 1960-1988, New York, New York, based in New York, New York\",\n          },\n        });\n\n        expect(result).toStrictEqualTyped({\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          data: {\n            search: {\n              edges,\n              pageInfo: {\n                __typename: \"PageInfo\",\n                startCursor: fourthPageInfo.startCursor,\n                endCursor: fifthPageInfo.endCursor,\n                hasPreviousPage: false,\n                hasNextPage: true,\n              },\n              totalCount: 1292,\n            },\n          },\n          dataState: \"complete\",\n          partial: false,\n        });\n\n        expect(cache.extract()).toMatchSnapshot();\n      }\n\n      {\n        // Now search for James Turrell again with args.first === 2\n        // (turrellVariables2), but without args.after, so that the\n        // new results overwrite the existing results (#6592).\n        const result = await client.query({\n          query,\n          variables: turrellVariables2,\n          // Necessary to skip the cache, like fetchMore does.\n          fetchPolicy: \"network-only\",\n        });\n        const snapshot = cache.extract();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            search: {\n              edges: turrellEdges,\n              pageInfo: turrellPageInfo2,\n              totalCount: 13531,\n            },\n          },\n        });\n\n        expect(snapshot).toMatchSnapshot();\n        expect(\n          // Note that Turrell's name has been lower-cased.\n          snapshot.ROOT_QUERY![\"search:james turrell\"]\n        ).toEqual({\n          edges: turrellEdges.map((edge, i) => ({\n            ...edge,\n            // This time the cursors are different depending on which\n            // of the two edges we're considering.\n            cursor: [turrellPageInfo2.startCursor, turrellPageInfo2.endCursor][\n              i\n            ],\n            node: [\n              // Artist objects are normalized by HREF:\n              { __ref: 'Artist:{\"href\":\"/artist/james-turrell\"}' },\n              // However, SearchableItem objects are not normalized.\n              edge.node,\n            ][i],\n          })),\n          pageInfo: turrellPageInfo2,\n          totalCount: 13531,\n        });\n      }\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"runs nested merge functions as well as ancestors\", function () {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      let eventMergeCount = 0;\n      let attendeeMergeCount = 0;\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Event: {\n            fields: {\n              attendees: {\n                merge(existing: any[], incoming: any[]) {\n                  ++eventMergeCount;\n                  expect(Array.isArray(incoming)).toBe(true);\n                  return existing ? existing.concat(incoming) : incoming;\n                },\n              },\n            },\n          },\n\n          Attendee: {\n            fields: {\n              events: {\n                merge(existing: any[], incoming: any[]) {\n                  ++attendeeMergeCount;\n                  expect(Array.isArray(incoming)).toBe(true);\n                  return existing ? existing.concat(incoming) : incoming;\n                },\n              },\n            },\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            eventsToday {\n              name\n              attendees {\n                name\n                events {\n                  time\n                }\n              }\n            }\n          }\n        `,\n        data: {\n          eventsToday: [\n            {\n              __typename: \"Event\",\n              id: 123,\n              name: \"One-person party\",\n              time: \"noonish\",\n              attendees: [\n                {\n                  __typename: \"Attendee\",\n                  id: 234,\n                  name: \"Ben Newman\",\n                  events: [{ __typename: \"Event\", id: 123 }],\n                },\n              ],\n            },\n          ],\n        },\n      });\n\n      expect(eventMergeCount).toBe(1);\n      expect(attendeeMergeCount).toBe(1);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          eventsToday: [{ __ref: \"Event:123\" }],\n        },\n        \"Event:123\": {\n          __typename: \"Event\",\n          id: 123,\n          name: \"One-person party\",\n          attendees: [{ __ref: \"Attendee:234\" }],\n        },\n        \"Attendee:234\": {\n          __typename: \"Attendee\",\n          id: 234,\n          name: \"Ben Newman\",\n          events: [{ __ref: \"Event:123\" }],\n        },\n      });\n\n      cache.writeQuery({\n        query: gql`\n          query {\n            people {\n              name\n              events {\n                time\n                attendees {\n                  name\n                }\n              }\n            }\n          }\n        `,\n        data: {\n          people: [\n            {\n              __typename: \"Attendee\",\n              id: 234,\n              name: \"Ben Newman\",\n              events: [\n                {\n                  __typename: \"Event\",\n                  id: 345,\n                  name: \"Rooftop dog party\",\n                  attendees: [\n                    {\n                      __typename: \"Attendee\",\n                      id: 456,\n                      name: \"Inspector Beckett\",\n                    },\n                    {\n                      __typename: \"Attendee\",\n                      id: 234,\n                    },\n                  ],\n                },\n              ],\n            },\n          ],\n        },\n      });\n\n      expect(eventMergeCount).toBe(2);\n      expect(attendeeMergeCount).toBe(2);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          eventsToday: [{ __ref: \"Event:123\" }],\n          people: [{ __ref: \"Attendee:234\" }],\n        },\n        \"Event:123\": {\n          __typename: \"Event\",\n          id: 123,\n          name: \"One-person party\",\n          attendees: [{ __ref: \"Attendee:234\" }],\n        },\n        \"Event:345\": {\n          __typename: \"Event\",\n          id: 345,\n          attendees: [{ __ref: \"Attendee:456\" }, { __ref: \"Attendee:234\" }],\n        },\n        \"Attendee:234\": {\n          __typename: \"Attendee\",\n          id: 234,\n          name: \"Ben Newman\",\n          events: [{ __ref: \"Event:123\" }, { __ref: \"Event:345\" }],\n        },\n        \"Attendee:456\": {\n          __typename: \"Attendee\",\n          id: 456,\n          name: \"Inspector Beckett\",\n        },\n      });\n\n      expect(cache.gc()).toEqual([]);\n    });\n\n    it(\"should report dangling references returned by read functions\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              book: {\n                keyArgs: [\"isbn\"],\n                read(existing, { args, toReference }) {\n                  return (\n                    existing ||\n                    toReference({\n                      __typename: \"Book\",\n                      isbn: args!.isbn,\n                    })\n                  );\n                },\n              },\n            },\n          },\n\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n        },\n      });\n\n      const query = gql`\n        query {\n          book(isbn: $isbn) {\n            title\n            author\n          }\n        }\n      `;\n\n      function read(isbn = \"156858217X\") {\n        return cache.readQuery({\n          query,\n          variables: { isbn },\n        });\n      }\n\n      function diff(isbn = \"156858217X\") {\n        return cache.diff({\n          query,\n          variables: { isbn },\n          returnPartialData: false,\n          optimistic: true,\n        });\n      }\n\n      expect(read()).toBe(null);\n\n      cache.writeQuery({\n        query,\n        variables: { isbn: \"0393354326\" },\n        data: {\n          book: {\n            __typename: \"Book\",\n            isbn: \"0393354326\",\n            title: \"Guns, Germs, and Steel\",\n            author: \"Jared Diamond\",\n          },\n        },\n      });\n\n      expect(read()).toBe(null);\n\n      expect(diff()).toEqual({\n        complete: false,\n        result: null,\n        missing: new MissingFieldError(\n          'Dangling reference to missing Book:{\"isbn\":\"156858217X\"} object',\n          {\n            book: 'Dangling reference to missing Book:{\"isbn\":\"156858217X\"} object',\n          },\n          query,\n          { isbn: \"156858217X\" }\n        ),\n      });\n\n      const stealThisData = {\n        __typename: \"Book\",\n        isbn: \"156858217X\",\n        title: \"Steal This Book\",\n        author: \"Abbie Hoffman\",\n      };\n\n      const stealThisID = cache.identify(stealThisData)!;\n\n      cache.writeFragment({\n        id: stealThisID,\n        fragment: gql`\n          fragment BookTitleAuthor on Book {\n            title\n            author\n          }\n        `,\n        data: stealThisData,\n      });\n\n      expect(read()).toEqual({\n        book: {\n          __typename: \"Book\",\n          title: \"Steal This Book\",\n          author: \"Abbie Hoffman\",\n        },\n      });\n\n      expect(read(\"0393354326\")).toEqual({\n        book: {\n          __typename: \"Book\",\n          title: \"Guns, Germs, and Steel\",\n          author: \"Jared Diamond\",\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        __META: {\n          extraRootIds: ['Book:{\"isbn\":\"156858217X\"}'],\n        },\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'book:{\"isbn\":\"0393354326\"}': {\n            __ref: 'Book:{\"isbn\":\"0393354326\"}',\n          },\n        },\n        'Book:{\"isbn\":\"0393354326\"}': {\n          __typename: \"Book\",\n          isbn: \"0393354326\",\n          author: \"Jared Diamond\",\n          title: \"Guns, Germs, and Steel\",\n        },\n        'Book:{\"isbn\":\"156858217X\"}': {\n          __typename: \"Book\",\n          isbn: \"156858217X\",\n          author: \"Abbie Hoffman\",\n          title: \"Steal This Book\",\n        },\n      });\n\n      // Nothing removed because stealThisID was retained by writeFragment.\n      expect(cache.gc()).toEqual([]);\n      expect(cache.release(stealThisID)).toBe(0);\n      expect(cache.gc()).toEqual([stealThisID]);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'book:{\"isbn\":\"0393354326\"}': {\n            __ref: 'Book:{\"isbn\":\"0393354326\"}',\n          },\n        },\n        'Book:{\"isbn\":\"0393354326\"}': {\n          __typename: \"Book\",\n          isbn: \"0393354326\",\n          author: \"Jared Diamond\",\n          title: \"Guns, Germs, and Steel\",\n        },\n      });\n\n      cache.writeQuery({\n        query,\n        variables: { isbn: \"156858217X\" },\n        data: {\n          book: stealThisData,\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          'book:{\"isbn\":\"0393354326\"}': {\n            __ref: 'Book:{\"isbn\":\"0393354326\"}',\n          },\n          'book:{\"isbn\":\"156858217X\"}': {\n            __ref: 'Book:{\"isbn\":\"156858217X\"}',\n          },\n        },\n        'Book:{\"isbn\":\"0393354326\"}': {\n          __typename: \"Book\",\n          isbn: \"0393354326\",\n          author: \"Jared Diamond\",\n          title: \"Guns, Germs, and Steel\",\n        },\n        'Book:{\"isbn\":\"156858217X\"}': {\n          __typename: \"Book\",\n          isbn: \"156858217X\",\n          author: \"Abbie Hoffman\",\n          title: \"Steal This Book\",\n        },\n      });\n\n      expect(cache.gc()).toEqual([]);\n\n      expect(\n        cache.evict({\n          fieldName: \"book\",\n        })\n      ).toBe(true);\n\n      expect(cache.gc().sort()).toEqual([\n        'Book:{\"isbn\":\"0393354326\"}',\n        'Book:{\"isbn\":\"156858217X\"}',\n      ]);\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n        },\n      });\n\n      expect(read(\"0393354326\")).toBe(null);\n      expect(diff(\"0393354326\")).toEqual({\n        complete: false,\n        result: null,\n        missing: new MissingFieldError(\n          'Dangling reference to missing Book:{\"isbn\":\"0393354326\"} object',\n          {\n            book: 'Dangling reference to missing Book:{\"isbn\":\"0393354326\"} object',\n          },\n          query,\n          { isbn: \"0393354326\" }\n        ),\n      });\n\n      expect(read(\"156858217X\")).toBe(null);\n      expect(diff(\"156858217X\")).toEqual({\n        complete: false,\n        result: null,\n        missing: new MissingFieldError(\n          'Dangling reference to missing Book:{\"isbn\":\"156858217X\"} object',\n          {\n            book: 'Dangling reference to missing Book:{\"isbn\":\"156858217X\"} object',\n          },\n          query,\n          { isbn: \"156858217X\" }\n        ),\n      });\n    });\n\n    it(\"can force merging of unidentified non-normalized data\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n            fields: {\n              author: {\n                merge(\n                  existing: StoreObject,\n                  incoming: StoreObject,\n                  { mergeObjects }\n                ) {\n                  expect(mergeObjects(void 0 as any, null)).toBe(null);\n\n                  expect(() => {\n                    // The type system does a pretty good job of defending\n                    // against this mistake.\n                    mergeObjects(\n                      [1, 2, 3] as any as StoreObject,\n                      [4] as any as StoreObject\n                    );\n                  }).toThrow(/Cannot automatically merge arrays/);\n\n                  const a = { __typename: \"A\", a: \"ay\" };\n                  const b = { __typename: \"B\", a: \"bee\" };\n                  expect(mergeObjects(a, b)).toBe(b);\n                  expect(mergeObjects(b, a)).toBe(a);\n\n                  return mergeObjects(existing, incoming);\n                },\n              },\n            },\n          },\n\n          Author: {\n            keyFields: false,\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n        },\n      });\n\n      testForceMerges(cache);\n    });\n\n    function booksMergePolicy(): FieldPolicy<any[]> {\n      return {\n        merge(existing, incoming, { isReference }) {\n          const merged = existing ? existing.slice(0) : [];\n          const seen = new Set<string>();\n          if (existing) {\n            existing.forEach((book) => {\n              if (isReference(book)) {\n                seen.add(book.__ref);\n              }\n            });\n          }\n          incoming.forEach((book) => {\n            if (isReference(book)) {\n              if (!seen.has(book.__ref)) {\n                merged.push(book);\n                seen.add(book.__ref);\n              }\n            } else {\n              merged.push(book);\n            }\n          });\n          return merged;\n        },\n      };\n    }\n\n    function testForceMerges(cache: InMemoryCache) {\n      const queryWithAuthorName = gql`\n        query {\n          currentlyReading {\n            isbn\n            title\n            author {\n              name\n            }\n          }\n        }\n      `;\n\n      const queryWithAuthorBooks = gql`\n        query {\n          currentlyReading {\n            isbn\n            author {\n              books {\n                isbn\n                title\n              }\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query: queryWithAuthorName,\n        data: {\n          currentlyReading: {\n            __typename: \"Book\",\n            isbn: \"1250758009\",\n            title: \"The Topeka School\",\n            author: {\n              __typename: \"Author\",\n              name: \"Ben Lerner\",\n            },\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          currentlyReading: {\n            __ref: 'Book:{\"isbn\":\"1250758009\"}',\n          },\n        },\n        'Book:{\"isbn\":\"1250758009\"}': {\n          __typename: \"Book\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ben Lerner\",\n          },\n          isbn: \"1250758009\",\n          title: \"The Topeka School\",\n        },\n      });\n\n      cache.writeQuery({\n        query: queryWithAuthorBooks,\n        data: {\n          currentlyReading: {\n            __typename: \"Book\",\n            isbn: \"1250758009\",\n            author: {\n              __typename: \"Author\",\n              books: [\n                {\n                  __typename: \"Book\",\n                  isbn: \"1250758009\",\n                  title: \"The Topeka School\",\n                },\n              ],\n            },\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          currentlyReading: {\n            __ref: 'Book:{\"isbn\":\"1250758009\"}',\n          },\n        },\n        'Book:{\"isbn\":\"1250758009\"}': {\n          __typename: \"Book\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ben Lerner\",\n            books: [{ __ref: 'Book:{\"isbn\":\"1250758009\"}' }],\n          },\n          isbn: \"1250758009\",\n          title: \"The Topeka School\",\n        },\n      });\n\n      cache.writeQuery({\n        query: queryWithAuthorBooks,\n        data: {\n          currentlyReading: {\n            __typename: \"Book\",\n            isbn: \"1250758009\",\n            author: {\n              __typename: \"Author\",\n              books: [\n                {\n                  __typename: \"Book\",\n                  isbn: \"1566892740\",\n                  title: \"Leaving the Atocha Station\",\n                },\n              ],\n            },\n          },\n        },\n      });\n\n      expect(cache.extract()).toEqual({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          currentlyReading: {\n            __ref: 'Book:{\"isbn\":\"1250758009\"}',\n          },\n        },\n        'Book:{\"isbn\":\"1250758009\"}': {\n          __typename: \"Book\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ben Lerner\",\n            books: [\n              { __ref: 'Book:{\"isbn\":\"1250758009\"}' },\n              { __ref: 'Book:{\"isbn\":\"1566892740\"}' },\n            ],\n          },\n          isbn: \"1250758009\",\n          title: \"The Topeka School\",\n        },\n        'Book:{\"isbn\":\"1566892740\"}': {\n          __typename: \"Book\",\n          isbn: \"1566892740\",\n          title: \"Leaving the Atocha Station\",\n        },\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithAuthorBooks,\n        })\n      ).toEqual({\n        currentlyReading: {\n          __typename: \"Book\",\n          isbn: \"1250758009\",\n          author: {\n            __typename: \"Author\",\n            books: [\n              {\n                __typename: \"Book\",\n                isbn: \"1250758009\",\n                title: \"The Topeka School\",\n              },\n              {\n                __typename: \"Book\",\n                isbn: \"1566892740\",\n                title: \"Leaving the Atocha Station\",\n              },\n            ],\n          },\n        },\n      });\n\n      expect(\n        cache.readQuery({\n          query: queryWithAuthorName,\n        })\n      ).toEqual({\n        currentlyReading: {\n          __typename: \"Book\",\n          isbn: \"1250758009\",\n          title: \"The Topeka School\",\n          author: {\n            __typename: \"Author\",\n            name: \"Ben Lerner\",\n          },\n        },\n      });\n    }\n\n    // Same as previous test, except with merge:true for Book.author.\n    it(\"can force merging with merge:true field policy\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n            fields: {\n              author: {\n                merge: true,\n              },\n            },\n          },\n\n          Author: {\n            keyFields: false,\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n        },\n      });\n\n      testForceMerges(cache);\n    });\n\n    // Same as previous test, except configuring merge:true for the Author\n    // type instead of for the Book.author field.\n    it(\"can force merging with merge:true type policy\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n\n          Author: {\n            keyFields: false,\n            merge: true,\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n        },\n      });\n\n      testForceMerges(cache);\n    });\n\n    it(\"can force merging with inherited merge:true field policy\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Authored: {\n            fields: {\n              author: {\n                merge: true,\n              },\n            },\n          },\n\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n\n          Author: {\n            keyFields: false,\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n        },\n\n        possibleTypes: {\n          Authored: [\"Book\", \"Destruction\"],\n        },\n      });\n\n      testForceMerges(cache);\n    });\n\n    it(\"can force merging with inherited merge:true type policy\", function () {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n\n          Author: {\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n\n          Person: {\n            keyFields: false,\n            merge: true,\n          },\n        },\n\n        possibleTypes: {\n          Person: [\"Author\"],\n        },\n      });\n\n      testForceMerges(cache);\n    });\n\n    function checkAuthor<TData>(data: TData, canBeUndefined = false) {\n      if (data || !canBeUndefined) {\n        expect(data).toBeTruthy();\n        expect(typeof data).toBe(\"object\");\n        expect((data as any).__typename).toBe(\"Author\");\n      }\n      return data;\n    }\n\n    it(\"can force merging with inherited type policy merge function\", function () {\n      let personMergeCount = 0;\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n\n          Author: {\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n\n          Person: {\n            keyFields: false,\n\n            merge(existing, incoming) {\n              checkAuthor(existing, true);\n              checkAuthor(incoming);\n              ++personMergeCount;\n              return { ...existing, ...incoming };\n            },\n          },\n        },\n\n        possibleTypes: {\n          Person: [\"Author\"],\n        },\n      });\n\n      testForceMerges(cache);\n\n      expect(personMergeCount).toBe(3);\n    });\n\n    it(\"can force merging references with non-normalized objects\", async function () {\n      const nameQuery = gql`\n        query GetName {\n          viewer {\n            name\n          }\n        }\n      `;\n\n      const emailQuery = gql`\n        query GetEmail {\n          viewer {\n            id\n            email\n          }\n        }\n      `;\n\n      await check(\n        new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                viewer: {\n                  merge: true,\n                },\n              },\n            },\n          },\n        })\n      );\n\n      await check(\n        new InMemoryCache({\n          typePolicies: {\n            User: {\n              merge: true,\n            },\n          },\n        })\n      );\n\n      async function check(cache: InMemoryCache) {\n        // Write nameQuery first, so the existing data will be a\n        // non-normalized object when we write emailQuery next.\n        cache.writeQuery({\n          query: nameQuery,\n          data: {\n            viewer: {\n              __typename: \"User\",\n              name: \"Alice\",\n            },\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            viewer: {\n              __typename: \"User\",\n              name: \"Alice\",\n            },\n          },\n        });\n\n        cache.writeQuery({\n          query: emailQuery,\n          data: {\n            viewer: {\n              __typename: \"User\",\n              id: 12345,\n              email: \"alice@example.com\",\n            },\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            viewer: {\n              __ref: \"User:12345\",\n            },\n          },\n          \"User:12345\": {\n            __typename: \"User\",\n            name: \"Alice\",\n            id: 12345,\n            email: \"alice@example.com\",\n          },\n        });\n\n        expect(\n          cache.readQuery({\n            query: nameQuery,\n          })\n        ).toEqual({\n          viewer: {\n            __typename: \"User\",\n            name: \"Alice\",\n          },\n        });\n\n        expect(\n          cache.readQuery({\n            query: emailQuery,\n          })\n        ).toEqual({\n          viewer: {\n            __typename: \"User\",\n            id: 12345,\n            email: \"alice@example.com\",\n          },\n        });\n\n        await cache.reset();\n        expect(cache.extract()).toEqual({});\n\n        // Write emailQuery first, so the existing data will be a\n        // normalized reference when we write nameQuery next.\n        cache.writeQuery({\n          query: emailQuery,\n          data: {\n            viewer: {\n              __typename: \"User\",\n              id: 12345,\n              email: \"alice@example.com\",\n            },\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          \"User:12345\": {\n            id: 12345,\n            __typename: \"User\",\n            email: \"alice@example.com\",\n          },\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            viewer: {\n              __ref: \"User:12345\",\n            },\n          },\n        });\n\n        cache.writeQuery({\n          query: nameQuery,\n          data: {\n            viewer: {\n              __typename: \"User\",\n              name: \"Alice\",\n            },\n          },\n        });\n\n        expect(cache.extract()).toEqual({\n          \"User:12345\": {\n            id: 12345,\n            __typename: \"User\",\n            email: \"alice@example.com\",\n            name: \"Alice\",\n          },\n          ROOT_QUERY: {\n            __typename: \"Query\",\n            viewer: {\n              __ref: \"User:12345\",\n            },\n          },\n        });\n\n        expect(\n          cache.readQuery({\n            query: nameQuery,\n          })\n        ).toEqual({\n          viewer: {\n            __typename: \"User\",\n            name: \"Alice\",\n          },\n        });\n\n        expect(\n          cache.readQuery({\n            query: emailQuery,\n          })\n        ).toEqual({\n          viewer: {\n            __typename: \"User\",\n            id: 12345,\n            email: \"alice@example.com\",\n          },\n        });\n      }\n    });\n\n    it(\"can force merging with inherited field merge function\", function () {\n      let authorMergeCount = 0;\n\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Book: {\n            keyFields: [\"isbn\"],\n          },\n\n          Authored: {\n            fields: {\n              author: {\n                merge(existing, incoming) {\n                  checkAuthor(existing, true);\n                  checkAuthor(incoming);\n                  ++authorMergeCount;\n                  return { ...existing, ...incoming };\n                },\n              },\n            },\n          },\n\n          Author: {\n            fields: {\n              books: booksMergePolicy(),\n            },\n          },\n\n          Person: {\n            keyFields: false,\n          },\n        },\n\n        possibleTypes: {\n          Authored: [\"Destiny\", \"Book\"],\n          Person: [\"Author\"],\n        },\n      });\n\n      testForceMerges(cache);\n\n      expect(authorMergeCount).toBe(3);\n    });\n  });\n\n  it(\"runs read and merge functions for unidentified data\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n\n        Author: {\n          // Passing false for keyFields disables normalization of Author\n          // objects, which should not interfere with the operation of\n          // their read and/or merge functions. However, disabling\n          // normalization means the merge function for the name field\n          // will be called only once, because we never merge fields when\n          // the IDs of the enclosing objects are unknown or unequal.\n          keyFields: false,\n\n          fields: {\n            name: {\n              read(name: string) {\n                return reverse(name).toUpperCase();\n              },\n              merge(oldName, newName: string) {\n                expect(oldName).toBe(void 0);\n                expect(typeof newName).toBe(\"string\");\n                return reverse(newName);\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        currentlyReading {\n          title\n          authors {\n            name\n          }\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        currentlyReading: [\n          {\n            __typename: \"Book\",\n            isbn: \"0525558616\",\n            title:\n              \"Human Compatible: Artificial Intelligence and the Problem of Control\",\n            authors: [\n              {\n                __typename: \"Author\",\n                name: \"Stuart Russell\",\n              },\n            ],\n          },\n          {\n            __typename: \"Book\",\n            isbn: \"1541698967\",\n            title: \"The Book of Why: The New Science of Cause and Effect\",\n            authors: [\n              {\n                __typename: \"Author\",\n                name: \"Judea Pearl\",\n              },\n              {\n                __typename: \"Author\",\n                name: \"Dana Mackenzie\",\n              },\n            ],\n          },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        currentlyReading: [\n          { __ref: 'Book:{\"isbn\":\"0525558616\"}' },\n          { __ref: 'Book:{\"isbn\":\"1541698967\"}' },\n        ],\n      },\n      'Book:{\"isbn\":\"0525558616\"}': {\n        __typename: \"Book\",\n        isbn: \"0525558616\",\n        authors: [\n          {\n            __typename: \"Author\",\n            // Note the successful reversal of the Author names.\n            name: \"llessuR trautS\",\n          },\n        ],\n        title:\n          \"Human Compatible: Artificial Intelligence and the Problem of Control\",\n      },\n      'Book:{\"isbn\":\"1541698967\"}': {\n        __typename: \"Book\",\n        isbn: \"1541698967\",\n        authors: [\n          {\n            __typename: \"Author\",\n            name: \"lraeP aeduJ\",\n          },\n          {\n            __typename: \"Author\",\n            name: \"eiznekcaM anaD\",\n          },\n        ],\n        title: \"The Book of Why: The New Science of Cause and Effect\",\n      },\n    });\n\n    expect(cache.readQuery({ query })).toEqual({\n      currentlyReading: [\n        {\n          __typename: \"Book\",\n          title:\n            \"Human Compatible: Artificial Intelligence and the Problem of Control\",\n          authors: [\n            {\n              __typename: \"Author\",\n              name: \"STUART RUSSELL\",\n            },\n          ],\n        },\n        {\n          __typename: \"Book\",\n          title: \"The Book of Why: The New Science of Cause and Effect\",\n          authors: [\n            {\n              __typename: \"Author\",\n              // Note the successful re-reversal and uppercasing, thanks to\n              // the custom read function.\n              name: \"JUDEA PEARL\",\n            },\n            {\n              __typename: \"Author\",\n              name: \"DANA MACKENZIE\",\n            },\n          ],\n        },\n      ],\n    });\n  });\n\n  it(`allows keyFields and keyArgs functions to return false`, function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Person: {\n          keyFields() {\n            return false;\n          },\n          fields: {\n            height: {\n              keyArgs() {\n                return false;\n              },\n              merge(_, height, { args }) {\n                if (args) {\n                  if (args.units === \"feet\") {\n                    return height;\n                  }\n                  if (args.units === \"meters\") {\n                    // Convert to feet so we don't have to remember the units.\n                    return height * 3.28084;\n                  }\n                }\n                throw new Error(\"unexpected units: \" + args);\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const query = gql`\n      query GetUser($units: string) {\n        people {\n          id\n          height(units: $units)\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      variables: {\n        units: \"meters\",\n      },\n      data: {\n        people: [\n          {\n            __typename: \"Person\",\n            id: 12345,\n            height: 1.75,\n          },\n          {\n            __typename: \"Person\",\n            id: 23456,\n            height: 2,\n          },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        // An array of non-normalized objects, not Reference objects.\n        people: [\n          {\n            __typename: \"Person\",\n            // No serialized units argument, just \"height\".\n            height: 5.74147,\n            id: 12345,\n          },\n          {\n            __typename: \"Person\",\n            height: 6.56168,\n            id: 23456,\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"can read from foreign references using read helper\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Author: {\n          keyFields: [\"name\"],\n\n          fields: {\n            books: {\n              merge(existing: Reference[] = [], incoming: Reference[]) {\n                return [...existing, ...incoming];\n              },\n            },\n\n            // A dynamically computed field that returns the Book\n            // Reference with the earliest year, which requires reading\n            // fields from foreign references.\n            firstBook(_, { isReference, readField }) {\n              let firstBook: Reference | null = null;\n              let firstYear: number;\n              const bookRefs = readField<Reference[]>(\"books\") || [];\n              bookRefs.forEach((bookRef) => {\n                expect(isReference(bookRef)).toBe(true);\n                const year = readField<number>(\"year\", bookRef);\n                if (firstYear === void 0 || year! < firstYear) {\n                  firstBook = bookRef;\n                  firstYear = year!;\n                }\n              });\n              // Return a Book Reference, which can have a nested\n              // selection set applied to it.\n              return firstBook;\n            },\n          },\n        },\n\n        Book: {\n          keyFields: [\"isbn\"],\n        },\n      },\n    });\n\n    interface BookData {\n      __typename: \"Book\";\n      isbn: string;\n      title: string;\n      year: number;\n    }\n\n    function addBook(bookData: BookData) {\n      cache.writeQuery({\n        query: gql`\n          query {\n            author {\n              name\n              books {\n                isbn\n                title\n                year\n              }\n            }\n          }\n        `,\n        data: {\n          author: {\n            __typename: \"Author\",\n            name: \"Virginia Woolf\",\n            books: [bookData],\n          },\n        },\n      });\n    }\n\n    addBook({\n      __typename: \"Book\",\n      isbn: \"1853262390\",\n      title: \"Orlando\",\n      year: 1928,\n    });\n\n    addBook({\n      __typename: \"Book\",\n      isbn: \"9353420717\",\n      title: \"A Room of One's Own\",\n      year: 1929,\n    });\n\n    addBook({\n      __typename: \"Book\",\n      isbn: \"0156907399\",\n      title: \"To the Lighthouse\",\n      year: 1927,\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: {\n          __ref: 'Author:{\"name\":\"Virginia Woolf\"}',\n        },\n      },\n      'Author:{\"name\":\"Virginia Woolf\"}': {\n        __typename: \"Author\",\n        name: \"Virginia Woolf\",\n        books: [\n          { __ref: 'Book:{\"isbn\":\"1853262390\"}' },\n          { __ref: 'Book:{\"isbn\":\"9353420717\"}' },\n          { __ref: 'Book:{\"isbn\":\"0156907399\"}' },\n        ],\n      },\n      'Book:{\"isbn\":\"1853262390\"}': {\n        __typename: \"Book\",\n        isbn: \"1853262390\",\n        title: \"Orlando\",\n        year: 1928,\n      },\n      'Book:{\"isbn\":\"9353420717\"}': {\n        __typename: \"Book\",\n        isbn: \"9353420717\",\n        title: \"A Room of One's Own\",\n        year: 1929,\n      },\n      'Book:{\"isbn\":\"0156907399\"}': {\n        __typename: \"Book\",\n        isbn: \"0156907399\",\n        title: \"To the Lighthouse\",\n        year: 1927,\n      },\n    });\n\n    const firstBookQuery = gql`\n      query {\n        author {\n          name\n          firstBook {\n            title\n            year\n          }\n        }\n      }\n    `;\n\n    function readFirstBookResult() {\n      return cache.readQuery<{ author: any }>({\n        query: firstBookQuery,\n      })!;\n    }\n\n    const firstBookResult = readFirstBookResult();\n    expect(firstBookResult).toEqual({\n      author: {\n        __typename: \"Author\",\n        name: \"Virginia Woolf\",\n        firstBook: {\n          __typename: \"Book\",\n          title: \"To the Lighthouse\",\n          year: 1927,\n        },\n      },\n    });\n\n    expect(readFirstBookResult()).toBe(firstBookResult);\n\n    // Add an even earlier book.\n    addBook({\n      __typename: \"Book\",\n      isbn: \"1420959719\",\n      title: \"The Voyage Out\",\n      year: 1915,\n    });\n\n    const secondFirstBookResult = readFirstBookResult();\n    expect(secondFirstBookResult).not.toBe(firstBookResult);\n    expect(secondFirstBookResult).toEqual({\n      author: {\n        __typename: \"Author\",\n        name: \"Virginia Woolf\",\n        firstBook: {\n          __typename: \"Book\",\n          title: \"The Voyage Out\",\n          year: 1915,\n        },\n      },\n    });\n\n    // Write a new, unrelated field.\n    cache.writeQuery({\n      query: gql`\n        query {\n          author {\n            afraidCount\n          }\n        }\n      `,\n      data: {\n        author: {\n          __typename: \"Author\",\n          name: \"Virginia Woolf\",\n          afraidCount: 2,\n        },\n      },\n    });\n\n    // Make sure afraidCount was written.\n    expect(\n      cache.readFragment({\n        id: cache.identify({\n          __typename: \"Author\",\n          name: \"Virginia Woolf\",\n        })!,\n        fragment: gql`\n          fragment AfraidFragment on Author {\n            name\n            afraidCount\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"Author\",\n      name: \"Virginia Woolf\",\n      afraidCount: 2,\n    });\n\n    // Since we wrote only the afraidCount field, the firstBook result\n    // should be completely unchanged.\n    expect(readFirstBookResult()).toBe(secondFirstBookResult);\n\n    // Add another book, not published first.\n    addBook({\n      __typename: \"Book\",\n      isbn: \"9780156949606\",\n      title: \"The Waves\",\n      year: 1931,\n    });\n\n    const thirdFirstBookResult = readFirstBookResult();\n    expect(thirdFirstBookResult).toEqual(secondFirstBookResult);\n  });\n\n  it(\"readField can read fields with arguments\", function () {\n    const enum Style {\n      UPPER,\n      LOWER,\n      TITLE,\n    }\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Word: {\n          keyFields: [\"text\"],\n\n          fields: {\n            style(_, { args, readField }) {\n              const text = readField<string>(\"text\");\n              switch (args?.style) {\n                case Style.UPPER:\n                  return text?.toUpperCase();\n                case Style.LOWER:\n                  return text?.toLowerCase();\n                case Style.TITLE:\n                  return (\n                    text &&\n                    text.charAt(0).toUpperCase() + text.slice(1).toLowerCase()\n                  );\n              }\n            },\n            upperCase(_, { readField }) {\n              return readField<string>({\n                fieldName: \"style\",\n                args: { style: Style.UPPER },\n              });\n            },\n            lowerCase(_, { readField }) {\n              return readField<string>({\n                fieldName: \"style\",\n                args: { style: Style.LOWER },\n              });\n            },\n            titleCase(_, { readField }) {\n              return readField<string>({\n                fieldName: \"style\",\n                args: { style: Style.TITLE },\n              });\n            },\n          },\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          wordOfTheDay {\n            text\n          }\n        }\n      `,\n      data: {\n        wordOfTheDay: {\n          __typename: \"Word\",\n          text: \"inveigle\",\n        },\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            wordOfTheDay {\n              upperCase\n              lowerCase\n              titleCase\n            }\n          }\n        `,\n      })\n    ).toEqual({\n      wordOfTheDay: {\n        __typename: \"Word\",\n        upperCase: \"INVEIGLE\",\n        lowerCase: \"inveigle\",\n        titleCase: \"Inveigle\",\n      },\n    });\n  });\n\n  it(\"readField warns if explicitly passed undefined `from` option\", function () {\n    using _consoleSpies = spyOnConsole.takeSnapshots(\"warn\");\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            fullNameWithDefaults(_, { readField }) {\n              return `${readField<string>({\n                fieldName: \"firstName\",\n              })} ${readField<string>(\"lastName\")}`;\n            },\n\n            fullNameWithVoids(_, { readField }) {\n              return `${readField<string>({\n                fieldName: \"firstName\",\n                // If options.from is explicitly passed but undefined,\n                // readField should not default to reading from the current\n                // object (see issue #8499).\n                from: void 0,\n              })} ${\n                // Likewise for the shorthand version of readField.\n                readField<string>(\"lastName\", void 0)\n              }`;\n            },\n          },\n        },\n      },\n    });\n\n    const firstNameLastNameQuery = gql`\n      query {\n        firstName\n        lastName\n      }\n    `;\n\n    const fullNamesQuery = gql`\n      query {\n        fullNameWithVoids\n        fullNameWithDefaults\n      }\n    `;\n\n    cache.writeQuery({\n      query: firstNameLastNameQuery,\n      data: {\n        firstName: \"Alan\",\n        lastName: \"Turing\",\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: fullNamesQuery,\n      })\n    ).toEqual({\n      fullNameWithDefaults: \"Alan Turing\",\n      fullNameWithVoids: \"undefined undefined\",\n    });\n  });\n\n  it(\"can return existing object from merge function (issue #6245)\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Person: {\n          fields: {\n            currentTask: {\n              merge(existing, incoming) {\n                // Not a very reasonable merge strategy, but returning\n                // existing here triggers issue #6245, presumably because\n                // the existing data is frozen.\n                return existing || incoming;\n              },\n            },\n          },\n        },\n        Task: {\n          keyFields: false,\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        person {\n          currentTask {\n            __typename\n            description\n          }\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        person: {\n          __typename: \"Person\",\n          id: 1234,\n          currentTask: {\n            __typename: \"Task\",\n            description: \"writing tests\",\n          },\n        },\n      },\n    });\n\n    const snapshot = cache.extract();\n    expect(snapshot).toEqual({\n      \"Person:1234\": {\n        __typename: \"Person\",\n        id: 1234,\n        currentTask: {\n          __typename: \"Task\",\n          description: \"writing tests\",\n        },\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        person: {\n          __ref: \"Person:1234\",\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        person: {\n          __typename: \"Person\",\n          id: 1234,\n          currentTask: {\n            __typename: \"Task\",\n            description: \"polishing knives\",\n          },\n        },\n      },\n    });\n\n    // Unchanged because the merge function prefers the existing object.\n    expect(cache.extract()).toEqual(snapshot);\n  });\n\n  it(\"can alter the root query __typename\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        RootQuery: {\n          queryType: true,\n        },\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            __typename\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"RootQuery\",\n    });\n\n    const ALL_ITEMS = gql`\n      query Items {\n        __typename\n        items {\n          id\n          query {\n            id\n          }\n        }\n      }\n    `;\n\n    function makeItem(id: number) {\n      return {\n        id,\n        query: {\n          __typename: \"Query\",\n          id,\n        },\n      };\n    }\n\n    cache.writeQuery({\n      query: ALL_ITEMS,\n      data: {\n        __typename: \"RootQuery\",\n        items: [makeItem(0), makeItem(1), makeItem(2), makeItem(3)],\n      },\n    });\n\n    expect(cache.extract()).toMatchSnapshot();\n\n    expect(\n      cache.readQuery({\n        query: ALL_ITEMS,\n      })\n    ).toEqual({\n      __typename: \"RootQuery\",\n      items: [makeItem(0), makeItem(1), makeItem(2), makeItem(3)],\n    });\n  });\n\n  it(\"can configure {query,mutation,subscription}Type:true\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        RootQuery: {\n          queryType: true,\n        },\n        RootMutation: {\n          mutationType: true,\n        },\n        RootSubscription: {\n          subscriptionType: true,\n        },\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            __typename\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"RootQuery\",\n    });\n\n    expect(\n      cache.readFragment({\n        id: \"ROOT_MUTATION\",\n        fragment: gql`\n          fragment MutationTypename on RootMutation {\n            __typename\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"RootMutation\",\n    });\n\n    expect(\n      cache.readFragment({\n        id: \"ROOT_SUBSCRIPTION\",\n        fragment: gql`\n          fragment SubscriptionTypename on RootSubscription {\n            __typename\n          }\n        `,\n      })\n    ).toEqual({\n      __typename: \"RootSubscription\",\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/readFromStore.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport { assign, omit } from \"lodash\";\n\nimport type { Reference, TypedDocumentNode } from \"@apollo/client\";\nimport { isReference } from \"@apollo/client\";\nimport { InMemoryCache, MissingFieldError } from \"@apollo/client/cache\";\nimport { makeReference } from \"@apollo/client/utilities/internal\";\n\nimport { defaultCacheSizes } from \"../../../utilities/caching/sizes.js\";\nimport type { Cache } from \"../../core/types/Cache.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreReader } from \"../readFromStore.js\";\nimport type { StoreObject } from \"../types.js\";\n\nimport {\n  defaultNormalizedCacheFactory,\n  readQueryFromStore,\n  withError,\n} from \"./helpers.js\";\n\ndescribe(\"resultCacheMaxSize\", () => {\n  const cache = new InMemoryCache();\n\n  it(\"uses default max size on caches\", () => {\n    const reader = new StoreReader({ cache });\n    expect(reader[\"executeSelectionSet\"].options.max).toBe(\n      defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"]\n    );\n  });\n});\n\ndescribe(\"reading from the store\", () => {\n  const reader = new StoreReader({\n    cache: new InMemoryCache(),\n  });\n\n  it(\"runs a nested query with proper fragment fields in arrays\", () => {\n    withError(() => {\n      const store = defaultNormalizedCacheFactory({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          nestedObj: makeReference(\"abcde\"),\n        } as StoreObject,\n        abcde: {\n          id: \"abcde\",\n          innerArray: [\n            {\n              id: \"abcdef\",\n              someField: 3,\n            },\n          ],\n        } as StoreObject,\n      });\n\n      const queryResult = readQueryFromStore(reader, {\n        store,\n        query: gql`\n          {\n            ... on DummyQuery {\n              nestedObj {\n                innerArray {\n                  id\n                  otherField\n                }\n              }\n            }\n            ... on Query {\n              nestedObj {\n                innerArray {\n                  id\n                  someField\n                }\n              }\n            }\n            ... on DummyQuery2 {\n              nestedObj {\n                innerArray {\n                  id\n                  otherField2\n                }\n              }\n            }\n          }\n        `,\n      });\n\n      expect(queryResult).toEqual({\n        nestedObj: {\n          innerArray: [{ id: \"abcdef\", someField: 3 }],\n        },\n      });\n    });\n  });\n\n  it(\"rejects malformed queries\", () => {\n    expect(() => {\n      readQueryFromStore(reader, {\n        store: defaultNormalizedCacheFactory(),\n        query: gql`\n          query {\n            name\n          }\n\n          query {\n            address\n          }\n        `,\n      });\n    }).toThrow(/2 operations/);\n\n    expect(() => {\n      readQueryFromStore(reader, {\n        store: defaultNormalizedCacheFactory(),\n        query: gql`\n          fragment x on y {\n            name\n          }\n        `,\n      });\n    }).toThrow(/contain a query/);\n  });\n\n  it(\"runs a basic query\", () => {\n    const result = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n    } as StoreObject;\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: result,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        query {\n          stringField\n          numberField\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: result[\"stringField\"],\n      numberField: result[\"numberField\"],\n    });\n  });\n\n  it(\"runs a basic query with arguments\", () => {\n    const query = gql`\n      query {\n        id\n        stringField(arg: $stringArg)\n        numberField(intArg: $intArg, floatArg: $floatArg)\n        nullField\n      }\n    `;\n\n    const variables = {\n      intArg: 5,\n      floatArg: 3.14,\n      stringArg: \"This is a string!\",\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        id: \"abcd\",\n        nullField: null,\n        'numberField({\"floatArg\":3.14,\"intArg\":5})': 5,\n        'stringField({\"arg\":\"This is a string!\"})': \"Heyo\",\n      },\n    });\n\n    const result = readQueryFromStore(reader, {\n      store,\n      query,\n      variables,\n    });\n\n    expect(result).toEqual({\n      id: \"abcd\",\n      nullField: null,\n      numberField: 5,\n      stringField: \"Heyo\",\n    });\n  });\n\n  it(\"runs a basic query with custom directives\", () => {\n    const query = gql`\n      query {\n        id\n        firstName @include(if: true)\n        lastName @upperCase\n        birthDate @dateFormat(format: \"DD-MM-YYYY\")\n      }\n    `;\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        id: \"abcd\",\n        firstName: \"James\",\n        \"lastName@upperCase\": \"BOND\",\n        'birthDate@dateFormat({\"format\":\"DD-MM-YYYY\"})': \"20-05-1940\",\n      },\n    });\n\n    const result = readQueryFromStore(reader, {\n      store,\n      query,\n    });\n\n    expect(result).toEqual({\n      id: \"abcd\",\n      firstName: \"James\",\n      lastName: \"BOND\",\n      birthDate: \"20-05-1940\",\n    });\n  });\n\n  it(\"runs a basic query with default values for arguments\", () => {\n    const query = gql`\n      query someBigQuery(\n        $stringArg: String = \"This is a default string!\"\n        $intArg: Int = 0\n        $floatArg: Float\n      ) {\n        id\n        stringField(arg: $stringArg)\n        numberField(intArg: $intArg, floatArg: $floatArg)\n        nullField\n      }\n    `;\n\n    const variables = {\n      floatArg: 3.14,\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        id: \"abcd\",\n        nullField: null,\n        'numberField({\"floatArg\":3.14,\"intArg\":0})': 5,\n        'stringField({\"arg\":\"This is a default string!\"})': \"Heyo\",\n      },\n    });\n\n    const result = readQueryFromStore(reader, {\n      store,\n      query,\n      variables,\n    });\n\n    expect(result).toEqual({\n      id: \"abcd\",\n      nullField: null,\n      numberField: 5,\n      stringField: \"Heyo\",\n    });\n  });\n\n  it(\"runs a nested query\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        id: \"abcde\",\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      } as StoreObject,\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: assign({}, assign({}, omit(result, \"nestedObj\")), {\n        nestedObj: makeReference(\"abcde\"),\n      } as StoreObject),\n      abcde: result.nestedObj,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedObj {\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nestedObj: {\n        stringField: \"This is a string too!\",\n        numberField: 6,\n      },\n    });\n  });\n\n  it(\"runs a nested query with multiple fragments\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        id: \"abcde\",\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      } as StoreObject,\n      deepNestedObj: {\n        stringField: \"This is a deep string\",\n        numberField: 7,\n        nullField: null,\n      } as StoreObject,\n      nullObject: null,\n      __typename: \"Item\",\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: assign(\n        {},\n        assign({}, omit(result, \"nestedObj\", \"deepNestedObj\")),\n        {\n          __typename: \"Query\",\n          nestedObj: makeReference(\"abcde\"),\n        } as StoreObject\n      ),\n      abcde: assign({}, result.nestedObj, {\n        deepNestedObj: makeReference(\"abcdef\"),\n      }) as StoreObject,\n      abcdef: result.deepNestedObj as StoreObject,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nullField\n          ... on Query {\n            nestedObj {\n              stringField\n              nullField\n              deepNestedObj {\n                stringField\n                nullField\n              }\n            }\n          }\n          ... on Query {\n            nestedObj {\n              numberField\n              nullField\n              deepNestedObj {\n                numberField\n                nullField\n              }\n            }\n          }\n          ... on Query {\n            nullObject\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n        deepNestedObj: {\n          stringField: \"This is a deep string\",\n          numberField: 7,\n          nullField: null,\n        },\n      },\n      nullObject: null,\n    });\n  });\n\n  it(\"runs a nested query with an array without IDs\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        {\n          stringField: \"This is a string too!\",\n          numberField: 6,\n          nullField: null,\n        },\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ] as StoreObject[],\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: result,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedArray {\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nestedArray: [\n        {\n          stringField: \"This is a string too!\",\n          numberField: 6,\n        },\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n        },\n      ],\n    });\n  });\n\n  it(\"runs a nested query with an array without IDs and a null\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        null,\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ] as StoreObject[],\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: result,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedArray {\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nestedArray: [\n        null,\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n        },\n      ],\n    });\n  });\n\n  it(\"runs a nested query with an array with IDs and a null\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        null,\n        {\n          id: \"abcde\",\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ] as StoreObject[],\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: assign({}, assign({}, omit(result, \"nestedArray\")), {\n        nestedArray: [null, makeReference(\"abcde\")],\n      }) as StoreObject,\n      abcde: result.nestedArray[1],\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedArray {\n            id\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nestedArray: [\n        null,\n        {\n          id: \"abcde\",\n          stringField: \"This is a string also!\",\n          numberField: 7,\n        },\n      ],\n    });\n  });\n\n  it(\"runs a nested query - skips iterating into an empty array\", () => {\n    const reader = new StoreReader({\n      cache: new InMemoryCache(),\n    });\n\n    const result = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        {\n          id: \"abcde\",\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ],\n      emptyArray: [],\n    } satisfies StoreObject;\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: { ...result, nestedArray: [makeReference(\"abcde\")] },\n      abcde: result.nestedArray[0],\n    });\n\n    expect(reader[\"executeSubSelectedArray\"].size).toBe(0);\n\n    // assumption: cache size does not increase for empty array\n    readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          emptyArray {\n            id\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n    expect(reader[\"executeSubSelectedArray\"].size).toBe(0);\n\n    // assumption: cache size increases for array with content\n    readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedArray {\n            id\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n    expect(reader[\"executeSubSelectedArray\"].size).toBe(1);\n  });\n\n  it(\"returns null on a missing field\", () => {\n    const result = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n    } as StoreObject;\n\n    const store = defaultNormalizedCacheFactory({ ROOT_QUERY: result });\n\n    const cacheResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          missingField\n        }\n      `,\n    });\n\n    expect(cacheResult).toBeNull();\n  });\n\n  it(\"readQuery supports returnPartialData\", () => {\n    const cache = new InMemoryCache();\n    const aQuery = gql`\n      query {\n        a\n      }\n    `;\n    const bQuery = gql`\n      query {\n        b\n      }\n    `;\n    const abQuery = gql`\n      query {\n        a\n        b\n      }\n    `;\n\n    cache.writeQuery({\n      query: aQuery,\n      data: { a: 123 },\n    });\n\n    expect(cache.readQuery({ query: bQuery })).toBe(null);\n    expect(cache.readQuery({ query: abQuery })).toBe(null);\n\n    expect(\n      cache.readQuery({\n        query: bQuery,\n        returnPartialData: true,\n      })\n    ).toEqual(null);\n\n    expect(\n      cache.readQuery({\n        query: abQuery,\n        returnPartialData: true,\n      })\n    ).toEqual({ a: 123 });\n  });\n\n  it(\"readFragment supports returnPartialData\", () => {\n    const cache = new InMemoryCache();\n    const id = cache.identify({\n      __typename: \"ABObject\",\n      id: 321,\n    });\n\n    const aFragment = gql`\n      fragment AFragment on ABObject {\n        a\n      }\n    `;\n    const bFragment = gql`\n      fragment BFragment on ABObject {\n        b\n      }\n    `;\n    const abFragment = gql`\n      fragment ABFragment on ABObject {\n        a\n        b\n      }\n    `;\n\n    expect(cache.readFragment({ id, fragment: aFragment })).toBe(null);\n    expect(cache.readFragment({ id, fragment: bFragment })).toBe(null);\n    expect(cache.readFragment({ id, fragment: abFragment })).toBe(null);\n\n    const ref = cache.writeFragment({\n      id,\n      fragment: aFragment,\n      data: {\n        __typename: \"ABObject\",\n        a: 123,\n      },\n    });\n    expect(isReference(ref)).toBe(true);\n    expect(ref!.__ref).toBe(id);\n\n    expect(\n      cache.readFragment({\n        id,\n        fragment: bFragment,\n      })\n    ).toBe(null);\n\n    expect(\n      cache.readFragment({\n        id,\n        fragment: abFragment,\n      })\n    ).toBe(null);\n\n    expect(\n      cache.readFragment({\n        id,\n        fragment: bFragment,\n        returnPartialData: true,\n      })\n    ).toEqual({\n      __typename: \"ABObject\",\n    });\n\n    expect(\n      cache.readFragment({\n        id,\n        fragment: abFragment,\n        returnPartialData: true,\n      })\n    ).toEqual({\n      __typename: \"ABObject\",\n      a: 123,\n    });\n  });\n\n  it(\"distinguishes between missing @client and non-@client fields\", () => {\n    const query = gql`\n      query {\n        normal {\n          present @client\n          missing\n        }\n        clientOnly @client {\n          present\n          missing\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            normal() {\n              return { present: \"here\" };\n            },\n            clientOnly() {\n              return { present: \"also here\" };\n            },\n          },\n        },\n      },\n    });\n\n    const { result, complete, missing } = cache.diff({\n      query,\n      optimistic: true,\n      returnPartialData: true,\n    });\n\n    expect(complete).toBe(false);\n\n    expect(result).toEqual({\n      normal: {\n        present: \"here\",\n      },\n      clientOnly: {\n        present: \"also here\",\n      },\n    });\n\n    expect(missing).toEqual(\n      new MissingFieldError(\n        `Can't find field 'missing' on object ${JSON.stringify(\n          {\n            present: \"here\",\n          },\n          null,\n          2\n        )}`,\n        {\n          normal: {\n            missing: `Can't find field 'missing' on object ${JSON.stringify(\n              { present: \"here\" },\n              null,\n              2\n            )}`,\n          },\n          clientOnly: {\n            missing: `Can't find field 'missing' on object ${JSON.stringify(\n              { present: \"also here\" },\n              null,\n              2\n            )}`,\n          },\n        },\n        query,\n        {} // variables\n      )\n    );\n  });\n\n  it(\"runs a nested query where the reference is null\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: null,\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: assign({}, assign({}, omit(result, \"nestedObj\")), {\n        nestedObj: null,\n      }) as StoreObject,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          nestedObj {\n            stringField\n            numberField\n          }\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nestedObj: null,\n    });\n  });\n\n  it(\"runs an array of non-objects\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      simpleArray: [\"one\", \"two\", \"three\"],\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: result,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          simpleArray\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      simpleArray: [\"one\", \"two\", \"three\"],\n    });\n  });\n\n  it(\"runs an array of non-objects with null\", () => {\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      simpleArray: [null, \"two\", \"three\"],\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: result,\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          stringField\n          numberField\n          simpleArray\n        }\n      `,\n    });\n\n    // The result of the query shouldn't contain __data_id fields\n    expect(queryResult).toEqual({\n      stringField: \"This is a string!\",\n      numberField: 5,\n      simpleArray: [null, \"two\", \"three\"],\n    });\n  });\n\n  it(\"will read from an arbitrary root id\", () => {\n    const data: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        id: \"abcde\",\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      } as StoreObject,\n      deepNestedObj: {\n        stringField: \"This is a deep string\",\n        numberField: 7,\n        nullField: null,\n      } as StoreObject,\n      nullObject: null,\n      __typename: \"Item\",\n    };\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: assign(\n        {},\n        assign({}, omit(data, \"nestedObj\", \"deepNestedObj\")),\n        {\n          __typename: \"Query\",\n          nestedObj: makeReference(\"abcde\"),\n        }\n      ) as StoreObject,\n      abcde: assign({}, data.nestedObj, {\n        deepNestedObj: makeReference(\"abcdef\"),\n      }) as StoreObject,\n      abcdef: data.deepNestedObj as StoreObject,\n    });\n\n    const queryResult1 = readQueryFromStore(reader, {\n      store,\n      rootId: \"abcde\",\n      query: gql`\n        {\n          stringField\n          numberField\n          nullField\n          deepNestedObj {\n            stringField\n            numberField\n            nullField\n          }\n        }\n      `,\n    });\n\n    expect(queryResult1).toEqual({\n      stringField: \"This is a string too!\",\n      numberField: 6,\n      nullField: null,\n      deepNestedObj: {\n        stringField: \"This is a deep string\",\n        numberField: 7,\n        nullField: null,\n      },\n    });\n\n    const queryResult2 = readQueryFromStore(reader, {\n      store,\n      rootId: \"abcdef\",\n      query: gql`\n        {\n          stringField\n          numberField\n          nullField\n        }\n      `,\n    });\n\n    expect(queryResult2).toEqual({\n      stringField: \"This is a deep string\",\n      numberField: 7,\n      nullField: null,\n    });\n  });\n\n  it(\"properly handles the @connection directive\", () => {\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        \"books:abc\": [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          books(skip: 0, limit: 2) @connection(key: \"abc\") {\n            name\n          }\n        }\n      `,\n    });\n\n    expect(queryResult).toEqual({\n      books: [\n        {\n          name: \"efgh\",\n        },\n      ],\n    });\n  });\n\n  it(\"can use keyArgs function instead of @connection directive\", () => {\n    const reader = new StoreReader({\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              books: {\n                // Even though we're returning an arbitrary string here,\n                // the InMemoryCache will ensure the actual key begins\n                // with \"books\".\n                keyArgs: () => \"abc\",\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        \"books:abc\": [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n    });\n\n    const queryResult = readQueryFromStore(reader, {\n      store,\n      query: gql`\n        {\n          books(skip: 0, limit: 2) {\n            name\n          }\n        }\n      `,\n    });\n\n    expect(queryResult).toEqual({\n      books: [\n        {\n          name: \"efgh\",\n        },\n      ],\n    });\n  });\n\n  it(\"refuses to return raw Reference objects\", () => {\n    const store = defaultNormalizedCacheFactory({\n      ROOT_QUERY: {\n        author: {\n          __typename: \"Author\",\n          name: \"Toni Morrison\",\n          books: [\n            {\n              title: \"The Bluest Eye\",\n              publisher: makeReference(\"Publisher1\"),\n            },\n            {\n              title: \"Song of Solomon\",\n              publisher: makeReference(\"Publisher2\"),\n            },\n            {\n              title: \"Beloved\",\n              publisher: makeReference(\"Publisher2\"),\n            },\n          ],\n        },\n      },\n      Publisher1: {\n        __typename: \"Publisher\",\n        id: 1,\n        name: \"Holt, Rinehart and Winston\",\n      },\n      Publisher2: {\n        __typename: \"Publisher\",\n        id: 2,\n        name: \"Alfred A. Knopf, Inc.\",\n      },\n    });\n\n    expect(() => {\n      readQueryFromStore(reader, {\n        store,\n        query: gql`\n          {\n            author {\n              name\n              books\n            }\n          }\n        `,\n      });\n    }).toThrow(\n      /Missing selection set for object of type Publisher returned for query field books/\n    );\n\n    expect(\n      readQueryFromStore(reader, {\n        store,\n        query: gql`\n          {\n            author {\n              name\n              books {\n                title\n                publisher {\n                  name\n                }\n              }\n            }\n          }\n        `,\n      })\n    ).toEqual({\n      author: {\n        __typename: \"Author\",\n        name: \"Toni Morrison\",\n        books: [\n          {\n            title: \"The Bluest Eye\",\n            publisher: {\n              __typename: \"Publisher\",\n              name: \"Holt, Rinehart and Winston\",\n            },\n          },\n          {\n            title: \"Song of Solomon\",\n            publisher: {\n              __typename: \"Publisher\",\n              name: \"Alfred A. Knopf, Inc.\",\n            },\n          },\n          {\n            title: \"Beloved\",\n            publisher: {\n              __typename: \"Publisher\",\n              name: \"Alfred A. Knopf, Inc.\",\n            },\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"read functions for root query fields work with empty cache\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            uuid() {\n              return \"8d573b9c-cfcf-4e3e-98dd-14d255af577e\";\n            },\n            null() {\n              return null;\n            },\n          },\n        },\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            uuid\n            null\n          }\n        `,\n      })\n    ).toEqual({\n      uuid: \"8d573b9c-cfcf-4e3e-98dd-14d255af577e\",\n      null: null,\n    });\n\n    expect(cache.extract()).toEqual({});\n\n    expect(\n      cache.readFragment({\n        id: \"ROOT_QUERY\",\n        fragment: gql`\n          fragment UUIDFragment on Query {\n            null\n            uuid\n          }\n        `,\n      })\n    ).toEqual({\n      uuid: \"8d573b9c-cfcf-4e3e-98dd-14d255af577e\",\n      null: null,\n    });\n\n    expect(cache.extract()).toEqual({});\n\n    expect(\n      cache.readFragment({\n        id: \"does not exist\",\n        fragment: gql`\n          fragment F on Never {\n            whatever\n          }\n        `,\n      })\n    ).toBe(null);\n\n    expect(cache.extract()).toEqual({});\n  });\n\n  it(\"custom read functions can map/filter dangling references\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            ducks(existing: Reference[] = [], { canRead }) {\n              return existing.map((duck) => (canRead(duck) ? duck : null));\n            },\n            chickens(existing: Reference[] = [], { canRead }) {\n              return existing.map((chicken) =>\n                canRead(chicken) ? chicken : {}\n              );\n            },\n            oxen(existing: Reference[] = [], { canRead }) {\n              return existing.filter(canRead);\n            },\n          },\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          ducks {\n            quacking\n          }\n          chickens {\n            inCoop\n          }\n          oxen {\n            gee\n            haw\n          }\n        }\n      `,\n      data: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          { __typename: \"Duck\", id: 3, quacking: false },\n        ],\n        chickens: [\n          { __typename: \"Chicken\", id: 1, inCoop: true },\n          { __typename: \"Chicken\", id: 2, inCoop: true },\n          { __typename: \"Chicken\", id: 3, inCoop: false },\n        ],\n        oxen: [\n          { __typename: \"Ox\", id: 1, gee: true, haw: false },\n          { __typename: \"Ox\", id: 2, gee: false, haw: true },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Chicken:1\": {\n        __typename: \"Chicken\",\n        id: 1,\n        inCoop: true,\n      },\n      \"Chicken:2\": {\n        __typename: \"Chicken\",\n        id: 2,\n        inCoop: true,\n      },\n      \"Chicken:3\": {\n        __typename: \"Chicken\",\n        id: 3,\n        inCoop: false,\n      },\n      \"Duck:1\": {\n        __typename: \"Duck\",\n        id: 1,\n        quacking: true,\n      },\n      \"Duck:2\": {\n        __typename: \"Duck\",\n        id: 2,\n        quacking: false,\n      },\n      \"Duck:3\": {\n        __typename: \"Duck\",\n        id: 3,\n        quacking: false,\n      },\n      \"Ox:1\": {\n        __typename: \"Ox\",\n        id: 1,\n        gee: true,\n        haw: false,\n      },\n      \"Ox:2\": {\n        __typename: \"Ox\",\n        id: 2,\n        gee: false,\n        haw: true,\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        chickens: [\n          { __ref: \"Chicken:1\" },\n          { __ref: \"Chicken:2\" },\n          { __ref: \"Chicken:3\" },\n        ],\n        ducks: [{ __ref: \"Duck:1\" }, { __ref: \"Duck:2\" }, { __ref: \"Duck:3\" }],\n        oxen: [{ __ref: \"Ox:1\" }, { __ref: \"Ox:2\" }],\n      },\n    });\n\n    function diffChickens() {\n      return cache.diff({\n        query: gql`\n          query {\n            chickens {\n              id\n              inCoop\n            }\n          }\n        `,\n        optimistic: true,\n      });\n    }\n\n    expect(diffChickens()).toEqual({\n      complete: true,\n      result: {\n        chickens: [\n          { __typename: \"Chicken\", id: 1, inCoop: true },\n          { __typename: \"Chicken\", id: 2, inCoop: true },\n          { __typename: \"Chicken\", id: 3, inCoop: false },\n        ],\n      },\n    });\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Chicken\",\n          id: 2,\n        }),\n      })\n    ).toBe(true);\n\n    expect(diffChickens()).toEqual({\n      complete: false,\n      missing: new MissingFieldError(\n        \"Can't find field 'id' on object {}\",\n        {\n          chickens: {\n            1: {\n              id: \"Can't find field 'id' on object {}\",\n              inCoop: \"Can't find field 'inCoop' on object {}\",\n            },\n          },\n        },\n        expect.anything(), // query\n        expect.anything() // variables\n      ),\n\n      result: {\n        chickens: [\n          { __typename: \"Chicken\", id: 1, inCoop: true },\n          {},\n          { __typename: \"Chicken\", id: 3, inCoop: false },\n        ],\n      },\n    });\n\n    function diffDucks() {\n      return cache.diff({\n        query: gql`\n          query {\n            ducks {\n              id\n              quacking\n            }\n          }\n        `,\n        optimistic: true,\n      });\n    }\n\n    expect(diffDucks()).toEqual({\n      complete: true,\n      result: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          { __typename: \"Duck\", id: 3, quacking: false },\n        ],\n      },\n    });\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Duck\",\n          id: 3,\n        }),\n      })\n    ).toBe(true);\n\n    // Returning null as a placeholder in a list is a way to indicate that\n    // a list element has been removed, without causing an incomplete\n    // diff, and without altering the positions of later elements.\n    expect(diffDucks()).toEqual({\n      complete: true,\n      result: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          null,\n        ],\n      },\n    });\n\n    function diffOxen() {\n      return cache.diff({\n        query: gql`\n          query {\n            oxen {\n              id\n              gee\n              haw\n            }\n          }\n        `,\n        optimistic: true,\n      });\n    }\n\n    expect(diffOxen()).toEqual({\n      complete: true,\n      result: {\n        oxen: [\n          { __typename: \"Ox\", id: 1, gee: true, haw: false },\n          { __typename: \"Ox\", id: 2, gee: false, haw: true },\n        ],\n      },\n    });\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Ox\",\n          id: 1,\n        }),\n      })\n    ).toBe(true);\n\n    expect(diffOxen()).toEqual({\n      complete: true,\n      result: {\n        oxen: [{ __typename: \"Ox\", id: 2, gee: false, haw: true }],\n      },\n    });\n  });\n\n  it(\"does not filter explicit undefined items in array returned from read function\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            ducks(existing: Reference[] = [], { canRead }) {\n              return existing.map((duck) => (canRead(duck) ? duck : undefined));\n            },\n          },\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: gql`\n        query {\n          ducks {\n            quacking\n          }\n        }\n      `,\n      data: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          { __typename: \"Duck\", id: 3, quacking: false },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Duck:1\": {\n        __typename: \"Duck\",\n        id: 1,\n        quacking: true,\n      },\n      \"Duck:2\": {\n        __typename: \"Duck\",\n        id: 2,\n        quacking: false,\n      },\n      \"Duck:3\": {\n        __typename: \"Duck\",\n        id: 3,\n        quacking: false,\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ducks: [{ __ref: \"Duck:1\" }, { __ref: \"Duck:2\" }, { __ref: \"Duck:3\" }],\n      },\n    });\n\n    function diffDucks() {\n      return cache.diff({\n        query: gql`\n          query {\n            ducks {\n              id\n              quacking\n            }\n          }\n        `,\n        optimistic: true,\n      });\n    }\n\n    expect(diffDucks()).toEqual({\n      complete: true,\n      result: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          { __typename: \"Duck\", id: 3, quacking: false },\n        ],\n      },\n    });\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Duck\",\n          id: 3,\n        }),\n      })\n    ).toBe(true);\n\n    expect(diffDucks()).toEqual({\n      complete: false,\n      result: {\n        ducks: [\n          { __typename: \"Duck\", id: 1, quacking: true },\n          { __typename: \"Duck\", id: 2, quacking: false },\n          {},\n        ],\n      },\n      missing: new MissingFieldError(\n        \"Can't find field 'id' on object undefined\",\n        {\n          ducks: {\n            2: {\n              id: \"Can't find field 'id' on object undefined\",\n              quacking: \"Can't find field 'quacking' on object undefined\",\n            },\n          },\n        },\n        expect.anything(), // query\n        expect.anything() // variables\n      ),\n    });\n  });\n\n  it(\"propagates eviction signals to parent queries\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Deity: {\n          keyFields: [\"name\"],\n          fields: {\n            children(offspring: Reference[], { canRead }) {\n              // Automatically filter out any dangling references, and\n              // supply a default empty array if !offspring.\n              return offspring ? offspring.filter(canRead) : [];\n            },\n          },\n        },\n\n        Query: {\n          fields: {\n            ruler(ruler, { canRead, toReference }) {\n              // If the throne is empty, promote Apollo!\n              return canRead(ruler) ? ruler : (\n                  toReference({\n                    __typename: \"Deity\",\n                    name: \"Apollo\",\n                  })\n                );\n            },\n          },\n        },\n      },\n    });\n\n    const rulerQuery = gql`\n      query {\n        ruler {\n          name\n          children {\n            name\n            children {\n              name\n            }\n          }\n        }\n      }\n    `;\n\n    const children = [\n      // Sons #1 and #2 don't have names because Cronus (l.k.a. Saturn)\n      // devoured them shortly after birth, as famously painted by\n      // Francisco Goya:\n      \"Son #1\",\n      \"Hera\",\n      \"Son #2\",\n      \"Zeus\",\n      \"Demeter\",\n      \"Hades\",\n      \"Poseidon\",\n      \"Hestia\",\n    ].map((name) => ({\n      __typename: \"Deity\",\n      name,\n      children: [],\n    }));\n\n    cache.writeQuery({\n      query: rulerQuery,\n      data: {\n        ruler: {\n          __typename: \"Deity\",\n          name: \"Cronus\",\n          children,\n        },\n      },\n    });\n\n    const diffs: Cache.DiffResult<any>[] = [];\n\n    function watch(immediate = true) {\n      return cache.watch({\n        query: rulerQuery,\n        immediate,\n        optimistic: true,\n        callback(diff) {\n          diffs.push(diff);\n        },\n      });\n    }\n\n    const cancel = watch();\n\n    function devour(name: string) {\n      return cache.evict({\n        id: cache.identify({ __typename: \"Deity\", name }),\n      });\n    }\n\n    const initialDiff = {\n      result: {\n        ruler: {\n          __typename: \"Deity\",\n          name: \"Cronus\",\n          children,\n        },\n      },\n      complete: true,\n    };\n\n    // We already have one diff because of the immediate:true above.\n    expect(diffs).toEqual([initialDiff]);\n\n    expect(devour(\"Son #1\")).toBe(true);\n\n    const childrenWithoutSon1 = children.filter(\n      (child) => child.name !== \"Son #1\"\n    );\n\n    expect(childrenWithoutSon1.length).toBe(children.length - 1);\n\n    const diffWithoutSon1 = {\n      result: {\n        ruler: {\n          name: \"Cronus\",\n          __typename: \"Deity\",\n          children: childrenWithoutSon1,\n        },\n      },\n      complete: true,\n    };\n\n    expect(diffs).toEqual([initialDiff, diffWithoutSon1]);\n\n    expect(devour(\"Son #1\")).toBe(false);\n\n    expect(diffs).toEqual([initialDiff, diffWithoutSon1]);\n\n    expect(devour(\"Son #2\")).toBe(true);\n\n    const diffWithoutDevouredSons = {\n      result: {\n        ruler: {\n          name: \"Cronus\",\n          __typename: \"Deity\",\n          children: childrenWithoutSon1.filter((child) => {\n            return child.name !== \"Son #2\";\n          }),\n        },\n      },\n      complete: true,\n    };\n\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n    ]);\n\n    const childrenOfZeus = [\n      \"Ares\",\n      \"Artemis\",\n      // Fun fact: Apollo is the only major Greco-Roman deity whose name\n      // is the same in both traditions.\n      \"Apollo\",\n      \"Athena\",\n    ].map((name) => ({\n      __typename: \"Deity\",\n      name,\n      children: [],\n    }));\n\n    const zeusRef = cache.writeFragment({\n      id: cache.identify({\n        __typename: \"Deity\",\n        name: \"Zeus\",\n      }),\n      fragment: gql`\n        fragment Offspring on Deity {\n          children {\n            name\n          }\n        }\n      `,\n      data: {\n        children: childrenOfZeus,\n      },\n    });\n\n    expect(isReference(zeusRef)).toBe(true);\n    expect(zeusRef!.__ref).toBe('Deity:{\"name\":\"Zeus\"}');\n\n    const diffWithChildrenOfZeus = {\n      complete: true,\n      result: {\n        ...diffWithoutDevouredSons.result,\n        ruler: {\n          ...diffWithoutDevouredSons.result.ruler,\n          children: diffWithoutDevouredSons.result.ruler.children.map(\n            (child) => {\n              return child.name === \"Zeus\" ?\n                  {\n                    ...child,\n                    children: childrenOfZeus\n                      // Remove empty child.children arrays.\n                      .map(({ children, ...child }) => child),\n                  }\n                : child;\n            }\n          ),\n        },\n      },\n    };\n\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n    ]);\n\n    // Zeus usurps the throne from Cronus!\n    cache.writeQuery({\n      query: rulerQuery,\n      data: {\n        ruler: {\n          __typename: \"Deity\",\n          name: \"Zeus\",\n        },\n      },\n    });\n\n    const diffWithZeusAsRuler = {\n      complete: true,\n      result: {\n        ruler: {\n          __typename: \"Deity\",\n          name: \"Zeus\",\n          children: childrenOfZeus,\n        },\n      },\n    };\n\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n    ]);\n\n    expect(cache.gc().sort()).toEqual([\n      'Deity:{\"name\":\"Cronus\"}',\n      'Deity:{\"name\":\"Demeter\"}',\n      'Deity:{\"name\":\"Hades\"}',\n      'Deity:{\"name\":\"Hera\"}',\n      'Deity:{\"name\":\"Hestia\"}',\n      'Deity:{\"name\":\"Poseidon\"}',\n    ]);\n\n    const snapshotAfterGC = {\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ruler: { __ref: 'Deity:{\"name\":\"Zeus\"}' },\n      },\n      'Deity:{\"name\":\"Zeus\"}': {\n        __typename: \"Deity\",\n        name: \"Zeus\",\n        children: [\n          { __ref: 'Deity:{\"name\":\"Ares\"}' },\n          { __ref: 'Deity:{\"name\":\"Artemis\"}' },\n          { __ref: 'Deity:{\"name\":\"Apollo\"}' },\n          { __ref: 'Deity:{\"name\":\"Athena\"}' },\n        ],\n      },\n      'Deity:{\"name\":\"Apollo\"}': {\n        __typename: \"Deity\",\n        name: \"Apollo\",\n      },\n      'Deity:{\"name\":\"Artemis\"}': {\n        __typename: \"Deity\",\n        name: \"Artemis\",\n      },\n      'Deity:{\"name\":\"Ares\"}': {\n        __typename: \"Deity\",\n        name: \"Ares\",\n      },\n      'Deity:{\"name\":\"Athena\"}': {\n        __typename: \"Deity\",\n        name: \"Athena\",\n      },\n    };\n\n    const zeusMeta = {\n      extraRootIds: ['Deity:{\"name\":\"Zeus\"}'],\n    };\n\n    expect(cache.extract()).toEqual({\n      ...snapshotAfterGC,\n      __META: zeusMeta,\n    });\n\n    // There should be no diff generated by garbage collection.\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n    ]);\n\n    cancel();\n\n    const lastDiff = diffs[diffs.length - 1];\n\n    expect(\n      cache.readQuery({\n        query: rulerQuery,\n      })\n    ).toEqual(lastDiff.result);\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Deity\",\n          name: \"Ares\",\n        }),\n      })\n    ).toBe(true);\n\n    // No new diff generated since we called cancel() above.\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n    ]);\n\n    const snapshotWithoutAres = {\n      ...snapshotAfterGC,\n      __META: zeusMeta,\n    };\n    delete (snapshotWithoutAres as any)['Deity:{\"name\":\"Ares\"}'];\n    expect(cache.extract()).toEqual(snapshotWithoutAres);\n    // Ares already removed, so no new garbage to collect.\n    expect(cache.gc()).toEqual([]);\n\n    const childrenOfZeusWithoutAres = childrenOfZeus.filter((child) => {\n      return child.name !== \"Ares\";\n    });\n\n    expect(childrenOfZeusWithoutAres).toEqual([\n      { __typename: \"Deity\", name: \"Artemis\", children: [] },\n      { __typename: \"Deity\", name: \"Apollo\", children: [] },\n      { __typename: \"Deity\", name: \"Athena\", children: [] },\n    ]);\n\n    expect(\n      cache.readQuery({\n        query: rulerQuery,\n      })\n    ).toEqual({\n      ruler: {\n        __typename: \"Deity\",\n        name: \"Zeus\",\n        children: childrenOfZeusWithoutAres,\n      },\n    });\n\n    expect(\n      cache.evict({\n        id: cache.identify({\n          __typename: \"Deity\",\n          name: \"Zeus\",\n        }),\n      })\n    ).toBe(true);\n\n    // You didn't think we were going to let Apollo be garbage-collected,\n    // did you?\n    cache.retain(\n      cache.identify({\n        __typename: \"Deity\",\n        name: \"Apollo\",\n      })!\n    );\n\n    expect(cache.gc().sort()).toEqual([\n      'Deity:{\"name\":\"Artemis\"}',\n      'Deity:{\"name\":\"Athena\"}',\n    ]);\n\n    expect(cache.extract()).toEqual({\n      __META: {\n        extraRootIds: ['Deity:{\"name\":\"Apollo\"}', 'Deity:{\"name\":\"Zeus\"}'],\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ruler: { __ref: 'Deity:{\"name\":\"Zeus\"}' },\n      },\n      'Deity:{\"name\":\"Apollo\"}': {\n        __typename: \"Deity\",\n        name: \"Apollo\",\n      },\n    });\n\n    const apolloRulerResult = cache.readQuery<{\n      ruler: Record<string, any>;\n    }>({ query: rulerQuery })!;\n\n    expect(apolloRulerResult).toEqual({\n      ruler: {\n        __typename: \"Deity\",\n        name: \"Apollo\",\n        children: [],\n      },\n    });\n\n    // No new diffs since before.\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n    ]);\n\n    // Rewatch the rulerQuery, but avoid delivering an immediate initial\n    // result (by passing false), so that we can use cache.modify to\n    // trigger the delivery of diffWithApolloAsRuler below.\n    const cancel2 = watch(false);\n\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n    ]);\n\n    cache.modify({\n      fields: {\n        ruler(value, { toReference }) {\n          expect(isReference(value)).toBe(true);\n          expect(value.__ref).toBe(\n            cache.identify(diffWithZeusAsRuler.result.ruler)\n          );\n          expect(value.__ref).toBe('Deity:{\"name\":\"Zeus\"}');\n          // Interim ruler Apollo takes over for real.\n          return toReference(apolloRulerResult.ruler)!;\n        },\n      },\n    });\n\n    cancel2();\n\n    const diffWithApolloAsRuler = {\n      complete: true,\n      result: apolloRulerResult,\n    };\n\n    // The cache.modify call should have triggered another diff, since we\n    // overwrote the ROOT_QUERY.ruler field with a valid Reference to the\n    // Apollo entity object.\n    expect(diffs).toEqual([\n      initialDiff,\n      diffWithoutSon1,\n      diffWithoutDevouredSons,\n      diffWithChildrenOfZeus,\n      diffWithZeusAsRuler,\n      diffWithApolloAsRuler,\n    ]);\n\n    expect(\n      // Undo the cache.retain call above.\n      cache.release(\n        cache.identify({\n          __typename: \"Deity\",\n          name: \"Apollo\",\n        })!\n      )\n    ).toBe(0);\n\n    // Since ROOT_QUERY.ruler points to Apollo, nothing needs to be\n    // garbage collected.\n    expect(cache.gc()).toEqual([]);\n\n    // Having survived GC, Apollo reigns supreme atop Olympus... or\n    // something like that.\n    expect(cache.extract()).toEqual({\n      __META: zeusMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ruler: { __ref: 'Deity:{\"name\":\"Apollo\"}' },\n      },\n      'Deity:{\"name\":\"Apollo\"}': {\n        __typename: \"Deity\",\n        name: \"Apollo\",\n      },\n    });\n  });\n\n  it(\"does not canonicalize custom scalar objects\", function () {\n    const now = new Date();\n    const abc = { a: 1, b: 2, c: 3 };\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            now() {\n              return now;\n            },\n\n            abc() {\n              return abc;\n            },\n          },\n        },\n      },\n    });\n\n    const query: TypedDocumentNode<{\n      now: typeof now;\n      abc: typeof abc;\n    }> = gql`\n      query {\n        now\n        abc\n      }\n    `;\n\n    const result1 = cache.readQuery({ query })!;\n    const result2 = cache.readQuery({ query })!;\n\n    expect(result1).toBe(result2);\n    expect(result1.now).toBeInstanceOf(Date);\n\n    // We already know result1.now === result2.now, but it's also\n    // important that it be the very same (===) Date object that was\n    // returned from the read function for the Query.now field, not a\n    // canonicalized version.\n    expect(result1.now).toBe(now);\n    expect(result2.now).toBe(now);\n\n    // The Query.abc field returns a \"normal\" object, but we know from the\n    // structure of the query that it's a scalar object, so it will not be\n    // canonicalized.\n    expect(result1.abc).toEqual(abc);\n    expect(result2.abc).toEqual(abc);\n    expect(result1.abc).toBe(result2.abc);\n    expect(result1.abc).toBe(abc);\n    expect(result2.abc).toBe(abc);\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/recordingCache.ts",
    "content": "import { EntityStore, InMemoryCache, Policies } from \"@apollo/client/cache\";\n\nimport type { NormalizedCacheObject, StoreObject } from \"../types.js\";\n\ndescribe(\"Optimistic EntityStore layering\", () => {\n  function makeLayer(root: EntityStore) {\n    return root.addLayer(\"whatever\", () => {});\n  }\n\n  function lookup(store: EntityStore, dataId: string) {\n    return (store as any).lookup(dataId) as StoreObject;\n  }\n\n  describe(\"returns correct values during recording\", () => {\n    const data = {\n      Human: { __typename: \"Human\", name: \"Mark\" },\n      Animal: { __typename: \"Mouse\", name: \"🐭\" },\n    };\n\n    const dataToRecord = {\n      Human: { __typename: \"Human\", name: \"John\" },\n    };\n\n    const underlyingStore = new EntityStore.Root({\n      seed: data,\n      policies: new Policies({\n        cache: new InMemoryCache(),\n      }),\n    });\n\n    let store = makeLayer(underlyingStore);\n    beforeEach(() => {\n      store = makeLayer(underlyingStore);\n    });\n\n    it(\"should passthrough values if not defined in recording\", () => {\n      expect(lookup(store, \"Human\")).toBe(data.Human);\n      expect(lookup(store, \"Animal\")).toBe(data.Animal);\n    });\n\n    it(\"should return values defined during recording\", () => {\n      store.merge(\"Human\", dataToRecord.Human);\n      expect(lookup(store, \"Human\")).toEqual(dataToRecord.Human);\n      expect(lookup(underlyingStore, \"Human\")).toBe(data.Human);\n    });\n\n    it(\"should return undefined for values deleted during recording\", () => {\n      expect(lookup(store, \"Animal\")).toBe(data.Animal);\n      // delete should be registered in the recording:\n      store.delete(\"Animal\");\n      expect(lookup(store, \"Animal\")).toBeUndefined();\n      expect(store.toObject()).toHaveProperty(\"Animal\");\n      expect(lookup(underlyingStore, \"Animal\")).toBe(data.Animal);\n    });\n  });\n\n  describe(\"returns correct result of a recorded transaction\", () => {\n    const data = {\n      Human: { __typename: \"Human\", name: \"Mark\" },\n      Animal: { __typename: \"Mouse\", name: \"🐭\" },\n    };\n\n    const dataToRecord = {\n      Human: { __typename: \"Human\", name: \"John\" },\n    };\n\n    const underlyingStore = new EntityStore.Root({\n      seed: data,\n      policies: new Policies({\n        cache: new InMemoryCache(),\n      }),\n    });\n    let store = makeLayer(underlyingStore);\n    let recording: NormalizedCacheObject;\n\n    beforeEach(() => {\n      store = makeLayer(underlyingStore);\n      store.merge(\"Human\", dataToRecord.Human);\n      store.delete(\"Animal\");\n      recording = store.toObject();\n    });\n\n    it(\"should contain the property indicating deletion\", () => {\n      expect(recording).toHaveProperty(\"Animal\");\n    });\n\n    it(\"should have recorded the changes made during recording\", () => {\n      expect(recording).toEqual({\n        Human: dataToRecord.Human,\n        Animal: undefined,\n      });\n    });\n\n    it(\"should keep the original data unaffected\", () => {\n      expect(underlyingStore.toObject()).toEqual(data);\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/roundtrip.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport { EntityStore, InMemoryCache } from \"@apollo/client/cache\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreReader } from \"../readFromStore.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreWriter } from \"../writeToStore.js\";\n\nimport { readQueryFromStore, withError, writeQueryToStore } from \"./helpers.js\";\n\nfunction assertDeeplyFrozen(value: any, stack: any[] = []) {\n  if (value !== null && typeof value === \"object\" && stack.indexOf(value) < 0) {\n    expect(Object.isExtensible(value)).toBe(false);\n    expect(Object.isFrozen(value)).toBe(true);\n    stack.push(value);\n    Object.keys(value).forEach((key) => {\n      assertDeeplyFrozen(value[key], stack);\n    });\n    expect(stack.pop()).toBe(value);\n  }\n}\n\nfunction storeRoundtrip(\n  query: DocumentNode,\n  result: any,\n  variables = {},\n  expectedResult = result\n) {\n  const cache = new InMemoryCache({\n    possibleTypes: {\n      Character: [\"Jedi\", \"Droid\"],\n    },\n  });\n\n  const reader = new StoreReader({ cache });\n  const writer = new StoreWriter(cache);\n\n  const store = writeQueryToStore({\n    writer,\n    result,\n    query,\n    variables,\n  });\n\n  const readOptions = {\n    store,\n    query,\n    variables,\n  };\n\n  const reconstructedResult = readQueryFromStore(reader, readOptions);\n  expect(reconstructedResult).toEqual(expectedResult);\n\n  // Make sure the result is identical if we haven't written anything new\n  // to the store. https://github.com/apollographql/apollo-client/pull/3394\n  expect(store).toBeInstanceOf(EntityStore);\n  expect(readQueryFromStore(reader, readOptions)).toBe(reconstructedResult);\n\n  const immutableResult = readQueryFromStore(reader, readOptions);\n  expect(immutableResult).toEqual(reconstructedResult);\n  expect(readQueryFromStore(reader, readOptions)).toBe(immutableResult);\n  if (__DEV__) {\n    try {\n      // Note: this illegal assignment will only throw in strict mode, but that's\n      // safe to assume because this test file is a module.\n      (immutableResult as any).illegal = \"this should not work\";\n      throw new Error(\"unreached\");\n    } catch (e) {\n      expect((e as Error).message).not.toMatch(/unreached/);\n      expect(e).toBeInstanceOf(TypeError);\n    }\n    assertDeeplyFrozen(immutableResult);\n  }\n\n  // Now make sure subtrees of the result are identical even after we write\n  // an additional bogus field to the store.\n  writeQueryToStore({\n    writer,\n    store,\n    result: { oyez: 1234 },\n    query: gql`\n      {\n        oyez\n      }\n    `,\n  });\n\n  const deletedRootResult = readQueryFromStore(reader, readOptions);\n  expect(deletedRootResult).toEqual(expectedResult);\n\n  if (deletedRootResult === reconstructedResult) {\n    // We don't expect the new result to be identical to the previous result,\n    // but there are some rare cases where that can happen, and it's a good\n    // thing, because it means the caching system is working slightly better\n    // than expected... and we don't need to continue with the rest of the\n    // comparison logic below.\n    return;\n  }\n\n  Object.keys(result).forEach((key) => {\n    expect(deletedRootResult[key]).toBe(reconstructedResult[key]);\n  });\n}\n\ndescribe(\"roundtrip\", () => {\n  it(\"real graphql result\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          people_one(id: \"1\") {\n            name\n          }\n        }\n      `,\n      {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      }\n    );\n  });\n\n  it(\"multidimensional array (#776)\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          rows {\n            value\n          }\n        }\n      `,\n      {\n        rows: [\n          [{ value: 1 }, { value: 2 }],\n          [{ value: 3 }, { value: 4 }],\n        ],\n      }\n    );\n  });\n\n  it(\"array with null values (#1551)\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          list {\n            value\n          }\n        }\n      `,\n      {\n        list: [null, { value: 1 }],\n      }\n    );\n  });\n\n  it(\"enum arguments\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          hero(episode: JEDI) {\n            name\n          }\n        }\n      `,\n      {\n        hero: {\n          name: \"Luke Skywalker\",\n        },\n      }\n    );\n  });\n\n  it(\"with an alias\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          luke: people_one(id: \"1\") {\n            name\n          }\n          vader: people_one(id: \"4\") {\n            name\n          }\n        }\n      `,\n      {\n        luke: {\n          name: \"Luke Skywalker\",\n        },\n        vader: {\n          name: \"Darth Vader\",\n        },\n      }\n    );\n  });\n\n  it(\"with variables\", () => {\n    storeRoundtrip(\n      gql`\n        {\n          luke: people_one(id: $lukeId) {\n            name\n          }\n          vader: people_one(id: $vaderId) {\n            name\n          }\n        }\n      `,\n      {\n        luke: {\n          name: \"Luke Skywalker\",\n        },\n        vader: {\n          name: \"Darth Vader\",\n        },\n      },\n      {\n        lukeId: \"1\",\n        vaderId: \"4\",\n      }\n    );\n  });\n\n  it(\"with GraphQLJSON scalar type\", () => {\n    const updateClub = {\n      uid: \"1d7f836018fc11e68d809dfee940f657\",\n      name: \"Eple\",\n      settings: {\n        name: \"eple\",\n        currency: \"AFN\",\n        calendarStretch: 2,\n        defaultPreAllocationPeriod: 1,\n        confirmationEmailCopy: null,\n        emailDomains: null,\n      },\n    } as any;\n\n    storeRoundtrip(\n      gql`\n        {\n          updateClub {\n            uid\n            name\n            settings\n          }\n        }\n      `,\n      {\n        updateClub,\n      }\n    );\n\n    // Reading immutable results from the store does not mean the original\n    // data should get frozen.\n    expect(Object.isExtensible(updateClub)).toBe(true);\n    expect(Object.isFrozen(updateClub)).toBe(false);\n  });\n\n  describe(\"directives\", () => {\n    it(\"should be able to query with skip directive true\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            fortuneCookie @skip(if: true)\n          }\n        `,\n        {},\n        {},\n        {}\n      );\n    });\n\n    it(\"should be able to query with include directive false\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            fortuneCookie @include(if: false)\n          }\n        `,\n        {},\n        {},\n        {}\n      );\n    });\n\n    it(\"should be able to query with skip directive false\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            fortuneCookie @skip(if: false)\n          }\n        `,\n        { fortuneCookie: \"live long and prosper\" }\n      );\n    });\n  });\n\n  describe(\"fragments\", () => {\n    it(\"should work on null fields\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            field {\n              ... on Obj {\n                stuff\n              }\n            }\n          }\n        `,\n        {\n          field: null,\n        }\n      );\n    });\n\n    it(\"should work on basic inline fragments\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            field {\n              __typename\n              ... on Obj {\n                stuff\n              }\n            }\n          }\n        `,\n        {\n          field: {\n            __typename: \"Obj\",\n            stuff: \"Result\",\n          },\n        }\n      );\n    });\n\n    // XXX this test is weird because it assumes the server returned an incorrect result\n    // However, the user may have written this result with client.writeQuery.\n    it(\"should throw an error on two of the same inline fragment types\", () => {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      storeRoundtrip(\n        gql`\n          query {\n            all_people {\n              __typename\n              name\n              ... on Jedi {\n                side\n              }\n              ... on Jedi {\n                rank\n              }\n            }\n          }\n        `,\n        {\n          all_people: [\n            {\n              __typename: \"Jedi\",\n              name: \"Luke Skywalker\",\n              side: \"bright\",\n            },\n          ],\n        },\n        {},\n        null\n      );\n    });\n\n    it(\"should resolve fields it can on interface with non matching inline fragments\", () => {\n      return withError(() => {\n        storeRoundtrip(\n          gql`\n            query {\n              dark_forces {\n                __typename\n                name\n                ... on Droid {\n                  model\n                }\n              }\n            }\n          `,\n          {\n            dark_forces: [\n              {\n                __typename: \"Droid\",\n                name: \"8t88\",\n                model: \"88\",\n              },\n              {\n                __typename: \"Darth\",\n                name: \"Anakin Skywalker\",\n              },\n            ],\n          }\n        );\n      });\n    });\n\n    it(\"should resolve on union types with spread fragments\", () => {\n      return withError(() => {\n        storeRoundtrip(\n          gql`\n            fragment jediFragment on Jedi {\n              side\n            }\n\n            fragment droidFragment on Droid {\n              model\n            }\n\n            query {\n              all_people {\n                __typename\n                name\n                ...jediFragment\n                ...droidFragment\n              }\n            }\n          `,\n          {\n            all_people: [\n              {\n                __typename: \"Jedi\",\n                name: \"Luke Skywalker\",\n                side: \"bright\",\n              },\n              {\n                __typename: \"Droid\",\n                name: \"R2D2\",\n                model: \"astromech\",\n              },\n            ],\n          }\n        );\n      });\n    });\n\n    it(\"should work with a fragment on the actual interface or union\", () => {\n      return withError(() => {\n        storeRoundtrip(\n          gql`\n            fragment jediFragment on Character {\n              side\n            }\n\n            fragment droidFragment on Droid {\n              model\n            }\n\n            query {\n              all_people {\n                name\n                __typename\n                ...jediFragment\n                ...droidFragment\n              }\n            }\n          `,\n          {\n            all_people: [\n              {\n                __typename: \"Jedi\",\n                name: \"Luke Skywalker\",\n                side: \"bright\",\n              },\n              {\n                __typename: \"Droid\",\n                name: \"R2D2\",\n                model: \"astromech\",\n                side: \"bright\",\n              },\n            ],\n          }\n        );\n      });\n    });\n\n    it(\"should throw on error on two of the same spread fragment types\", () => {\n      using _consoleSpies = spyOnConsole.takeSnapshots(\"error\");\n      storeRoundtrip(\n        gql`\n          fragment jediSide on Jedi {\n            side\n          }\n\n          fragment jediRank on Jedi {\n            rank\n          }\n\n          query {\n            all_people {\n              __typename\n              name\n              ...jediSide\n              ...jediRank\n            }\n          }\n        `,\n        {\n          all_people: [\n            {\n              __typename: \"Jedi\",\n              name: \"Luke Skywalker\",\n              side: \"bright\",\n            },\n          ],\n        },\n        {},\n        null\n      );\n    });\n\n    it(\"should resolve on @include and @skip with inline fragments\", () => {\n      storeRoundtrip(\n        gql`\n          query {\n            person {\n              name\n              __typename\n              ... on Jedi @include(if: true) {\n                side\n              }\n              ... on Droid @skip(if: true) {\n                model\n              }\n            }\n          }\n        `,\n        {\n          person: {\n            __typename: \"Jedi\",\n            name: \"Luke Skywalker\",\n            side: \"bright\",\n          },\n        }\n      );\n    });\n\n    it(\"should resolve on @include and @skip with spread fragments\", () => {\n      storeRoundtrip(\n        gql`\n          fragment jediFragment on Jedi {\n            side\n          }\n\n          fragment droidFragment on Droid {\n            model\n          }\n\n          query {\n            person {\n              name\n              __typename\n              ...jediFragment @include(if: true)\n              ...droidFragment @skip(if: true)\n            }\n          }\n        `,\n        {\n          person: {\n            __typename: \"Jedi\",\n            name: \"Luke Skywalker\",\n            side: \"bright\",\n          },\n        }\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/__tests__/writeToStore.ts",
    "content": "import type {\n  ASTNode,\n  DefinitionNode,\n  DocumentNode,\n  FieldNode,\n  OperationDefinitionNode,\n  SelectionNode,\n} from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { assign, omit } from \"lodash\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport type { Reference, StoreObject } from \"@apollo/client/utilities\";\nimport { addTypenameToDocument, isReference } from \"@apollo/client/utilities\";\nimport {\n  cloneDeep,\n  getMainDefinition,\n  makeReference,\n  storeKeyNameFromField,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant, InvariantError } from \"@apollo/client/utilities/invariant\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { extractFragmentContext } from \"../helpers.js\";\nimport type { KeyFieldsFunction } from \"../policies.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { StoreWriter } from \"../writeToStore.js\";\n\nimport { defaultNormalizedCacheFactory, writeQueryToStore } from \"./helpers.js\";\n\nconst getIdField: KeyFieldsFunction = ({ id }) => {\n  invariant(typeof id === \"string\", \"id is not a string\");\n  return id;\n};\n\ndescribe(\"writing to the store\", () => {\n  const cache = new InMemoryCache({\n    dataIdFromObject(object: any) {\n      if (object.__typename && object.id) {\n        return object.__typename + \"__\" + object.id;\n      }\n    },\n  });\n\n  const writer = new StoreWriter(cache);\n\n  it(\"properly normalizes a trivial item\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"properly normalizes an aliased field\", () => {\n    const query = gql`\n      {\n        id\n        aliasedField: stringField\n        numberField\n        nullField\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      aliasedField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      result,\n      query,\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"abcd\",\n        stringField: \"This is a string!\",\n        numberField: 5,\n        nullField: null,\n      },\n    });\n  });\n\n  it(\"properly normalizes a aliased fields with arguments\", () => {\n    const query = gql`\n      {\n        id\n        aliasedField1: stringField(arg: 1)\n        aliasedField2: stringField(arg: 2)\n        numberField\n        nullField\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      aliasedField1: \"The arg was 1!\",\n      aliasedField2: \"The arg was 2!\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      result,\n      query,\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"abcd\",\n        'stringField({\"arg\":1})': \"The arg was 1!\",\n        'stringField({\"arg\":2})': \"The arg was 2!\",\n        numberField: 5,\n        nullField: null,\n      },\n    });\n  });\n\n  it(\"properly normalizes a query with variables\", () => {\n    const query = gql`\n      {\n        id\n        stringField(arg: $stringArg)\n        numberField(intArg: $intArg, floatArg: $floatArg)\n        nullField\n      }\n    `;\n\n    const variables = {\n      intArg: 5,\n      floatArg: 3.14,\n      stringArg: \"This is a string!\",\n    };\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"Heyo\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      result,\n      query,\n      variables,\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"abcd\",\n        nullField: null,\n        'numberField({\"floatArg\":3.14,\"intArg\":5})': 5,\n        'stringField({\"arg\":\"This is a string!\"})': \"Heyo\",\n      },\n    });\n  });\n\n  it(\"properly normalizes a query with default values\", () => {\n    const query = gql`\n      query someBigQuery(\n        $stringArg: String = \"This is a default string!\"\n        $intArg: Int\n        $floatArg: Float\n      ) {\n        id\n        stringField(arg: $stringArg)\n        numberField(intArg: $intArg, floatArg: $floatArg)\n        nullField\n      }\n    `;\n\n    const variables = {\n      intArg: 5,\n      floatArg: 3.14,\n    };\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"Heyo\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      result,\n      query,\n      variables,\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"abcd\",\n        nullField: null,\n        'numberField({\"floatArg\":3.14,\"intArg\":5})': 5,\n        'stringField({\"arg\":\"This is a default string!\"})': \"Heyo\",\n      },\n    });\n  });\n\n  it(\"properly normalizes a query with custom directives\", () => {\n    const query = gql`\n      query {\n        id\n        firstName @include(if: true)\n        lastName @upperCase\n        birthDate @dateFormat(format: \"DD-MM-YYYY\")\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      firstName: \"James\",\n      lastName: \"BOND\",\n      birthDate: \"20-05-1940\",\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      result,\n      query,\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"abcd\",\n        firstName: \"James\",\n        \"lastName@upperCase\": \"BOND\",\n        'birthDate@dateFormat({\"format\":\"DD-MM-YYYY\"})': \"20-05-1940\",\n      },\n    });\n  });\n\n  it(\"properly normalizes a nested object with an ID\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedObj {\n          id\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        id: \"abcde\",\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      },\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n        nestedObj: makeReference(result.nestedObj.id),\n      },\n      [result.nestedObj.id]: result.nestedObj,\n    });\n  });\n\n  it(\"properly normalizes a nested object without an ID\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedObj {\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      },\n    };\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"properly normalizes a nested object with arguments but without an ID\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedObj(arg: \"val\") {\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: {\n        stringField: \"This is a string too!\",\n        numberField: 6,\n        nullField: null,\n      },\n    };\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: assign(omit(result, \"nestedObj\"), {\n        __typename: \"Query\",\n        'nestedObj({\"arg\":\"val\"})': result.nestedObj,\n      }),\n    });\n  });\n\n  it(\"properly normalizes a nested array with IDs\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedArray {\n          id\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        {\n          id: \"abcde\",\n          stringField: \"This is a string too!\",\n          numberField: 6,\n          nullField: null,\n        },\n        {\n          id: \"abcdef\",\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ],\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: assign({}, assign({}, omit(result, \"nestedArray\")), {\n        __typename: \"Query\",\n        nestedArray: result.nestedArray.map((obj: any) =>\n          makeReference(obj.id)\n        ),\n      }),\n      [result.nestedArray[0].id]: result.nestedArray[0],\n      [result.nestedArray[1].id]: result.nestedArray[1],\n    });\n  });\n\n  it(\"properly normalizes a nested array with IDs and a null\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedArray {\n          id\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        {\n          id: \"abcde\",\n          stringField: \"This is a string too!\",\n          numberField: 6,\n          nullField: null,\n        },\n        null,\n      ],\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: assign({}, assign({}, omit(result, \"nestedArray\")), {\n        __typename: \"Query\",\n        nestedArray: [makeReference(result.nestedArray[0].id), null],\n      }),\n      [result.nestedArray[0].id]: result.nestedArray[0],\n    });\n  });\n\n  it(\"properly normalizes a nested array without IDs\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedArray {\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        {\n          stringField: \"This is a string too!\",\n          numberField: 6,\n          nullField: null,\n        },\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ],\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"properly normalizes a nested array without IDs and a null item\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedArray {\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedArray: [\n        null,\n        {\n          stringField: \"This is a string also!\",\n          numberField: 7,\n          nullField: null,\n        },\n      ],\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"properly normalizes an array of non-objects\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        simpleArray\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      simpleArray: [\"one\", \"two\", \"three\"],\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"properly normalizes an array of non-objects with null\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        simpleArray\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      simpleArray: [null, \"two\", \"three\"],\n    };\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n      },\n    });\n  });\n\n  it(\"refuses to normalize objects with nullish id fields\", () => {\n    const query: TypedDocumentNode<{\n      objects: Array<{\n        __typename: string;\n        id?: any;\n        text?: string;\n      }>;\n    }> = gql`\n      query {\n        objects {\n          id\n          text\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      // No keyFields type policy or dataIdFromObject, so we're using/testing\n      // the default implementation, defaultDataIdFromObject.\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        objects: [\n          { __typename: \"Object\", text: \"a\", id: 123 },\n          { __typename: \"Object\", text: \"b\", id: null },\n          { __typename: \"Object\", text: \"c\", id: void 0 },\n          { __typename: \"Object\", text: \"d\", id: 0 },\n          { __typename: \"Object\", text: \"e\", id: \"\" },\n          { __typename: \"Object\", text: \"f\", id: false },\n          { __typename: \"Object\", text: \"g\" },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Object:123\": {\n        __typename: \"Object\",\n        id: 123,\n        text: \"a\",\n      },\n      \"Object:0\": {\n        __typename: \"Object\",\n        id: 0,\n        text: \"d\",\n      },\n      \"Object:\": {\n        __typename: \"Object\",\n        id: \"\",\n        text: \"e\",\n      },\n      \"Object:false\": {\n        __typename: \"Object\",\n        id: false,\n        text: \"f\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        objects: [\n          { __ref: \"Object:123\" },\n          {\n            __typename: \"Object\",\n            id: null,\n            text: \"b\",\n          },\n          { __typename: \"Object\", text: \"c\" },\n          { __ref: \"Object:0\" },\n          { __ref: \"Object:\" },\n          { __ref: \"Object:false\" },\n          { __typename: \"Object\", text: \"g\" },\n        ],\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            objects {\n              text\n            }\n          }\n        `,\n      })\n    ).toEqual({\n      objects: [\n        { __typename: \"Object\", text: \"a\" },\n        { __typename: \"Object\", text: \"b\" },\n        { __typename: \"Object\", text: \"c\" },\n        { __typename: \"Object\", text: \"d\" },\n        { __typename: \"Object\", text: \"e\" },\n        { __typename: \"Object\", text: \"f\" },\n        { __typename: \"Object\", text: \"g\" },\n      ],\n    });\n  });\n\n  it(\"refuses to normalize objects with nullish id fields\", () => {\n    const query: TypedDocumentNode<{\n      objects: Array<{\n        __typename: string;\n        _id?: any;\n        text?: string;\n      }>;\n    }> = gql`\n      query {\n        objects {\n          _id\n          text\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      // No keyFields type policy or dataIdFromObject, so we're using/testing\n      // the default implementation, defaultDataIdFromObject.\n    });\n\n    cache.writeQuery({\n      query,\n      data: {\n        objects: [\n          { __typename: \"Object\", text: \"a\", _id: 123 },\n          { __typename: \"Object\", text: \"b\", _id: null },\n          { __typename: \"Object\", text: \"c\", _id: void 0 },\n          { __typename: \"Object\", text: \"d\", _id: 0 },\n          { __typename: \"Object\", text: \"e\", _id: \"\" },\n          { __typename: \"Object\", text: \"f\", _id: false },\n          { __typename: \"Object\", text: \"g\" },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Object:123\": {\n        __typename: \"Object\",\n        _id: 123,\n        text: \"a\",\n      },\n      \"Object:0\": {\n        __typename: \"Object\",\n        _id: 0,\n        text: \"d\",\n      },\n      \"Object:\": {\n        __typename: \"Object\",\n        _id: \"\",\n        text: \"e\",\n      },\n      \"Object:false\": {\n        __typename: \"Object\",\n        _id: false,\n        text: \"f\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        objects: [\n          { __ref: \"Object:123\" },\n          {\n            __typename: \"Object\",\n            _id: null,\n            text: \"b\",\n          },\n          { __typename: \"Object\", text: \"c\" },\n          { __ref: \"Object:0\" },\n          { __ref: \"Object:\" },\n          { __ref: \"Object:false\" },\n          { __typename: \"Object\", text: \"g\" },\n        ],\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: gql`\n          query {\n            objects {\n              text\n            }\n          }\n        `,\n      })\n    ).toEqual({\n      objects: [\n        { __typename: \"Object\", text: \"a\" },\n        { __typename: \"Object\", text: \"b\" },\n        { __typename: \"Object\", text: \"c\" },\n        { __typename: \"Object\", text: \"d\" },\n        { __typename: \"Object\", text: \"e\" },\n        { __typename: \"Object\", text: \"f\" },\n        { __typename: \"Object\", text: \"g\" },\n      ],\n    });\n  });\n\n  it(\"properly normalizes an object occurring in different graphql paths twice\", () => {\n    const query = gql`\n      {\n        id\n        object1 {\n          id\n          stringField\n        }\n        object2 {\n          id\n          numberField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"a\",\n      object1: {\n        id: \"aa\",\n        stringField: \"string\",\n      },\n      object2: {\n        id: \"aa\",\n        numberField: 1,\n      },\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"a\",\n        object1: makeReference(\"aa\"),\n        object2: makeReference(\"aa\"),\n      },\n      aa: {\n        id: \"aa\",\n        stringField: \"string\",\n        numberField: 1,\n      },\n    });\n  });\n\n  it(\"properly normalizes an object occurring in different graphql array paths twice\", () => {\n    const query = gql`\n      {\n        id\n        array1 {\n          id\n          stringField\n          obj {\n            id\n            stringField\n          }\n        }\n        array2 {\n          id\n          stringField\n          obj {\n            id\n            numberField\n          }\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"a\",\n      array1: [\n        {\n          id: \"aa\",\n          stringField: \"string\",\n          obj: {\n            id: \"aaa\",\n            stringField: \"string\",\n          },\n        },\n      ],\n      array2: [\n        {\n          id: \"ab\",\n          stringField: \"string2\",\n          obj: {\n            id: \"aaa\",\n            numberField: 1,\n          },\n        },\n      ],\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"a\",\n        array1: [makeReference(\"aa\")],\n        array2: [makeReference(\"ab\")],\n      },\n      aa: {\n        id: \"aa\",\n        stringField: \"string\",\n        obj: makeReference(\"aaa\"),\n      },\n      ab: {\n        id: \"ab\",\n        stringField: \"string2\",\n        obj: makeReference(\"aaa\"),\n      },\n      aaa: {\n        id: \"aaa\",\n        stringField: \"string\",\n        numberField: 1,\n      },\n    });\n  });\n\n  it(\"properly normalizes an object occurring in the same graphql array path twice\", () => {\n    const query = gql`\n      {\n        id\n        array1 {\n          id\n          stringField\n          obj {\n            id\n            stringField\n            numberField\n          }\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"a\",\n      array1: [\n        {\n          id: \"aa\",\n          stringField: \"string\",\n          obj: {\n            id: \"aaa\",\n            stringField: \"string\",\n            numberField: 1,\n          },\n        },\n        {\n          id: \"ab\",\n          stringField: \"string2\",\n          obj: {\n            id: \"aaa\",\n            stringField: \"should not be written\",\n            numberField: 2,\n          },\n        },\n      ],\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    const normalized = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    expect(normalized.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        id: \"a\",\n        array1: [makeReference(\"aa\"), makeReference(\"ab\")],\n      },\n      aa: {\n        id: \"aa\",\n        stringField: \"string\",\n        obj: makeReference(\"aaa\"),\n      },\n      ab: {\n        id: \"ab\",\n        stringField: \"string2\",\n        obj: makeReference(\"aaa\"),\n      },\n      aaa: {\n        id: \"aaa\",\n        stringField: \"string\",\n        numberField: 1,\n      },\n    });\n  });\n\n  it(\"merges nodes\", () => {\n    const query = gql`\n      {\n        id\n        numberField\n        nullField\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      numberField: 5,\n      nullField: null,\n    };\n\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        dataIdFromObject: getIdField,\n      })\n    );\n\n    const store = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    const query2 = gql`\n      {\n        id\n        stringField\n        nullField\n      }\n    `;\n\n    const result2: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      nullField: null,\n    };\n\n    const store2 = writeQueryToStore({\n      writer,\n      store,\n      query: query2,\n      result: result2,\n    });\n\n    expect(store2.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n        ...result2,\n      },\n    });\n  });\n\n  it(\"properly normalizes a nested object that returns null\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n        nestedObj {\n          id\n          stringField\n          numberField\n          nullField\n        }\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n      nestedObj: null,\n    };\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        ...result,\n        nestedObj: null,\n      },\n    });\n  });\n\n  it(\"properly normalizes an object with an ID when no extension is passed\", () => {\n    const query = gql`\n      {\n        people_one(id: \"5\") {\n          id\n          stringField\n        }\n      }\n    `;\n\n    const result: any = {\n      people_one: {\n        id: \"abcd\",\n        stringField: \"This is a string!\",\n      },\n    };\n\n    expect(\n      writeQueryToStore({\n        writer,\n        query,\n        result: cloneDeep(result),\n      }).toObject()\n    ).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        'people_one({\"id\":\"5\"})': {\n          id: \"abcd\",\n          stringField: \"This is a string!\",\n        },\n      },\n    });\n  });\n\n  it(\"consistently serialize different types of input when passed inlined or as variable\", () => {\n    const testData = [\n      {\n        mutation: gql`\n          mutation mut($in: Int!) {\n            mut(inline: 5, variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: 5 },\n        expected: 'mut({\"inline\":5,\"variable\":5})',\n      },\n      {\n        mutation: gql`\n          mutation mut($in: Float!) {\n            mut(inline: 5.5, variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: 5.5 },\n        expected: 'mut({\"inline\":5.5,\"variable\":5.5})',\n      },\n      {\n        mutation: gql`\n          mutation mut($in: String!) {\n            mut(inline: \"abc\", variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: \"abc\" },\n        expected: 'mut({\"inline\":\"abc\",\"variable\":\"abc\"})',\n      },\n      {\n        mutation: gql`\n          mutation mut($in: Array!) {\n            mut(inline: [1, 2], variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: [1, 2] },\n        expected: 'mut({\"inline\":[1,2],\"variable\":[1,2]})',\n      },\n      {\n        mutation: gql`\n          mutation mut($in: Object!) {\n            mut(inline: { a: 1 }, variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: { a: 1 } },\n        expected: 'mut({\"inline\":{\"a\":1},\"variable\":{\"a\":1}})',\n      },\n      {\n        mutation: gql`\n          mutation mut($in: Boolean!) {\n            mut(inline: true, variable: $in) {\n              id\n            }\n          }\n        `,\n        variables: { in: true },\n        expected: 'mut({\"inline\":true,\"variable\":true})',\n      },\n    ];\n\n    function isOperationDefinition(\n      definition: DefinitionNode\n    ): definition is OperationDefinitionNode {\n      return definition.kind === \"OperationDefinition\";\n    }\n\n    function isField(selection: SelectionNode): selection is FieldNode {\n      return selection.kind === \"Field\";\n    }\n\n    testData.forEach((data) => {\n      data.mutation.definitions.forEach((definition) => {\n        if (isOperationDefinition(definition)) {\n          definition.selectionSet.selections.forEach((selection) => {\n            if (isField(selection)) {\n              expect(storeKeyNameFromField(selection, data.variables)).toEqual(\n                data.expected\n              );\n            }\n          });\n        }\n      });\n    });\n  });\n\n  it(\"properly normalizes a mutation with object or array parameters and variables\", () => {\n    const mutation = gql`\n      mutation some_mutation($nil: ID, $in: Object) {\n        some_mutation(\n          input: {\n            id: \"5\"\n            arr: [1, { a: \"b\" }]\n            obj: { a: \"b\" }\n            num: 5.5\n            nil: $nil\n            bo: true\n          }\n        ) {\n          id\n        }\n        some_mutation_with_variables(input: $in) {\n          id\n        }\n      }\n    `;\n\n    const result: any = {\n      some_mutation: {\n        id: \"id\",\n      },\n      some_mutation_with_variables: {\n        id: \"id\",\n      },\n    };\n\n    const variables: any = {\n      nil: null,\n      in: {\n        id: \"5\",\n        arr: [1, { a: \"b\" }],\n        obj: { a: \"b\" },\n        num: 5.5,\n        nil: null,\n        bo: true,\n      },\n    };\n\n    function isOperationDefinition(\n      value: ASTNode\n    ): value is OperationDefinitionNode {\n      return value.kind === \"OperationDefinition\";\n    }\n\n    mutation.definitions.map((def) => {\n      if (isOperationDefinition(def)) {\n        const writer = new StoreWriter(\n          new InMemoryCache({\n            dataIdFromObject() {\n              return \"5\";\n            },\n          })\n        );\n\n        expect(\n          writeQueryToStore({\n            writer,\n            query: {\n              kind: \"Document\",\n              definitions: [def],\n            } as DocumentNode,\n            dataId: \"5\",\n            result,\n            variables,\n          }).toObject()\n        ).toEqual({\n          \"5\": {\n            id: \"id\",\n            'some_mutation({\"input\":{\"arr\":[1,{\"a\":\"b\"}],\"bo\":true,\"id\":\"5\",\"nil\":null,\"num\":5.5,\"obj\":{\"a\":\"b\"}}})':\n              makeReference(\"5\"),\n            'some_mutation_with_variables({\"input\":{\"arr\":[1,{\"a\":\"b\"}],\"bo\":true,\"id\":\"5\",\"nil\":null,\"num\":5.5,\"obj\":{\"a\":\"b\"}}})':\n              makeReference(\"5\"),\n          },\n        });\n      } else {\n        throw \"No operation definition found\";\n      }\n    });\n  });\n\n  describe(\"type escaping\", () => {\n    it(\"should correctly escape generated ids\", () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const expStore = defaultNormalizedCacheFactory({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          ...data,\n        },\n      });\n      expect(\n        writeQueryToStore({\n          writer,\n          result: data,\n          query,\n        }).toObject()\n      ).toEqual(expStore.toObject());\n    });\n\n    it(\"should correctly escape real ids\", () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            id\n            __typename\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          id: \"129\",\n          __typename: \"Author\",\n        },\n      };\n      const expStore = defaultNormalizedCacheFactory({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          author: makeReference(cache.identify(data.author)!),\n        },\n        [cache.identify(data.author)!]: {\n          firstName: data.author.firstName,\n          id: data.author.id,\n          __typename: data.author.__typename,\n        },\n      });\n      expect(\n        writeQueryToStore({\n          writer,\n          result: data,\n          query,\n        }).toObject()\n      ).toEqual(expStore.toObject());\n    });\n\n    it(\"should not need to escape json blobs\", () => {\n      const query = gql`\n        query {\n          author {\n            info\n            id\n            __typename\n          }\n        }\n      `;\n      const data = {\n        author: {\n          info: {\n            name: \"John\",\n          },\n          id: \"129\",\n          __typename: \"Author\",\n        },\n      };\n      const expStore = defaultNormalizedCacheFactory({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          author: makeReference(cache.identify(data.author)!),\n        },\n        [cache.identify(data.author)!]: {\n          __typename: data.author.__typename,\n          id: data.author.id,\n          info: data.author.info,\n        },\n      });\n      expect(\n        writeQueryToStore({\n          writer,\n          result: data,\n          query,\n        }).toObject()\n      ).toEqual(expStore.toObject());\n    });\n  });\n\n  it(\"should not merge unidentified data when replacing with ID reference\", () => {\n    const dataWithoutId = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        __typename: \"Author\",\n      },\n    };\n\n    const dataWithId = {\n      author: {\n        firstName: \"John\",\n        id: \"129\",\n        __typename: \"Author\",\n      },\n    };\n\n    const queryWithoutId = gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n    const queryWithId = gql`\n      query {\n        author {\n          firstName\n          id\n          __typename\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            author: {\n              // Silence \"Cache data may be lost...\" warnings by always\n              // preferring the incoming value.\n              merge(existing, incoming, { readField, isReference }) {\n                if (existing) {\n                  expect(isReference(existing)).toBe(false);\n                  expect(\n                    readField({\n                      fieldName: \"__typename\",\n                      from: existing,\n                    })\n                  ).toBe(\"Author\");\n\n                  expect(isReference(incoming)).toBe(true);\n                  expect(\n                    readField({\n                      fieldName: \"__typename\",\n                      from: incoming,\n                    })\n                  ).toBe(\"Author\");\n                }\n\n                return incoming;\n              },\n            },\n          },\n        },\n      },\n      dataIdFromObject(object: any) {\n        if (object.__typename && object.id) {\n          return object.__typename + \"__\" + object.id;\n        }\n      },\n    });\n\n    cache.writeQuery({\n      query: queryWithoutId,\n      data: dataWithoutId,\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n          __typename: \"Author\",\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: queryWithId,\n      data: dataWithId,\n    });\n\n    expect(cache.extract()).toEqual({\n      Author__129: {\n        firstName: \"John\",\n        id: \"129\",\n        __typename: \"Author\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: makeReference(\"Author__129\"),\n      },\n    });\n  });\n\n  it(\"correctly merges fragment fields along multiple paths\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Container: {\n          // Uncommenting this line fixes the test, but should not be necessary,\n          // since the Container response object in question has the same\n          // identity along both paths.\n          // merge: true,\n        },\n      },\n    });\n\n    const query = gql`\n      query Query {\n        item(id: \"123\") {\n          id\n          value {\n            ...ContainerFragment\n          }\n        }\n      }\n\n      fragment ContainerFragment on Container {\n        value {\n          ...ValueFragment\n          item {\n            id\n            value {\n              text\n            }\n          }\n        }\n      }\n\n      fragment ValueFragment on Value {\n        item {\n          ...ItemFragment\n        }\n      }\n\n      fragment ItemFragment on Item {\n        value {\n          value {\n            __typename\n          }\n        }\n      }\n    `;\n\n    const data = {\n      item: {\n        __typename: \"Item\",\n        id: \"0f47f85d-8081-466e-9121-c94069a77c3e\",\n        value: {\n          __typename: \"Container\",\n          value: {\n            __typename: \"Value\",\n            item: {\n              __typename: \"Item\",\n              id: \"6dc3530b-6731-435e-b12a-0089d0ae05ac\",\n              value: {\n                __typename: \"Container\",\n                text: \"Hello World\",\n                value: {\n                  __typename: \"Value\",\n                },\n              },\n            },\n          },\n        },\n      },\n    };\n\n    cache.writeQuery({\n      query,\n      data,\n    });\n\n    expect(cache.readQuery({ query })).toEqual(data);\n    expect(cache.extract()).toMatchSnapshot();\n  });\n\n  it(\"regression test for issue #8600\", () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Country: {\n          fields: {\n            cities: {\n              keyArgs: [\"size\"],\n              merge(existing, incoming, { args }) {\n                if (!args) return incoming;\n                const items = existing ? existing.slice(0) : [];\n                const offset = args.offset ?? 0;\n                for (let i = 0; i < incoming.length; ++i) {\n                  items[offset + i] = incoming[i];\n                }\n                return items;\n              },\n            },\n          },\n        },\n        CityInfo: {\n          merge: true,\n        },\n      },\n    });\n\n    const GET_COUNTRIES = gql`\n      query GetCountries {\n        countries {\n          id\n          ...WithSmallCities\n          ...WithAirQuality\n        }\n      }\n\n      fragment WithSmallCities on Country {\n        biggestCity {\n          id\n        }\n        smallCities: cities(size: SMALL) {\n          id\n        }\n      }\n\n      fragment WithAirQuality on Country {\n        biggestCity {\n          id\n          info {\n            airQuality\n          }\n        }\n      }\n    `;\n\n    const countries = [\n      {\n        __typename: \"Country\",\n        id: 123,\n        biggestCity: {\n          __typename: \"City\",\n          id: 234,\n          info: {\n            __typename: \"CityInfo\",\n            airQuality: 0,\n          },\n        },\n        smallCities: [{ __typename: \"City\", id: 345 }],\n      },\n    ];\n\n    cache.writeQuery({\n      query: GET_COUNTRIES,\n      data: { countries },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"City:234\": {\n        __typename: \"City\",\n        id: 234,\n        info: {\n          __typename: \"CityInfo\",\n          airQuality: 0,\n        },\n      },\n      \"City:345\": {\n        __typename: \"City\",\n        id: 345,\n      },\n      \"Country:123\": {\n        __typename: \"Country\",\n        id: 123,\n        biggestCity: { __ref: \"City:234\" },\n        'cities:{\"size\":\"SMALL\"}': [{ __ref: \"City:345\" }],\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        countries: [{ __ref: \"Country:123\" }],\n      },\n    });\n\n    expect(\n      cache.readQuery({\n        query: GET_COUNTRIES,\n      })\n    ).toEqual({ countries });\n  });\n\n  it(\"should respect id fields added by fragments\", () => {\n    const query = gql`\n      query ABCQuery {\n        __typename\n        a {\n          __typename\n          id\n          ...SharedFragment\n          b {\n            __typename\n            c {\n              __typename\n              title\n              titleSize\n            }\n          }\n        }\n      }\n      fragment SharedFragment on AShared {\n        __typename\n        b {\n          __typename\n          id\n          c {\n            __typename\n          }\n        }\n      }\n    `;\n\n    const data = {\n      __typename: \"Query\",\n      a: {\n        __typename: \"AType\",\n        id: \"a-id\",\n        b: [\n          {\n            __typename: \"BType\",\n            id: \"b-id\",\n            c: {\n              __typename: \"CType\",\n              title: \"Your experience\",\n              titleSize: null,\n            },\n          },\n        ],\n      },\n    };\n\n    const cache = new InMemoryCache({\n      possibleTypes: { AShared: [\"AType\"] },\n    });\n\n    cache.writeQuery({ query, data });\n    expect(cache.readQuery({ query })).toEqual(data);\n\n    expect(cache.extract()).toMatchSnapshot();\n  });\n\n  it(\"should allow a union of objects of a different type, when overwriting a generated id with a real id\", async () => {\n    const dataWithPlaceholder = {\n      author: {\n        hello: \"Foo\",\n        __typename: \"Placeholder\",\n      },\n    };\n    const dataWithAuthor = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        id: \"129\",\n        __typename: \"Author\",\n      },\n    };\n    const query = gql`\n      query {\n        author {\n          ... on Author {\n            firstName\n            lastName\n            id\n            __typename\n          }\n          ... on Placeholder {\n            hello\n            __typename\n          }\n        }\n      }\n    `;\n\n    let mergeCount = 0;\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            author: {\n              merge(existing, incoming, { isReference, readField }) {\n                switch (++mergeCount) {\n                  case 1:\n                    expect(existing).toBeUndefined();\n                    expect(isReference(incoming)).toBe(false);\n                    expect(incoming).toEqual(dataWithPlaceholder.author);\n                    break;\n                  case 2:\n                    expect(existing).toEqual(dataWithPlaceholder.author);\n                    expect(isReference(incoming)).toBe(true);\n                    expect(readField(\"__typename\", incoming)).toBe(\"Author\");\n                    break;\n                  case 3:\n                    expect(isReference(existing)).toBe(true);\n                    expect(readField(\"__typename\", existing)).toBe(\"Author\");\n                    expect(incoming).toEqual(dataWithPlaceholder.author);\n                    break;\n                  default:\n                    throw new Error(\"unreached\");\n                }\n                return incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    // write the first object, without an ID, placeholder\n    cache.writeQuery({\n      query,\n      data: dataWithPlaceholder,\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: {\n          hello: \"Foo\",\n          __typename: \"Placeholder\",\n        },\n      },\n    });\n\n    // replace with another one of different type with ID\n    cache.writeQuery({\n      query,\n      data: dataWithAuthor,\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Author:129\": {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        id: \"129\",\n        __typename: \"Author\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: makeReference(\"Author:129\"),\n      },\n    });\n\n    // and go back to the original:\n    cache.writeQuery({\n      query,\n      data: dataWithPlaceholder,\n    });\n\n    // Author__129 will remain in the store,\n    // but will not be referenced by any of the fields,\n    // hence we combine, and in that very order\n    expect(cache.extract()).toEqual({\n      \"Author:129\": {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        id: \"129\",\n        __typename: \"Author\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        author: {\n          hello: \"Foo\",\n          __typename: \"Placeholder\",\n        },\n      },\n    });\n  });\n\n  it(\"does not swallow errors other than field errors\", () => {\n    const query = gql`\n      query {\n        ...notARealFragment\n        fortuneCookie\n      }\n    `;\n    const result: any = {\n      fortuneCookie: \"Star Wars unit tests are boring\",\n    };\n    expect(() => {\n      writeQueryToStore({\n        writer,\n        result,\n        query,\n      });\n    }).toThrow(/No fragment/);\n  });\n\n  it(\"does not change object references if the value is the same\", () => {\n    const query = gql`\n      {\n        id\n        stringField\n        numberField\n        nullField\n      }\n    `;\n\n    const result: any = {\n      id: \"abcd\",\n      stringField: \"This is a string!\",\n      numberField: 5,\n      nullField: null,\n    };\n    const store = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n    });\n\n    const newStore = writeQueryToStore({\n      writer,\n      query,\n      result: cloneDeep(result),\n      store: defaultNormalizedCacheFactory(store.toObject()),\n    });\n\n    Object.keys(store.toObject()).forEach((field) => {\n      expect((store as any).lookup(field)).toEqual(\n        (newStore as any).lookup(field)\n      );\n    });\n  });\n\n  describe('\"Cache data may be lost...\" warnings', () => {\n    it('should warn \"Cache data may be lost...\" message', () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"warn\");\n      const cache = new InMemoryCache();\n\n      const query = gql`\n        query {\n          someJSON {\n            name\n            age\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          someJSON: {\n            name: \"Tom\",\n          },\n        },\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n\n      cache.writeQuery({\n        query,\n        data: {\n          someJSON: {\n            age: 20,\n          },\n        },\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n    });\n\n    it(\"should not warn when scalar fields are updated\", () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"warn\");\n      const cache = new InMemoryCache();\n\n      const query = gql`\n        query {\n          someJSON\n          currentTime(tz: \"UTC-5\")\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        data: {\n          someJSON: {\n            oyez: 3,\n            foos: [\"bar\", \"baz\"],\n          },\n          currentTime: {\n            localeString: \"9/25/2020, 1:08:33 PM\",\n          },\n        },\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n\n      cache.writeQuery({\n        query,\n        data: {\n          someJSON: {\n            qwer: \"upper\",\n            asdf: \"middle\",\n            zxcv: \"lower\",\n          },\n          currentTime: {\n            msSinceEpoch: 1601053713081,\n          },\n        },\n      });\n\n      expect(cache.extract()).toMatchSnapshot();\n    });\n  });\n\n  describe(\"writeResultToStore shape checking\", () => {\n    const query = gql`\n      query {\n        todos {\n          id\n          name\n          description\n        }\n      }\n    `;\n\n    it(\"should write the result data without validating its shape when a fragment matcher is not provided\", () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"error\");\n      const result = {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n          },\n        ],\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n        })\n      );\n\n      const newStore = writeQueryToStore({\n        writer,\n        query,\n        result,\n      });\n\n      expect((newStore as any).lookup(\"1\")).toEqual(result.todos[0]);\n    });\n\n    it(\"should warn when it receives the wrong data with non-union fragments\", () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"error\");\n      const result = {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n          },\n        ],\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n          possibleTypes: {},\n        })\n      );\n\n      writeQueryToStore({\n        writer,\n        query,\n        result,\n      });\n    });\n\n    it(\"should warn when it receives the wrong data inside a fragment\", () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"error\");\n      const queryWithInterface = gql`\n        query {\n          todos {\n            id\n            name\n            description\n            ...TodoFragment\n          }\n        }\n\n        fragment TodoFragment on Todo {\n          ... on ShoppingCartItem {\n            price\n            __typename\n          }\n          ... on TaskItem {\n            date\n            __typename\n          }\n          __typename\n        }\n      `;\n\n      const result = {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n            description: \"Description 1\",\n            __typename: \"ShoppingCartItem\",\n          },\n        ],\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n          possibleTypes: {\n            Todo: [\"ShoppingCartItem\", \"TaskItem\"],\n          },\n        })\n      );\n\n      writeQueryToStore({\n        writer,\n        query: queryWithInterface,\n        result,\n      });\n    });\n\n    it(\"should warn if a result is missing __typename when required\", () => {\n      const result: any = {\n        todos: [\n          {\n            id: \"1\",\n            name: \"Todo 1\",\n            description: \"Description 1\",\n          },\n        ],\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n          possibleTypes: {},\n        })\n      );\n\n      writeQueryToStore({\n        writer,\n        query: addTypenameToDocument(query),\n        result,\n      });\n    });\n\n    it(\"should not warn if a field is null\", () => {\n      const result: any = {\n        todos: null,\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n        })\n      );\n\n      const newStore = writeQueryToStore({\n        writer,\n        query,\n        result,\n      });\n\n      expect((newStore as any).lookup(\"ROOT_QUERY\")).toEqual({\n        __typename: \"Query\",\n        todos: null,\n      });\n    });\n\n    it(\"should not warn if a field is deferred\", () => {\n      using _consoleSpy = spyOnConsole.takeSnapshots(\"error\");\n      const deferred = gql`\n        query LazyLoad {\n          id\n          expensive @defer\n        }\n      `;\n      const result: any = {\n        id: 1,\n      };\n\n      const writer = new StoreWriter(\n        new InMemoryCache({\n          dataIdFromObject: getIdField,\n        })\n      );\n\n      const newStore = writeQueryToStore({\n        writer,\n        query: deferred,\n        result,\n      });\n\n      expect((newStore as any).lookup(\"ROOT_QUERY\")).toEqual({\n        __typename: \"Query\",\n        id: 1,\n      });\n    });\n  });\n\n  it(\"properly handles the @connection directive\", () => {\n    const store = defaultNormalizedCacheFactory();\n\n    writeQueryToStore({\n      writer,\n      query: gql`\n        {\n          books(skip: 0, limit: 2) @connection(key: \"abc\") {\n            name\n          }\n        }\n      `,\n      result: {\n        books: [\n          {\n            name: \"abcd\",\n          },\n        ],\n      },\n      store,\n    });\n\n    writeQueryToStore({\n      writer,\n      query: gql`\n        {\n          books(skip: 2, limit: 4) @connection(key: \"abc\") {\n            name\n          }\n        }\n      `,\n      result: {\n        books: [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        \"books:abc\": [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"can use keyArgs function instead of @connection directive\", () => {\n    const store = defaultNormalizedCacheFactory();\n    const writer = new StoreWriter(\n      new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              books: {\n                keyArgs: () => \"abc\",\n              },\n            },\n          },\n        },\n      })\n    );\n\n    writeQueryToStore({\n      writer,\n      query: gql`\n        {\n          books(skip: 0, limit: 2) {\n            name\n          }\n        }\n      `,\n      result: {\n        books: [\n          {\n            name: \"abcd\",\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        \"books:abc\": [\n          {\n            name: \"abcd\",\n          },\n        ],\n      },\n    });\n\n    writeQueryToStore({\n      writer,\n      query: gql`\n        {\n          books(skip: 2, limit: 4) {\n            name\n          }\n        }\n      `,\n      result: {\n        books: [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        \"books:abc\": [\n          {\n            name: \"efgh\",\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"should keep reference when type of mixed inlined field changes\", () => {\n    const store = defaultNormalizedCacheFactory();\n\n    const query = gql`\n      query {\n        animals {\n          species {\n            name\n          }\n        }\n      }\n    `;\n\n    writeQueryToStore({\n      writer,\n      query,\n      result: {\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Cat\",\n              name: \"cat\",\n            },\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Cat\",\n              name: \"cat\",\n            },\n          },\n        ],\n      },\n    });\n\n    writeQueryToStore({\n      writer,\n      query,\n      result: {\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Dog\",\n              name: \"dog\",\n            },\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Dog\",\n              name: \"dog\",\n            },\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"should not keep reference when type of mixed inlined field changes to non-inlined field\", () => {\n    using _consoleSpy = spyOnConsole.takeSnapshots(\"error\");\n    const store = defaultNormalizedCacheFactory();\n\n    const query = gql`\n      query {\n        animals {\n          species {\n            id\n            name\n          }\n        }\n      }\n    `;\n\n    writeQueryToStore({\n      writer,\n      query,\n      result: {\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Cat\",\n              name: \"cat\",\n            },\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              __typename: \"Cat\",\n              name: \"cat\",\n            },\n          },\n        ],\n      },\n    });\n\n    writeQueryToStore({\n      writer,\n      query,\n      result: {\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: {\n              id: \"dog-species\",\n              __typename: \"Dog\",\n              name: \"dog\",\n            },\n          },\n        ],\n      },\n      store,\n    });\n\n    expect(store.toObject()).toEqual({\n      \"Dog__dog-species\": {\n        id: \"dog-species\",\n        __typename: \"Dog\",\n        name: \"dog\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        animals: [\n          {\n            __typename: \"Animal\",\n            species: makeReference(\"Dog__dog-species\"),\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"should not merge { __ref } as StoreObject when mergeObjects used\", () => {\n    const merges: Array<{\n      existing: Reference | undefined;\n      incoming: Reference | StoreObject;\n      merged: Reference;\n    }> = [];\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Account: {\n          merge(existing, incoming, { mergeObjects }) {\n            const merged = mergeObjects(existing, incoming);\n            merges.push({ existing, incoming, merged });\n            return merged;\n          },\n        },\n      },\n    });\n\n    const contactLocationQuery = gql`\n      query {\n        account {\n          contact\n          location\n        }\n      }\n    `;\n\n    const contactOnlyQuery = gql`\n      query {\n        account {\n          contact\n        }\n      }\n    `;\n\n    const locationOnlyQuery = gql`\n      query {\n        account {\n          location\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query: contactLocationQuery,\n      data: {\n        account: {\n          __typename: \"Account\",\n          contact: \"billing@example.com\",\n          location: \"Exampleville, Ohio\",\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        account: {\n          __typename: \"Account\",\n          contact: \"billing@example.com\",\n          location: \"Exampleville, Ohio\",\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: contactOnlyQuery,\n      data: {\n        account: {\n          __typename: \"Account\",\n          id: 12345,\n          contact: \"support@example.com\",\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Account:12345\": {\n        __typename: \"Account\",\n        id: 12345,\n        contact: \"support@example.com\",\n        location: \"Exampleville, Ohio\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        account: {\n          __ref: \"Account:12345\",\n        },\n      },\n    });\n\n    cache.writeQuery({\n      query: locationOnlyQuery,\n      data: {\n        account: {\n          __typename: \"Account\",\n          location: \"Nowhere, New Mexico\",\n        },\n      },\n    });\n\n    expect(cache.extract()).toEqual({\n      \"Account:12345\": {\n        __typename: \"Account\",\n        id: 12345,\n        contact: \"support@example.com\",\n        location: \"Nowhere, New Mexico\",\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        account: {\n          __ref: \"Account:12345\",\n        },\n      },\n    });\n\n    expect(merges).toEqual([\n      {\n        existing: void 0,\n        incoming: {\n          __typename: \"Account\",\n          contact: \"billing@example.com\",\n          location: \"Exampleville, Ohio\",\n        },\n        merged: {\n          __typename: \"Account\",\n          contact: \"billing@example.com\",\n          location: \"Exampleville, Ohio\",\n        },\n      },\n\n      {\n        existing: {\n          __typename: \"Account\",\n          contact: \"billing@example.com\",\n          location: \"Exampleville, Ohio\",\n        },\n        incoming: {\n          __ref: \"Account:12345\",\n        },\n        merged: {\n          __ref: \"Account:12345\",\n        },\n      },\n\n      {\n        existing: { __ref: \"Account:12345\" },\n        incoming: {\n          __typename: \"Account\",\n          location: \"Nowhere, New Mexico\",\n        },\n        merged: { __ref: \"Account:12345\" },\n      },\n    ]);\n  });\n\n  it(\"should not deep-freeze scalar objects\", () => {\n    const query = gql`\n      query {\n        scalarFieldWithObjectValue\n      }\n    `;\n\n    const scalarObject = {\n      a: 1,\n      b: [2, 3],\n      c: {\n        d: 4,\n        e: 5,\n      },\n    };\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: {\n        scalarFieldWithObjectValue: scalarObject,\n      },\n    });\n\n    expect(Object.isFrozen(scalarObject)).toBe(false);\n    expect(Object.isFrozen(scalarObject.b)).toBe(false);\n    expect(Object.isFrozen(scalarObject.c)).toBe(false);\n\n    const result = cache.readQuery<any>({ query });\n    expect(result.scalarFieldWithObjectValue).not.toBe(scalarObject);\n    expect(Object.isFrozen(result.scalarFieldWithObjectValue)).toBe(true);\n    expect(Object.isFrozen(result.scalarFieldWithObjectValue.b)).toBe(true);\n    expect(Object.isFrozen(result.scalarFieldWithObjectValue.c)).toBe(true);\n  });\n\n  it(\"should skip writing still-fresh result objects\", function () {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Todo: {\n          fields: {\n            text: {\n              merge(_, text: string) {\n                mergeCounts[text] = ~~mergeCounts[text] + 1;\n                return text;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const mergeCounts: Record<string, number> = {};\n\n    const query = gql`\n      query {\n        todos {\n          id\n          text\n        }\n      }\n    `;\n\n    expect(mergeCounts).toEqual({});\n\n    cache.writeQuery({\n      query,\n      data: {\n        todos: [\n          { __typename: \"Todo\", id: 1, text: \"first\" },\n          { __typename: \"Todo\", id: 2, text: \"second\" },\n        ],\n      },\n    });\n\n    expect(mergeCounts).toEqual({ first: 1, second: 1 });\n\n    function read() {\n      return cache.readQuery<{ todos: any[] }>({ query })!.todos;\n    }\n\n    const twoTodos = read();\n\n    expect(mergeCounts).toEqual({ first: 1, second: 1 });\n\n    const threeTodos = [\n      ...twoTodos,\n      { __typename: \"Todo\", id: 3, text: \"third\" },\n    ];\n\n    cache.writeQuery({\n      query,\n      data: {\n        todos: threeTodos,\n      },\n    });\n\n    expect(mergeCounts).toEqual({ first: 1, second: 1, third: 1 });\n\n    const threeTodosAgain = read();\n    twoTodos.forEach((todo, i) => expect(todo).toBe(threeTodosAgain[i]));\n\n    const fourTodos = [\n      threeTodosAgain[2],\n      threeTodosAgain[0],\n      { __typename: \"Todo\", id: 4, text: \"fourth\" },\n      threeTodosAgain[1],\n    ];\n\n    cache.writeQuery({\n      query,\n      data: {\n        todos: fourTodos,\n      },\n    });\n\n    expect(mergeCounts).toEqual({ first: 1, second: 1, third: 1, fourth: 1 });\n  });\n\n  it(\"should allow silencing broadcast of cache updates\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Counter: {\n          // Counter is a singleton, but we want to be able to test\n          // writing to it with writeFragment, so it needs to have an ID.\n          keyFields: [],\n        },\n      },\n    });\n\n    type Data = {\n      counter: {\n        __typename: \"Counter\";\n        count: number;\n      };\n    };\n\n    const query: TypedDocumentNode<Data> = gql`\n      query {\n        counter {\n          count\n        }\n      }\n    `;\n\n    const results: Data[] = [];\n\n    const promise = new Promise<void>((resolve) => {\n      cache.watch({\n        query,\n        optimistic: true,\n        callback(diff) {\n          results.push(diff.result as Data);\n          expect(diff.result).toEqual({\n            counter: {\n              __typename: \"Counter\",\n              count: 3,\n            },\n          });\n          resolve();\n        },\n      });\n    });\n\n    let count = 0;\n\n    cache.writeQuery({\n      query,\n      data: {\n        counter: {\n          __typename: \"Counter\",\n          count: ++count,\n        },\n      },\n      broadcast: false,\n    });\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        counter: { __ref: \"Counter:{}\" },\n      },\n      \"Counter:{}\": {\n        __typename: \"Counter\",\n        count: 1,\n      },\n    });\n\n    expect(results).toEqual([]);\n\n    const counterId = cache.identify({\n      __typename: \"Counter\",\n    })!;\n\n    cache.writeFragment({\n      id: counterId,\n      fragment: gql`\n        fragment Count on Counter {\n          count\n        }\n      `,\n      data: {\n        count: ++count,\n      },\n      broadcast: false,\n    });\n\n    const counterMeta = {\n      extraRootIds: [\"Counter:{}\"],\n    };\n\n    expect(cache.extract()).toEqual({\n      __META: counterMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        counter: { __ref: \"Counter:{}\" },\n      },\n      \"Counter:{}\": {\n        __typename: \"Counter\",\n        count: 2,\n      },\n    });\n\n    expect(results).toEqual([]);\n\n    expect(\n      cache.evict({\n        id: counterId,\n        fieldName: \"count\",\n        broadcast: false,\n      })\n    ).toBe(true);\n\n    expect(cache.extract()).toEqual({\n      __META: counterMeta,\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        counter: { __ref: \"Counter:{}\" },\n      },\n      \"Counter:{}\": {\n        __typename: \"Counter\",\n      },\n    });\n\n    expect(results).toEqual([]);\n\n    // Only this write should trigger a broadcast.\n    cache.writeQuery({\n      query,\n      data: {\n        counter: {\n          __typename: \"Counter\",\n          count: 3,\n        },\n      },\n    });\n\n    await promise;\n  });\n\n  it(\"writeFragment should be able to infer ROOT_QUERY\", () => {\n    const cache = new InMemoryCache();\n\n    const ref = cache.writeFragment({\n      fragment: gql`\n        fragment RootField on Query {\n          field\n        }\n      `,\n      data: {\n        __typename: \"Query\",\n        field: \"value\",\n      },\n    });\n\n    expect(isReference(ref)).toBe(true);\n    expect(ref!.__ref).toBe(\"ROOT_QUERY\");\n\n    expect(cache.extract()).toEqual({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        field: \"value\",\n      },\n    });\n  });\n\n  it(\"should warn if it cannot identify the result object\", () => {\n    const cache = new InMemoryCache();\n\n    expect(() => {\n      cache.writeFragment({\n        fragment: gql`\n          fragment Count on Counter {\n            count\n          }\n        `,\n        data: {\n          count: 1,\n        },\n      });\n    }).toThrow(/Could not identify object/);\n  });\n\n  it('user objects should be able to have { __typename: \"Subscription\" }', () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Subscription: {\n          keyFields: [\"subId\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        subscriptions {\n          __typename\n          subscriber {\n            name\n          }\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        subscriptions: [\n          {\n            __typename: \"Subscription\",\n            subId: 1,\n            subscriber: {\n              name: \"Alice\",\n            },\n          },\n          {\n            __typename: \"Subscription\",\n            subId: 2,\n            subscriber: {\n              name: \"Bob\",\n            },\n          },\n          {\n            __typename: \"Subscription\",\n            subId: 3,\n            subscriber: {\n              name: \"Clytemnestra\",\n            },\n          },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toMatchSnapshot();\n    expect(cache.readQuery({ query })).toEqual({\n      subscriptions: [\n        { __typename: \"Subscription\", subscriber: { name: \"Alice\" } },\n        { __typename: \"Subscription\", subscriber: { name: \"Bob\" } },\n        { __typename: \"Subscription\", subscriber: { name: \"Clytemnestra\" } },\n      ],\n    });\n  });\n\n  it('user objects should be able to have { __typename: \"Mutation\" }', () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Mutation: {\n          keyFields: [\"gene\", [\"id\"], \"name\"],\n        },\n        Gene: {\n          keyFields: [\"id\"],\n        },\n      },\n    });\n\n    const query = gql`\n      query {\n        mutations {\n          __typename\n          gene {\n            id\n          }\n          name\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query,\n      data: {\n        mutations: [\n          {\n            __typename: \"Mutation\",\n            gene: {\n              __typename: \"Gene\",\n              id: \"SLC45A2\",\n            },\n            name: \"albinism\",\n          },\n          {\n            __typename: \"Mutation\",\n            gene: {\n              __typename: \"Gene\",\n              id: \"SNAI2\",\n            },\n            name: \"piebaldism\",\n          },\n        ],\n      },\n    });\n\n    expect(cache.extract()).toMatchSnapshot();\n    expect(cache.readQuery({ query })).toEqual({\n      mutations: [\n        {\n          __typename: \"Mutation\",\n          gene: { __typename: \"Gene\", id: \"SLC45A2\" },\n          name: \"albinism\",\n        },\n        {\n          __typename: \"Mutation\",\n          gene: { __typename: \"Gene\", id: \"SNAI2\" },\n          name: \"piebaldism\",\n        },\n      ],\n    });\n  });\n\n  describe(\"StoreWriter\", () => {\n    const writer = new StoreWriter(new InMemoryCache());\n\n    function check(\n      query: TypedDocumentNode<{\n        aField: string;\n        bField: string;\n        rootField: string;\n      }>,\n      expectedContextValues: {\n        clientOnly: Record<string, boolean> | boolean;\n        deferred: Record<string, boolean> | boolean;\n      }\n    ) {\n      const { selectionSet } = getMainDefinition(query);\n\n      const flat = writer[\"flattenFields\"](\n        selectionSet,\n        {\n          __typename: \"Query\",\n          aField: \"a\",\n          bField: \"b\",\n          rootField: \"root\",\n        },\n        {\n          ...extractFragmentContext(query),\n          clientOnly: false,\n          deferred: false,\n          flavors: new Map(),\n          variables: {\n            true: true,\n            false: false,\n          },\n        }\n      );\n\n      expect(flat.size).toBe(3);\n\n      flat.forEach((context, field) => {\n        const fieldName = field.name.value;\n\n        if (typeof expectedContextValues.clientOnly === \"boolean\") {\n          expect(context.clientOnly).toBe(expectedContextValues.clientOnly);\n        } else {\n          expect(expectedContextValues.clientOnly).toHaveProperty(fieldName);\n          expect(context.clientOnly).toBe(\n            expectedContextValues.clientOnly[fieldName]\n          );\n        }\n\n        if (typeof expectedContextValues.deferred === \"boolean\") {\n          expect(context.deferred).toBe(expectedContextValues.deferred);\n        } else {\n          expect(expectedContextValues.deferred).toHaveProperty(fieldName);\n          expect(context.deferred).toBe(\n            expectedContextValues.deferred[fieldName]\n          );\n        }\n      });\n    }\n\n    it(\"flattenFields flattens fields with appropriate @client context\", () => {\n      check(\n        gql`\n          query Q {\n            ...FragAB @client\n            ...FragB\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            ...FragAB @client\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            ...FragAB @client\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField @client\n          }\n        `,\n        {\n          clientOnly: {\n            aField: true,\n            bField: true,\n            rootField: false,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            rootField\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField @client\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @client\n            ...FragB\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            ...FragB @client\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: false,\n            rootField: true,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @client\n            ...FragB @client\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @client\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: true,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @client\n            ...FragB\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            ...FragB @client\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: false,\n            rootField: true,\n          },\n          deferred: false,\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @client\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: true,\n            bField: true,\n            rootField: false,\n          },\n          deferred: false,\n        }\n      );\n    });\n\n    it(\"flattenFields flattens fields with appropriate @defer context\", () => {\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            ...FragB\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            ...FragAB @defer\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            ...FragAB @defer\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField @defer\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragB\n            rootField\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField @defer\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @defer\n            ...FragB\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            ...FragB @defer\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            bField: false,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @defer\n            ...FragB @defer\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @defer\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            bField: true,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            rootField @defer\n            ...FragB\n            ...FragAB\n          }\n\n          fragment FragAB on Query {\n            ...FragB @defer\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            bField: false,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            rootField\n          }\n\n          fragment FragAB on Query {\n            ...FragB\n            aField\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n    });\n\n    it(\"flattenFields flattens fields mixing @client and @defer\", () => {\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            ...FragB @client\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @client\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer @client\n            ...FragB @client\n            rootField @client @defer\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @defer\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: true,\n            bField: true,\n            rootField: true,\n          },\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB\n            ...FragB @client\n            rootField @defer\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @client\n          }\n\n          fragment FragB on Query {\n            bField @defer\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n          deferred: {\n            aField: false,\n            bField: true,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            ...FragB @skip(if: true)\n            rootField @client\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @client\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: true,\n          },\n          deferred: {\n            aField: true,\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            aField @defer\n            ...FragAB @include(if: false)\n            ...FragB @client\n            rootField @defer\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: true,\n          },\n        }\n      );\n    });\n\n    it(\"flattenFields understands conditional @defer(if: boolean)\", () => {\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            ...FragB @defer(if: false)\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField @defer(if: true)\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: false,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer\n            ...FragB @defer(if: $true)\n            rootField @defer(if: $true)\n          }\n\n          fragment FragAB on Query {\n            aField @defer(if: $false)\n            ...FragB\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: true,\n            bField: true,\n            rootField: true,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB @defer(if: $false)\n            ...FragB @defer\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @defer(if: true)\n          }\n\n          fragment FragB on Query {\n            bField\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n\n      check(\n        gql`\n          query Q {\n            ...FragAB\n            ...FragB @defer\n            rootField\n          }\n\n          fragment FragAB on Query {\n            aField\n            ...FragB @defer\n          }\n\n          fragment FragB on Query {\n            bField @defer(if: false)\n          }\n        `,\n        {\n          clientOnly: false,\n          deferred: {\n            aField: false,\n            // The bField is deferred despite having @defer(if: false), because it\n            // inherits the @defer directives from above.\n            bField: true,\n            rootField: false,\n          },\n        }\n      );\n    });\n  });\n\n  test(\"prevent that a crafted query can overwrite Post:1 with what should be User:5\", () => {\n    const postFragment = gql`\n      fragment PostFragment on Post {\n        id\n        title\n      }\n    `;\n\n    const cache = new InMemoryCache();\n    cache.writeFragment({\n      fragment: postFragment,\n      data: {\n        __typename: \"Post\",\n        id: \"1\",\n        title: \"Hello\",\n      },\n    });\n\n    expect(cache.extract()[\"Post:1\"]).toMatchInlineSnapshot(`\n      Object {\n        \"__typename\": \"Post\",\n        \"id\": \"1\",\n        \"title\": \"Hello\",\n      }\n    `);\n\n    const injectingQuery = gql`\n      query ($id: String) {\n        user(id: $id) {\n          __typename: firstName\n          id: lastName\n          title\n          ignore: __typename\n          ignore2: id\n        }\n      }\n    `;\n    expect(() =>\n      cache.write({\n        query: injectingQuery,\n        variables: { id: 5 },\n        dataId: \"ROOT_QUERY\",\n        result: {\n          user: {\n            __typename: \"Post\",\n            id: \"1\",\n            title: \"Incorrect!\",\n            ignore: \"User\",\n            ignore2: \"5\",\n          },\n        },\n      })\n    ).toThrow(\n      new InvariantError(\n        '`__typename` is a forbidden field alias name in the selection set for field `user.firstName` in query \"(anonymous)\".'\n      )\n    );\n\n    expect(cache.extract()[\"Post:1\"]).toMatchInlineSnapshot(`\n      Object {\n        \"__typename\": \"Post\",\n        \"id\": \"1\",\n        \"title\": \"Hello\",\n      }\n    `);\n\n    expect(cache.extract()[\"User:5\"]).toBeUndefined();\n  });\n});\n"
  },
  {
    "path": "src/cache/inmemory/entityStore.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\nimport type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep } from \"optimism\";\n\nimport type {\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\nimport { isReference } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  DeepMerger,\n  isNonNullObject,\n  makeReference,\n  maybeDeepFreeze,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type {\n  CanReadFunction,\n  DeleteModifier,\n  InvalidateModifier,\n  Modifier,\n  ModifierDetails,\n  Modifiers,\n  ReadFieldOptions,\n  SafeReadonly,\n  ToReferenceFunction,\n} from \"../core/types/common.js\";\n\nimport { fieldNameFromStoreName, hasOwn } from \"./helpers.js\";\nimport type { Policies, StorageType } from \"./policies.js\";\nimport type { NormalizedCache, NormalizedCacheObject } from \"./types.js\";\n\nconst DELETE = {} as DeleteModifier;\nconst delModifier: Modifier<any> = () => DELETE;\nconst INVALIDATE = {} as InvalidateModifier;\n\nexport abstract class EntityStore implements NormalizedCache {\n  public declare static Root: typeof Root;\n\n  protected data: NormalizedCacheObject = {};\n\n  constructor(\n    public readonly policies: Policies,\n    public readonly group: CacheGroup\n  ) {}\n\n  public abstract addLayer(\n    layerId: string,\n    replay: (layer: EntityStore) => any\n  ): Layer;\n\n  public abstract removeLayer(layerId: string): EntityStore;\n\n  // Although the EntityStore class is abstract, it contains concrete\n  // implementations of the various NormalizedCache interface methods that\n  // are inherited by the Root and Layer subclasses.\n\n  public toObject(): NormalizedCacheObject {\n    return { ...this.data };\n  }\n\n  public has(dataId: string): boolean {\n    return this.lookup(dataId, true) !== void 0;\n  }\n\n  public get(dataId: string, fieldName: string): StoreValue {\n    this.group.depend(dataId, fieldName);\n    if (hasOwn.call(this.data, dataId)) {\n      const storeObject = this.data[dataId];\n      if (storeObject && hasOwn.call(storeObject, fieldName)) {\n        return storeObject[fieldName];\n      }\n    }\n    if (\n      fieldName === \"__typename\" &&\n      hasOwn.call(this.policies.rootTypenamesById, dataId)\n    ) {\n      return this.policies.rootTypenamesById[dataId];\n    }\n    if (this instanceof Layer) {\n      return this.parent.get(dataId, fieldName);\n    }\n  }\n\n  protected lookup(\n    dataId: string,\n    dependOnExistence?: boolean\n  ): StoreObject | undefined {\n    // The has method (above) calls lookup with dependOnExistence = true, so\n    // that it can later be invalidated when we add or remove a StoreObject for\n    // this dataId. Any consumer who cares about the contents of the StoreObject\n    // should not rely on this dependency, since the contents could change\n    // without the object being added or removed.\n    if (dependOnExistence) this.group.depend(dataId, \"__exists\");\n\n    if (hasOwn.call(this.data, dataId)) {\n      return this.data[dataId];\n    }\n\n    if (this instanceof Layer) {\n      return this.parent.lookup(dataId, dependOnExistence);\n    }\n\n    if (this.policies.rootTypenamesById[dataId]) {\n      return {};\n    }\n  }\n\n  public merge(older: string | StoreObject, newer: StoreObject | string): void {\n    let dataId: string | undefined;\n\n    // Convert unexpected references to ID strings.\n    if (isReference(older)) older = older.__ref;\n    if (isReference(newer)) newer = newer.__ref;\n\n    const existing: StoreObject | undefined =\n      typeof older === \"string\" ? this.lookup((dataId = older)) : older;\n\n    const incoming: StoreObject | undefined =\n      typeof newer === \"string\" ? this.lookup((dataId = newer)) : newer;\n\n    // If newer was a string ID, but that ID was not defined in this store,\n    // then there are no fields to be merged, so we're done.\n    if (!incoming) return;\n\n    invariant(typeof dataId === \"string\", \"store.merge expects a string ID\");\n\n    const merged: StoreObject = new DeepMerger({\n      reconciler: storeObjectReconciler,\n    }).merge(existing, incoming);\n\n    // Even if merged === existing, existing may have come from a lower\n    // layer, so we always need to set this.data[dataId] on this level.\n    this.data[dataId] = merged;\n\n    if (merged !== existing) {\n      delete this.refs[dataId];\n      if (this.group.caching) {\n        const fieldsToDirty: Record<string, 1> = {};\n\n        // If we added a new StoreObject where there was previously none, dirty\n        // anything that depended on the existence of this dataId, such as the\n        // EntityStore#has method.\n        if (!existing) fieldsToDirty.__exists = 1;\n\n        // Now invalidate dependents who called getFieldValue for any fields\n        // that are changing as a result of this merge.\n        Object.keys(incoming).forEach((storeFieldName) => {\n          if (\n            !existing ||\n            existing[storeFieldName] !== merged[storeFieldName]\n          ) {\n            // Always dirty the full storeFieldName, which may include\n            // serialized arguments following the fieldName prefix.\n            fieldsToDirty[storeFieldName] = 1;\n\n            // Also dirty fieldNameFromStoreName(storeFieldName) if it's\n            // different from storeFieldName and this field does not have\n            // keyArgs configured, because that means the cache can't make\n            // any assumptions about how field values with the same field\n            // name but different arguments might be interrelated, so it\n            // must err on the side of invalidating all field values that\n            // share the same short fieldName, regardless of arguments.\n            const fieldName = fieldNameFromStoreName(storeFieldName);\n            if (\n              fieldName !== storeFieldName &&\n              !this.policies.hasKeyArgs(merged.__typename, fieldName)\n            ) {\n              fieldsToDirty[fieldName] = 1;\n            }\n\n            // If merged[storeFieldName] has become undefined, and this is the\n            // Root layer, actually delete the property from the merged object,\n            // which is guaranteed to have been created fresh in this method.\n            if (merged[storeFieldName] === void 0 && !(this instanceof Layer)) {\n              delete merged[storeFieldName];\n            }\n          }\n        });\n\n        if (\n          fieldsToDirty.__typename &&\n          !(existing && existing.__typename) &&\n          // Since we return default root __typename strings\n          // automatically from store.get, we don't need to dirty the\n          // ROOT_QUERY.__typename field if merged.__typename is equal\n          // to the default string (usually \"Query\").\n          this.policies.rootTypenamesById[dataId] === merged.__typename\n        ) {\n          delete fieldsToDirty.__typename;\n        }\n\n        Object.keys(fieldsToDirty).forEach((fieldName) =>\n          this.group.dirty(dataId as string, fieldName)\n        );\n      }\n    }\n  }\n\n  public modify(\n    dataId: string,\n    fields: Modifier<any> | Modifiers<Record<string, any>>,\n    exact: boolean\n  ): boolean {\n    const storeObject = this.lookup(dataId);\n\n    if (storeObject) {\n      const changedFields: Record<string, any> = {};\n      let needToMerge = false;\n      let allDeleted = true;\n\n      const sharedDetails = {\n        DELETE,\n        INVALIDATE,\n        isReference,\n        toReference: this.toReference,\n        canRead: this.canRead,\n        readField: <V = StoreValue>(\n          fieldNameOrOptions: string | ReadFieldOptions,\n          from?: StoreObject | Reference\n        ) =>\n          this.policies.readField<V>(\n            typeof fieldNameOrOptions === \"string\" ?\n              {\n                fieldName: fieldNameOrOptions,\n                from: from || makeReference(dataId),\n              }\n            : fieldNameOrOptions,\n            { store: this }\n          ),\n      } satisfies Partial<ModifierDetails>;\n\n      Object.keys(storeObject).forEach((storeFieldName) => {\n        const fieldName = fieldNameFromStoreName(storeFieldName);\n        let fieldValue = storeObject[storeFieldName];\n        if (fieldValue === void 0) return;\n        const modify: Modifier<StoreValue> | undefined =\n          typeof fields === \"function\" ? fields : (\n            fields[storeFieldName] || (exact ? undefined : fields[fieldName])\n          );\n        if (modify) {\n          let newValue =\n            modify === delModifier ? DELETE : (\n              modify(maybeDeepFreeze(fieldValue), {\n                ...sharedDetails,\n                fieldName,\n                storeFieldName,\n                storage: this.getStorage(dataId, storeFieldName),\n              })\n            );\n          if (newValue === INVALIDATE) {\n            this.group.dirty(dataId, storeFieldName);\n          } else {\n            if (newValue === DELETE) newValue = void 0;\n            if (newValue !== fieldValue) {\n              changedFields[storeFieldName] = newValue;\n              needToMerge = true;\n              fieldValue = newValue as StoreValue;\n\n              if (__DEV__) {\n                const checkReference = (ref: Reference) => {\n                  if (this.lookup(ref.__ref) === undefined) {\n                    invariant.warn(\n                      \"cache.modify: You are trying to write a Reference that is not part of the store: %o\\n\" +\n                        \"Please make sure to set the `mergeIntoStore` parameter to `true` when creating a Reference that is not part of the store yet:\\n\" +\n                        \"`toReference(object, true)`\",\n                      ref\n                    );\n                    return true;\n                  }\n                };\n                if (isReference(newValue)) {\n                  checkReference(newValue);\n                } else if (Array.isArray(newValue)) {\n                  // Warn about writing \"mixed\" arrays of Reference and non-Reference objects\n                  let seenReference: boolean = false;\n                  let someNonReference: unknown;\n                  for (const value of newValue) {\n                    if (isReference(value)) {\n                      seenReference = true;\n                      if (checkReference(value)) break;\n                    } else {\n                      // Do not warn on primitive values, since those could never be represented\n                      // by a reference. This is a valid (albeit uncommon) use case.\n                      if (typeof value === \"object\" && !!value) {\n                        const [id] = this.policies.identify(value);\n                        // check if object could even be referenced, otherwise we are not interested in it for this warning\n                        if (id) {\n                          someNonReference = value;\n                        }\n                      }\n                    }\n                    if (seenReference && someNonReference !== undefined) {\n                      invariant.warn(\n                        \"cache.modify: Writing an array with a mix of both References and Objects will not result in the Objects being normalized correctly.\\n\" +\n                          \"Please convert the object instance %o to a Reference before writing it to the cache by calling `toReference(object, true)`.\",\n                        someNonReference\n                      );\n                      break;\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n        if (fieldValue !== void 0) {\n          allDeleted = false;\n        }\n      });\n\n      if (needToMerge) {\n        this.merge(dataId, changedFields);\n\n        if (allDeleted) {\n          if (this instanceof Layer) {\n            this.data[dataId] = void 0;\n          } else {\n            delete this.data[dataId];\n          }\n          this.group.dirty(dataId, \"__exists\");\n        }\n\n        return true;\n      }\n    }\n\n    return false;\n  }\n\n  // If called with only one argument, removes the entire entity\n  // identified by dataId. If called with a fieldName as well, removes all\n  // fields of that entity whose names match fieldName according to the\n  // fieldNameFromStoreName helper function. If called with a fieldName\n  // and variables, removes all fields of that entity whose names match fieldName\n  // and whose arguments when cached exactly match the variables passed.\n  public delete(\n    dataId: string,\n    fieldName?: string,\n    args?: Record<string, any>\n  ) {\n    const storeObject = this.lookup(dataId);\n    if (storeObject) {\n      const typename = this.getFieldValue<string>(storeObject, \"__typename\");\n      const storeFieldName =\n        fieldName && args ?\n          this.policies.getStoreFieldName({ typename, fieldName, args })\n        : fieldName;\n      return this.modify(\n        dataId,\n        storeFieldName ?\n          {\n            [storeFieldName]: delModifier,\n          }\n        : delModifier,\n        !!args\n      );\n    }\n    return false;\n  }\n\n  public evict(options: Cache.EvictOptions, limit: EntityStore): boolean {\n    let evicted = false;\n    if (options.id) {\n      if (hasOwn.call(this.data, options.id)) {\n        evicted = this.delete(options.id, options.fieldName, options.args);\n      }\n      if (this instanceof Layer && this !== limit) {\n        evicted = this.parent.evict(options, limit) || evicted;\n      }\n      // Always invalidate the field to trigger rereading of watched\n      // queries, even if no cache data was modified by the eviction,\n      // because queries may depend on computed fields with custom read\n      // functions, whose values are not stored in the EntityStore.\n      if (options.fieldName || evicted) {\n        this.group.dirty(options.id, options.fieldName || \"__exists\");\n      }\n    }\n    return evicted;\n  }\n\n  public clear(): void {\n    this.replace(null);\n  }\n\n  public extract(): NormalizedCacheObject {\n    const obj = this.toObject();\n    const extraRootIds: string[] = [];\n    this.getRootIdSet().forEach((id) => {\n      if (!hasOwn.call(this.policies.rootTypenamesById, id)) {\n        extraRootIds.push(id);\n      }\n    });\n    if (extraRootIds.length) {\n      obj.__META = { extraRootIds: extraRootIds.sort() };\n    }\n    return obj;\n  }\n\n  public replace(newData: NormalizedCacheObject | null): void {\n    Object.keys(this.data).forEach((dataId) => {\n      if (!(newData && hasOwn.call(newData, dataId))) {\n        this.delete(dataId);\n      }\n    });\n    if (newData) {\n      const { __META, ...rest } = newData;\n      Object.keys(rest).forEach((dataId) => {\n        this.merge(dataId, rest[dataId] as StoreObject);\n      });\n      if (__META) {\n        __META.extraRootIds.forEach(this.retain, this);\n      }\n    }\n  }\n\n  public abstract getStorage(\n    idOrObj: string | StoreObject,\n    ...storeFieldNames: (string | number)[]\n  ): StorageType;\n\n  // Maps root entity IDs to the number of times they have been retained, minus\n  // the number of times they have been released. Retained entities keep other\n  // entities they reference (even indirectly) from being garbage collected.\n  private rootIds: {\n    [rootId: string]: number;\n  } = {};\n\n  public retain(rootId: string): number {\n    return (this.rootIds[rootId] = (this.rootIds[rootId] || 0) + 1);\n  }\n\n  public release(rootId: string): number {\n    if (this.rootIds[rootId] > 0) {\n      const count = --this.rootIds[rootId];\n      if (!count) delete this.rootIds[rootId];\n      return count;\n    }\n    return 0;\n  }\n\n  // Return a Set<string> of all the ID strings that have been retained by\n  // this layer/root *and* any layers/roots beneath it.\n  public getRootIdSet(ids = new Set<string>()) {\n    Object.keys(this.rootIds).forEach(ids.add, ids);\n    if (this instanceof Layer) {\n      this.parent.getRootIdSet(ids);\n    } else {\n      // Official singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n      // always considered roots for garbage collection, regardless of\n      // their retainment counts in this.rootIds.\n      Object.keys(this.policies.rootTypenamesById).forEach(ids.add, ids);\n    }\n    return ids;\n  }\n\n  // The goal of garbage collection is to remove IDs from the Root layer of the\n  // store that are no longer reachable starting from any IDs that have been\n  // explicitly retained (see retain and release, above). Returns an array of\n  // dataId strings that were removed from the store.\n  public gc() {\n    const ids = this.getRootIdSet();\n    const snapshot = this.toObject();\n    ids.forEach((id) => {\n      if (hasOwn.call(snapshot, id)) {\n        // Because we are iterating over an ECMAScript Set, the IDs we add here\n        // will be visited in later iterations of the forEach loop only if they\n        // were not previously contained by the Set.\n        Object.keys(this.findChildRefIds(id)).forEach(ids.add, ids);\n        // By removing IDs from the snapshot object here, we protect them from\n        // getting removed from the root store layer below.\n        delete snapshot[id];\n      }\n    });\n    const idsToRemove = Object.keys(snapshot);\n    if (idsToRemove.length) {\n      let root: EntityStore = this;\n      while (root instanceof Layer) root = root.parent;\n      idsToRemove.forEach((id) => root.delete(id));\n    }\n    return idsToRemove;\n  }\n\n  // Lazily tracks { __ref: <dataId> } strings contained by this.data[dataId].\n  private refs: {\n    [dataId: string]: Record<string, true>;\n  } = {};\n\n  public findChildRefIds(dataId: string): Record<string, true> {\n    if (!hasOwn.call(this.refs, dataId)) {\n      const found = (this.refs[dataId] = {} as Record<string, true>);\n      const root = this.data[dataId];\n      if (!root) return found;\n\n      const workSet = new Set<Record<string | number, any>>([root]);\n      // Within the store, only arrays and objects can contain child entity\n      // references, so we can prune the traversal using this predicate:\n      workSet.forEach((obj) => {\n        if (isReference(obj)) {\n          found[obj.__ref] = true;\n          // In rare cases, a { __ref } Reference object may have other fields.\n          // This often indicates a mismerging of References with StoreObjects,\n          // but garbage collection should not be fooled by a stray __ref\n          // property in a StoreObject (ignoring all the other fields just\n          // because the StoreObject looks like a Reference). To avoid this\n          // premature termination of findChildRefIds recursion, we fall through\n          // to the code below, which will handle any other properties of obj.\n        }\n        if (isNonNullObject(obj)) {\n          Object.keys(obj).forEach((key) => {\n            const child = obj[key];\n            // No need to add primitive values to the workSet, since they cannot\n            // contain reference objects.\n            if (isNonNullObject(child)) {\n              workSet.add(child);\n            }\n          });\n        }\n      });\n    }\n    return this.refs[dataId];\n  }\n\n  // Used to compute cache keys specific to this.group.\n  /** overload for `InMemoryCache.maybeBroadcastWatch` */\n  public makeCacheKey(\n    document: DocumentNode,\n    callback: Cache.WatchCallback<any>,\n    details: string\n  ): object;\n  /** overload for `StoreReader.executeSelectionSet` */\n  public makeCacheKey(\n    selectionSet: SelectionSetNode,\n    parent: string /* = ( Reference.__ref ) */ | StoreObject,\n    varString: string | undefined\n  ): object;\n  /** overload for `StoreReader.executeSubSelectedArray` */\n  public makeCacheKey(\n    field: FieldNode,\n    array: readonly any[],\n    varString: string | undefined\n  ): object;\n  /**\n   * @deprecated This is only meant for internal usage,\n   * in your own code please use a `Trie` instance instead.\n   */\n  public makeCacheKey(...args: any[]): object;\n  public makeCacheKey() {\n    return this.group.keyMaker.lookupArray(arguments);\n  }\n\n  // Bound function that can be passed around to provide easy access to fields\n  // of Reference objects as well as ordinary objects.\n  public getFieldValue = <T = StoreValue>(\n    objectOrReference: StoreObject | Reference | undefined,\n    storeFieldName: string\n  ) =>\n    maybeDeepFreeze(\n      isReference(objectOrReference) ?\n        this.get(objectOrReference.__ref, storeFieldName)\n      : objectOrReference && objectOrReference[storeFieldName]\n    ) as SafeReadonly<T>;\n\n  // Returns true for non-normalized StoreObjects and non-dangling\n  // References, indicating that readField(name, objOrRef) has a chance of\n  // working. Useful for filtering out dangling references from lists.\n  public canRead: CanReadFunction = (objOrRef) => {\n    return isReference(objOrRef) ?\n        this.has(objOrRef.__ref)\n      : typeof objOrRef === \"object\";\n  };\n\n  // Bound function that converts an id or an object with a __typename and\n  // primary key fields to a Reference object. If called with a Reference object,\n  // that same Reference object is returned. Pass true for mergeIntoStore to persist\n  // an object into the store.\n  public toReference: ToReferenceFunction = (objOrIdOrRef, mergeIntoStore) => {\n    if (typeof objOrIdOrRef === \"string\") {\n      return makeReference(objOrIdOrRef);\n    }\n\n    if (isReference(objOrIdOrRef)) {\n      return objOrIdOrRef;\n    }\n\n    const [id] = this.policies.identify(objOrIdOrRef);\n\n    if (id) {\n      const ref = makeReference(id);\n      if (mergeIntoStore) {\n        this.merge(id, objOrIdOrRef);\n      }\n      return ref;\n    }\n  };\n\n  public get supportsResultCaching(): boolean {\n    return this.group.caching;\n  }\n}\n\nexport type FieldValueGetter = EntityStore[\"getFieldValue\"];\n\n// A single CacheGroup represents a set of one or more EntityStore objects,\n// typically the Root store in a CacheGroup by itself, and all active Layer\n// stores in a group together. A single EntityStore object belongs to only\n// one CacheGroup, store.group. The CacheGroup is responsible for tracking\n// dependencies, so store.group is helpful for generating unique keys for\n// cached results that need to be invalidated when/if those dependencies\n// change. If we used the EntityStore objects themselves as cache keys (that\n// is, store rather than store.group), the cache would become unnecessarily\n// fragmented by all the different Layer objects. Instead, the CacheGroup\n// approach allows all optimistic Layer objects in the same linked list to\n// belong to one CacheGroup, with the non-optimistic Root object belonging\n// to another CacheGroup, allowing resultCaching dependencies to be tracked\n// separately for optimistic and non-optimistic entity data.\nclass CacheGroup {\n  private d: OptimisticDependencyFunction<string> | null = null;\n\n  // Used by the EntityStore#makeCacheKey method to compute cache keys\n  // specific to this CacheGroup.\n  public keyMaker!: Trie<object>;\n\n  constructor(\n    public readonly caching: boolean,\n    private parent: CacheGroup | null = null\n  ) {\n    this.resetCaching();\n  }\n\n  public resetCaching() {\n    this.d = this.caching ? dep<string>() : null;\n    this.keyMaker = new Trie();\n  }\n\n  public depend(dataId: string, storeFieldName: string) {\n    if (this.d) {\n      this.d(makeDepKey(dataId, storeFieldName));\n      const fieldName = fieldNameFromStoreName(storeFieldName);\n      if (fieldName !== storeFieldName) {\n        // Fields with arguments that contribute extra identifying\n        // information to the fieldName (thus forming the storeFieldName)\n        // depend not only on the full storeFieldName but also on the\n        // short fieldName, so the field can be invalidated using either\n        // level of specificity.\n        this.d(makeDepKey(dataId, fieldName));\n      }\n      if (this.parent) {\n        this.parent.depend(dataId, storeFieldName);\n      }\n    }\n  }\n\n  public dirty(dataId: string, storeFieldName: string) {\n    if (this.d) {\n      this.d.dirty(\n        makeDepKey(dataId, storeFieldName),\n        // When storeFieldName === \"__exists\", that means the entity identified\n        // by dataId has either disappeared from the cache or was newly added,\n        // so the result caching system would do well to \"forget everything it\n        // knows\" about that object. To achieve that kind of invalidation, we\n        // not only dirty the associated result cache entry, but also remove it\n        // completely from the dependency graph. For the optimism implementation\n        // details, see https://github.com/benjamn/optimism/pull/195.\n        storeFieldName === \"__exists\" ? \"forget\" : \"setDirty\"\n      );\n    }\n  }\n}\n\nfunction makeDepKey(dataId: string, storeFieldName: string) {\n  // Since field names cannot have '#' characters in them, this method\n  // of joining the field name and the ID should be unambiguous, and much\n  // cheaper than JSON.stringify([dataId, fieldName]).\n  return storeFieldName + \"#\" + dataId;\n}\n\nexport function maybeDependOnExistenceOfEntity(\n  store: NormalizedCache,\n  entityId: string\n) {\n  if (supportsResultCaching(store)) {\n    // We use this pseudo-field __exists elsewhere in the EntityStore code to\n    // represent changes in the existence of the entity object identified by\n    // entityId. This dependency gets reliably dirtied whenever an object with\n    // this ID is deleted (or newly created) within this group, so any result\n    // cache entries (for example, StoreReader#executeSelectionSet results) that\n    // depend on __exists for this entityId will get dirtied as well, leading to\n    // the eventual recomputation (instead of reuse) of those result objects the\n    // next time someone reads them from the cache.\n    store.group.depend(entityId, \"__exists\");\n  }\n}\n\nclass Root extends EntityStore {\n  constructor({\n    policies,\n    resultCaching = true,\n    seed,\n  }: {\n    policies: Policies;\n    resultCaching?: boolean;\n    seed?: NormalizedCacheObject;\n  }) {\n    super(policies, new CacheGroup(resultCaching));\n    if (seed) this.replace(seed);\n  }\n\n  public readonly stump = new Stump(this);\n\n  public addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer {\n    // Adding an optimistic Layer on top of the Root actually adds the Layer\n    // on top of the Stump, so the Stump always comes between the Root and\n    // any Layer objects that we've added.\n    return this.stump.addLayer(layerId, replay);\n  }\n\n  public removeLayer(): Root {\n    // Never remove the root layer.\n    return this;\n  }\n\n  public readonly storageTrie = new Trie<StorageType>();\n  public getStorage(): StorageType {\n    return this.storageTrie.lookupArray(arguments);\n  }\n}\nEntityStore.Root = Root;\n\n// Not exported, since all Layer instances are created by the addLayer method\n// of the EntityStore.Root class.\nclass Layer extends EntityStore {\n  constructor(\n    public readonly id: string,\n    public readonly parent: EntityStore,\n    public readonly replay: (layer: EntityStore) => any,\n    public readonly group: CacheGroup\n  ) {\n    super(parent.policies, group);\n    replay(this);\n  }\n\n  public addLayer(layerId: string, replay: (layer: EntityStore) => any): Layer {\n    return new Layer(layerId, this, replay, this.group);\n  }\n\n  public removeLayer(layerId: string): EntityStore {\n    // Remove all instances of the given id, not just the first one.\n    const parent = this.parent.removeLayer(layerId);\n\n    if (layerId === this.id) {\n      if (this.group.caching) {\n        // Dirty every ID we're removing. Technically we might be able to avoid\n        // dirtying fields that have values in higher layers, but we don't have\n        // easy access to higher layers here, and we're about to recreate those\n        // layers anyway (see parent.addLayer below).\n        Object.keys(this.data).forEach((dataId) => {\n          const ownStoreObject = this.data[dataId];\n          const parentStoreObject = parent[\"lookup\"](dataId);\n          if (!parentStoreObject) {\n            // The StoreObject identified by dataId was defined in this layer\n            // but will be undefined in the parent layer, so we can delete the\n            // whole entity using this.delete(dataId). Since we're about to\n            // throw this layer away, the only goal of this deletion is to dirty\n            // the removed fields.\n            this.delete(dataId);\n          } else if (!ownStoreObject) {\n            // This layer had an entry for dataId but it was undefined, which\n            // means the entity was deleted in this layer, and it's about to\n            // become undeleted when we remove this layer, so we need to dirty\n            // all fields that are about to be reexposed.\n            this.group.dirty(dataId, \"__exists\");\n            Object.keys(parentStoreObject).forEach((storeFieldName) => {\n              this.group.dirty(dataId, storeFieldName);\n            });\n          } else if (ownStoreObject !== parentStoreObject) {\n            // If ownStoreObject is not exactly the same as parentStoreObject,\n            // dirty any fields whose values will change as a result of this\n            // removal.\n            Object.keys(ownStoreObject).forEach((storeFieldName) => {\n              if (\n                !equal(\n                  ownStoreObject[storeFieldName],\n                  parentStoreObject[storeFieldName]\n                )\n              ) {\n                this.group.dirty(dataId, storeFieldName);\n              }\n            });\n          }\n        });\n      }\n\n      return parent;\n    }\n\n    // No changes are necessary if the parent chain remains identical.\n    if (parent === this.parent) return this;\n\n    // Recreate this layer on top of the new parent.\n    return parent.addLayer(this.id, this.replay);\n  }\n\n  public toObject(): NormalizedCacheObject {\n    return {\n      ...this.parent.toObject(),\n      ...this.data,\n    };\n  }\n\n  public findChildRefIds(dataId: string): Record<string, true> {\n    const fromParent = this.parent.findChildRefIds(dataId);\n    return hasOwn.call(this.data, dataId) ?\n        {\n          ...fromParent,\n          ...super.findChildRefIds(dataId),\n        }\n      : fromParent;\n  }\n\n  public getStorage(\n    ...args: Parameters<EntityStore[\"getStorage\"]>\n  ): StorageType {\n    let p: EntityStore = this.parent;\n    while ((p as Layer).parent) p = (p as Layer).parent;\n    return p.getStorage(...args);\n  }\n}\n\n// Represents a Layer permanently installed just above the Root, which allows\n// reading optimistically (and registering optimistic dependencies) even when\n// no optimistic layers are currently active. The stump.group CacheGroup object\n// is shared by any/all Layer objects added on top of the Stump.\nclass Stump extends Layer {\n  constructor(root: Root) {\n    super(\n      \"EntityStore.Stump\",\n      root,\n      () => {},\n      new CacheGroup(root.group.caching, root.group)\n    );\n  }\n\n  public removeLayer() {\n    // Never remove the Stump layer.\n    return this;\n  }\n\n  public merge(older: string | StoreObject, newer: string | StoreObject) {\n    // We never want to write any data into the Stump, so we forward any merge\n    // calls to the Root instead. Another option here would be to throw an\n    // exception, but the toReference(object, true) function can sometimes\n    // trigger Stump writes (which used to be Root writes, before the Stump\n    // concept was introduced).\n    return this.parent.merge(older, newer);\n  }\n}\n\nfunction storeObjectReconciler(\n  existingObject: StoreObject,\n  incomingObject: StoreObject,\n  property: string | number\n): StoreValue {\n  const existingValue = existingObject[property];\n  const incomingValue = incomingObject[property];\n  // Wherever there is a key collision, prefer the incoming value, unless\n  // it is deeply equal to the existing value. It's worth checking deep\n  // equality here (even though blindly returning incoming would be\n  // logically correct) because preserving the referential identity of\n  // existing data can prevent needless rereading and rerendering.\n  return equal(existingValue, incomingValue) ? existingValue : incomingValue;\n}\n\nexport function supportsResultCaching(store: any): store is EntityStore {\n  // When result caching is disabled, store.depend will be null.\n  return !!(store && store.supportsResultCaching);\n}\n"
  },
  {
    "path": "src/cache/inmemory/fragmentRegistry.ts",
    "content": "import { WeakCache } from \"@wry/caches\";\nimport type {\n  ASTNode,\n  DocumentNode,\n  FragmentDefinitionNode,\n  FragmentSpreadNode,\n} from \"graphql\";\nimport { visit } from \"graphql\";\nimport { wrap } from \"optimism\";\n\nimport { cacheSizes } from \"@apollo/client/utilities\";\nimport type { FragmentMap } from \"@apollo/client/utilities/internal\";\nimport {\n  bindCacheKey,\n  getFragmentDefinitions,\n} from \"@apollo/client/utilities/internal\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\nexport interface FragmentRegistryAPI {\n  register(...fragments: DocumentNode[]): this;\n  lookup(fragmentName: string): FragmentDefinitionNode | null;\n  transform<D extends DocumentNode>(document: D): D;\n  resetCaches(): void;\n}\n\n// As long as createFragmentRegistry is not imported or used, the\n// FragmentRegistry example implementation provided below should not be bundled\n// (by tree-shaking bundlers like Rollup), because the implementation of\n// InMemoryCache refers only to the TypeScript interface FragmentRegistryAPI,\n// never the concrete implementation FragmentRegistry (which is deliberately not\n// exported from this module).\nexport function createFragmentRegistry(\n  ...fragments: DocumentNode[]\n): FragmentRegistryAPI {\n  return new FragmentRegistry(...fragments);\n}\n\nclass FragmentRegistry implements FragmentRegistryAPI {\n  private registry: FragmentMap = {};\n\n  // Call `createFragmentRegistry` instead of invoking the\n  // FragmentRegistry constructor directly. This reserves the constructor for\n  // future configuration of the FragmentRegistry.\n  constructor(...fragments: DocumentNode[]) {\n    this.resetCaches();\n    if (fragments.length) {\n      this.register(...fragments);\n    }\n  }\n\n  public register(...fragments: DocumentNode[]): this {\n    const definitions = new Map<string, FragmentDefinitionNode>();\n    fragments.forEach((doc: DocumentNode) => {\n      getFragmentDefinitions(doc).forEach((node) => {\n        definitions.set(node.name.value, node);\n      });\n    });\n\n    definitions.forEach((node, name) => {\n      if (node !== this.registry[name]) {\n        this.registry[name] = node;\n        this.invalidate(name);\n      }\n    });\n\n    return this;\n  }\n\n  // Overridden in the resetCaches method below.\n  private invalidate(name: string) {}\n\n  public resetCaches() {\n    const proto = FragmentRegistry.prototype;\n    this.invalidate = (this.lookup = wrap(proto.lookup.bind(this), {\n      // This is intentionally an identity function - a string cannot be keyed weakly.\n      // This is not a memory leak, as lifetime is bound to the `FragmentRegistry` instance,\n      // and max size is configurable.\n      makeCacheKey: (arg) => arg,\n      max:\n        cacheSizes[\"fragmentRegistry.lookup\"] ||\n        defaultCacheSizes[\"fragmentRegistry.lookup\"],\n    })).dirty; // This dirty function is bound to the wrapped lookup method.\n    this.transform = wrap(proto.transform.bind(this), {\n      makeCacheKey: bindCacheKey(this),\n      cache: WeakCache,\n      max:\n        cacheSizes[\"fragmentRegistry.transform\"] ||\n        defaultCacheSizes[\"fragmentRegistry.transform\"],\n    });\n    this.findFragmentSpreads = wrap(proto.findFragmentSpreads.bind(this), {\n      makeCacheKey: bindCacheKey(this),\n      cache: WeakCache,\n      max:\n        cacheSizes[\"fragmentRegistry.findFragmentSpreads\"] ||\n        defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"],\n    });\n  }\n\n  /*\n   * Note:\n   * This method is only memoized so it can serve as a dependency to `transform`,\n   * so calling `invalidate` will invalidate cache entries for `transform`.\n   */\n  public lookup(fragmentName: string): FragmentDefinitionNode | null {\n    return this.registry[fragmentName] || null;\n  }\n\n  public transform<D extends DocumentNode>(document: D): D {\n    const defined = new Map<string, FragmentDefinitionNode>();\n    getFragmentDefinitions(document).forEach((def) => {\n      defined.set(def.name.value, def);\n    });\n\n    const unbound = new Set<string>();\n    const enqueue = (spreadName: string) => {\n      if (!defined.has(spreadName)) {\n        unbound.add(spreadName);\n      }\n    };\n\n    const enqueueChildSpreads = (node: ASTNode) =>\n      Object.keys(this.findFragmentSpreads(node)).forEach(enqueue);\n\n    enqueueChildSpreads(document);\n\n    const missing: string[] = [];\n    const map: FragmentMap = {};\n\n    // This Set forEach loop can be extended during iteration by adding\n    // additional strings to the unbound set.\n    unbound.forEach((fragmentName) => {\n      const knownFragmentDef = defined.get(fragmentName);\n      if (knownFragmentDef) {\n        enqueueChildSpreads((map[fragmentName] = knownFragmentDef));\n      } else {\n        missing.push(fragmentName);\n        const def = this.lookup(fragmentName);\n        if (def) {\n          enqueueChildSpreads((map[fragmentName] = def));\n        }\n      }\n    });\n\n    if (missing.length) {\n      const defsToAppend: FragmentDefinitionNode[] = [];\n      missing.forEach((name) => {\n        const def = map[name];\n        if (def) {\n          defsToAppend.push(def);\n        }\n      });\n\n      if (defsToAppend.length) {\n        document = {\n          ...document,\n          definitions: document.definitions.concat(defsToAppend),\n        };\n      }\n    }\n\n    return document;\n  }\n\n  public findFragmentSpreads(root: ASTNode): FragmentSpreadMap {\n    const spreads: FragmentSpreadMap = {};\n\n    visit(root, {\n      FragmentSpread(node) {\n        spreads[node.name.value] = node;\n      },\n    });\n\n    return spreads;\n  }\n}\n\ninterface FragmentSpreadMap {\n  [fragmentSpreadName: string]: FragmentSpreadNode;\n}\n"
  },
  {
    "path": "src/cache/inmemory/helpers.ts",
    "content": "import type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  SelectionSetNode,\n} from \"graphql\";\n\nimport type {\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\nimport { isReference } from \"@apollo/client/utilities\";\nimport type {\n  FragmentMap,\n  FragmentMapFunction,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  compact,\n  createFragmentMap,\n  DeepMerger,\n  getFragmentDefinitions,\n  isArray,\n  isField,\n  isNonNullObject,\n  resultKeyNameFromField,\n  shouldInclude,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { FragmentRegistryAPI } from \"./fragmentRegistry.js\";\nimport type { KeyFieldsContext } from \"./policies.js\";\nimport type { InMemoryCacheConfig, NormalizedCache } from \"./types.js\";\n\nexport const { hasOwnProperty: hasOwn } = Object.prototype;\n\nexport function defaultDataIdFromObject(\n  { __typename, id, _id }: Readonly<StoreObject>,\n  context?: KeyFieldsContext\n): string | undefined {\n  if (typeof __typename === \"string\") {\n    if (context) {\n      context.keyObject =\n        id != null ? { id }\n        : _id != null ? { _id }\n        : void 0;\n    }\n\n    // If there is no object.id, fall back to object._id.\n    if (id == null && _id != null) {\n      id = _id;\n    }\n\n    if (id != null) {\n      return `${__typename}:${\n        typeof id === \"number\" || typeof id === \"string\" ?\n          id\n        : JSON.stringify(id)\n      }`;\n    }\n  }\n}\n\nconst defaultConfig: InMemoryCacheConfig = {\n  dataIdFromObject: defaultDataIdFromObject,\n  resultCaching: true,\n};\n\nexport function normalizeConfig(config: InMemoryCacheConfig) {\n  return compact(defaultConfig, config);\n}\n\nexport function getTypenameFromStoreObject(\n  store: NormalizedCache,\n  objectOrReference: StoreObject | Reference\n): string | undefined {\n  return isReference(objectOrReference) ?\n      (store.get(objectOrReference.__ref, \"__typename\") as string)\n    : objectOrReference && objectOrReference.__typename;\n}\n\nexport const TypeOrFieldNameRegExp = /^[_a-z][_0-9a-z]*/i;\n\nexport function fieldNameFromStoreName(storeFieldName: string): string {\n  const match = storeFieldName.match(TypeOrFieldNameRegExp);\n  return match ? match[0] : storeFieldName;\n}\n\nexport function selectionSetMatchesResult(\n  selectionSet: SelectionSetNode,\n  result: Record<string, any>,\n  variables?: Record<string, any>\n): boolean {\n  if (isNonNullObject(result)) {\n    return isArray(result) ?\n        result.every((item) =>\n          selectionSetMatchesResult(selectionSet, item, variables)\n        )\n      : selectionSet.selections.every((field) => {\n          if (isField(field) && shouldInclude(field, variables)) {\n            const key = resultKeyNameFromField(field);\n            return (\n              hasOwn.call(result, key) &&\n              (!field.selectionSet ||\n                selectionSetMatchesResult(\n                  field.selectionSet,\n                  result[key],\n                  variables\n                ))\n            );\n          }\n          // If the selection has been skipped with @skip(true) or\n          // @include(false), it should not count against the matching. If\n          // the selection is not a field, it must be a fragment (inline or\n          // named). We will determine if selectionSetMatchesResult for that\n          // fragment when we get to it, so for now we return true.\n          return true;\n        });\n  }\n  return false;\n}\n\nexport function storeValueIsStoreObject(\n  value: StoreValue\n): value is StoreObject {\n  return isNonNullObject(value) && !isReference(value) && !isArray(value);\n}\n\nexport function makeProcessedFieldsMerger() {\n  return new DeepMerger();\n}\n\nexport function extractFragmentContext(\n  document: DocumentNode,\n  fragments?: FragmentRegistryAPI\n): {\n  fragmentMap: FragmentMap;\n  lookupFragment: FragmentMapFunction;\n} {\n  // FragmentMap consisting only of fragments defined directly in document, not\n  // including other fragments registered in the FragmentRegistry.\n  const fragmentMap = createFragmentMap(getFragmentDefinitions(document));\n  return {\n    fragmentMap,\n    lookupFragment(name) {\n      let def: FragmentDefinitionNode | null = fragmentMap[name];\n      if (!def && fragments) {\n        def = fragments.lookup(name);\n      }\n      return def || null;\n    },\n  };\n}\n"
  },
  {
    "path": "src/cache/inmemory/inMemoryCache.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  InlineFragmentNode,\n} from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport type {\n  DeepPartial,\n  Reference,\n  StoreObject,\n} from \"@apollo/client/utilities\";\nimport {\n  addTypenameToDocument,\n  cacheSizes,\n  canonicalStringify,\n  DocumentTransform,\n  isReference,\n  print,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { getInMemoryCacheMemoryInternals } from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\nimport { ApolloCache } from \"../core/cache.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\n\nimport { EntityStore, supportsResultCaching } from \"./entityStore.js\";\nimport { hasOwn, normalizeConfig } from \"./helpers.js\";\nimport { Policies } from \"./policies.js\";\nimport { forgetCache, makeVar, recallCache } from \"./reactiveVars.js\";\nimport { StoreReader } from \"./readFromStore.js\";\nimport type { InMemoryCacheConfig, NormalizedCacheObject } from \"./types.js\";\nimport { StoreWriter } from \"./writeToStore.js\";\n\ntype BroadcastOptions = Pick<\n  Cache.BatchOptions<InMemoryCache>,\n  \"optimistic\" | \"onWatchUpdated\"\n>;\n\nexport class InMemoryCache extends ApolloCache {\n  private data!: EntityStore;\n  private optimisticData!: EntityStore;\n\n  protected config: InMemoryCacheConfig;\n  private watches = new Set<Cache.WatchOptions<any, any>>();\n\n  private storeReader!: StoreReader;\n  private storeWriter!: StoreWriter;\n  private addTypenameTransform = new DocumentTransform(addTypenameToDocument);\n\n  private maybeBroadcastWatch!: OptimisticWrapperFunction<\n    [Cache.WatchOptions<any, any>, BroadcastOptions?],\n    any,\n    [Cache.WatchOptions<any, any>]\n  >;\n\n  // Override the default value, since InMemoryCache result objects are frozen\n  // in development and expected to remain logically immutable in production.\n  public readonly assumeImmutableResults = true;\n\n  // Dynamically imported code can augment existing typePolicies or\n  // possibleTypes by calling cache.policies.addTypePolicies or\n  // cache.policies.addPossibletypes.\n  public readonly policies: Policies;\n\n  public readonly makeVar = makeVar;\n\n  constructor(config: InMemoryCacheConfig = {}) {\n    super();\n    this.config = normalizeConfig(config);\n\n    this.policies = new Policies({\n      cache: this,\n      dataIdFromObject: this.config.dataIdFromObject,\n      possibleTypes: this.config.possibleTypes,\n      typePolicies: this.config.typePolicies,\n    });\n\n    this.init();\n  }\n\n  private init() {\n    // Passing { resultCaching: false } in the InMemoryCache constructor options\n    // will completely disable dependency tracking, which will improve memory\n    // usage but worsen the performance of repeated reads.\n    const rootStore = (this.data = new EntityStore.Root({\n      policies: this.policies,\n      resultCaching: this.config.resultCaching,\n    }));\n\n    // When no optimistic writes are currently active, cache.optimisticData ===\n    // cache.data, so there are no additional layers on top of the actual data.\n    // When an optimistic update happens, this.optimisticData will become a\n    // linked list of EntityStore Layer objects that terminates with the\n    // original this.data cache object.\n    this.optimisticData = rootStore.stump;\n\n    this.resetResultCache();\n  }\n\n  private resetResultCache() {\n    const { fragments } = this.config;\n\n    this.addTypenameTransform.resetCache();\n    fragments?.resetCaches();\n\n    // The StoreWriter is mostly stateless and so doesn't really need to be\n    // reset, but it does need to have its writer.storeReader reference updated,\n    // so it's simpler to update this.storeWriter as well.\n    this.storeWriter = new StoreWriter(\n      this,\n      (this.storeReader = new StoreReader({ cache: this, fragments })),\n      fragments\n    );\n\n    this.maybeBroadcastWatch = wrap(\n      (c: Cache.WatchOptions, options?: BroadcastOptions) => {\n        return this.broadcastWatch(c, options);\n      },\n      {\n        max:\n          cacheSizes[\"inMemoryCache.maybeBroadcastWatch\"] ||\n          defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n        makeCacheKey: (c: Cache.WatchOptions) => {\n          // Return a cache key (thus enabling result caching) only if we're\n          // currently using a data store that can track cache dependencies.\n          const store = c.optimistic ? this.optimisticData : this.data;\n          if (supportsResultCaching(store)) {\n            const { optimistic, id, variables } = c;\n            return store.makeCacheKey(\n              c.query,\n              // Different watches can have the same query, optimistic\n              // status, rootId, and variables, but if their callbacks are\n              // different, the (identical) result needs to be delivered to\n              // each distinct callback. The easiest way to achieve that\n              // separation is to include c.callback in the cache key for\n              // maybeBroadcastWatch calls. See issue #5733.\n              c.callback,\n              canonicalStringify({ optimistic, id, variables })\n            );\n          }\n        },\n      }\n    );\n\n    // Since we have thrown away all the cached functions that depend on the\n    // CacheGroup dependencies maintained by EntityStore, we should also reset\n    // all CacheGroup dependency information.\n    new Set([this.data.group, this.optimisticData.group]).forEach((group) =>\n      group.resetCaching()\n    );\n  }\n\n  public restore(data: NormalizedCacheObject): this {\n    this.init();\n    // Since calling this.init() discards/replaces the entire StoreReader, along\n    // with the result caches it maintains, this.data.replace(data) won't have\n    // to bother deleting the old data.\n    if (data) this.data.replace(data);\n    return this;\n  }\n\n  public extract(optimistic: boolean = false): NormalizedCacheObject {\n    return (optimistic ? this.optimisticData : this.data).extract();\n  }\n\n  public read<TData = unknown>(\n    options: Cache.ReadOptions<TData, OperationVariables> & {\n      returnPartialData: true;\n    }\n  ): TData | DeepPartial<TData> | null;\n\n  public read<TData = unknown>(\n    options: Cache.ReadOptions<TData, OperationVariables>\n  ): TData | null;\n\n  public read<TData = unknown>(\n    options: Cache.ReadOptions<TData, OperationVariables>\n  ): TData | DeepPartial<TData> | null {\n    const {\n      // Since read returns data or null, without any additional metadata\n      // about whether/where there might have been missing fields, the\n      // default behavior cannot be returnPartialData = true (like it is\n      // for the diff method), since defaulting to true would violate the\n      // integrity of the T in the return type. However, partial data may\n      // be useful in some cases, so returnPartialData:true may be\n      // specified explicitly.\n      returnPartialData = false,\n    } = options;\n\n    return this.storeReader.diffQueryAgainstStore<TData>({\n      ...options,\n      store: options.optimistic ? this.optimisticData : this.data,\n      config: this.config,\n      returnPartialData,\n    }).result;\n  }\n\n  public write<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(options: Cache.WriteOptions<TData, TVariables>): Reference | undefined {\n    try {\n      ++this.txCount;\n      return this.storeWriter.writeToStore(this.data, options);\n    } finally {\n      if (!--this.txCount && options.broadcast !== false) {\n        this.broadcastWatches();\n      }\n    }\n  }\n\n  public modify<Entity extends Record<string, any> = Record<string, any>>(\n    options: Cache.ModifyOptions<Entity>\n  ): boolean {\n    if (hasOwn.call(options, \"id\") && !options.id) {\n      // To my knowledge, TypeScript does not currently provide a way to\n      // enforce that an optional property?:type must *not* be undefined\n      // when present. That ability would be useful here, because we want\n      // options.id to default to ROOT_QUERY only when no options.id was\n      // provided. If the caller attempts to pass options.id with a\n      // falsy/undefined value (perhaps because cache.identify failed), we\n      // should not assume the goal was to modify the ROOT_QUERY object.\n      // We could throw, but it seems natural to return false to indicate\n      // that nothing was modified.\n      return false;\n    }\n    const store =\n      (\n        options.optimistic // Defaults to false.\n      ) ?\n        this.optimisticData\n      : this.data;\n    try {\n      ++this.txCount;\n      return store.modify(options.id || \"ROOT_QUERY\", options.fields, false);\n    } finally {\n      if (!--this.txCount && options.broadcast !== false) {\n        this.broadcastWatches();\n      }\n    }\n  }\n\n  public diff<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(options: Cache.DiffOptions<TData, TVariables>): Cache.DiffResult<TData> {\n    return this.storeReader.diffQueryAgainstStore({\n      ...options,\n      store: options.optimistic ? this.optimisticData : this.data,\n      rootId: options.id || \"ROOT_QUERY\",\n      config: this.config,\n    });\n  }\n\n  public watch<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(watch: Cache.WatchOptions<TData, TVariables>): () => void {\n    if (!this.watches.size) {\n      // In case we previously called forgetCache(this) because\n      // this.watches became empty (see below), reattach this cache to any\n      // reactive variables on which it previously depended. It might seem\n      // paradoxical that we're able to recall something we supposedly\n      // forgot, but the point of calling forgetCache(this) is to silence\n      // useless broadcasts while this.watches is empty, and to allow the\n      // cache to be garbage collected. If, however, we manage to call\n      // recallCache(this) here, this cache object must not have been\n      // garbage collected yet, and should resume receiving updates from\n      // reactive variables, now that it has a watcher to notify.\n      recallCache(this);\n    }\n    this.watches.add(watch);\n    if (watch.immediate) {\n      this.maybeBroadcastWatch(watch);\n    }\n    return () => {\n      // Once we remove the last watch from this.watches, cache.broadcastWatches\n      // no longer does anything, so we preemptively tell the reactive variable\n      // system to exclude this cache from future broadcasts.\n      if (this.watches.delete(watch) && !this.watches.size) {\n        forgetCache(this);\n      }\n      // Remove this watch from the LRU cache managed by the\n      // maybeBroadcastWatch OptimisticWrapperFunction, to prevent memory\n      // leaks involving the closure of watch.callback.\n      this.maybeBroadcastWatch.forget(watch);\n    };\n  }\n\n  public gc(options?: {\n    // If true, also free non-essential result cache memory by bulk-releasing\n    // this.{store{Reader,Writer},maybeBroadcastWatch}. Defaults to false.\n    resetResultCache?: boolean;\n  }) {\n    canonicalStringify.reset();\n    print.reset();\n    const ids = this.optimisticData.gc();\n    if (options && !this.txCount && options.resetResultCache) {\n      this.resetResultCache();\n    }\n    return ids;\n  }\n\n  // Call this method to ensure the given root ID remains in the cache after\n  // garbage collection, along with its transitive child entities. Note that\n  // the cache automatically retains all directly written entities. By default,\n  // the retainment persists after optimistic updates are removed. Pass true\n  // for the optimistic argument if you would prefer for the retainment to be\n  // discarded when the top-most optimistic layer is removed. Returns the\n  // resulting (non-negative) retainment count.\n  public retain(rootId: string, optimistic?: boolean): number {\n    return (optimistic ? this.optimisticData : this.data).retain(rootId);\n  }\n\n  // Call this method to undo the effect of the retain method, above. Once the\n  // retainment count falls to zero, the given ID will no longer be preserved\n  // during garbage collection, though it may still be preserved by other safe\n  // entities that refer to it. Returns the resulting (non-negative) retainment\n  // count, in case that's useful.\n  public release(rootId: string, optimistic?: boolean): number {\n    return (optimistic ? this.optimisticData : this.data).release(rootId);\n  }\n\n  // Returns the canonical ID for a given StoreObject, obeying typePolicies\n  // and keyFields (and dataIdFromObject, if you still use that). At minimum,\n  // the object must contain a __typename and any primary key fields required\n  // to identify entities of that type. If you pass a query result object, be\n  // sure that none of the primary key fields have been renamed by aliasing.\n  // If you pass a Reference object, its __ref ID string will be returned.\n  public identify(object: StoreObject | Reference): string | undefined {\n    if (isReference(object)) return object.__ref;\n    try {\n      return this.policies.identify(object)[0];\n    } catch (e) {\n      invariant.warn(e);\n    }\n  }\n\n  public evict(options: Cache.EvictOptions): boolean {\n    if (!options.id) {\n      if (hasOwn.call(options, \"id\")) {\n        // See comment in modify method about why we return false when\n        // options.id exists but is falsy/undefined.\n        return false;\n      }\n      options = { ...options, id: \"ROOT_QUERY\" };\n    }\n    try {\n      // It's unlikely that the eviction will end up invoking any other\n      // cache update operations while it's running, but {in,de}crementing\n      // this.txCount still seems like a good idea, for uniformity with\n      // the other update methods.\n      ++this.txCount;\n      // Pass this.data as a limit on the depth of the eviction, so evictions\n      // during optimistic updates (when this.data is temporarily set equal to\n      // this.optimisticData) do not escape their optimistic Layer.\n      return this.optimisticData.evict(options, this.data);\n    } finally {\n      if (!--this.txCount && options.broadcast !== false) {\n        this.broadcastWatches();\n      }\n    }\n  }\n\n  public reset(options?: Cache.ResetOptions): Promise<void> {\n    this.init();\n\n    canonicalStringify.reset();\n\n    if (options && options.discardWatches) {\n      // Similar to what happens in the unsubscribe function returned by\n      // cache.watch, applied to all current watches.\n      this.watches.forEach((watch) => this.maybeBroadcastWatch.forget(watch));\n      this.watches.clear();\n      forgetCache(this);\n    } else {\n      // Calling this.init() above unblocks all maybeBroadcastWatch caching, so\n      // this.broadcastWatches() triggers a broadcast to every current watcher\n      // (letting them know their data is now missing). This default behavior is\n      // convenient because it means the watches do not have to be manually\n      // reestablished after resetting the cache. To prevent this broadcast and\n      // cancel all watches, pass true for options.discardWatches.\n      this.broadcastWatches();\n    }\n\n    return Promise.resolve();\n  }\n\n  public removeOptimistic(idToRemove: string) {\n    const newOptimisticData = this.optimisticData.removeLayer(idToRemove);\n    if (newOptimisticData !== this.optimisticData) {\n      this.optimisticData = newOptimisticData;\n      this.broadcastWatches();\n    }\n  }\n\n  private txCount = 0;\n\n  /**\n   * {@inheritDoc @apollo/client/cache!ApolloCache#batch:member(1)}\n   */\n  public batch<TUpdateResult>(\n    options: Cache.BatchOptions<InMemoryCache, TUpdateResult>\n  ): TUpdateResult {\n    const {\n      update,\n      optimistic = true,\n      removeOptimistic,\n      onWatchUpdated,\n    } = options;\n\n    let updateResult: TUpdateResult;\n    const perform = (layer?: EntityStore): TUpdateResult => {\n      const { data, optimisticData } = this;\n      ++this.txCount;\n      if (layer) {\n        this.data = this.optimisticData = layer;\n      }\n      try {\n        return (updateResult = update(this));\n      } finally {\n        --this.txCount;\n        this.data = data;\n        this.optimisticData = optimisticData;\n      }\n    };\n\n    const alreadyDirty = new Set<Cache.WatchOptions>();\n\n    if (onWatchUpdated && !this.txCount) {\n      // If an options.onWatchUpdated callback is provided, we want to call it\n      // with only the Cache.WatchOptions objects affected by options.update,\n      // but there might be dirty watchers already waiting to be broadcast that\n      // have nothing to do with the update. To prevent including those watchers\n      // in the post-update broadcast, we perform this initial broadcast to\n      // collect the dirty watchers, so we can re-dirty them later, after the\n      // post-update broadcast, allowing them to receive their pending\n      // broadcasts the next time broadcastWatches is called, just as they would\n      // if we never called cache.batch.\n      this.broadcastWatches({\n        ...options,\n        onWatchUpdated(watch) {\n          alreadyDirty.add(watch);\n          return false;\n        },\n      });\n    }\n\n    if (typeof optimistic === \"string\") {\n      // Note that there can be multiple layers with the same optimistic ID.\n      // When removeOptimistic(id) is called for that id, all matching layers\n      // will be removed, and the remaining layers will be reapplied.\n      this.optimisticData = this.optimisticData.addLayer(optimistic, perform);\n    } else if (optimistic === false) {\n      // Ensure both this.data and this.optimisticData refer to the root\n      // (non-optimistic) layer of the cache during the update. Note that\n      // this.data could be a Layer if we are currently executing an optimistic\n      // update function, but otherwise will always be an EntityStore.Root\n      // instance.\n      perform(this.data);\n    } else {\n      // Otherwise, leave this.data and this.optimisticData unchanged and run\n      // the update with broadcast batching.\n      perform();\n    }\n\n    if (typeof removeOptimistic === \"string\") {\n      this.optimisticData = this.optimisticData.removeLayer(removeOptimistic);\n    }\n\n    // Note: if this.txCount > 0, then alreadyDirty.size === 0, so this code\n    // takes the else branch and calls this.broadcastWatches(options), which\n    // does nothing when this.txCount > 0.\n    if (onWatchUpdated && alreadyDirty.size) {\n      this.broadcastWatches({\n        ...options,\n        onWatchUpdated(watch, diff) {\n          const result = onWatchUpdated.call(this, watch, diff);\n          if (result !== false) {\n            // Since onWatchUpdated did not return false, this diff is\n            // about to be broadcast to watch.callback, so we don't need\n            // to re-dirty it with the other alreadyDirty watches below.\n            alreadyDirty.delete(watch);\n          }\n          return result;\n        },\n      });\n      // Silently re-dirty any watches that were already dirty before the update\n      // was performed, and were not broadcast just now.\n      if (alreadyDirty.size) {\n        alreadyDirty.forEach((watch) => this.maybeBroadcastWatch.dirty(watch));\n      }\n    } else {\n      // If alreadyDirty is empty or we don't have an onWatchUpdated\n      // function, we don't need to go to the trouble of wrapping\n      // options.onWatchUpdated.\n      this.broadcastWatches(options);\n    }\n\n    return updateResult!;\n  }\n\n  public performTransaction(\n    update: (cache: InMemoryCache) => any,\n    optimisticId?: string | null\n  ) {\n    return this.batch({\n      update,\n      optimistic: optimisticId || optimisticId !== null,\n    });\n  }\n\n  public transformDocument(document: DocumentNode): DocumentNode {\n    return this.addTypenameTransform.transformDocument(\n      this.addFragmentsToDocument(document)\n    );\n  }\n\n  public fragmentMatches(\n    fragment: InlineFragmentNode | FragmentDefinitionNode,\n    typename: string\n  ): boolean {\n    return this.policies.fragmentMatches(fragment, typename);\n  }\n\n  public lookupFragment(fragmentName: string): FragmentDefinitionNode | null {\n    return this.config.fragments?.lookup(fragmentName) || null;\n  }\n\n  public resolvesClientField(typename: string, fieldName: string): boolean {\n    return !!this.policies.getReadFunction(typename, fieldName);\n  }\n\n  protected broadcastWatches(options?: BroadcastOptions) {\n    if (!this.txCount) {\n      const prevOnAfter = this.onAfterBroadcast;\n      const callbacks = new Set<() => void>();\n      this.onAfterBroadcast = (cb: () => void) => {\n        callbacks.add(cb);\n      };\n      try {\n        this.watches.forEach((c) => this.maybeBroadcastWatch(c, options));\n        callbacks.forEach((cb) => cb());\n      } finally {\n        this.onAfterBroadcast = prevOnAfter;\n      }\n    }\n  }\n\n  private addFragmentsToDocument(document: DocumentNode) {\n    const { fragments } = this.config;\n    return fragments ? fragments.transform(document) : document;\n  }\n\n  // This method is wrapped by maybeBroadcastWatch, which is called by\n  // broadcastWatches, so that we compute and broadcast results only when\n  // the data that would be broadcast might have changed. It would be\n  // simpler to check for changes after recomputing a result but before\n  // broadcasting it, but this wrapping approach allows us to skip both\n  // the recomputation and the broadcast, in most cases.\n  private broadcastWatch(c: Cache.WatchOptions, options?: BroadcastOptions) {\n    const { lastDiff } = c;\n\n    // Both WatchOptions and DiffOptions extend ReadOptions, and DiffOptions\n    // currently requires no additional properties, so we can use c (a\n    // WatchOptions object) as DiffOptions, without having to allocate a new\n    // object, and without having to enumerate the relevant properties (query,\n    // variables, etc.) explicitly. There will be some additional properties\n    // (lastDiff, callback, etc.), but cache.diff ignores them.\n    const diff = this.diff<any>(c);\n\n    if (options) {\n      if (c.optimistic && typeof options.optimistic === \"string\") {\n        diff.fromOptimisticTransaction = true;\n      }\n\n      if (\n        options.onWatchUpdated &&\n        options.onWatchUpdated.call(this, c, diff, lastDiff) === false\n      ) {\n        // Returning false from the onWatchUpdated callback will prevent\n        // calling c.callback(diff) for this watcher.\n        return;\n      }\n    }\n\n    if (!lastDiff || !equal(lastDiff.result, diff.result)) {\n      c.callback((c.lastDiff = diff), lastDiff);\n    }\n  }\n\n  /**\n   * @experimental\n   * @internal\n   * This is not a stable API - it is used in development builds to expose\n   * information to the DevTools.\n   * Use at your own risk!\n   */\n  public declare getMemoryInternals?: typeof getInMemoryCacheMemoryInternals;\n}\n\nif (__DEV__) {\n  InMemoryCache.prototype.getMemoryInternals = getInMemoryCacheMemoryInternals;\n}\n"
  },
  {
    "path": "src/cache/inmemory/key-extractor.ts",
    "content": "import {\n  argumentsObjectFromField,\n  DeepMerger,\n  isArray,\n  isNonEmptyArray,\n  isNonNullObject,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { hasOwn } from \"./helpers.js\";\nimport type {\n  KeyArgsFunction,\n  KeyFieldsFunction,\n  KeySpecifier,\n} from \"./policies.js\";\n\n// Mapping from JSON-encoded KeySpecifier strings to associated information.\nconst specifierInfoCache: Record<\n  string,\n  {\n    paths?: string[][];\n    keyFieldsFn?: KeyFieldsFunction;\n    keyArgsFn?: KeyArgsFunction;\n  }\n> = {};\n\nfunction lookupSpecifierInfo(spec: KeySpecifier) {\n  // It's safe to encode KeySpecifier arrays with JSON.stringify, since they're\n  // just arrays of strings or nested KeySpecifier arrays, and the order of the\n  // array elements is important (and suitably preserved by JSON.stringify).\n  const cacheKey = JSON.stringify(spec);\n  return specifierInfoCache[cacheKey] || (specifierInfoCache[cacheKey] = {});\n}\n\nexport function keyFieldsFnFromSpecifier(\n  specifier: KeySpecifier\n): KeyFieldsFunction {\n  const info = lookupSpecifierInfo(specifier);\n\n  return (\n    info.keyFieldsFn ||\n    (info.keyFieldsFn = (object, context) => {\n      const extract: typeof extractKey = (from, key) =>\n        context.readField(key, from);\n\n      const keyObject = (context.keyObject = collectSpecifierPaths(\n        specifier,\n        (schemaKeyPath) => {\n          let extracted = extractKeyPath(\n            context.storeObject,\n            schemaKeyPath,\n            // Using context.readField to extract paths from context.storeObject\n            // allows the extraction to see through Reference objects and respect\n            // custom read functions.\n            extract\n          );\n\n          if (\n            extracted === void 0 &&\n            object !== context.storeObject &&\n            hasOwn.call(object, schemaKeyPath[0])\n          ) {\n            // If context.storeObject fails to provide a value for the requested\n            // path, fall back to the raw result object, if it has a top-level key\n            // matching the first key in the path (schemaKeyPath[0]). This allows\n            // key fields included in the written data to be saved in the cache\n            // even if they are not selected explicitly in context.selectionSet.\n            // Not being mentioned by context.selectionSet is convenient here,\n            // since it means these extra fields cannot be affected by field\n            // aliasing, which is why we can use extractKey instead of\n            // context.readField for this extraction.\n            extracted = extractKeyPath(object, schemaKeyPath, extractKey);\n          }\n\n          invariant(\n            extracted !== void 0,\n            `Missing field '%s' while extracting keyFields from %s`,\n            schemaKeyPath.join(\".\"),\n            object\n          );\n\n          return extracted;\n        }\n      ));\n\n      return `${context.typename}:${JSON.stringify(keyObject)}`;\n    })\n  );\n}\n\n// The keyArgs extraction process is roughly analogous to keyFields extraction,\n// but there are no aliases involved, missing fields are tolerated (by merely\n// omitting them from the key), and drawing from field.directives or variables\n// is allowed (in addition to drawing from the field's arguments object).\n// Concretely, these differences mean passing a different key path extractor\n// function to collectSpecifierPaths, reusing the shared extractKeyPath helper\n// wherever possible.\nexport function keyArgsFnFromSpecifier(\n  specifier: KeySpecifier\n): KeyArgsFunction {\n  const info = lookupSpecifierInfo(specifier);\n\n  return (\n    info.keyArgsFn ||\n    (info.keyArgsFn = (args, { field, variables, fieldName }) => {\n      const collected = collectSpecifierPaths(specifier, (keyPath) => {\n        const firstKey = keyPath[0];\n        const firstChar = firstKey.charAt(0);\n\n        if (firstChar === \"@\") {\n          if (field && isNonEmptyArray(field.directives)) {\n            const directiveName = firstKey.slice(1);\n            // If the directive appears multiple times, only the first\n            // occurrence's arguments will be used. TODO Allow repetition?\n            // TODO Cache this work somehow, a la aliasMap?\n            const d = field.directives.find(\n              (d) => d.name.value === directiveName\n            );\n            // Fortunately argumentsObjectFromField works for DirectiveNode!\n            const directiveArgs = d && argumentsObjectFromField(d, variables);\n            // For directives without arguments (d defined, but directiveArgs ===\n            // null), the presence or absence of the directive still counts as\n            // part of the field key, so we return null in those cases. If no\n            // directive with this name was found for this field (d undefined and\n            // thus directiveArgs undefined), we return undefined, which causes\n            // this value to be omitted from the key object returned by\n            // collectSpecifierPaths.\n            return (\n              directiveArgs &&\n              extractKeyPath(\n                directiveArgs,\n                // If keyPath.length === 1, this code calls extractKeyPath with an\n                // empty path, which works because it uses directiveArgs as the\n                // extracted value.\n                keyPath.slice(1)\n              )\n            );\n          }\n          // If the key started with @ but there was no corresponding directive,\n          // we want to omit this value from the key object, not fall through to\n          // treating @whatever as a normal argument name.\n          return;\n        }\n\n        if (firstChar === \"$\") {\n          const variableName = firstKey.slice(1);\n          if (variables && hasOwn.call(variables, variableName)) {\n            const varKeyPath = keyPath.slice(0);\n            varKeyPath[0] = variableName;\n            return extractKeyPath(variables, varKeyPath);\n          }\n          // If the key started with $ but there was no corresponding variable, we\n          // want to omit this value from the key object, not fall through to\n          // treating $whatever as a normal argument name.\n          return;\n        }\n\n        if (args) {\n          return extractKeyPath(args, keyPath);\n        }\n      });\n\n      const suffix = JSON.stringify(collected);\n\n      // If no arguments were passed to this field, and it didn't have any other\n      // field key contributions from directives or variables, hide the empty\n      // :{} suffix from the field key. However, a field passed no arguments can\n      // still end up with a non-empty :{...} suffix if its key configuration\n      // refers to directives or variables.\n      if (args || suffix !== \"{}\") {\n        fieldName += \":\" + suffix;\n      }\n\n      return fieldName;\n    })\n  );\n}\n\nexport function collectSpecifierPaths(\n  specifier: KeySpecifier,\n  extractor: (path: string[]) => any\n): Record<string, any> {\n  // For each path specified by specifier, invoke the extractor, and repeatedly\n  // merge the results together, with appropriate ancestor context.\n  const merger = new DeepMerger();\n  return getSpecifierPaths(specifier).reduce((collected, path) => {\n    let toMerge = extractor(path);\n    if (toMerge !== void 0) {\n      // This path is not expected to contain array indexes, so the toMerge\n      // reconstruction will not contain arrays. TODO Fix this?\n      for (let i = path.length - 1; i >= 0; --i) {\n        toMerge = { [path[i]]: toMerge };\n      }\n      collected = merger.merge(collected, toMerge);\n    }\n    return collected;\n  }, {});\n}\n\nexport function getSpecifierPaths(spec: KeySpecifier): string[][] {\n  const info = lookupSpecifierInfo(spec);\n\n  if (!info.paths) {\n    const paths: string[][] = (info.paths = []);\n    const currentPath: string[] = [];\n\n    spec.forEach((s, i) => {\n      if (isArray(s)) {\n        getSpecifierPaths(s).forEach((p) => paths.push(currentPath.concat(p)));\n        currentPath.length = 0;\n      } else {\n        currentPath.push(s);\n        if (!isArray(spec[i + 1])) {\n          paths.push(currentPath.slice(0));\n          currentPath.length = 0;\n        }\n      }\n    });\n  }\n\n  return info.paths!;\n}\n\nfunction extractKey<TObj extends Record<string, any>, TKey extends string>(\n  object: TObj,\n  key: TKey\n): TObj[TKey] | undefined {\n  return object[key];\n}\n\nexport function extractKeyPath(\n  object: Record<string, any>,\n  path: string[],\n  extract?: typeof extractKey\n): any {\n  // For each key in path, extract the corresponding child property from obj,\n  // flattening arrays if encountered (uncommon for keyFields and keyArgs, but\n  // possible). The final result of path.reduce is normalized so unexpected leaf\n  // objects have their keys safely sorted. That final result is difficult to\n  // type as anything other than any. You're welcome to try to improve the\n  // return type, but keep in mind extractKeyPath is not a public function\n  // (exported only for testing), so the effort may not be worthwhile unless the\n  // limited set of actual callers (see above) pass arguments that TypeScript\n  // can statically type. If we know only that path is some array of strings\n  // (and not, say, a specific tuple of statically known strings), any (or\n  // possibly unknown) is the honest answer.\n  extract = extract || extractKey;\n  return normalize(\n    path.reduce(function reducer(obj, key): any {\n      return isArray(obj) ?\n          obj.map((child) => reducer(child, key))\n        : obj && extract!(obj, key);\n    }, object)\n  );\n}\n\nfunction normalize<T>(value: T): T {\n  // Usually the extracted value will be a scalar value, since most primary\n  // key fields are scalar, but just in case we get an object or an array, we\n  // need to do some normalization of the order of (nested) keys.\n  if (isNonNullObject(value)) {\n    if (isArray(value)) {\n      return value.map(normalize) as any;\n    }\n    return collectSpecifierPaths(Object.keys(value).sort(), (path) =>\n      extractKeyPath(value, path)\n    ) as T;\n  }\n  return value;\n}\n"
  },
  {
    "path": "src/cache/inmemory/policies.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type {\n  FieldNode,\n  FragmentDefinitionNode,\n  InlineFragmentNode,\n  SelectionSetNode,\n} from \"graphql\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport type { Incremental } from \"@apollo/client/incremental\";\nimport { disableWarningsSlot } from \"@apollo/client/masking\";\nimport type {\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\nimport { isReference } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { FragmentMap } from \"@apollo/client/utilities/internal\";\nimport { streamInfoSymbol } from \"@apollo/client/utilities/internal\";\nimport {\n  argumentsObjectFromField,\n  getStoreKeyName,\n  isArray,\n  isNonNullObject,\n  storeKeyNameFromField,\n  stringifyForDisplay,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nimport type {\n  CanReadFunction,\n  FieldSpecifier,\n  ReadFieldFunction,\n  ReadFieldOptions,\n  SafeReadonly,\n  ToReferenceFunction,\n} from \"../core/types/common.js\";\n\nimport {\n  defaultDataIdFromObject,\n  fieldNameFromStoreName,\n  hasOwn,\n  selectionSetMatchesResult,\n  storeValueIsStoreObject,\n  TypeOrFieldNameRegExp,\n} from \"./helpers.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport {\n  keyArgsFnFromSpecifier,\n  keyFieldsFnFromSpecifier,\n} from \"./key-extractor.js\";\nimport { cacheSlot } from \"./reactiveVars.js\";\nimport type {\n  IdGetter,\n  MergeInfo,\n  NormalizedCache,\n  ReadMergeModifyContext,\n} from \"./types.js\";\nimport type { WriteContext } from \"./writeToStore.js\";\n\nexport type TypePolicies = {\n  [__typename: string]: TypePolicy;\n};\n\n// TypeScript 3.7 will allow recursive type aliases, so this should work:\n// type KeySpecifier = (string | KeySpecifier)[]\nexport type KeySpecifier = ReadonlyArray<string | KeySpecifier>;\n\nexport type KeyFieldsContext = {\n  // The __typename of the incoming object, even if the __typename field was\n  // aliased to another name in the raw result object. May be undefined when\n  // dataIdFromObject is called for objects without __typename fields.\n  typename: string | undefined;\n\n  // The object to be identified, after processing to remove aliases and\n  // normalize identifiable child objects with references.\n  storeObject: StoreObject;\n\n  // Handy tool for reading additional fields from context.storeObject, either\n  // readField(\"fieldName\") to read storeObject[fieldName], or readField(\"name\",\n  // objectOrReference) to read from another object or Reference. If you read a\n  // field with a read function, that function will be invoked.\n  readField: ReadFieldFunction;\n\n  // If you are writing a custom keyFields function, and you plan to use the raw\n  // result object passed as the first argument, you may also need access to the\n  // selection set and available fragments for this object, just in case any\n  // fields have aliases. Since this logic is tricky to get right, and these\n  // context properties are not even always provided (for example, they are\n  // omitted when calling cache.identify(object), where object is assumed to be\n  // a StoreObject), we recommend you use context.storeObject (which has already\n  // been de-aliased) and context.readField (which can read from references as\n  // well as objects) instead of the raw result object in your keyFields\n  // functions, or just rely on the internal implementation of keyFields:[...]\n  // syntax to get these details right for you.\n  selectionSet?: SelectionSetNode;\n  fragmentMap?: FragmentMap;\n\n  // Internal. May be set by the KeyFieldsFunction to report fields that were\n  // involved in computing the ID. Never passed in by the caller.\n  keyObject?: Record<string, any>;\n};\n\nexport type KeyFieldsFunction = (\n  object: Readonly<StoreObject>,\n  context: KeyFieldsContext\n) => KeySpecifier | false | ReturnType<IdGetter>;\n\ntype KeyFieldsResult = Exclude<ReturnType<KeyFieldsFunction>, KeySpecifier>;\n\n// TODO Should TypePolicy be a generic type, with a TObject or TEntity\n// type parameter?\nexport type TypePolicy = {\n  // Allows defining the primary key fields for this type, either using an\n  // array of field names or a function that returns an arbitrary string.\n  keyFields?: KeySpecifier | KeyFieldsFunction | false;\n\n  // Allows defining a merge function (or merge:true/false shorthand) to\n  // be used for merging objects of this type wherever they appear, unless\n  // the parent field also defines a merge function/boolean (that is,\n  // parent field merge functions take precedence over type policy merge\n  // functions). In many cases, defining merge:true for a given type\n  // policy can save you from specifying merge:true for all the field\n  // policies where that type might be encountered.\n  merge?: FieldMergeFunction | boolean;\n\n  // In the rare event that your schema happens to use a different\n  // __typename for the root Query, Mutation, and/or Schema types, you can\n  // express your deviant preferences by enabling one of these options.\n  queryType?: true;\n  mutationType?: true;\n  subscriptionType?: true;\n\n  fields?: {\n    [fieldName: string]: FieldPolicy<any> | FieldReadFunction<any>;\n  };\n};\n\nexport type KeyArgsFunction = (\n  args: Record<string, any> | null,\n  context: {\n    typename: string;\n    fieldName: string;\n    field: FieldNode | null;\n    variables?: Record<string, any>;\n  }\n) => KeySpecifier | false | ReturnType<IdGetter>;\n\nexport type FieldPolicy<\n  // The internal representation used to store the field's data in the\n  // cache. Must be JSON-serializable if you plan to serialize the result\n  // of cache.extract() using JSON.\n  TExisting = any,\n  // The type of the incoming parameter passed to the merge function,\n  // typically matching the GraphQL response format, but with Reference\n  // objects substituted for any identifiable child objects. Often the\n  // same as TExisting, but not necessarily.\n  TIncoming = TExisting,\n  // The type that the read function actually returns, using TExisting\n  // data and options.args as input. Usually the same as TIncoming.\n  TReadResult = TIncoming,\n  // Allows FieldReadFunctionOptions definition to be overwritten by the\n  // developer\n  TReadOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions,\n  // Allows FieldMergeFunctionOptions definition to be overwritten by the\n  // developer\n  TMergeOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions,\n> = {\n  keyArgs?: KeySpecifier | KeyArgsFunction | false;\n  read?: FieldReadFunction<TExisting, TReadResult, TReadOptions>;\n  merge?: FieldMergeFunction<TExisting, TIncoming, TMergeOptions> | boolean;\n};\n\nexport type StorageType = Record<string, any>;\n\nfunction argsFromFieldSpecifier(spec: FieldSpecifier) {\n  return (\n    spec.args !== void 0 ? spec.args\n    : spec.field ? argumentsObjectFromField(spec.field, spec.variables)\n    : null\n  );\n}\n\nexport interface FieldFunctionOptions<\n  TArgs = Record<string, any>,\n  TVariables extends OperationVariables = Record<string, any>,\n> {\n  args: TArgs | null;\n\n  // The name of the field, equal to options.field.name.value when\n  // options.field is available. Useful if you reuse the same function for\n  // multiple fields, and you need to know which field you're currently\n  // processing. Always a string, even when options.field is null.\n  fieldName: string;\n\n  // The full field key used internally, including serialized key arguments.\n  storeFieldName: string;\n\n  // The FieldNode object used to read this field. Useful if you need to\n  // know about other attributes of the field, such as its directives. This\n  // option will be null when a string was passed to options.readField.\n  field: FieldNode | null;\n\n  variables?: TVariables;\n\n  // Utilities for dealing with { __ref } objects.\n  isReference: typeof isReference;\n  toReference: ToReferenceFunction;\n\n  // A handy place to put field-specific data that you want to survive\n  // across multiple read function calls. Useful for field-level caching,\n  // if your read function does any expensive work.\n  storage: StorageType;\n\n  cache: InMemoryCache;\n\n  // Helper function for reading other fields within the current object.\n  // If a foreign object or reference is provided, the field will be read\n  // from that object instead of the current object, so this function can\n  // be used (together with isReference) to examine the cache outside the\n  // current object. If a FieldNode is passed instead of a string, and\n  // that FieldNode has arguments, the same options.variables will be used\n  // to compute the argument values. Note that this function will invoke\n  // custom read functions for other fields, if defined. Always returns\n  // immutable data (enforced with Object.freeze in development).\n  readField: ReadFieldFunction;\n\n  // Returns true for non-normalized StoreObjects and non-dangling\n  // References, indicating that readField(name, objOrRef) has a chance of\n  // working. Useful for filtering out dangling references from lists.\n  canRead: CanReadFunction;\n\n  // Instead of just merging objects with { ...existing, ...incoming }, this\n  // helper function can be used to merge objects in a way that respects any\n  // custom merge functions defined for their fields.\n  mergeObjects: MergeObjectsFunction;\n}\n\nexport interface FieldReadFunctionOptions<\n  TArgs = Record<string, any>,\n  TVariables extends OperationVariables = Record<string, any>,\n> extends FieldFunctionOptions<TArgs, TVariables> {}\n\nexport interface FieldMergeFunctionOptions<\n  TArgs = Record<string, any>,\n  TVariables extends OperationVariables = Record<string, any>,\n> extends FieldFunctionOptions<TArgs, TVariables> {\n  /**\n   * Any `extensions` provided when writing the cache.\n   */\n  extensions: Record<string, unknown> | undefined;\n\n  /**\n   * Details about the field when the `@stream` directive is used. Useful with\n   * custom merge functions to determine how to merge existing cache data with\n   * the incoming stream array.\n   *\n   * This field is only available in `merge` functions when the `@stream`\n   * directive is used on the field.\n   *\n   * > [!NOTE]\n   * > This field is not available when using the `Defer20220824Handler`\n   */\n  streamFieldInfo?: Incremental.StreamFieldInfo;\n\n  /**\n   * The same value as the `existing` argument, but preserves the `existing`\n   * value on refetches when `refetchWritePolicy` is `overwrite` (the default).\n   */\n  existingData: unknown;\n}\n\ntype MergeObjectsFunction = <T extends StoreObject | Reference>(\n  existing: T,\n  incoming: T\n) => T;\n\nexport type FieldReadFunction<\n  TExisting = any,\n  TReadResult = TExisting,\n  TOptions extends FieldReadFunctionOptions = FieldReadFunctionOptions,\n> = (\n  // When reading a field, one often needs to know about any existing\n  // value stored for that field. If the field is read before any value\n  // has been written to the cache, this existing parameter will be\n  // undefined, which makes it easy to use a default parameter expression\n  // to supply the initial value. This parameter is positional (rather\n  // than one of the named options) because that makes it possible for the\n  // developer to annotate it with a type, without also having to provide\n  // a whole new type for the options object.\n  existing: SafeReadonly<TExisting> | undefined,\n  options: TOptions\n) => TReadResult | undefined;\n\nexport type FieldMergeFunction<\n  TExisting = any,\n  TIncoming = TExisting,\n  // Passing the whole FieldFunctionOptions makes the current definition\n  // independent from its implementation\n  TOptions extends FieldMergeFunctionOptions = FieldMergeFunctionOptions,\n> = (\n  existing: SafeReadonly<TExisting> | undefined,\n  // The incoming parameter needs to be positional as well, for the same\n  // reasons discussed in FieldReadFunction above.\n  incoming: SafeReadonly<TIncoming>,\n  options: TOptions\n) => SafeReadonly<TExisting>;\n\nconst nullKeyFieldsFn: KeyFieldsFunction = () => void 0;\nconst simpleKeyArgsFn: KeyArgsFunction = (_args, context) => context.fieldName;\n\n// These merge functions can be selected by specifying merge:true or\n// merge:false in a field policy.\nconst mergeTrueFn: FieldMergeFunction<any> = (\n  existing,\n  incoming,\n  { mergeObjects }\n) => mergeObjects(existing, incoming);\nconst mergeFalseFn: FieldMergeFunction<any> = (_, incoming) => incoming;\n\nexport const defaultStreamFieldMergeFn: FieldMergeFunction<Array<any>> = (\n  existing,\n  incoming,\n  { streamFieldInfo, existingData }\n) => {\n  if (!existing && !existingData) {\n    return incoming;\n  }\n\n  const results = [];\n  const previous = existing ?? (existingData as any[]);\n  const length =\n    streamFieldInfo?.isLastChunk ?\n      incoming.length\n    : Math.max(previous.length, incoming.length);\n\n  for (let i = 0; i < length; i++) {\n    results[i] = incoming[i] === undefined ? previous[i] : incoming[i];\n  }\n\n  return results;\n};\n\nexport type PossibleTypesMap = {\n  [supertype: string]: string[];\n};\n\ntype InternalFieldPolicy = {\n  typename: string;\n  keyFn?: KeyArgsFunction;\n  read?: FieldReadFunction<any>;\n  merge?: FieldMergeFunction<any>;\n};\n\nexport class Policies {\n  private typePolicies: {\n    [__typename: string]: {\n      keyFn?: KeyFieldsFunction;\n      merge?: FieldMergeFunction<any>;\n      fields: {\n        [fieldName: string]: InternalFieldPolicy;\n      };\n    };\n  } = {};\n\n  private toBeAdded: {\n    [__typename: string]: TypePolicy[];\n  } = {};\n\n  // Map from subtype names to sets of supertype names. Note that this\n  // representation inverts the structure of possibleTypes (whose keys are\n  // supertypes and whose values are arrays of subtypes) because it tends\n  // to be much more efficient to search upwards than downwards.\n  private supertypeMap = new Map<string, Set<string>>();\n\n  // Any fuzzy subtypes specified by possibleTypes will be converted to\n  // RegExp objects and recorded here. Every key of this map can also be\n  // found in supertypeMap. In many cases this Map will be empty, which\n  // means no fuzzy subtype checking will happen in fragmentMatches.\n  private fuzzySubtypes = new Map<string, RegExp>();\n\n  public readonly cache: InMemoryCache;\n\n  public readonly rootIdsByTypename: Record<string, string> = {};\n  public readonly rootTypenamesById: Record<string, string> = {};\n\n  public readonly usingPossibleTypes = false;\n\n  constructor(\n    private config: {\n      cache: InMemoryCache;\n      dataIdFromObject?: KeyFieldsFunction;\n      possibleTypes?: PossibleTypesMap;\n      typePolicies?: TypePolicies;\n    }\n  ) {\n    this.config = {\n      dataIdFromObject: defaultDataIdFromObject,\n      ...config,\n    };\n\n    this.cache = this.config.cache;\n\n    this.setRootTypename(\"Query\");\n    this.setRootTypename(\"Mutation\");\n    this.setRootTypename(\"Subscription\");\n\n    if (config.possibleTypes) {\n      this.addPossibleTypes(config.possibleTypes);\n    }\n\n    if (config.typePolicies) {\n      this.addTypePolicies(config.typePolicies);\n    }\n  }\n\n  public identify(\n    object: StoreObject,\n    partialContext?: Partial<KeyFieldsContext>\n  ): [string?, StoreObject?] {\n    const policies = this;\n\n    const typename =\n      (partialContext &&\n        (partialContext.typename || partialContext.storeObject?.__typename)) ||\n      object.__typename;\n\n    // It should be possible to write root Query fields with writeFragment,\n    // using { __typename: \"Query\", ... } as the data, but it does not make\n    // sense to allow the same identification behavior for the Mutation and\n    // Subscription types, since application code should never be writing\n    // directly to (or reading directly from) those root objects.\n    if (typename === this.rootTypenamesById.ROOT_QUERY) {\n      return [\"ROOT_QUERY\"];\n    }\n\n    // Default context.storeObject to object if not otherwise provided.\n    const storeObject =\n      (partialContext && partialContext.storeObject) || object;\n\n    const context: KeyFieldsContext = {\n      ...partialContext,\n      typename,\n      storeObject,\n      readField:\n        (partialContext && partialContext.readField) ||\n        (((...args) => {\n          const options = normalizeReadFieldOptions(args, storeObject);\n          return policies.readField(options, {\n            store: policies.cache[\"data\"],\n            variables: options.variables,\n          });\n        }) satisfies ReadFieldFunction),\n    };\n\n    let id: KeyFieldsResult;\n\n    const policy = typename && this.getTypePolicy(typename);\n    let keyFn = (policy && policy.keyFn) || this.config.dataIdFromObject;\n\n    disableWarningsSlot.withValue(true, () => {\n      while (keyFn) {\n        const specifierOrId = keyFn({ ...object, ...storeObject }, context);\n        if (isArray(specifierOrId)) {\n          keyFn = keyFieldsFnFromSpecifier(specifierOrId);\n        } else {\n          id = specifierOrId;\n          break;\n        }\n      }\n    });\n\n    id = id ? String(id) : void 0;\n    return context.keyObject ? [id, context.keyObject] : [id];\n  }\n\n  public addTypePolicies(typePolicies: TypePolicies) {\n    Object.keys(typePolicies).forEach((typename) => {\n      const { queryType, mutationType, subscriptionType, ...incoming } =\n        typePolicies[typename];\n\n      // Though {query,mutation,subscription}Type configurations are rare,\n      // it's important to call setRootTypename as early as possible,\n      // since these configurations should apply consistently for the\n      // entire lifetime of the cache. Also, since only one __typename can\n      // qualify as one of these root types, these three properties cannot\n      // be inherited, unlike the rest of the incoming properties. That\n      // restriction is convenient, because the purpose of this.toBeAdded\n      // is to delay the processing of type/field policies until the first\n      // time they're used, allowing policies to be added in any order as\n      // long as all relevant policies (including policies for supertypes)\n      // have been added by the time a given policy is used for the first\n      // time. In other words, since inheritance doesn't matter for these\n      // properties, there's also no need to delay their processing using\n      // the this.toBeAdded queue.\n      if (queryType) this.setRootTypename(\"Query\", typename);\n      if (mutationType) this.setRootTypename(\"Mutation\", typename);\n      if (subscriptionType) this.setRootTypename(\"Subscription\", typename);\n\n      if (hasOwn.call(this.toBeAdded, typename)) {\n        this.toBeAdded[typename].push(incoming);\n      } else {\n        this.toBeAdded[typename] = [incoming];\n      }\n    });\n  }\n\n  private updateTypePolicy(\n    typename: string,\n    incoming: TypePolicy,\n    existingFieldPolicies: Record<string, InternalFieldPolicy>\n  ) {\n    const existing = this.getTypePolicy(typename);\n    const { keyFields, fields } = incoming;\n\n    function setMerge(\n      existing: { merge?: FieldMergeFunction | boolean },\n      merge?: FieldMergeFunction | boolean\n    ) {\n      existing.merge =\n        typeof merge === \"function\" ? merge\n          // Pass merge:true as a shorthand for a merge implementation\n          // that returns options.mergeObjects(existing, incoming).\n        : merge === true ? mergeTrueFn\n          // Pass merge:false to make incoming always replace existing\n          // without any warnings about data clobbering.\n        : merge === false ? mergeFalseFn\n        : existing.merge;\n    }\n\n    // Type policies can define merge functions, as an alternative to\n    // using field policies to merge child objects.\n    setMerge(existing, incoming.merge);\n\n    existing.keyFn =\n      // Pass false to disable normalization for this typename.\n      keyFields === false ? nullKeyFieldsFn\n        // Pass an array of strings to use those fields to compute a\n        // composite ID for objects of this typename.\n      : isArray(keyFields) ? keyFieldsFnFromSpecifier(keyFields)\n        // Pass a function to take full control over identification.\n      : typeof keyFields === \"function\" ? keyFields\n        // Leave existing.keyFn unchanged if above cases fail.\n      : existing.keyFn;\n\n    if (fields) {\n      Object.keys(fields).forEach((fieldName) => {\n        let existing = existingFieldPolicies[fieldName] as\n          | InternalFieldPolicy\n          | undefined;\n        // Field policy inheritance is atomic/shallow: you can't inherit a\n        // field policy and then override just its read function, since read\n        // and merge functions often need to cooperate, so changing only one\n        // of them would be a recipe for inconsistency.\n        // So here we avoid merging an inherited field policy with an updated one.\n        if (!existing || existing?.typename !== typename) {\n          existing = existingFieldPolicies[fieldName] = { typename };\n        }\n        const incoming = fields[fieldName];\n\n        if (typeof incoming === \"function\") {\n          existing.read = incoming;\n        } else {\n          const { keyArgs, read, merge } = incoming;\n\n          existing.keyFn =\n            // Pass false to disable argument-based differentiation of\n            // field identities.\n            keyArgs === false ? simpleKeyArgsFn\n              // Pass an array of strings to use named arguments to\n              // compute a composite identity for the field.\n            : isArray(keyArgs) ? keyArgsFnFromSpecifier(keyArgs)\n              // Pass a function to take full control over field identity.\n            : typeof keyArgs === \"function\" ? keyArgs\n              // Leave existing.keyFn unchanged if above cases fail.\n            : existing.keyFn;\n\n          if (typeof read === \"function\") {\n            existing.read = read;\n          }\n\n          setMerge(existing, merge);\n        }\n\n        if (existing.read && existing.merge) {\n          // If we have both a read and a merge function, assume\n          // keyArgs:false, because read and merge together can take\n          // responsibility for interpreting arguments in and out. This\n          // default assumption can always be overridden by specifying\n          // keyArgs explicitly in the FieldPolicy.\n          existing.keyFn = existing.keyFn || simpleKeyArgsFn;\n        }\n      });\n    }\n  }\n\n  private setRootTypename(\n    which: \"Query\" | \"Mutation\" | \"Subscription\",\n    typename: string = which\n  ) {\n    const rootId = \"ROOT_\" + which.toUpperCase();\n    const old = this.rootTypenamesById[rootId];\n    if (typename !== old) {\n      invariant(\n        !old || old === which,\n        `Cannot change root %s __typename more than once`,\n        which\n      );\n      // First, delete any old __typename associated with this rootId from\n      // rootIdsByTypename.\n      if (old) delete this.rootIdsByTypename[old];\n      // Now make this the only __typename that maps to this rootId.\n      this.rootIdsByTypename[typename] = rootId;\n      // Finally, update the __typename associated with this rootId.\n      this.rootTypenamesById[rootId] = typename;\n    }\n  }\n\n  public addPossibleTypes(possibleTypes: PossibleTypesMap) {\n    (this.usingPossibleTypes as boolean) = true;\n    Object.keys(possibleTypes).forEach((supertype) => {\n      // Make sure all types have an entry in this.supertypeMap, even if\n      // their supertype set is empty, so we can return false immediately\n      // from policies.fragmentMatches for unknown supertypes.\n      this.getSupertypeSet(supertype, true);\n\n      possibleTypes[supertype].forEach((subtype) => {\n        this.getSupertypeSet(subtype, true)!.add(supertype);\n        const match = subtype.match(TypeOrFieldNameRegExp);\n        if (!match || match[0] !== subtype) {\n          // TODO Don't interpret just any invalid typename as a RegExp.\n          this.fuzzySubtypes.set(subtype, new RegExp(subtype));\n        }\n      });\n    });\n  }\n\n  private getTypePolicy(typename: string): Policies[\"typePolicies\"][string] {\n    if (!hasOwn.call(this.typePolicies, typename)) {\n      const policy: Policies[\"typePolicies\"][string] = (this.typePolicies[\n        typename\n      ] = {} as any);\n      policy.fields = {};\n\n      // When the TypePolicy for typename is first accessed, instead of\n      // starting with an empty policy object, inherit any properties or\n      // fields from the type policies of the supertypes of typename.\n      //\n      // Any properties or fields defined explicitly within the TypePolicy\n      // for typename will take precedence, and if there are multiple\n      // supertypes, the properties of policies whose types were added\n      // later via addPossibleTypes will take precedence over those of\n      // earlier supertypes. TODO Perhaps we should warn about these\n      // conflicts in development, and recommend defining the property\n      // explicitly in the subtype policy?\n      //\n      // Field policy inheritance is atomic/shallow: you can't inherit a\n      // field policy and then override just its read function, since read\n      // and merge functions often need to cooperate, so changing only one\n      // of them would be a recipe for inconsistency.\n      //\n      // Once the TypePolicy for typename has been accessed, its properties can\n      // still be updated directly using addTypePolicies, but future changes to\n      // inherited supertype policies will not be reflected in this subtype\n      // policy, because this code runs at most once per typename.\n      let supertypes = this.supertypeMap.get(typename);\n      if (!supertypes && this.fuzzySubtypes.size) {\n        // To make the inheritance logic work for unknown typename strings that\n        // may have fuzzy supertypes, we give this typename an empty supertype\n        // set and then populate it with any fuzzy supertypes that match.\n        supertypes = this.getSupertypeSet(typename, true)!;\n        // This only works for typenames that are directly matched by a fuzzy\n        // supertype. What if there is an intermediate chain of supertypes?\n        // While possible, that situation can only be solved effectively by\n        // specifying the intermediate relationships via possibleTypes, manually\n        // and in a non-fuzzy way.\n        this.fuzzySubtypes.forEach((regExp, fuzzy) => {\n          if (regExp.test(typename)) {\n            // The fuzzy parameter is just the original string version of regExp\n            // (not a valid __typename string), but we can look up the\n            // associated supertype(s) in this.supertypeMap.\n            const fuzzySupertypes = this.supertypeMap.get(fuzzy);\n            if (fuzzySupertypes) {\n              fuzzySupertypes.forEach((supertype) =>\n                supertypes!.add(supertype)\n              );\n            }\n          }\n        });\n      }\n      if (supertypes && supertypes.size) {\n        supertypes.forEach((supertype) => {\n          const { fields, ...rest } = this.getTypePolicy(supertype);\n          Object.assign(policy, rest);\n          Object.assign(policy.fields, fields);\n        });\n      }\n    }\n\n    const inbox = this.toBeAdded[typename];\n    if (inbox && inbox.length) {\n      // Merge the pending policies into this.typePolicies, in the order they\n      // were originally passed to addTypePolicy.\n      inbox.splice(0).forEach((policy) => {\n        this.updateTypePolicy(\n          typename,\n          policy,\n          this.typePolicies[typename].fields\n        );\n      });\n    }\n\n    return this.typePolicies[typename];\n  }\n\n  private getFieldPolicy(\n    typename: string | undefined,\n    fieldName: string\n  ): InternalFieldPolicy | undefined {\n    if (typename) {\n      return this.getTypePolicy(typename).fields[fieldName];\n    }\n  }\n\n  private getSupertypeSet(\n    subtype: string,\n    createIfMissing: boolean\n  ): Set<string> | undefined {\n    let supertypeSet = this.supertypeMap.get(subtype);\n    if (!supertypeSet && createIfMissing) {\n      this.supertypeMap.set(subtype, (supertypeSet = new Set<string>()));\n    }\n    return supertypeSet;\n  }\n\n  public fragmentMatches(\n    fragment: InlineFragmentNode | FragmentDefinitionNode,\n    typename: string | undefined,\n    result?: Record<string, any>,\n    variables?: Record<string, any>\n  ): boolean {\n    if (!fragment.typeCondition) return true;\n\n    // If the fragment has a type condition but the object we're matching\n    // against does not have a __typename, the fragment cannot match.\n    if (!typename) return false;\n\n    const supertype = fragment.typeCondition.name.value;\n    // Common case: fragment type condition and __typename are the same.\n    if (typename === supertype) return true;\n\n    if (this.usingPossibleTypes && this.supertypeMap.has(supertype)) {\n      const typenameSupertypeSet = this.getSupertypeSet(typename, true)!;\n      const workQueue = [typenameSupertypeSet];\n      const maybeEnqueue = (subtype: string) => {\n        const supertypeSet = this.getSupertypeSet(subtype, false);\n        if (\n          supertypeSet &&\n          supertypeSet.size &&\n          workQueue.indexOf(supertypeSet) < 0\n        ) {\n          workQueue.push(supertypeSet);\n        }\n      };\n\n      // We need to check fuzzy subtypes only if we encountered fuzzy\n      // subtype strings in addPossibleTypes, and only while writing to\n      // the cache, since that's when selectionSetMatchesResult gives a\n      // strong signal of fragment matching. The StoreReader class calls\n      // policies.fragmentMatches without passing a result object, so\n      // needToCheckFuzzySubtypes is always false while reading.\n      let needToCheckFuzzySubtypes = !!(result && this.fuzzySubtypes.size);\n      let checkingFuzzySubtypes = false;\n\n      // It's important to keep evaluating workQueue.length each time through\n      // the loop, because the queue can grow while we're iterating over it.\n      for (let i = 0; i < workQueue.length; ++i) {\n        const supertypeSet = workQueue[i];\n\n        if (supertypeSet.has(supertype)) {\n          if (!typenameSupertypeSet.has(supertype)) {\n            if (checkingFuzzySubtypes) {\n              invariant.warn(\n                `Inferring subtype %s of supertype %s`,\n                typename,\n                supertype\n              );\n            }\n            // Record positive results for faster future lookup.\n            // Unfortunately, we cannot safely cache negative results,\n            // because new possibleTypes data could always be added to the\n            // Policies class.\n            typenameSupertypeSet.add(supertype);\n          }\n          return true;\n        }\n\n        supertypeSet.forEach(maybeEnqueue);\n\n        if (\n          needToCheckFuzzySubtypes &&\n          // Start checking fuzzy subtypes only after exhausting all\n          // non-fuzzy subtypes (after the final iteration of the loop).\n          i === workQueue.length - 1 &&\n          // We could wait to compare fragment.selectionSet to result\n          // after we verify the supertype, but this check is often less\n          // expensive than that search, and we will have to do the\n          // comparison anyway whenever we find a potential match.\n          selectionSetMatchesResult(fragment.selectionSet, result!, variables)\n        ) {\n          // We don't always need to check fuzzy subtypes (if no result\n          // was provided, or !this.fuzzySubtypes.size), but, when we do,\n          // we only want to check them once.\n          needToCheckFuzzySubtypes = false;\n          checkingFuzzySubtypes = true;\n\n          // If we find any fuzzy subtypes that match typename, extend the\n          // workQueue to search through the supertypes of those fuzzy\n          // subtypes. Otherwise the for-loop will terminate and we'll\n          // return false below.\n          this.fuzzySubtypes.forEach((regExp, fuzzyString) => {\n            const match = typename.match(regExp);\n            if (match && match[0] === typename) {\n              maybeEnqueue(fuzzyString);\n            }\n          });\n        }\n      }\n    }\n\n    return false;\n  }\n\n  public hasKeyArgs(typename: string | undefined, fieldName: string) {\n    const policy = this.getFieldPolicy(typename, fieldName);\n    return !!(policy && policy.keyFn);\n  }\n\n  public getStoreFieldName(fieldSpec: FieldSpecifier): string {\n    const { typename, fieldName } = fieldSpec;\n    const policy = this.getFieldPolicy(typename, fieldName);\n    let storeFieldName: Exclude<ReturnType<KeyArgsFunction>, KeySpecifier>;\n\n    let keyFn = policy && policy.keyFn;\n    if (keyFn && typename) {\n      const context: Parameters<KeyArgsFunction>[1] = {\n        typename,\n        fieldName,\n        field: fieldSpec.field || null,\n        variables: fieldSpec.variables,\n      };\n      const args = argsFromFieldSpecifier(fieldSpec);\n      while (keyFn) {\n        const specifierOrString = keyFn(args, context);\n        if (isArray(specifierOrString)) {\n          keyFn = keyArgsFnFromSpecifier(specifierOrString);\n        } else {\n          // If the custom keyFn returns a falsy value, fall back to\n          // fieldName instead.\n          storeFieldName = specifierOrString || fieldName;\n          break;\n        }\n      }\n    }\n\n    if (storeFieldName === void 0) {\n      storeFieldName =\n        fieldSpec.field ?\n          storeKeyNameFromField(fieldSpec.field, fieldSpec.variables)\n        : getStoreKeyName(fieldName, argsFromFieldSpecifier(fieldSpec));\n    }\n\n    // Returning false from a keyArgs function is like configuring\n    // keyArgs: false, but more dynamic.\n    if (storeFieldName === false) {\n      return fieldName;\n    }\n\n    // Make sure custom field names start with the actual field.name.value\n    // of the field, so we can always figure out which properties of a\n    // StoreObject correspond to which original field names.\n    return fieldName === fieldNameFromStoreName(storeFieldName) ? storeFieldName\n      : fieldName + \":\" + storeFieldName;\n  }\n\n  public readField<V = StoreValue>(\n    options: ReadFieldOptions,\n    context: ReadMergeModifyContext\n  ): SafeReadonly<V> | undefined {\n    const objectOrReference = options.from;\n    if (!objectOrReference) return;\n\n    const nameOrField = options.field || options.fieldName;\n    if (!nameOrField) return;\n\n    if (options.typename === void 0) {\n      const typename = context.store.getFieldValue<string>(\n        objectOrReference,\n        \"__typename\"\n      );\n      if (typename) options.typename = typename;\n    }\n\n    const storeFieldName = this.getStoreFieldName(options);\n    const fieldName = fieldNameFromStoreName(storeFieldName);\n    const existing = context.store.getFieldValue<V>(\n      objectOrReference,\n      storeFieldName\n    );\n    const policy = this.getFieldPolicy(options.typename, fieldName);\n    const read = policy && policy.read;\n\n    if (read) {\n      const readOptions = makeFieldFunctionOptions(\n        this,\n        objectOrReference,\n        options,\n        context,\n        context.store.getStorage(\n          isReference(objectOrReference) ?\n            objectOrReference.__ref\n          : objectOrReference,\n          storeFieldName\n        )\n      );\n\n      // Call read(existing, readOptions) with cacheSlot holding this.cache.\n      return cacheSlot.withValue(this.cache, read, [\n        existing,\n        readOptions,\n      ]) as SafeReadonly<V>;\n    }\n\n    return existing;\n  }\n\n  public getReadFunction(\n    typename: string | undefined,\n    fieldName: string\n  ): FieldReadFunction | undefined {\n    const policy = this.getFieldPolicy(typename, fieldName);\n    return policy && policy.read;\n  }\n\n  public getMergeFunction(\n    parentTypename: string | undefined,\n    fieldName: string,\n    childTypename: string | undefined\n  ): FieldMergeFunction | undefined {\n    let policy:\n      | Policies[\"typePolicies\"][string]\n      | Policies[\"typePolicies\"][string][\"fields\"][string]\n      | undefined = this.getFieldPolicy(parentTypename, fieldName);\n    let merge = policy && policy.merge;\n    if (!merge && childTypename) {\n      policy = this.getTypePolicy(childTypename);\n      merge = policy && policy.merge;\n    }\n    return merge;\n  }\n\n  public runMergeFunction(\n    existing: StoreValue,\n    incoming: StoreValue,\n    { field, typename, merge, path }: MergeInfo,\n    context: WriteContext,\n    storage?: StorageType\n  ) {\n    // Preserve the value in case `context.overwrite` is set.\n    const existingData = existing;\n    if (merge === mergeTrueFn) {\n      // Instead of going to the trouble of creating a full\n      // FieldFunctionOptions object and calling mergeTrueFn, we can\n      // simply call mergeObjects, as mergeTrueFn would.\n      return makeMergeObjectsFunction(context.store)(\n        existing as StoreObject,\n        incoming as StoreObject\n      );\n    }\n\n    if (merge === mergeFalseFn) {\n      // Likewise for mergeFalseFn, whose implementation is even simpler.\n      return incoming;\n    }\n\n    // If cache.writeQuery or cache.writeFragment was called with\n    // options.overwrite set to true, we still call merge functions, but\n    // the existing data is always undefined, so the merge function will\n    // not attempt to combine the incoming data with the existing data.\n    if (context.overwrite) {\n      existing = void 0;\n    }\n\n    const streamInfo = context.extensions?.[streamInfoSymbol]\n      ?.deref()\n      ?.peekArray(path);\n\n    if (streamInfo) {\n      const { current, previous } = streamInfo;\n\n      if (\n        previous &&\n        equal(previous.incoming, incoming) &&\n        equal(previous.streamFieldInfo, current)\n      ) {\n        return previous.result;\n      }\n    }\n\n    const result = merge(\n      existing,\n      incoming,\n      makeMergeFieldFunctionOptions(\n        this,\n        // Unlike options.readField for read functions, we do not fall\n        // back to the current object if no foreignObjOrRef is provided,\n        // because it's not clear what the current object should be for\n        // merge functions: the (possibly undefined) existing object, or\n        // the incoming object? If you think your merge function needs\n        // to read sibling fields in order to produce a new value for\n        // the current field, you might want to rethink your strategy,\n        // because that's a recipe for making merge behavior sensitive\n        // to the order in which fields are written into the cache.\n        // However, readField(name, ref) is useful for merge functions\n        // that need to deduplicate child objects and references.\n        void 0,\n        {\n          typename,\n          fieldName: field.name.value,\n          field,\n          variables: context.variables,\n          path,\n        },\n        context,\n        storage || {},\n        existingData\n      )\n    );\n\n    if (streamInfo) {\n      streamInfo.previous = {\n        incoming,\n        streamFieldInfo: streamInfo.current,\n        result,\n      };\n    }\n\n    return result;\n  }\n}\n\nfunction makeFieldFunctionOptions(\n  policies: Policies,\n  objectOrReference: StoreObject | Reference | undefined,\n  fieldSpec: FieldSpecifier,\n  context: ReadMergeModifyContext,\n  storage: StorageType\n): FieldFunctionOptions {\n  const storeFieldName = policies.getStoreFieldName(fieldSpec);\n  const fieldName = fieldNameFromStoreName(storeFieldName);\n  const variables = fieldSpec.variables || context.variables;\n  const { toReference, canRead } = context.store;\n\n  return {\n    args: argsFromFieldSpecifier(fieldSpec),\n    field: fieldSpec.field || null,\n    fieldName,\n    storeFieldName,\n    variables,\n    isReference,\n    toReference,\n    storage,\n    cache: policies.cache,\n    canRead,\n    readField<T>(...args: any[]) {\n      return policies.readField<T>(\n        normalizeReadFieldOptions(args, objectOrReference, variables),\n        context\n      );\n    },\n    mergeObjects: makeMergeObjectsFunction(context.store),\n  };\n}\n\nfunction makeMergeFieldFunctionOptions(\n  policies: Policies,\n  objectOrReference: StoreObject | Reference | undefined,\n  fieldSpec: FieldSpecifier & { path: Array<string | number> },\n  context: ReadMergeModifyContext,\n  storage: StorageType,\n  existingData?: unknown\n): FieldMergeFunctionOptions {\n  const options: FieldMergeFunctionOptions = {\n    ...makeFieldFunctionOptions(\n      policies,\n      objectOrReference,\n      fieldSpec,\n      context,\n      storage\n    ),\n    extensions: context.extensions,\n    existingData,\n  };\n\n  const extensions = context.extensions;\n\n  if (extensions && streamInfoSymbol in extensions) {\n    const { [streamInfoSymbol]: streamInfo, ...otherExtensions } = extensions;\n\n    const streamFieldInfo = streamInfo?.deref()?.peekArray(fieldSpec.path);\n    if (streamFieldInfo) {\n      options.streamFieldInfo = streamFieldInfo.current;\n    }\n\n    // If the only key in `extensions` was the stream details key, we didn't\n    // receive any remote extensions, so we reset extensions back to undefined\n    options.extensions =\n      Object.keys(otherExtensions).length === 0 ? undefined : otherExtensions;\n  }\n\n  return options;\n}\n\nexport function normalizeReadFieldOptions(\n  readFieldArgs: any[],\n  objectOrReference: StoreObject | Reference | undefined,\n  variables?: ReadMergeModifyContext[\"variables\"]\n): ReadFieldOptions {\n  const { 0: fieldNameOrOptions, 1: from, length: argc } = readFieldArgs;\n\n  let options: ReadFieldOptions;\n\n  if (typeof fieldNameOrOptions === \"string\") {\n    options = {\n      fieldName: fieldNameOrOptions,\n      // Default to objectOrReference only when no second argument was\n      // passed for the from parameter, not when undefined is explicitly\n      // passed as the second argument.\n      from: argc > 1 ? from : objectOrReference,\n    };\n  } else {\n    options = { ...fieldNameOrOptions };\n    // Default to objectOrReference only when fieldNameOrOptions.from is\n    // actually omitted, rather than just undefined.\n    if (!hasOwn.call(options, \"from\")) {\n      options.from = objectOrReference;\n    }\n  }\n\n  if (__DEV__ && options.from === void 0) {\n    invariant.warn(\n      `Undefined 'from' passed to readField with arguments %s`,\n      stringifyForDisplay(Array.from(readFieldArgs))\n    );\n  }\n\n  if (void 0 === options.variables) {\n    options.variables = variables;\n  }\n\n  return options;\n}\n\nfunction makeMergeObjectsFunction(\n  store: NormalizedCache\n): MergeObjectsFunction {\n  return function mergeObjects(existing, incoming) {\n    if (isArray(existing) || isArray(incoming)) {\n      throw newInvariantError(\"Cannot automatically merge arrays\");\n    }\n\n    // These dynamic checks are necessary because the parameters of a\n    // custom merge function can easily have the any type, so the type\n    // system cannot always enforce the StoreObject | Reference parameter\n    // types of options.mergeObjects.\n    if (isNonNullObject(existing) && isNonNullObject(incoming)) {\n      const eType = store.getFieldValue(existing, \"__typename\");\n      const iType = store.getFieldValue(incoming, \"__typename\");\n      const typesDiffer = eType && iType && eType !== iType;\n\n      if (typesDiffer) {\n        return incoming;\n      }\n\n      if (isReference(existing) && storeValueIsStoreObject(incoming)) {\n        // Update the normalized EntityStore for the entity identified by\n        // existing.__ref, preferring/overwriting any fields contributed by the\n        // newer incoming StoreObject.\n        store.merge(existing.__ref, incoming);\n        return existing;\n      }\n\n      if (storeValueIsStoreObject(existing) && isReference(incoming)) {\n        // Update the normalized EntityStore for the entity identified by\n        // incoming.__ref, taking fields from the older existing object only if\n        // those fields are not already present in the newer StoreObject\n        // identified by incoming.__ref.\n        store.merge(existing, incoming.__ref);\n        return incoming;\n      }\n\n      if (\n        storeValueIsStoreObject(existing) &&\n        storeValueIsStoreObject(incoming)\n      ) {\n        return { ...existing, ...incoming };\n      }\n    }\n\n    return incoming;\n  };\n}\n"
  },
  {
    "path": "src/cache/inmemory/reactiveVars.ts",
    "content": "import type { OptimisticDependencyFunction } from \"optimism\";\nimport { dep, Slot } from \"optimism\";\n\nimport type { ApolloCache } from \"@apollo/client\";\n\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\n\nexport interface ReactiveVar<T> {\n  (newValue?: T): T;\n  onNextChange(listener: ReactiveListener<T>): () => void;\n  attachCache(cache: ApolloCache): this;\n  forgetCache(cache: ApolloCache): boolean;\n}\n\ntype ReactiveListener<T> = (value: T) => any;\n\n// Contextual Slot that acquires its value when custom read functions are\n// called in Policies#readField.\nexport const cacheSlot = new Slot<ApolloCache>();\n\nconst cacheInfoMap = new WeakMap<\n  ApolloCache,\n  {\n    vars: Set<ReactiveVar<any>>;\n    dep: OptimisticDependencyFunction<ReactiveVar<any>>;\n  }\n>();\n\nfunction getCacheInfo(cache: ApolloCache) {\n  let info = cacheInfoMap.get(cache)!;\n  if (!info) {\n    cacheInfoMap.set(\n      cache,\n      (info = {\n        vars: new Set(),\n        dep: dep(),\n      })\n    );\n  }\n  return info;\n}\n\nexport function forgetCache(cache: ApolloCache) {\n  getCacheInfo(cache).vars.forEach((rv) => rv.forgetCache(cache));\n}\n\n// Calling forgetCache(cache) serves to silence broadcasts and allows the\n// cache to be garbage collected. However, the varsByCache WeakMap\n// preserves the set of reactive variables that were previously associated\n// with this cache, which makes it possible to \"recall\" the cache at a\n// later time, by reattaching it to those variables. If the cache has been\n// garbage collected in the meantime, because it is no longer reachable,\n// you won't be able to call recallCache(cache), and the cache will\n// automatically disappear from the varsByCache WeakMap.\nexport function recallCache(cache: ApolloCache) {\n  getCacheInfo(cache).vars.forEach((rv) => rv.attachCache(cache));\n}\n\nexport function makeVar<T>(value: T): ReactiveVar<T> {\n  const caches = new Set<ApolloCache>();\n  const listeners = new Set<ReactiveListener<T>>();\n\n  const rv: ReactiveVar<T> = function (newValue) {\n    if (arguments.length > 0) {\n      if (value !== newValue) {\n        value = newValue!;\n        caches.forEach((cache) => {\n          // Invalidate any fields with custom read functions that\n          // consumed this variable, so query results involving those\n          // fields will be recomputed the next time we read them.\n          getCacheInfo(cache).dep.dirty(rv);\n          // Broadcast changes to any caches that have previously read\n          // from this variable.\n          broadcast(cache);\n        });\n        // Finally, notify any listeners added via rv.onNextChange.\n        const oldListeners = Array.from(listeners);\n        listeners.clear();\n        oldListeners.forEach((listener) => listener(value));\n      }\n    } else {\n      // When reading from the variable, obtain the current cache from\n      // context via cacheSlot. This isn't entirely foolproof, but it's\n      // the same system that powers varDep.\n      const cache = cacheSlot.getValue();\n      if (cache) {\n        attach(cache);\n        getCacheInfo(cache).dep(rv);\n      }\n    }\n\n    return value;\n  };\n\n  rv.onNextChange = (listener) => {\n    listeners.add(listener);\n    return () => {\n      listeners.delete(listener);\n    };\n  };\n\n  const attach = (rv.attachCache = (cache) => {\n    caches.add(cache);\n    getCacheInfo(cache).vars.add(rv);\n    return rv;\n  });\n\n  rv.forgetCache = (cache) => caches.delete(cache);\n\n  return rv;\n}\n\ntype Broadcastable = ApolloCache & {\n  // This method is protected in InMemoryCache, which we are ignoring, but\n  // we still want some semblance of type safety when we call it.\n  broadcastWatches?: InMemoryCache[\"broadcastWatches\"];\n};\n\nfunction broadcast(cache: Broadcastable) {\n  if (cache.broadcastWatches) {\n    cache.broadcastWatches();\n  }\n}\n"
  },
  {
    "path": "src/cache/inmemory/readFromStore.ts",
    "content": "import type { DocumentNode, FieldNode, SelectionSetNode } from \"graphql\";\nimport { Kind } from \"graphql\";\nimport type { OptimisticWrapperFunction } from \"optimism\";\nimport { wrap } from \"optimism\";\n\nimport type { Reference, StoreObject } from \"@apollo/client/utilities\";\nimport {\n  addTypenameToDocument,\n  cacheSizes,\n  canonicalStringify,\n  isReference,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  FragmentMap,\n  FragmentMapFunction,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  DeepMerger,\n  getDefaultValues,\n  getFragmentFromSelection,\n  getMainDefinition,\n  getQueryDefinition,\n  isArray,\n  isField,\n  isNonNullObject,\n  makeReference,\n  maybeDeepFreeze,\n  mergeDeepArray,\n  resultKeyNameFromField,\n  shouldInclude,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\nimport type { Cache } from \"../core/types/Cache.js\";\nimport type { MissingTree } from \"../core/types/common.js\";\nimport { MissingFieldError } from \"../core/types/common.js\";\n\nimport {\n  maybeDependOnExistenceOfEntity,\n  supportsResultCaching,\n} from \"./entityStore.js\";\nimport {\n  extractFragmentContext,\n  getTypenameFromStoreObject,\n} from \"./helpers.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport type { Policies } from \"./policies.js\";\nimport type {\n  DiffQueryAgainstStoreOptions,\n  InMemoryCacheConfig,\n  NormalizedCache,\n  ReadMergeModifyContext,\n} from \"./types.js\";\n\ninterface ReadContext extends ReadMergeModifyContext {\n  query: DocumentNode;\n  policies: Policies;\n  fragmentMap: FragmentMap;\n  lookupFragment: FragmentMapFunction;\n}\n\ntype ExecResult<R = any> = {\n  result: R;\n  missing?: MissingTree;\n};\n\ntype ExecSelectionSetOptions = {\n  selectionSet: SelectionSetNode;\n  objectOrReference: StoreObject | Reference;\n  enclosingRef: Reference;\n  context: ReadContext;\n};\n\ntype ExecSubSelectedArrayOptions = {\n  field: FieldNode;\n  array: readonly any[];\n  enclosingRef: Reference;\n  context: ReadContext;\n};\n\ninterface StoreReaderConfig {\n  cache: InMemoryCache;\n  fragments?: InMemoryCacheConfig[\"fragments\"];\n}\n\n// Arguments type after keyArgs translation.\ntype ExecSelectionSetKeyArgs = [\n  SelectionSetNode,\n  StoreObject | Reference,\n  ReadMergeModifyContext,\n];\n\nfunction execSelectionSetKeyArgs(\n  options: ExecSelectionSetOptions\n): ExecSelectionSetKeyArgs {\n  return [options.selectionSet, options.objectOrReference, options.context];\n}\n\nexport class StoreReader {\n  // cached version of executeSelectionSet\n  private executeSelectionSet: OptimisticWrapperFunction<\n    [ExecSelectionSetOptions], // Actual arguments tuple type.\n    ExecResult, // Actual return type.\n    ExecSelectionSetKeyArgs\n  >;\n\n  // cached version of executeSubSelectedArray\n  private executeSubSelectedArray: OptimisticWrapperFunction<\n    [ExecSubSelectedArrayOptions],\n    ExecResult<any>,\n    [ExecSubSelectedArrayOptions]\n  >;\n\n  private config: {\n    cache: InMemoryCache;\n    fragments?: InMemoryCacheConfig[\"fragments\"];\n  };\n\n  private knownResults = new WeakMap<Record<string, any>, SelectionSetNode>();\n\n  constructor(config: StoreReaderConfig) {\n    this.config = config;\n\n    // memoized functions in this class will be \"garbage-collected\"\n    // by recreating the whole `StoreReader` in\n    // `InMemoryCache.resetResultsCache`\n    // (triggered from `InMemoryCache.gc` with `resetResultCache: true`)\n    this.executeSelectionSet = wrap(\n      (options) => {\n        const peekArgs = execSelectionSetKeyArgs(options);\n\n        const other = this.executeSelectionSet.peek(...peekArgs);\n\n        if (other) {\n          // If we previously read this result with canonization enabled, we can\n          // return that canonized result as-is.\n          return other;\n        }\n\n        maybeDependOnExistenceOfEntity(\n          options.context.store,\n          options.enclosingRef.__ref\n        );\n\n        // Finally, if we didn't find any useful previous results, run the real\n        // execSelectionSetImpl method with the given options.\n        return this.execSelectionSetImpl(options);\n      },\n      {\n        max:\n          cacheSizes[\"inMemoryCache.executeSelectionSet\"] ||\n          defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n        keyArgs: execSelectionSetKeyArgs,\n        // Note that the parameters of makeCacheKey are determined by the\n        // array returned by keyArgs.\n        makeCacheKey(selectionSet, parent, context) {\n          if (supportsResultCaching(context.store)) {\n            return context.store.makeCacheKey(\n              selectionSet,\n              isReference(parent) ? parent.__ref : parent,\n              context.varString\n            );\n          }\n        },\n      }\n    );\n\n    this.executeSubSelectedArray = wrap(\n      (options: ExecSubSelectedArrayOptions) => {\n        maybeDependOnExistenceOfEntity(\n          options.context.store,\n          options.enclosingRef.__ref\n        );\n        return this.execSubSelectedArrayImpl(options);\n      },\n      {\n        max:\n          cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] ||\n          defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n        makeCacheKey({ field, array, context }) {\n          if (supportsResultCaching(context.store)) {\n            return context.store.makeCacheKey(field, array, context.varString);\n          }\n        },\n      }\n    );\n  }\n\n  /**\n   * Given a store and a query, return as much of the result as possible and\n   * identify if any data was missing from the store.\n   */\n  public diffQueryAgainstStore<T>({\n    store,\n    query,\n    rootId = \"ROOT_QUERY\",\n    variables,\n    returnPartialData = true,\n  }: DiffQueryAgainstStoreOptions): Cache.DiffResult<T> {\n    const policies = this.config.cache.policies;\n\n    variables = {\n      ...getDefaultValues(getQueryDefinition(query)),\n      ...variables!,\n    };\n\n    const rootRef = makeReference(rootId);\n    const execResult = this.executeSelectionSet({\n      selectionSet: getMainDefinition(query).selectionSet,\n      objectOrReference: rootRef,\n      enclosingRef: rootRef,\n      context: {\n        store,\n        query,\n        policies,\n        variables,\n        varString: canonicalStringify(variables),\n        ...extractFragmentContext(query, this.config.fragments),\n      },\n    });\n\n    let missing: MissingFieldError | undefined;\n    if (execResult.missing) {\n      missing = new MissingFieldError(\n        firstMissing(execResult.missing)!,\n        execResult.missing,\n        query,\n        variables\n      );\n    }\n\n    const complete = !missing;\n    const { result } = execResult;\n\n    return {\n      result:\n        complete ? result\n        : returnPartialData ?\n          Object.keys(result).length === 0 ?\n            null\n          : result\n        : null,\n      complete,\n      missing,\n    } as Cache.DiffResult<T>;\n  }\n\n  public isFresh(\n    result: Record<string, any>,\n    parent: StoreObject | Reference,\n    selectionSet: SelectionSetNode,\n    context: ReadMergeModifyContext\n  ): boolean {\n    if (\n      supportsResultCaching(context.store) &&\n      this.knownResults.get(result) === selectionSet\n    ) {\n      const latest = this.executeSelectionSet.peek(\n        selectionSet,\n        parent,\n        context\n      );\n      if (latest && result === latest.result) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  // Uncached version of executeSelectionSet.\n  private execSelectionSetImpl({\n    selectionSet,\n    objectOrReference,\n    enclosingRef,\n    context,\n  }: ExecSelectionSetOptions): ExecResult {\n    if (\n      isReference(objectOrReference) &&\n      !context.policies.rootTypenamesById[objectOrReference.__ref] &&\n      !context.store.has(objectOrReference.__ref)\n    ) {\n      return {\n        result: {},\n        missing: `Dangling reference to missing ${objectOrReference.__ref} object`,\n      };\n    }\n\n    const { variables, policies, store } = context;\n    const typename = store.getFieldValue<string>(\n      objectOrReference,\n      \"__typename\"\n    );\n\n    const objectsToMerge: Record<string, any>[] = [];\n    let missing: MissingTree | undefined;\n    const missingMerger = new DeepMerger();\n\n    if (typeof typename === \"string\" && !policies.rootIdsByTypename[typename]) {\n      // Ensure we always include a default value for the __typename\n      // field, if we have one. Note that this field can be overridden by other\n      // merged objects.\n      objectsToMerge.push({ __typename: typename });\n    }\n\n    function handleMissing<T>(result: ExecResult<T>, resultName: string): T {\n      if (result.missing) {\n        missing = missingMerger.merge(missing, {\n          [resultName]: result.missing,\n        });\n      }\n      return result.result;\n    }\n\n    const workSet = new Set(selectionSet.selections);\n\n    workSet.forEach((selection) => {\n      // Omit fields with directives @skip(if: <truthy value>) or\n      // @include(if: <falsy value>).\n      if (!shouldInclude(selection, variables)) return;\n\n      if (isField(selection)) {\n        let fieldValue = policies.readField(\n          {\n            fieldName: selection.name.value,\n            field: selection,\n            variables: context.variables,\n            from: objectOrReference,\n          },\n          context\n        );\n\n        const resultName = resultKeyNameFromField(selection);\n\n        if (fieldValue === void 0) {\n          if (!addTypenameToDocument.added(selection)) {\n            missing = missingMerger.merge(missing, {\n              [resultName]: `Can't find field '${selection.name.value}' on ${\n                isReference(objectOrReference) ?\n                  objectOrReference.__ref + \" object\"\n                : \"object \" + JSON.stringify(objectOrReference, null, 2)\n              }`,\n            });\n          }\n        } else if (isArray(fieldValue)) {\n          if (fieldValue.length > 0) {\n            fieldValue = handleMissing(\n              this.executeSubSelectedArray({\n                field: selection,\n                array: fieldValue,\n                enclosingRef,\n                context,\n              }),\n              resultName\n            );\n          }\n        } else if (!selection.selectionSet) {\n          // do nothing\n        } else if (fieldValue != null) {\n          // In this case, because we know the field has a selection set,\n          // it must be trying to query a GraphQLObjectType, which is why\n          // fieldValue must be != null.\n          fieldValue = handleMissing(\n            this.executeSelectionSet({\n              selectionSet: selection.selectionSet,\n              objectOrReference: fieldValue as StoreObject | Reference,\n              enclosingRef: isReference(fieldValue) ? fieldValue : enclosingRef,\n              context,\n            }),\n            resultName\n          );\n        }\n\n        if (fieldValue !== void 0) {\n          objectsToMerge.push({ [resultName]: fieldValue });\n        }\n      } else {\n        const fragment = getFragmentFromSelection(\n          selection,\n          context.lookupFragment\n        );\n\n        if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n          throw newInvariantError(`No fragment named %s`, selection.name.value);\n        }\n\n        if (fragment && policies.fragmentMatches(fragment, typename)) {\n          fragment.selectionSet.selections.forEach(workSet.add, workSet);\n        }\n      }\n    });\n\n    const result = mergeDeepArray(objectsToMerge);\n    const finalResult: ExecResult = { result, missing };\n    const frozen = maybeDeepFreeze(finalResult);\n\n    // Store this result with its selection set so that we can quickly\n    // recognize it again in the StoreReader#isFresh method.\n    if (frozen.result) {\n      this.knownResults.set(frozen.result, selectionSet);\n    }\n\n    return frozen;\n  }\n\n  // Uncached version of executeSubSelectedArray.\n  private execSubSelectedArrayImpl({\n    field,\n    array,\n    enclosingRef,\n    context,\n  }: ExecSubSelectedArrayOptions): ExecResult {\n    let missing: MissingTree | undefined;\n    let missingMerger = new DeepMerger();\n\n    function handleMissing<T>(childResult: ExecResult<T>, i: number): T {\n      if (childResult.missing) {\n        missing = missingMerger.merge(missing, { [i]: childResult.missing });\n      }\n      return childResult.result;\n    }\n\n    if (field.selectionSet) {\n      array = array.filter(\n        (item) => item === undefined || context.store.canRead(item)\n      );\n    }\n\n    array = array.map((item, i) => {\n      // null value in array\n      if (item === null) {\n        return null;\n      }\n\n      // This is a nested array, recurse\n      if (isArray(item)) {\n        return handleMissing(\n          this.executeSubSelectedArray({\n            field,\n            array: item,\n            enclosingRef,\n            context,\n          }),\n          i\n        );\n      }\n\n      // This is an object, run the selection set on it\n      if (field.selectionSet) {\n        return handleMissing(\n          this.executeSelectionSet({\n            selectionSet: field.selectionSet,\n            objectOrReference: item,\n            enclosingRef: isReference(item) ? item : enclosingRef,\n            context,\n          }),\n          i\n        );\n      }\n\n      if (__DEV__) {\n        assertSelectionSetForIdValue(context.store, field, item);\n      }\n\n      return item;\n    });\n\n    return {\n      result: array,\n      missing,\n    };\n  }\n}\n\nfunction firstMissing(tree: MissingTree): string | undefined {\n  try {\n    JSON.stringify(tree, (_, value) => {\n      if (typeof value === \"string\") throw value;\n      return value;\n    });\n  } catch (result) {\n    return result as string;\n  }\n}\n\nfunction assertSelectionSetForIdValue(\n  store: NormalizedCache,\n  field: FieldNode,\n  fieldValue: any\n) {\n  if (!field.selectionSet) {\n    const workSet = new Set([fieldValue]);\n    workSet.forEach((value) => {\n      if (isNonNullObject(value)) {\n        invariant(\n          !isReference(value),\n          `Missing selection set for object of type %s returned for query field %s`,\n          getTypenameFromStoreObject(store, value),\n          field.name.value\n        );\n        Object.values(value).forEach(workSet.add, workSet);\n      }\n    });\n  }\n}\n"
  },
  {
    "path": "src/cache/inmemory/types.ts",
    "content": "import type { DocumentNode, FieldNode } from \"graphql\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport type {\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\nimport type { ExtensionsWithStreamInfo } from \"@apollo/client/utilities/internal\";\n\nimport type { Transaction } from \"../core/cache.js\";\nimport type {\n  AllFieldsModifier,\n  CanReadFunction,\n  Modifiers,\n  ToReferenceFunction,\n} from \"../core/types/common.js\";\n\nimport type { FieldValueGetter } from \"./entityStore.js\";\nimport type { FragmentRegistryAPI } from \"./fragmentRegistry.js\";\nimport type {\n  FieldMergeFunction,\n  KeyFieldsFunction,\n  PossibleTypesMap,\n  StorageType,\n  TypePolicies,\n} from \"./policies.js\";\n\nexport type { Reference, StoreObject, StoreValue };\n\nexport interface IdGetterObj extends Object {\n  __typename?: string;\n  id?: string;\n  _id?: string;\n}\n\nexport declare type IdGetter = (value: IdGetterObj) => string | undefined;\n\n/**\n * This is an interface used to access, set and remove\n * StoreObjects from the cache\n */\nexport interface NormalizedCache {\n  has(dataId: string): boolean;\n  get(dataId: string, fieldName: string): StoreValue;\n\n  // The store.merge method allows either argument to be a string ID, but\n  // the other argument has to be a StoreObject. Either way, newer fields\n  // always take precedence over older fields.\n  merge(olderId: string, newerObject: StoreObject): void;\n  merge(olderObject: StoreObject, newerId: string): void;\n\n  modify<Entity extends Record<string, any>>(\n    dataId: string,\n    fields: Modifiers<Entity> | AllFieldsModifier<Entity>,\n    exact: boolean\n  ): boolean;\n  delete(dataId: string, fieldName?: string): boolean;\n  clear(): void;\n\n  // non-Map elements:\n  /**\n   * returns an Object with key-value pairs matching the contents of the store\n   */\n  toObject(): NormalizedCacheObject;\n  /**\n   * replace the state of the store\n   */\n  replace(newData: NormalizedCacheObject): void;\n\n  /**\n   * Retain (or release) a given root ID to protect (or expose) it and its\n   * transitive child entities from (or to) garbage collection. The current\n   * retainment count is returned by both methods. Note that releasing a root\n   * ID does not cause that entity to be garbage collected, but merely removes\n   * it from the set of root IDs that will be considered during the next\n   * mark-and-sweep collection.\n   */\n  retain(rootId: string): number;\n  release(rootId: string): number;\n\n  getFieldValue: FieldValueGetter;\n  toReference: ToReferenceFunction;\n  canRead: CanReadFunction;\n\n  getStorage(\n    idOrObj: string | StoreObject,\n    ...storeFieldNames: (string | number)[]\n  ): StorageType;\n}\n\n/**\n * This is a normalized representation of the Apollo query result cache. It consists of\n * a flattened representation of query result trees.\n */\nexport interface NormalizedCacheObject {\n  __META?: {\n    // Well-known singleton IDs like ROOT_QUERY and ROOT_MUTATION are\n    // always considered to be root IDs during cache.gc garbage\n    // collection, but other IDs can become roots if they are written\n    // directly with cache.writeFragment or retained explicitly with\n    // cache.retain. When such IDs exist, we include them in the __META\n    // section so that they can survive cache.{extract,restore}.\n    extraRootIds: string[];\n  };\n  [dataId: string]: StoreObject | undefined;\n}\n\nexport type OptimisticStoreItem = {\n  id: string;\n  data: NormalizedCacheObject;\n  transaction: Transaction;\n};\n\nexport type ReadQueryOptions = {\n  /**\n   * The Apollo Client store object.\n   */\n  store: NormalizedCache;\n  /**\n   * A parsed GraphQL query document.\n   */\n  query: DocumentNode;\n  variables?: Object;\n  previousResult?: any;\n  rootId?: string;\n  config?: ApolloReducerConfig;\n};\n\nexport type DiffQueryAgainstStoreOptions = ReadQueryOptions & {\n  returnPartialData?: boolean;\n};\n\nexport type ApolloReducerConfig = {\n  dataIdFromObject?: KeyFieldsFunction;\n};\n\nexport interface InMemoryCacheConfig extends ApolloReducerConfig {\n  resultCaching?: boolean;\n  possibleTypes?: PossibleTypesMap;\n  typePolicies?: TypePolicies;\n  fragments?: FragmentRegistryAPI;\n}\n\nexport interface MergeInfo {\n  field: FieldNode;\n  typename: string | undefined;\n  merge: FieldMergeFunction;\n  path: Array<string | number>;\n}\n\nexport interface MergeTree {\n  info?: MergeInfo;\n  map: Map<string | number, MergeTree>;\n}\n\nexport interface ReadMergeModifyContext {\n  store: NormalizedCache;\n  variables?: OperationVariables;\n  // A JSON.stringify-serialized version of context.variables.\n  varString?: string;\n  extensions?: ExtensionsWithStreamInfo;\n}\n"
  },
  {
    "path": "src/cache/inmemory/writeToStore.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport { Trie } from \"@wry/trie\";\nimport type {\n  FieldNode,\n  FragmentSpreadNode,\n  InlineFragmentNode,\n  SelectionSetNode,\n} from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport type { Cache, OperationVariables } from \"@apollo/client\";\nimport type {\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"@apollo/client/utilities\";\nimport {\n  addTypenameToDocument,\n  canonicalStringify,\n  isReference,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  FragmentMap,\n  FragmentMapFunction,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  argumentsObjectFromField,\n  cloneDeep,\n  getDefaultValues,\n  getFragmentFromSelection,\n  getOperationDefinition,\n  hasDirectives,\n  isArray,\n  isField,\n  isNonEmptyArray,\n  makeReference,\n  resultKeyNameFromField,\n  shouldInclude,\n  streamInfoSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nimport type { ReadFieldFunction } from \"../core/types/common.js\";\n\nimport type { EntityStore } from \"./entityStore.js\";\nimport {\n  extractFragmentContext,\n  fieldNameFromStoreName,\n  makeProcessedFieldsMerger,\n  storeValueIsStoreObject,\n} from \"./helpers.js\";\nimport type { InMemoryCache } from \"./inMemoryCache.js\";\nimport {\n  defaultStreamFieldMergeFn,\n  normalizeReadFieldOptions,\n} from \"./policies.js\";\nimport type { StoreReader } from \"./readFromStore.js\";\nimport type {\n  InMemoryCacheConfig,\n  MergeTree,\n  NormalizedCache,\n  ReadMergeModifyContext,\n} from \"./types.js\";\n\nexport interface WriteContext extends ReadMergeModifyContext {\n  readonly written: {\n    [dataId: string]: SelectionSetNode[];\n  };\n  readonly fragmentMap: FragmentMap;\n  lookupFragment: FragmentMapFunction;\n  // General-purpose deep-merge function for use during writes.\n  merge<T>(existing: T, incoming: T): T;\n  // If true, merge functions will be called with undefined existing data.\n  overwrite: boolean;\n  incomingById: Map<\n    string,\n    {\n      storeObject: StoreObject;\n      mergeTree?: MergeTree;\n      fieldNodeSet: Set<FieldNode>;\n    }\n  >;\n  // Directive metadata for @client and @defer. We could use a bitfield for this\n  // information to save some space, and use that bitfield number as the keys in\n  // the context.flavors Map.\n  clientOnly: boolean;\n  deferred: boolean;\n  flavors: Map<string, FlavorableWriteContext>;\n}\n\ntype FlavorableWriteContext = Pick<\n  WriteContext,\n  \"clientOnly\" | \"deferred\" | \"flavors\"\n>;\n\n// Since there are only four possible combinations of context.clientOnly and\n// context.deferred values, we should need at most four \"flavors\" of any given\n// WriteContext. To avoid creating multiple copies of the same context, we cache\n// the contexts in the context.flavors Map (shared by all flavors) according to\n// their clientOnly and deferred values (always in that order).\nfunction getContextFlavor<TContext extends FlavorableWriteContext>(\n  context: TContext,\n  clientOnly: TContext[\"clientOnly\"],\n  deferred: TContext[\"deferred\"]\n): TContext {\n  const key = `${clientOnly}${deferred}`;\n  let flavored = context.flavors.get(key);\n  if (!flavored) {\n    context.flavors.set(\n      key,\n      (flavored =\n        context.clientOnly === clientOnly && context.deferred === deferred ?\n          context\n        : {\n            ...context,\n            clientOnly,\n            deferred,\n          })\n    );\n  }\n  return flavored as TContext;\n}\n\ninterface ProcessSelectionSetOptions {\n  dataId?: string;\n  result: Record<string, any>;\n  selectionSet: SelectionSetNode;\n  context: WriteContext;\n  mergeTree: MergeTree;\n  path: Array<string | number>;\n}\n\nexport class StoreWriter {\n  constructor(\n    public readonly cache: InMemoryCache,\n    private reader?: StoreReader,\n    private fragments?: InMemoryCacheConfig[\"fragments\"]\n  ) {}\n\n  public writeToStore<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    store: NormalizedCache,\n    {\n      query,\n      result,\n      dataId,\n      variables,\n      overwrite,\n      extensions,\n    }: Cache.WriteOptions<TData, TVariables>\n  ): Reference | undefined {\n    const operationDefinition = getOperationDefinition(query)!;\n    const merger = makeProcessedFieldsMerger();\n\n    variables = {\n      ...getDefaultValues(operationDefinition),\n      ...variables!,\n    };\n\n    const context: WriteContext = {\n      store,\n      written: {},\n      merge<T>(existing: T, incoming: T) {\n        return merger.merge(existing, incoming) as T;\n      },\n      variables: variables as OperationVariables,\n      varString: canonicalStringify(variables),\n      ...extractFragmentContext(query, this.fragments),\n      overwrite: !!overwrite,\n      incomingById: new Map(),\n      clientOnly: false,\n      deferred: false,\n      flavors: new Map(),\n      extensions,\n    };\n\n    const ref = this.processSelectionSet({\n      result: result || {},\n      dataId,\n      selectionSet: operationDefinition.selectionSet,\n      mergeTree: { map: new Map() },\n      context,\n      path: [],\n    });\n\n    if (!isReference(ref)) {\n      throw newInvariantError(`Could not identify object %s`, result);\n    }\n\n    // So far, the store has not been modified, so now it's time to process\n    // context.incomingById and merge those incoming fields into context.store.\n    context.incomingById.forEach(\n      ({ storeObject, mergeTree, fieldNodeSet }, dataId) => {\n        const entityRef = makeReference(dataId);\n\n        if (mergeTree && mergeTree.map.size) {\n          const applied = this.applyMerges(\n            mergeTree,\n            entityRef,\n            storeObject,\n            context\n          );\n          if (isReference(applied)) {\n            // Assume References returned by applyMerges have already been merged\n            // into the store. See makeMergeObjectsFunction in policies.ts for an\n            // example of how this can happen.\n            return;\n          }\n          // Otherwise, applyMerges returned a StoreObject, whose fields we should\n          // merge into the store (see store.merge statement below).\n          storeObject = applied;\n        }\n\n        if (__DEV__ && !context.overwrite) {\n          const fieldsWithSelectionSets: Record<string, true> = {};\n          fieldNodeSet.forEach((field) => {\n            if (field.selectionSet) {\n              fieldsWithSelectionSets[field.name.value] = true;\n            }\n          });\n\n          const hasSelectionSet = (storeFieldName: string) =>\n            fieldsWithSelectionSets[fieldNameFromStoreName(storeFieldName)] ===\n            true;\n\n          const hasMergeFunction = (storeFieldName: string) => {\n            const childTree = mergeTree && mergeTree.map.get(storeFieldName);\n            return Boolean(childTree && childTree.info && childTree.info.merge);\n          };\n\n          Object.keys(storeObject).forEach((storeFieldName) => {\n            // If a merge function was defined for this field, trust that it\n            // did the right thing about (not) clobbering data. If the field\n            // has no selection set, it's a scalar field, so it doesn't need\n            // a merge function (even if it's an object, like JSON data).\n            if (\n              hasSelectionSet(storeFieldName) &&\n              !hasMergeFunction(storeFieldName)\n            ) {\n              warnAboutDataLoss(\n                entityRef,\n                storeObject,\n                storeFieldName,\n                context.store\n              );\n            }\n          });\n        }\n\n        store.merge(dataId, storeObject);\n      }\n    );\n\n    // Any IDs written explicitly to the cache will be retained as\n    // reachable root IDs for garbage collection purposes. Although this\n    // logic includes root IDs like ROOT_QUERY and ROOT_MUTATION, their\n    // retainment counts are effectively ignored because cache.gc() always\n    // includes them in its root ID set.\n    store.retain(ref.__ref);\n\n    return ref;\n  }\n\n  private processSelectionSet({\n    dataId,\n    result,\n    selectionSet,\n    context,\n    // This object allows processSelectionSet to report useful information\n    // to its callers without explicitly returning that information.\n    mergeTree,\n    path: currentPath,\n  }: ProcessSelectionSetOptions): StoreObject | Reference {\n    const { policies } = this.cache;\n\n    // This variable will be repeatedly updated using context.merge to\n    // accumulate all fields that need to be written into the store.\n    let incoming: StoreObject = {};\n\n    // If typename was not passed in, infer it. Note that typename is\n    // always passed in for tricky-to-infer cases such as \"Query\" for\n    // ROOT_QUERY.\n    const typename: string | undefined =\n      (dataId && policies.rootTypenamesById[dataId]) ||\n      getTypenameFromResult(result, selectionSet, context.fragmentMap) ||\n      (dataId && (context.store.get(dataId, \"__typename\") as string));\n\n    if (\"string\" === typeof typename) {\n      incoming.__typename = typename;\n    }\n\n    // This readField function will be passed as context.readField in the\n    // KeyFieldsContext object created within policies.identify (called below).\n    // In addition to reading from the existing context.store (thanks to the\n    // policies.readField(options, context) line at the very bottom), this\n    // version of readField can read from Reference objects that are currently\n    // pending in context.incomingById, which is important whenever keyFields\n    // need to be extracted from a child object that processSelectionSet has\n    // turned into a Reference.\n    const readField: ReadFieldFunction = (...args) => {\n      const options = normalizeReadFieldOptions(\n        args,\n        incoming,\n        context.variables\n      );\n\n      if (isReference(options.from)) {\n        const info = context.incomingById.get(options.from.__ref);\n        if (info) {\n          const result = policies.readField(\n            {\n              ...options,\n              from: info.storeObject,\n            },\n            context\n          );\n\n          if (result !== void 0) {\n            return result;\n          }\n        }\n      }\n\n      return policies.readField(options, context);\n    };\n\n    const fieldNodeSet = new Set<FieldNode>();\n\n    this.flattenFields(\n      selectionSet,\n      result,\n      // This WriteContext will be the default context value for fields returned\n      // by the flattenFields method, but some fields may be assigned a modified\n      // context, depending on the presence of @client and other directives.\n      context,\n      typename\n    ).forEach((context, field) => {\n      const resultFieldKey = resultKeyNameFromField(field);\n      const value = result[resultFieldKey];\n      const path = [...currentPath, field.name.value];\n\n      fieldNodeSet.add(field);\n\n      if (value !== void 0) {\n        const storeFieldName = policies.getStoreFieldName({\n          typename,\n          fieldName: field.name.value,\n          field,\n          variables: context.variables,\n        });\n\n        const childTree = getChildMergeTree(mergeTree, storeFieldName);\n\n        let incomingValue = this.processFieldValue(\n          value,\n          field,\n          // Reset context.clientOnly and context.deferred to their default\n          // values before processing nested selection sets.\n          field.selectionSet ?\n            getContextFlavor(context, false, false)\n          : context,\n          childTree,\n          path\n        );\n\n        // To determine if this field holds a child object with a merge function\n        // defined in its type policy (see PR #7070), we need to figure out the\n        // child object's __typename.\n        let childTypename: string | undefined;\n\n        // The field's value can be an object that has a __typename only if the\n        // field has a selection set. Otherwise incomingValue is scalar.\n        if (\n          field.selectionSet &&\n          (isReference(incomingValue) || storeValueIsStoreObject(incomingValue))\n        ) {\n          childTypename = readField<string>(\"__typename\", incomingValue);\n        }\n\n        const merge = policies.getMergeFunction(\n          typename,\n          field.name.value,\n          childTypename\n        );\n\n        if (merge) {\n          childTree.info = {\n            // TODO Check compatibility against any existing childTree.field?\n            field,\n            typename,\n            merge,\n            path,\n          };\n        } else if (\n          hasDirectives([\"stream\"], field) &&\n          Array.isArray(incomingValue) &&\n          context.extensions?.[streamInfoSymbol]\n        ) {\n          childTree.info = {\n            field,\n            typename,\n            merge: defaultStreamFieldMergeFn,\n            path,\n          };\n        } else {\n          maybeRecycleChildMergeTree(mergeTree, storeFieldName);\n        }\n\n        incoming = context.merge(incoming, {\n          [storeFieldName]: incomingValue,\n        });\n      } else if (\n        __DEV__ &&\n        !context.clientOnly &&\n        !context.deferred &&\n        !addTypenameToDocument.added(field) &&\n        // If the field has a read function, it may be a synthetic field or\n        // provide a default value, so its absence from the written data should\n        // not be cause for alarm.\n        !policies.getReadFunction(typename, field.name.value)\n      ) {\n        invariant.error(\n          `Missing field '%s' while writing result %o`,\n          resultKeyNameFromField(field),\n          result\n        );\n      }\n    });\n\n    // Identify the result object, even if dataId was already provided,\n    // since we always need keyObject below.\n    try {\n      const [id, keyObject] = policies.identify(result, {\n        typename,\n        selectionSet,\n        fragmentMap: context.fragmentMap,\n        storeObject: incoming,\n        readField,\n      });\n\n      // If dataId was not provided, fall back to the id just generated by\n      // policies.identify.\n      dataId = dataId || id;\n\n      // Write any key fields that were used during identification, even if\n      // they were not mentioned in the original query.\n      if (keyObject) {\n        // TODO Reverse the order of the arguments?\n        incoming = context.merge(incoming, keyObject);\n      }\n    } catch (e) {\n      // If dataId was provided, tolerate failure of policies.identify.\n      if (!dataId) throw e;\n    }\n\n    if (\"string\" === typeof dataId) {\n      const dataRef = makeReference(dataId);\n\n      // Avoid processing the same entity object using the same selection\n      // set more than once. We use an array instead of a Set since most\n      // entity IDs will be written using only one selection set, so the\n      // size of this array is likely to be very small, meaning indexOf is\n      // likely to be faster than Set.prototype.has.\n      const sets = context.written[dataId] || (context.written[dataId] = []);\n      if (sets.indexOf(selectionSet) >= 0) return dataRef;\n      sets.push(selectionSet);\n\n      // If we're about to write a result object into the store, but we\n      // happen to know that the exact same (===) result object would be\n      // returned if we were to reread the result with the same inputs,\n      // then we can skip the rest of the processSelectionSet work for\n      // this object, and immediately return a Reference to it.\n      if (\n        this.reader &&\n        this.reader.isFresh(result, dataRef, selectionSet, context)\n      ) {\n        return dataRef;\n      }\n\n      const previous = context.incomingById.get(dataId);\n      if (previous) {\n        previous.storeObject = context.merge(previous.storeObject, incoming);\n        previous.mergeTree = mergeMergeTrees(previous.mergeTree, mergeTree);\n        fieldNodeSet.forEach((field) => previous.fieldNodeSet.add(field));\n      } else {\n        context.incomingById.set(dataId, {\n          storeObject: incoming,\n          // Save a reference to mergeTree only if it is not empty, because\n          // empty MergeTrees may be recycled by maybeRecycleChildMergeTree and\n          // reused for entirely different parts of the result tree.\n          mergeTree: mergeTreeIsEmpty(mergeTree) ? void 0 : mergeTree,\n          fieldNodeSet,\n        });\n      }\n\n      return dataRef;\n    }\n\n    return incoming;\n  }\n\n  private processFieldValue(\n    value: any,\n    field: FieldNode,\n    context: WriteContext,\n    mergeTree: MergeTree,\n    path: Array<string | number>\n  ): StoreValue {\n    if (!field.selectionSet || value === null) {\n      // In development, we need to clone scalar values so that they can be\n      // safely frozen with maybeDeepFreeze in readFromStore.ts. In production,\n      // it's cheaper to store the scalar values directly in the cache.\n      return __DEV__ ? cloneDeep(value) : value;\n    }\n\n    if (isArray(value)) {\n      return value.map((item, i) => {\n        const value = this.processFieldValue(\n          item,\n          field,\n          context,\n          getChildMergeTree(mergeTree, i),\n          [...path, i]\n        );\n        maybeRecycleChildMergeTree(mergeTree, i);\n        return value;\n      });\n    }\n\n    return this.processSelectionSet({\n      result: value,\n      selectionSet: field.selectionSet,\n      context,\n      mergeTree,\n      path,\n    });\n  }\n\n  // Implements https://spec.graphql.org/draft/#sec-Field-Collection, but with\n  // some additions for tracking @client and @defer directives.\n  private flattenFields<\n    TContext extends Pick<\n      WriteContext,\n      | \"clientOnly\"\n      | \"deferred\"\n      | \"flavors\"\n      | \"fragmentMap\"\n      | \"lookupFragment\"\n      | \"variables\"\n    >,\n  >(\n    selectionSet: SelectionSetNode,\n    result: Record<string, any>,\n    context: TContext,\n    typename = getTypenameFromResult(result, selectionSet, context.fragmentMap)\n  ): Map<FieldNode, TContext> {\n    const fieldMap = new Map<FieldNode, TContext>();\n    const { policies } = this.cache;\n\n    const limitingTrie = new Trie<{\n      // Tracks whether (selectionSet, clientOnly, deferred) has been flattened\n      // before. The GraphQL specification only uses the fragment name for\n      // skipping previously visited fragments, but the top-level fragment\n      // selection set corresponds 1:1 with the fagment name (and is slightly\n      // easier too work with), and we need to consider clientOnly and deferred\n      // values as well, potentially revisiting selection sets that were\n      // previously visited with different inherited configurations of those\n      // directives.\n      visited?: boolean;\n    }>(false); // No need for WeakMap, since limitingTrie does not escape.\n\n    (function flatten(\n      this: void,\n      selectionSet: SelectionSetNode,\n      inheritedContext: TContext\n    ) {\n      const visitedNode = limitingTrie.lookup(\n        selectionSet,\n        // Because we take inheritedClientOnly and inheritedDeferred into\n        // consideration here (in addition to selectionSet), it's possible for\n        // the same selection set to be flattened more than once, if it appears\n        // in the query with different @client and/or @directive configurations.\n        inheritedContext.clientOnly,\n        inheritedContext.deferred\n      );\n      if (visitedNode.visited) return;\n      visitedNode.visited = true;\n\n      selectionSet.selections.forEach((selection) => {\n        if (!shouldInclude(selection, context.variables)) return;\n\n        let { clientOnly, deferred } = inheritedContext;\n        if (\n          // Since the presence of @client or @defer on this field can only\n          // cause clientOnly or deferred to become true, we can skip the\n          // forEach loop if both clientOnly and deferred are already true.\n          !(clientOnly && deferred) &&\n          isNonEmptyArray(selection.directives)\n        ) {\n          selection.directives.forEach((dir) => {\n            const name = dir.name.value;\n            if (name === \"client\") clientOnly = true;\n            if (name === \"defer\") {\n              const args = argumentsObjectFromField(dir, context.variables);\n              // The @defer directive takes an optional args.if boolean\n              // argument, similar to @include(if: boolean). Note that\n              // @defer(if: false) does not make context.deferred false, but\n              // instead behaves as if there was no @defer directive.\n              if (!args || (args as { if?: boolean }).if !== false) {\n                deferred = true;\n              }\n              // TODO In the future, we may want to record args.label using\n              // context.deferred, if a label is specified.\n            }\n          });\n        }\n\n        if (isField(selection)) {\n          const existing = fieldMap.get(selection);\n          if (existing) {\n            // If this field has been visited along another recursive path\n            // before, the final context should have clientOnly or deferred set\n            // to true only if *all* paths have the directive (hence the &&).\n            clientOnly = clientOnly && existing.clientOnly;\n            deferred = deferred && existing.deferred;\n          }\n\n          fieldMap.set(\n            selection,\n            getContextFlavor(context, clientOnly, deferred)\n          );\n        } else {\n          const fragment = getFragmentFromSelection(\n            selection,\n            context.lookupFragment\n          );\n\n          if (!fragment && selection.kind === Kind.FRAGMENT_SPREAD) {\n            throw newInvariantError(\n              `No fragment named %s`,\n              selection.name.value\n            );\n          }\n\n          if (\n            fragment &&\n            policies.fragmentMatches(\n              fragment,\n              typename,\n              result,\n              context.variables\n            )\n          ) {\n            flatten(\n              fragment.selectionSet,\n              getContextFlavor(context, clientOnly, deferred)\n            );\n          }\n        }\n      });\n    })(selectionSet, context);\n\n    return fieldMap;\n  }\n\n  private applyMerges<T extends StoreValue>(\n    mergeTree: MergeTree,\n    existing: StoreValue,\n    incoming: T,\n    context: WriteContext,\n    getStorageArgs?: Parameters<EntityStore[\"getStorage\"]>\n  ): T | Reference {\n    if (mergeTree.map.size && !isReference(incoming)) {\n      const e: StoreObject | Reference | undefined =\n        // Items in the same position in different arrays are not\n        // necessarily related to each other, so when incoming is an array\n        // we process its elements as if there was no existing data.\n        (\n          !isArray(incoming) &&\n          // Likewise, existing must be either a Reference or a StoreObject\n          // in order for its fields to be safe to merge with the fields of\n          // the incoming object.\n          (isReference(existing) || storeValueIsStoreObject(existing))\n        ) ?\n          existing\n        : void 0;\n\n      // This narrowing is implied by mergeTree.map.size > 0 and\n      // !isReference(incoming), though TypeScript understandably cannot\n      // hope to infer this type.\n      const i = incoming as StoreObject | StoreValue[];\n\n      // The options.storage objects provided to read and merge functions\n      // are derived from the identity of the parent object plus a\n      // sequence of storeFieldName strings/numbers identifying the nested\n      // field name path of each field value to be merged.\n      if (e && !getStorageArgs) {\n        getStorageArgs = [isReference(e) ? e.__ref : e];\n      }\n\n      // It's possible that applying merge functions to this subtree will\n      // not change the incoming data, so this variable tracks the fields\n      // that did change, so we can create a new incoming object when (and\n      // only when) at least one incoming field has changed. We use a Map\n      // to preserve the type of numeric keys.\n      let changedFields: Map<string | number, StoreValue> | undefined;\n\n      const getValue = (\n        from: typeof e | typeof i,\n        name: string | number\n      ): StoreValue => {\n        return (\n          isArray(from) ?\n            typeof name === \"number\" ?\n              from[name]\n            : void 0\n          : context.store.getFieldValue(from, String(name))\n        );\n      };\n\n      mergeTree.map.forEach((childTree, storeFieldName) => {\n        const eVal = getValue(e, storeFieldName);\n        const iVal = getValue(i, storeFieldName);\n        // If we have no incoming data, leave any existing data untouched.\n        if (void 0 === iVal) return;\n        if (getStorageArgs) {\n          getStorageArgs.push(storeFieldName);\n        }\n        const aVal = this.applyMerges(\n          childTree,\n          eVal,\n          iVal,\n          context,\n          getStorageArgs\n        );\n        if (aVal !== iVal) {\n          changedFields = changedFields || new Map();\n          changedFields.set(storeFieldName, aVal);\n        }\n        if (getStorageArgs) {\n          invariant(getStorageArgs.pop() === storeFieldName);\n        }\n      });\n\n      if (changedFields) {\n        // Shallow clone i so we can add changed fields to it.\n        incoming = (isArray(i) ? i.slice(0) : { ...i }) as T;\n        changedFields.forEach((value, name) => {\n          (incoming as any)[name] = value;\n        });\n      }\n    }\n\n    if (mergeTree.info) {\n      return this.cache.policies.runMergeFunction(\n        existing,\n        incoming,\n        mergeTree.info,\n        context,\n        getStorageArgs && context.store.getStorage(...getStorageArgs)\n      );\n    }\n\n    return incoming;\n  }\n}\n\nconst emptyMergeTreePool: MergeTree[] = [];\n\nfunction getChildMergeTree(\n  { map }: MergeTree,\n  name: string | number\n): MergeTree {\n  if (!map.has(name)) {\n    map.set(name, emptyMergeTreePool.pop() || { map: new Map() });\n  }\n  return map.get(name)!;\n}\n\nfunction mergeMergeTrees(\n  left: MergeTree | undefined,\n  right: MergeTree | undefined\n): MergeTree {\n  if (left === right || !right || mergeTreeIsEmpty(right)) return left!;\n  if (!left || mergeTreeIsEmpty(left)) return right;\n\n  const info =\n    left.info && right.info ?\n      {\n        ...left.info,\n        ...right.info,\n      }\n    : left.info || right.info;\n\n  const needToMergeMaps = left.map.size && right.map.size;\n  const map =\n    needToMergeMaps ? new Map()\n    : left.map.size ? left.map\n    : right.map;\n\n  const merged = { info, map };\n\n  if (needToMergeMaps) {\n    const remainingRightKeys = new Set(right.map.keys());\n\n    left.map.forEach((leftTree, key) => {\n      merged.map.set(key, mergeMergeTrees(leftTree, right.map.get(key)));\n      remainingRightKeys.delete(key);\n    });\n\n    remainingRightKeys.forEach((key) => {\n      merged.map.set(\n        key,\n        mergeMergeTrees(right.map.get(key), left.map.get(key))\n      );\n    });\n  }\n\n  return merged;\n}\n\nfunction mergeTreeIsEmpty(tree: MergeTree | undefined): boolean {\n  return !tree || !(tree.info || tree.map.size);\n}\n\nfunction maybeRecycleChildMergeTree({ map }: MergeTree, name: string | number) {\n  const childTree = map.get(name);\n  if (childTree && mergeTreeIsEmpty(childTree)) {\n    emptyMergeTreePool.push(childTree);\n    map.delete(name);\n  }\n}\n\nconst warnings = new Set<string>();\n\n// Note that this function is unused in production, and thus should be\n// pruned by any well-configured minifier.\nfunction warnAboutDataLoss(\n  existingRef: Reference,\n  incomingObj: StoreObject,\n  storeFieldName: string,\n  store: NormalizedCache\n) {\n  const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {\n    const child = store.getFieldValue<StoreObject>(objOrRef, storeFieldName);\n    return typeof child === \"object\" && child;\n  };\n\n  const existing = getChild(existingRef);\n  if (!existing) return;\n\n  const incoming = getChild(incomingObj);\n  if (!incoming) return;\n\n  // It's always safe to replace a reference, since it refers to data\n  // safely stored elsewhere.\n  if (isReference(existing)) return;\n\n  // If the values are structurally equivalent, we do not need to worry\n  // about incoming replacing existing.\n  if (equal(existing, incoming)) return;\n\n  // If we're replacing every key of the existing object, then the\n  // existing data would be overwritten even if the objects were\n  // normalized, so warning would not be helpful here.\n  if (\n    Object.keys(existing).every(\n      (key) => store.getFieldValue(incoming, key) !== void 0\n    )\n  ) {\n    return;\n  }\n\n  const parentType =\n    store.getFieldValue<string>(existingRef, \"__typename\") ||\n    store.getFieldValue<string>(incomingObj, \"__typename\");\n  const fieldName = fieldNameFromStoreName(storeFieldName);\n  const typeDotName = `${parentType}.${fieldName}`;\n  // Avoid warning more than once for the same type and field name.\n  if (warnings.has(typeDotName)) return;\n  warnings.add(typeDotName);\n\n  const childTypenames: string[] = [];\n  // Arrays do not have __typename fields, and always need a custom merge\n  // function, even if their elements are normalized entities.\n  if (!isArray(existing) && !isArray(incoming)) {\n    [existing, incoming].forEach((child) => {\n      const typename = store.getFieldValue(child, \"__typename\");\n      if (typeof typename === \"string\" && !childTypenames.includes(typename)) {\n        childTypenames.push(typename);\n      }\n    });\n  }\n\n  invariant.warn(\n    `Cache data may be lost when replacing the %s field of a %s object.\n\nThis could cause additional (usually avoidable) network requests to fetch data that were otherwise cached.\n\nTo address this problem (which is not a bug in Apollo Client), %sdefine a custom merge function for the %s field, so InMemoryCache can safely merge these objects:\n\n  existing: %o\n  incoming: %o\n\nFor more information about these options, please refer to the documentation:\n\n  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers\n  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects\n`,\n    fieldName,\n    parentType,\n    childTypenames.length ?\n      \"either ensure all objects of type \" +\n        childTypenames.join(\" and \") +\n        \" have an ID or a custom merge function, or \"\n    : \"\",\n    typeDotName,\n    Array.isArray(existing) ? [...existing] : { ...existing },\n    Array.isArray(incoming) ? [...incoming] : { ...incoming }\n  );\n}\n\nfunction getTypenameFromResult(\n  result: Record<string, any>,\n  selectionSet: SelectionSetNode,\n  fragmentMap?: FragmentMap\n): string | undefined {\n  let fragments: undefined | Array<InlineFragmentNode | FragmentSpreadNode>;\n  for (const selection of selectionSet.selections) {\n    if (isField(selection)) {\n      if (selection.name.value === \"__typename\") {\n        return result[resultKeyNameFromField(selection)];\n      }\n    } else if (fragments) {\n      fragments.push(selection);\n    } else {\n      fragments = [selection];\n    }\n  }\n  if (typeof result.__typename === \"string\") {\n    return result.__typename;\n  }\n  if (fragments) {\n    for (const selection of fragments) {\n      const typename = getTypenameFromResult(\n        result,\n        getFragmentFromSelection(selection, fragmentMap)!.selectionSet,\n        fragmentMap\n      );\n      if (typeof typename === \"string\") {\n        return typename;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/config/jest/areCombinedGraphQLErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { CombinedGraphQLErrors } from \"@apollo/client\";\n\nexport const areCombinedGraphQLErrorsEqual: Tester = function (\n  a,\n  b,\n  customTesters\n) {\n  const isACombinedGraphQLErrors = CombinedGraphQLErrors.is(a);\n  const isBCombinedGraphQLErrors = CombinedGraphQLErrors.is(b);\n\n  if (isACombinedGraphQLErrors && isBCombinedGraphQLErrors) {\n    return (\n      a.message === b.message &&\n      this.equals(a.errors, b.errors, customTesters) &&\n      this.equals(a.data, b.data, customTesters) &&\n      this.equals(a.extensions, b.extensions, customTesters)\n    );\n  } else if (isACombinedGraphQLErrors === isBCombinedGraphQLErrors) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/config/jest/areCombinedProtocolErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { CombinedProtocolErrors } from \"@apollo/client\";\n\nexport const areCombinedProtocolErrorsEqual: Tester = function (\n  a,\n  b,\n  customTesters\n) {\n  const isACombinedProtocolErrors = CombinedProtocolErrors.is(a);\n  const isBCombinedProtocolErrors = CombinedProtocolErrors.is(b);\n\n  if (isACombinedProtocolErrors && isBCombinedProtocolErrors) {\n    return (\n      a.message === b.message && this.equals(a.errors, b.errors, customTesters)\n    );\n  } else if (isACombinedProtocolErrors === isBCombinedProtocolErrors) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/config/jest/areGraphQlErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\nimport { GraphQLError } from \"graphql\";\n\nexport const areGraphQLErrorsEqual: Tester = function (a, b, customTesters) {\n  if (a instanceof GraphQLError || b instanceof GraphQLError) {\n    return this.equals(\n      a instanceof GraphQLError ? a.toJSON() : a,\n      b instanceof GraphQLError ? b.toJSON() : b,\n      customTesters\n    );\n  }\n};\n"
  },
  {
    "path": "src/config/jest/areLocalStateErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { LocalStateError } from \"@apollo/client/errors\";\n\nexport const areLocalStateErrorsEqual: Tester = function (a, b, customTesters) {\n  const isALocalStateError = LocalStateError.is(a);\n  const isBLocalStateError = LocalStateError.is(b);\n\n  if (isALocalStateError && isBLocalStateError) {\n    return (\n      a.message === b.message &&\n      this.equals(a.path, b.path, customTesters) &&\n      this.equals(a.cause, b.cause, customTesters)\n    );\n  } else if (isALocalStateError === isBLocalStateError) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/config/jest/areMissingFieldErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nexport const areMissingFieldErrorsEqual: Tester = function (\n  a,\n  b,\n  customTesters\n) {\n  const isAMissingFieldError = a && a.name === \"MissingFieldError\";\n  const isBMissingFieldError = b && b.name === \"MissingFieldError\";\n\n  if (isAMissingFieldError && isBMissingFieldError) {\n    return (\n      a.message === b.message &&\n      this.equals(a.path, b.path, customTesters) &&\n      this.equals(a.query, b.query, customTesters) &&\n      this.equals(a.variables, b.variables, customTesters) &&\n      this.equals(a.missing, b.missing, customTesters)\n    );\n  }\n\n  if (isAMissingFieldError === isBMissingFieldError) {\n    return;\n  }\n\n  return false;\n};\n"
  },
  {
    "path": "src/config/jest/areServerErrorsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { ServerError } from \"@apollo/client\";\n\nexport const areServerErrorsEqual: Tester = function (a, b, customTesters) {\n  const isAServerError = ServerError.is(a);\n  const isBServerError = ServerError.is(b);\n\n  if (isAServerError && isBServerError) {\n    return (\n      a.message === b.message &&\n      this.equals(a.response, b.response, customTesters) &&\n      this.equals(a.statusCode, b.statusCode, customTesters) &&\n      this.equals(a.bodyText, b.bodyText, customTesters)\n    );\n  } else if (isAServerError === isBServerError) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/config/jest/areWeakRefsEqual.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nexport const areWeakRefsEqual: Tester = function (a, b, customTesters) {\n  if (a && a instanceof WeakRef && b && b instanceof WeakRef)\n    return this.equals(a.deref(), b.deref(), customTesters);\n};\n"
  },
  {
    "path": "src/config/jest/resolver.ts",
    "content": "import { join } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\nimport type { ResolverOptions } from \"jest-resolve\";\n\nconst possibleExtensions = [\".ts\", \".tsx\", \".js\", \".jsx\"];\n\nexport function sync(path: string, options: ResolverOptions): string {\n  const resolver = options.defaultResolver;\n\n  if (process.env.TEST_ENV === \"ci\" && path.startsWith(\"@apollo/client\")) {\n    if (path === \"@apollo/client/react\") {\n      path = \"@apollo/client/react/compiled\";\n    }\n    let result = import.meta.resolve(\n      path,\n      pathToFileURL(join(options.rootDir!, \"../dist/index.js\"))\n    );\n    if (result.includes(\"__cjs\")) {\n      throw new Error(\n        \"Resolved to CJS entry point, we want to test ESM entry points!\"\n      );\n    }\n    if (!result.includes(\"dist\")) {\n      throw new Error(\"Did not resolve to build artifact!\");\n    }\n    return fileURLToPath(result);\n  }\n\n  if (path.startsWith(\".\") && path.endsWith(\".js\")) {\n    for (const extension of possibleExtensions) {\n      try {\n        return resolver(path.replace(/\\.js$/i, extension), options);\n      } catch {}\n    }\n  }\n\n  if (path.startsWith(\"@apollo/client\")) {\n    return fileURLToPath(import.meta.resolve(path));\n  }\n\n  return resolver(path, options);\n}\n"
  },
  {
    "path": "src/config/jest/setup.ts",
    "content": "//@ts-ignore\nglobalThis.__DEV__ = true;\n\nimport { TextDecoder, TextEncoder } from \"util\";\n\nimport gql from \"graphql-tag\";\n\nglobal.TextEncoder ??= TextEncoder;\n// @ts-ignore\nglobal.TextDecoder ??= TextDecoder;\nimport \"@testing-library/jest-dom\";\n// eslint-disable-next-line local-rules/import-from-inside-other-export\nimport \"../../testing/matchers/index.js\";\nimport { setLogVerbosity } from \"@apollo/client\";\nimport {\n  loadDevMessages,\n  loadErrorMessageHandler,\n  loadErrorMessages,\n} from \"@apollo/client/dev\";\n\nimport { areCombinedGraphQLErrorsEqual } from \"./areCombinedGraphQLErrorsEqual.js\";\nimport { areCombinedProtocolErrorsEqual } from \"./areCombinedProtocolErrorsEqual.js\";\nimport { areGraphQLErrorsEqual } from \"./areGraphQlErrorsEqual.js\";\nimport { areLocalStateErrorsEqual } from \"./areLocalStateErrorsEqual.js\";\nimport { areMissingFieldErrorsEqual } from \"./areMissingFieldErrorsEqual.js\";\nimport { areServerErrorsEqual } from \"./areServerErrorsEqual.js\";\nimport { areWeakRefsEqual } from \"./areWeakRefsEqual.js\";\n\nsetLogVerbosity(\"log\");\n\n// Turn off warnings for repeated fragment names\ngql.disableFragmentWarnings();\n\nprocess.on(\"unhandledRejection\", () => {});\n\nif (process.env.TEST_ENV === \"ci\") {\n  // in CI, we work with the compiled code, so we need to load the error messages\n  loadDevMessages();\n  loadErrorMessages();\n} else {\n  // locally, the error messages are in the source code, so we need to load the\n  // error message handler\n  loadErrorMessageHandler();\n}\n\nfunction fail(reason = \"fail was called in a test.\") {\n  expect(reason).toBe(undefined);\n}\n\n// @ts-ignore\nglobalThis.fail = fail;\n\nif (!Symbol.dispose) {\n  Object.defineProperty(Symbol, \"dispose\", {\n    value: Symbol(\"dispose\"),\n  });\n}\nif (!Symbol.asyncDispose) {\n  Object.defineProperty(Symbol, \"asyncDispose\", {\n    value: Symbol(\"asyncDispose\"),\n  });\n}\n\n// @ts-ignore\nexpect.addEqualityTesters([\n  areServerErrorsEqual,\n  areCombinedGraphQLErrorsEqual,\n  areCombinedProtocolErrorsEqual,\n  areGraphQLErrorsEqual,\n  areLocalStateErrorsEqual,\n  areMissingFieldErrorsEqual,\n  areWeakRefsEqual,\n]);\n\n// not available in JSDOM 🙄\nglobal.structuredClone = (val) => JSON.parse(JSON.stringify(val));\nglobal.ReadableStream ||= require(\"stream/web\").ReadableStream;\nglobal.TransformStream ||= require(\"stream/web\").TransformStream;\n\nAbortSignal.timeout = (ms) => {\n  const controller = new AbortController();\n  setTimeout(\n    () =>\n      controller.abort(\n        new DOMException(\"The operation timed out.\", \"TimeoutError\")\n      ),\n    ms\n  );\n  return controller.signal;\n};\n"
  },
  {
    "path": "src/core/ApolloClient.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport { OperationTypeNode } from \"graphql\";\nimport type { Observable } from \"rxjs\";\nimport { map } from \"rxjs\";\n\nimport type {\n  ApolloCache,\n  Cache,\n  IgnoreModifier,\n  Reference,\n} from \"@apollo/client/cache\";\nimport type { Incremental } from \"@apollo/client/incremental\";\nimport { NotImplementedHandler } from \"@apollo/client/incremental\";\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport { execute } from \"@apollo/client/link\";\nimport type { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport type { LocalState } from \"@apollo/client/local-state\";\nimport type { MaybeMasked, Unmasked } from \"@apollo/client/masking\";\nimport { DocumentTransform } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  VariablesOption,\n  variablesUnknownSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  checkDocument,\n  compact,\n  getApolloClientMemoryInternals,\n  mapObservableFragmentMemoized,\n  mergeOptions,\n  removeMaskedFragmentSpreads,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { version } from \"../version.js\";\n\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport { QueryManager } from \"./QueryManager.js\";\nimport type {\n  DefaultContext,\n  ErrorLike,\n  InternalRefetchQueriesInclude,\n  InternalRefetchQueriesResult,\n  MutationQueryReducersMap,\n  MutationUpdaterFunction,\n  NormalizedExecutionResult,\n  OnQueryUpdated,\n  OperationVariables,\n  RefetchQueriesInclude,\n  RefetchQueriesPromiseResults,\n  SubscriptionObservable,\n  TypedDocumentNode,\n} from \"./types.js\";\nimport type {\n  ErrorPolicy,\n  FetchPolicy,\n  MutationFetchPolicy,\n  NextFetchPolicyContext,\n  RefetchWritePolicy,\n  WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\n\nlet hasSuggestedDevtools = false;\n\nexport declare namespace ApolloClient {\n  export interface DefaultOptions {\n    watchQuery?: Partial<ApolloClient.WatchQueryOptions<any, any>>;\n    query?: Partial<ApolloClient.QueryOptions<any, any>>;\n    mutate?: Partial<ApolloClient.MutateOptions<any, any, any>>;\n  }\n\n  export interface Options {\n    /**\n     * An `ApolloLink` instance to serve as Apollo Client's network layer. For more information, see [Advanced HTTP networking](https://www.apollographql.com/docs/react/networking/advanced-http-networking/).\n     */\n    link: ApolloLink;\n    /**\n     * The cache that Apollo Client should use to store query results locally. The recommended cache is `InMemoryCache`, which is provided by the `@apollo/client` package.\n     *\n     * For more information, see [Configuring the cache](https://www.apollographql.com/docs/react/caching/cache-configuration/).\n     */\n    cache: ApolloCache;\n    /**\n     * The time interval (in milliseconds) before Apollo Client force-fetches queries after a server-side render.\n     *\n     * @defaultValue `0` (no delay)\n     */\n    ssrForceFetchDelay?: number;\n    /**\n     * When using Apollo Client for [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/), set this to `true` so that the [`getDataFromTree` function](../react/ssr/#getdatafromtree) can work effectively.\n     *\n     * @defaultValue `false`\n     */\n    ssrMode?: boolean;\n    /**\n     * If `false`, Apollo Client sends every created query to the server, even if a _completely_ identical query (identical in terms of query string, variable values, and operationName) is already in flight.\n     *\n     * @defaultValue `true`\n     */\n    queryDeduplication?: boolean;\n    /**\n     * Provide this object to set application-wide default values for options you can provide to the `watchQuery`, `query`, and `mutate` functions. See below for an example object.\n     *\n     * See this [example object](https://www.apollographql.com/docs/react/api/core/ApolloClient#example-defaultoptions-object).\n     */\n    defaultOptions?: ApolloClient.DefaultOptions;\n    defaultContext?: Partial<DefaultContext>;\n    /**\n     * If `true`, Apollo Client will assume results read from the cache are never mutated by application code, which enables substantial performance optimizations.\n     *\n     * @defaultValue `false`\n     */\n    assumeImmutableResults?: boolean;\n    localState?: LocalState;\n    /** {@inheritDoc @apollo/client/link/client-awareness!ClientAwarenessLink.ClientAwarenessOptions:interface} */\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    /** {@inheritDoc @apollo/client/link/client-awareness!ClientAwarenessLink.EnhancedClientAwarenessOptions:interface} */\n    enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n    documentTransform?: DocumentTransform;\n\n    /**\n     * Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.\n     *\n     * @since 3.11.0\n     */\n    devtools?: ApolloClient.DevtoolsOptions;\n\n    /**\n     * Determines if data masking is enabled for the client.\n     *\n     * @defaultValue false\n     */\n    dataMasking?: boolean;\n\n    /**\n     * Determines the strategy used to parse incremental chunks from `@defer`\n     * queries.\n     */\n    incrementalHandler?: Incremental.Handler<any>;\n\n    /**\n     * @experimental\n     * Allows passing in \"experiments\", experimental features that might one day\n     * become part of Apollo Client's core functionality.\n     * Keep in mind that these features might change the core of Apollo Client.\n     * Do not pass in experiments that are not provided by Apollo.\n     */\n    experiments?: ApolloClient.Experiment[];\n  }\n\n  interface DevtoolsOptions {\n    /**\n     * If `true`, the [Apollo Client Devtools](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) browser extension can connect to this `ApolloClient` instance.\n     *\n     * The default value is `false` in production and `true` in development if there is a `window` object.\n     */\n    enabled?: boolean;\n\n    /**\n     * Optional name for this `ApolloClient` instance in the devtools. This is\n     * useful when you instantiate multiple clients and want to be able to\n     * identify them by name.\n     */\n    name?: string;\n  }\n\n  export type MutateOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n  > = {\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#optimisticResponse:member} */\n    optimisticResponse?:\n      | Unmasked<NoInfer<TData>>\n      | ((\n          vars: TVariables,\n          { IGNORE }: { IGNORE: IgnoreModifier }\n        ) => Unmasked<NoInfer<TData>> | IgnoreModifier);\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#updateQueries:member} */\n    updateQueries?: MutationQueryReducersMap<TData>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#refetchQueries:member} */\n    refetchQueries?:\n      | ((\n          result: NormalizedExecutionResult<Unmasked<TData>>\n        ) => InternalRefetchQueriesInclude)\n      | InternalRefetchQueriesInclude;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#awaitRefetchQueries:member} */\n    awaitRefetchQueries?: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#update:member} */\n    update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#onQueryUpdated:member} */\n    onQueryUpdated?: OnQueryUpdated<any>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: MutationFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#keepRootFields:member} */\n    keepRootFields?: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#mutation:member} */\n    mutation: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  } & VariablesOption<NoInfer<TVariables>>;\n\n  export interface MutateResult<TData = unknown> {\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#data:member} */\n    data: TData | undefined;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#error:member} */\n    error?: ErrorLike;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#extensions:member} */\n    extensions?: Record<string, unknown>;\n  }\n\n  /**\n   * Query options.\n   */\n  export type QueryOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: FetchPolicy;\n  } & VariablesOption<NoInfer<TVariables>>;\n\n  export interface QueryResult<TData = unknown> {\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n    data: TData | undefined;\n\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n    error?: ErrorLike;\n  }\n\n  /**\n   * Options object for the `client.refetchQueries` method.\n   */\n  export interface RefetchQueriesOptions<TCache extends ApolloCache, TResult> {\n    /**\n     * Optional function that updates cached fields to trigger refetches of queries that include those fields.\n     */\n    updateCache?: (cache: TCache) => void;\n\n    /**\n     * Optional array specifying queries to refetch. Each element can be either a query's string name or a `DocumentNode` object.\n     *\n     * Pass `\"active\"` as a shorthand to refetch all active queries, or `\"all\"` to refetch all active and inactive queries.\n     *\n     * Analogous to the [`options.refetchQueries`](https://www.apollographql.com/docs/react/data/mutations/#options) array for mutations.\n     */\n    include?: RefetchQueriesInclude;\n\n    /**\n     * If `true`, the `options.updateCache` function is executed on a temporary optimistic layer of `InMemoryCache`, so its modifications can be discarded from the cache after observing which fields it invalidated.\n     *\n     * Defaults to `false`, meaning `options.updateCache` updates the cache in a lasting way.\n     */\n    optimistic?: boolean;\n\n    /**\n     * Optional callback function that's called once for each `ObservableQuery` that's either affected by `options.updateCache` or listed in `options.include` (or both).\n     *\n     * If `onQueryUpdated` is not provided, the default implementation returns the result of calling `observableQuery.refetch()`. When `onQueryUpdated` is provided, it can dynamically decide whether (and how) each query should be refetched.\n     *\n     * Returning `false` from `onQueryUpdated` prevents the associated query from being refetched.\n     */\n    onQueryUpdated?: OnQueryUpdated<TResult> | null;\n  }\n\n  /**\n   * The result of client.refetchQueries is thenable/awaitable, if you just want\n   * an array of fully resolved results, but you can also access the raw results\n   * immediately by examining the additional `queries` and `results` properties of\n   * the `RefetchQueriesResult<TResult> object`.\n   */\n  export interface RefetchQueriesResult<TResult>\n    extends Promise<RefetchQueriesPromiseResults<TResult>>,\n      RefetchQueriesResult.AdditionalProperties<TResult> {}\n\n  export namespace RefetchQueriesResult {\n    export interface AdditionalProperties<TResult> {\n      /**\n       * An array of ObservableQuery objects corresponding 1:1 to TResult values\n       * in the results arrays (both the `result` property and the resolved value).\n       */\n      queries: ObservableQuery<any>[];\n      /**\n       * An array of results that were either returned by `onQueryUpdated`, or provided by default in the absence of `onQueryUpdated`, including pending promises.\n       *\n       * If `onQueryUpdated` returns `false` for a given query, no result is provided for that query.\n       *\n       * If `onQueryUpdated` returns `true`, the resulting `Promise<ApolloQueryResult<any>>` is included in the `results` array instead of `true`.\n       */\n      results: InternalRefetchQueriesResult<TResult>[];\n    }\n  }\n\n  export type SubscribeOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#query:member} */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: FetchPolicy;\n\n    /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#extensions:member} */\n    extensions?: Record<string, any>;\n  } & VariablesOption<NoInfer<TVariables>>;\n\n  export interface SubscribeResult<TData = unknown> {\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#data:member} */\n    data: TData | undefined;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#error:member} */\n    error?: ErrorLike;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#extensions:member} */\n    extensions?: Record<string, unknown>;\n  }\n\n  export type WatchFragmentOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = ApolloCache.WatchFragmentOptions<TData, TVariables>;\n\n  export type WatchFragmentResult<TData = unknown> =\n    ApolloCache.WatchFragmentResult<MaybeMasked<TData>>;\n\n  export interface ObservableFragment<TData = unknown>\n    extends Observable<ApolloClient.WatchFragmentResult<TData>> {\n    /**\n     * Return the current result for the fragment.\n     */\n    getCurrentResult: () => ApolloClient.WatchFragmentResult<TData>;\n  }\n\n  /**\n   * Watched query options.\n   */\n  export type WatchQueryOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: WatchQueryFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */\n    nextFetchPolicy?:\n      | WatchQueryFetchPolicy\n      | ((\n          this: WatchQueryOptions<TData, TVariables>,\n          currentFetchPolicy: WatchQueryFetchPolicy,\n          context: NextFetchPolicyContext<TData, TVariables>\n        ) => WatchQueryFetchPolicy);\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#initialFetchPolicy:member} */\n    initialFetchPolicy?: WatchQueryFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n    refetchWritePolicy?: RefetchWritePolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */\n    pollInterval?: number;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */\n    notifyOnNetworkStatusChange?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n    returnPartialData?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */\n    skipPollAttempt?: () => boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * @internal This API is meant for framework integrations only.\n     * Do not use for everyday use.\n     *\n     * Indicates that the variables are unknown at the time of query creation.\n     * This option can only be set when `fetchPolicy` is `'standby'`.\n     * Setting this to `true` will prevent `client.refetchQueries` from refetching\n     * this query before it has left the `'standby'` state, either by setting a\n     * `fetchPolicy`, or by calling `observableQuery.refetch()` explicitly.\n     *\n     * Changing this option after the query has been created will have no effect.\n     */\n    [variablesUnknownSymbol]?: boolean;\n  } & VariablesOption<NoInfer<TVariables>>;\n\n  namespace Base {\n    export interface ReadQueryOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > {\n      /**\n       * The GraphQL query shape to be used constructed using the `gql` template\n       * string tag. The query will be used to determine the\n       * shape of the data to be read.\n       */\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n      /**\n       * The root id to be used. Defaults to \"ROOT_QUERY\", which is the ID of the\n       * root query object. This property makes `readQuery` capable of reading data\n       * from any object in the cache.\n       */\n      id?: string;\n\n      /**\n       * Whether to return incomplete data rather than null.\n       * @defaultValue false\n       */\n      returnPartialData?: boolean;\n\n      /**\n       * Whether to read from optimistic or non-optimistic cache data.\n       * This option should be preferred over the `optimistic` parameter of the\n       * `readQuery` method.\n       * @defaultValue false\n       */\n      optimistic?: boolean;\n    }\n  }\n  export type ReadQueryOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = Base.ReadQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    export interface ReadQueryOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > extends Base.ReadQueryOptions<TData, TVariables> {\n      /**\n       * Any variables that the GraphQL query may depend on.\n       */\n      variables?: TVariables;\n    }\n  }\n\n  namespace Base {\n    export interface ReadFragmentOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > {\n      /**\n       * A GraphQL document created using the `gql` template string tag\n       * with one or more fragments which will be used to determine\n       * the shape of data to read. If you provide more than one fragment in this\n       * document then you must also specify `fragmentName` to specify which\n       * fragment is the root fragment.\n       */\n      fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n      /**\n       * The name of the fragment in your GraphQL document to be used. If you do\n       * not provide a `fragmentName` and there is only one fragment in your\n       * `fragment` document then that fragment will be used.\n       */\n      fragmentName?: string;\n\n      /**\n       * Whether to return incomplete data rather than null.\n       * @defaultValue false\n       */\n      returnPartialData?: boolean;\n      /**\n       * Whether to read from optimistic or non-optimistic cache data.\n       * This option should be preferred over the `optimistic` parameter of the\n       * `readFragment` method.\n       * @defaultValue false\n       */\n      optimistic?: boolean;\n    }\n  }\n\n  export namespace DocumentationTypes {\n    export interface ReadFragmentOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > extends Base.ReadFragmentOptions<TData, TVariables> {\n      /**\n       * The root id to be used. This id should take the same form as the\n       * value returned by the `cache.identify` function. If a value with your\n       * id does not exist in the store, `null` will be returned.\n       */\n      id?: string;\n\n      /**\n       * An object containing a `__typename` and primary key fields\n       * (such as `id`) identifying the entity object from which the fragment will\n       * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n       * (uncommon).\n       *\n       * @remarks\n       * `from` is given precedence over `id` when both are provided.\n       */\n      from?: ApolloCache.FromOptionValue<TData>;\n    }\n  }\n\n  export type ReadFragmentOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = Base.ReadFragmentOptions<TData, TVariables> &\n    VariablesOption<TVariables> &\n    Cache.CacheIdentifierOption<TData>;\n\n  export namespace DocumentationTypes {\n    export interface WriteQueryOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > extends Base.WriteQueryOptions<TData, TVariables> {\n      /**\n       * Any variables that your GraphQL fragments depend on.\n       */\n      variables?: TVariables;\n    }\n  }\n\n  namespace Base {\n    export interface WriteQueryOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > {\n      /**\n       * The GraphQL query shape to be used constructed using the `gql` template\n       * string tag. The query will be used to determine the\n       * shape of the data to be read.\n       */\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n      /**\n       * The root id to be used. Defaults to \"ROOT_QUERY\", which is the ID of the\n       * root query object. This property makes writeQuery capable of writing data\n       * to any object in the cache.\n       */\n      id?: string;\n      /**\n       * The data to write to the store.\n       */\n      data: Unmasked<TData>;\n      /**\n       * Whether to notify query watchers.\n       * @defaultValue true\n       */\n      broadcast?: boolean;\n      /**\n       * When true, ignore existing field data rather than merging it with\n       * incoming data.\n       * @defaultValue false\n       */\n      overwrite?: boolean;\n      /**\n       * GraphQL extensions for the write operation. Any provided `extensions`\n       * are available in `merge` functions.\n       */\n      extensions?: Record<string, unknown>;\n    }\n  }\n  export type WriteQueryOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = Base.WriteQueryOptions<TData, TVariables> & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    export interface WriteQueryOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > extends Base.WriteQueryOptions<TData, TVariables> {\n      /**\n       * Any variables that the GraphQL query may depend on.\n       */\n      variables?: TVariables;\n    }\n  }\n\n  namespace Base {\n    export interface WriteFragmentOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > {\n      /**\n       * A GraphQL document created using the `gql` template string tag from\n       * `graphql-tag` with one or more fragments which will be used to determine\n       * the shape of data to read. If you provide more than one fragment in this\n       * document then you must also specify `fragmentName` to specify which\n       * fragment is the root fragment.\n       */\n      fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n      /**\n       * The name of the fragment in your GraphQL document to be used. If you do\n       * not provide a `fragmentName` and there is only one fragment in your\n       * `fragment` document then that fragment will be used.\n       */\n      fragmentName?: string;\n\n      /**\n       * The data to write to the store.\n       */\n      data: Unmasked<TData>;\n      /**\n       * Whether to notify query watchers.\n       * @defaultValue true\n       */\n      broadcast?: boolean;\n      /**\n       * When true, ignore existing field data rather than merging it with\n       * incoming data.\n       * @defaultValue false\n       */\n      overwrite?: boolean;\n    }\n  }\n  export type WriteFragmentOptions<\n    TData,\n    TVariables extends OperationVariables,\n  > = Base.WriteFragmentOptions<TData, TVariables> &\n    VariablesOption<TVariables> &\n    Cache.CacheIdentifierOption<TData>;\n\n  export namespace DocumentationTypes {\n    export interface WriteFragmentOptions<\n      TData,\n      TVariables extends OperationVariables,\n    > extends Base.WriteFragmentOptions<TData, TVariables> {\n      /**\n       * The root id to be used. This id should take the same form as the\n       * value returned by the `cache.identify` function. If a value with your\n       * id does not exist in the store, `null` will be returned.\n       */\n      id?: string;\n\n      /**\n       * An object containing a `__typename` and primary key fields\n       * (such as `id`) identifying the entity object from which the fragment will\n       * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID\n       * (uncommon).\n       *\n       * @remarks\n       * `from` is given precedence over `id` when both are provided.\n       */\n      from?: ApolloCache.FromOptionValue<TData>;\n\n      /**\n       * Any variables that your GraphQL fragments depend on.\n       */\n      variables?: TVariables;\n    }\n  }\n\n  export interface Experiment {\n    (this: ApolloClient, options: ApolloClient.Options): void;\n    v: 1;\n  }\n}\n\n/**\n * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries\n * and mutations) to a GraphQL spec-compliant server over an `ApolloLink` instance,\n * receive results from the server and cache the results in a store. It also delivers updates\n * to GraphQL queries through `Observable` instances.\n */\nexport class ApolloClient {\n  public link: ApolloLink;\n  public cache: ApolloCache;\n  /**\n   * @deprecated `disableNetworkFetches` has been renamed to `prioritizeCacheValues`.\n   */\n  public disableNetworkFetches!: never;\n\n  public set prioritizeCacheValues(value: boolean) {\n    this.queryManager.prioritizeCacheValues = value;\n  }\n\n  /**\n   * Whether to prioritize cache values over network results when `query` or `watchQuery` is called.\n   * This will essentially turn a `\"network-only\"` or `\"cache-and-network\"` fetchPolicy into a `\"cache-first\"` fetchPolicy,\n   * but without influencing the `fetchPolicy` of the created `ObservableQuery` long-term.\n   *\n   * This can e.g. be used to prioritize the cache during the first render after SSR.\n   */\n  public get prioritizeCacheValues() {\n    return this.queryManager.prioritizeCacheValues;\n  }\n  public version: string;\n  public queryDeduplication: boolean;\n  public defaultOptions: ApolloClient.DefaultOptions;\n  public readonly devtoolsConfig: ApolloClient.DevtoolsOptions;\n\n  private queryManager: QueryManager;\n  private devToolsHookCb?: Function;\n  private resetStoreCallbacks: Array<() => Promise<any>> = [];\n  private clearStoreCallbacks: Array<() => Promise<any>> = [];\n\n  /**\n   * Constructs an instance of `ApolloClient`.\n   *\n   * @example\n   *\n   * ```js\n   * import { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n   *\n   * const cache = new InMemoryCache();\n   * const link = new HttpLink({ uri: \"http://localhost:4000/\" });\n   *\n   * const client = new ApolloClient({\n   *   // Provide required constructor fields\n   *   cache: cache,\n   *   link: link,\n   *\n   *   // Provide some optional constructor fields\n   *   clientAwareness: {\n   *     name: \"react-web-client\",\n   *     version: \"1.3\",\n   *   },\n   *   queryDeduplication: false,\n   * });\n   * ```\n   */\n  constructor(options: ApolloClient.Options) {\n    if (__DEV__) {\n      invariant(\n        options.cache,\n        \"To initialize Apollo Client, you must specify a 'cache' property \" +\n          \"in the options object. \\n\" +\n          \"For more information, please visit: https://go.apollo.dev/c/docs\"\n      );\n\n      invariant(\n        options.link,\n        \"To initialize Apollo Client, you must specify a 'link' property \" +\n          \"in the options object. \\n\" +\n          \"For more information, please visit: https://go.apollo.dev/c/docs\"\n      );\n    }\n\n    const {\n      cache,\n      documentTransform,\n      ssrMode = false,\n      ssrForceFetchDelay = 0,\n      queryDeduplication = true,\n      defaultOptions,\n      defaultContext,\n      assumeImmutableResults = cache.assumeImmutableResults,\n      localState,\n      devtools,\n      dataMasking,\n      link,\n      incrementalHandler = new NotImplementedHandler(),\n      experiments = [],\n    } = options;\n\n    this.link = link;\n    this.cache = cache;\n    this.queryDeduplication = queryDeduplication;\n    this.defaultOptions = defaultOptions || {};\n    this.devtoolsConfig = {\n      ...devtools,\n      enabled: devtools?.enabled ?? __DEV__,\n    };\n\n    this.watchQuery = this.watchQuery.bind(this);\n    this.query = this.query.bind(this);\n    this.mutate = this.mutate.bind(this);\n    this.watchFragment = this.watchFragment.bind(this);\n    this.resetStore = this.resetStore.bind(this);\n    this.reFetchObservableQueries = this.refetchObservableQueries =\n      this.refetchObservableQueries.bind(this);\n\n    this.version = version;\n\n    this.queryManager = new QueryManager({\n      client: this,\n      defaultOptions: this.defaultOptions,\n      defaultContext,\n      documentTransform,\n      queryDeduplication,\n      ssrMode,\n      dataMasking: !!dataMasking,\n      clientOptions: options,\n      incrementalHandler,\n      assumeImmutableResults,\n      onBroadcast:\n        this.devtoolsConfig.enabled ?\n          () => {\n            if (this.devToolsHookCb) {\n              this.devToolsHookCb();\n            }\n          }\n        : void 0,\n      localState,\n    });\n\n    this.prioritizeCacheValues = ssrMode || ssrForceFetchDelay > 0;\n    if (ssrForceFetchDelay) {\n      setTimeout(() => {\n        this.prioritizeCacheValues = false;\n      }, ssrForceFetchDelay);\n    }\n\n    if (this.devtoolsConfig.enabled) this.connectToDevTools();\n\n    experiments.forEach((experiment) => experiment.call(this, options));\n  }\n\n  private connectToDevTools() {\n    if (typeof window === \"undefined\") {\n      return;\n    }\n\n    type DevToolsConnector = {\n      push(client: ApolloClient): void;\n    };\n    const windowWithDevTools = window as Window & {\n      [devtoolsSymbol]?: DevToolsConnector;\n      __APOLLO_CLIENT__?: ApolloClient;\n    };\n    const devtoolsSymbol = Symbol.for(\"apollo.devtools\");\n    (windowWithDevTools[devtoolsSymbol] =\n      windowWithDevTools[devtoolsSymbol] || ([] as DevToolsConnector)).push(\n      this\n    );\n    windowWithDevTools.__APOLLO_CLIENT__ = this;\n\n    /**\n     * Suggest installing the devtools for developers who don't have them\n     */\n    if (!hasSuggestedDevtools && __DEV__) {\n      hasSuggestedDevtools = true;\n      if (\n        window.document &&\n        window.top === window.self &&\n        /^(https?|file):$/.test(window.location.protocol)\n      ) {\n        setTimeout(() => {\n          if (!(window as any).__APOLLO_DEVTOOLS_GLOBAL_HOOK__) {\n            const nav = window.navigator;\n            const ua = nav && nav.userAgent;\n            let url: string | undefined;\n            if (typeof ua === \"string\") {\n              if (ua.indexOf(\"Chrome/\") > -1) {\n                url =\n                  \"https://chrome.google.com/webstore/detail/\" +\n                  \"apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm\";\n              } else if (ua.indexOf(\"Firefox/\") > -1) {\n                url =\n                  \"https://addons.mozilla.org/en-US/firefox/addon/apollo-developer-tools/\";\n              }\n            }\n            if (url) {\n              invariant.log(\n                \"Download the Apollo DevTools for a better development \" +\n                  \"experience: %s\",\n                url\n              );\n            }\n          }\n        }, 10000);\n      }\n    }\n  }\n\n  /**\n   * The `DocumentTransform` used to modify GraphQL documents before a request\n   * is made. If a custom `DocumentTransform` is not provided, this will be the\n   * default document transform.\n   */\n  get documentTransform() {\n    return this.queryManager.documentTransform;\n  }\n\n  /**\n   * The configured `LocalState` instance used to enable the use of `@client`\n   * fields.\n   */\n  get localState(): LocalState | undefined {\n    return this.queryManager.localState;\n  }\n\n  set localState(localState: LocalState) {\n    this.queryManager.localState = localState;\n  }\n\n  /**\n   * Call this method to terminate any active client processes, making it safe\n   * to dispose of this `ApolloClient` instance.\n   *\n   * This method performs aggressive cleanup to prevent memory leaks:\n   *\n   * - Unsubscribes all active `ObservableQuery` instances by emitting a `completed` event\n   * - Rejects all currently running queries with \"QueryManager stopped while query was in flight\"\n   * - Removes all queryRefs from the suspense cache\n   */\n  public stop() {\n    this.queryManager.stop();\n  }\n\n  /**\n   * This watches the cache store of the query according to the options specified and\n   * returns an `ObservableQuery`. We can subscribe to this `ObservableQuery` and\n   * receive updated results through an observer when the cache store changes.\n   *\n   * Note that this method is not an implementation of GraphQL subscriptions. Rather,\n   * it uses Apollo's store in order to reactively deliver updates to your query results.\n   *\n   * For example, suppose you call watchQuery on a GraphQL query that fetches a person's\n   * first and last name and this person has a particular object identifier, provided by\n   * `cache.identify`. Later, a different query fetches that same person's\n   * first and last name and the first name has now changed. Then, any observers associated\n   * with the results of the first query will be updated with a new result object.\n   *\n   * Note that if the cache does not change, the subscriber will _not_ be notified.\n   *\n   * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for\n   * a description of store reactivity.\n   */\n  public watchQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>\n  ): ObservableQuery<TData, TVariables> {\n    if (this.defaultOptions.watchQuery) {\n      options = mergeOptions(\n        this.defaultOptions.watchQuery as Partial<\n          ApolloClient.WatchQueryOptions<TData, TVariables>\n        >,\n        options\n      );\n    }\n\n    return this.queryManager.watchQuery<TData, TVariables>(options);\n  }\n\n  /**\n   * This resolves a single query according to the options specified and\n   * returns a `Promise` which is either resolved with the resulting data\n   * or rejected with an error.\n   *\n   * @param options - An object of type `QueryOptions` that allows us to\n   * describe how this query should be treated e.g. whether it should hit the\n   * server at all or just resolve from the cache, etc.\n   */\n  public query<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.QueryOptions<TData, TVariables>\n  ): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>> {\n    if (this.defaultOptions.query) {\n      options = mergeOptions(this.defaultOptions.query, options);\n    }\n\n    if (__DEV__) {\n      invariant(\n        (options.fetchPolicy as WatchQueryFetchPolicy) !== \"cache-and-network\",\n        \"The cache-and-network fetchPolicy does not work with client.query, because \" +\n          \"client.query can only return a single result. Please use client.watchQuery \" +\n          \"to receive multiple results from the cache and the network, or consider \" +\n          \"using a different fetchPolicy, such as cache-first or network-only.\"\n      );\n\n      invariant(\n        (options.fetchPolicy as WatchQueryFetchPolicy) !== \"standby\",\n        \"The standby fetchPolicy does not work with client.query, because \" +\n          \"standby does not fetch. Consider using a different fetchPolicy, such \" +\n          \"as cache-first or network-only.\"\n      );\n\n      invariant(\n        options.query,\n        \"query option is required. You must specify your GraphQL document \" +\n          \"in the query option.\"\n      );\n\n      invariant(\n        options.query.kind === \"Document\",\n        'You must wrap the query string in a \"gql\" tag.'\n      );\n\n      invariant(\n        !(options as any).returnPartialData,\n        \"returnPartialData option only supported on watchQuery.\"\n      );\n\n      invariant(\n        !(options as any).pollInterval,\n        \"pollInterval option only supported on watchQuery.\"\n      );\n\n      invariant(\n        !(options as any).notifyOnNetworkStatusChange,\n        \"notifyOnNetworkStatusChange option only supported on watchQuery.\"\n      );\n    }\n\n    return this.queryManager.query<TData, TVariables>(options);\n  }\n\n  /**\n   * This resolves a single mutation according to the options specified and returns a\n   * Promise which is either resolved with the resulting data or rejected with an\n   * error. In some cases both `data` and `errors` might be undefined, for example\n   * when `errorPolicy` is set to `'ignore'`.\n   *\n   * It takes options as an object with the following keys and values:\n   */\n  public mutate<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n  >(\n    options: ApolloClient.MutateOptions<TData, TVariables, TCache>\n  ): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>> {\n    const optionsWithDefaults = mergeOptions(\n      compact(\n        {\n          fetchPolicy: \"network-only\" as MutationFetchPolicy,\n          errorPolicy: \"none\" as ErrorPolicy,\n        },\n        this.defaultOptions.mutate\n      ),\n      options\n    ) as ApolloClient.MutateOptions<TData, TVariables, TCache> & {\n      fetchPolicy: MutationFetchPolicy;\n      errorPolicy: ErrorPolicy;\n    };\n\n    if (__DEV__) {\n      invariant(\n        optionsWithDefaults.mutation,\n        \"The `mutation` option is required. Please provide a GraphQL document in the `mutation` option.\"\n      );\n\n      invariant(\n        optionsWithDefaults.fetchPolicy === \"network-only\" ||\n          optionsWithDefaults.fetchPolicy === \"no-cache\",\n        \"Mutations only support 'network-only' or 'no-cache' fetch policies. The default 'network-only' behavior automatically writes mutation results to the cache. Passing 'no-cache' skips the cache write.\"\n      );\n    }\n\n    checkDocument(optionsWithDefaults.mutation, OperationTypeNode.MUTATION);\n\n    return this.queryManager.mutate<TData, TVariables, TCache>(\n      optionsWithDefaults\n    );\n  }\n\n  /**\n   * This subscribes to a graphql subscription according to the options specified and returns an\n   * `Observable` which either emits received data or an error.\n   */\n  public subscribe<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.SubscribeOptions<TData, TVariables>\n  ): SubscriptionObservable<ApolloClient.SubscribeResult<MaybeMasked<TData>>> {\n    const cause = {};\n\n    const observable =\n      this.queryManager.startGraphQLSubscription<TData>(options);\n\n    const mapped = observable.pipe(\n      map((result) => ({\n        ...result,\n        data: this.queryManager.maskOperation({\n          document: options.query,\n          data: result.data,\n          fetchPolicy: options.fetchPolicy,\n          cause,\n        }),\n      }))\n    );\n\n    return Object.assign(mapped, { restart: observable.restart });\n  }\n\n  /**\n   * Tries to read some data from the store in the shape of the provided\n   * GraphQL query without making a network request. This method will start at\n   * the root query. To start at a specific id returned by `cache.identify`\n   * use `readFragment`.\n   *\n   * @param optimistic - Set to `true` to allow `readQuery` to return\n   * optimistic results. Is `false` by default.\n   */\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadQueryOptions<TData, TVariables>\n  ): Unmasked<TData> | null;\n\n  /**\n   * {@inheritDoc @apollo/client!ApolloClient#readQuery:member(1)}\n   *\n   * @deprecated Pass the `optimistic` argument as part of the first argument\n   * instead of passing it as a separate option.\n   */\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadQueryOptions<TData, TVariables>,\n    /**\n     * @deprecated Pass the `optimistic` argument as part of the first argument\n     * instead of passing it as a separate option.\n     */\n    optimistic: boolean\n  ): Unmasked<TData> | null;\n\n  public readQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadQueryOptions<TData, TVariables>,\n    optimistic: boolean = false\n  ): Unmasked<TData> | null {\n    return this.cache.readQuery<TData, TVariables>(\n      { ...options, query: this.transform(options.query) },\n      optimistic\n    );\n  }\n\n  /**\n   * Watches the cache store of the fragment according to the options specified\n   * and returns an `Observable`. We can subscribe to this\n   * `Observable` and receive updated results through an\n   * observer when the cache store changes.\n   *\n   * You must pass in a GraphQL document with a single fragment or a document\n   * with multiple fragments that represent what you are reading. If you pass\n   * in a document with multiple fragments then you must also specify a\n   * `fragmentName`.\n   *\n   * @since 3.10.0\n   * @param options - An object of type `WatchFragmentOptions` that allows\n   * the cache to identify the fragment and optionally specify whether to react\n   * to optimistic updates.\n   */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<ApolloCache.FromOptionValue<TData>>;\n    }\n  ): ApolloClient.ObservableFragment<Array<TData>>;\n\n  /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<null>;\n    }\n  ): ApolloClient.ObservableFragment<Array<null>>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: Array<ApolloCache.FromOptionValue<TData> | null>;\n    }\n  ): ApolloClient.ObservableFragment<Array<TData | null>>;\n\n  /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: null;\n    }\n  ): ApolloClient.ObservableFragment<null>;\n\n  /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: ApolloCache.FromOptionValue<TData>;\n    }\n  ): ApolloClient.ObservableFragment<TData>;\n\n  /** {@inheritDoc @apollo/client!ApolloClient#watchFragment:member(1)} */\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables>\n  ): ApolloClient.ObservableFragment<TData | null>;\n\n  public watchFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables>\n  ):\n    | ApolloClient.ObservableFragment<TData>\n    | ApolloClient.ObservableFragment<Array<TData>> {\n    const dataMasking = this.queryManager.dataMasking;\n    const observable = this.cache.watchFragment({\n      ...options,\n      fragment: this.transform(options.fragment, dataMasking),\n    });\n\n    if (__DEV__) {\n      return mapObservableFragmentMemoized(\n        observable,\n        Symbol.for(\"apollo.transform.dev.mask\"),\n        (\n          result: ApolloClient.WatchFragmentResult<any>\n        ): ApolloClient.WatchFragmentResult<any> => ({\n          ...result,\n          // The transform will remove fragment spreads from the fragment\n          // document when dataMasking is enabled. The `mask` function\n          // remains to apply warnings to fragments marked as\n          // `@unmask(mode: \"migrate\")`. Since these warnings are only applied\n          // in dev, we can skip the masking algorithm entirely for production.\n          data: this.queryManager.maskFragment({\n            ...options,\n            data: result.data,\n          }),\n        })\n      ) satisfies ApolloClient.ObservableFragment<any> as ApolloClient.ObservableFragment<any>;\n    }\n\n    return observable as ApolloClient.ObservableFragment<any>;\n  }\n\n  /**\n   * Tries to read some data from the store in the shape of the provided\n   * GraphQL fragment without making a network request. This method will read a\n   * GraphQL fragment from any arbitrary id that is currently cached, unlike\n   * `readQuery` which will only read from the root query.\n   *\n   * You must pass in a GraphQL document with a single fragment or a document\n   * with multiple fragments that represent what you are reading. If you pass\n   * in a document with multiple fragments then you must also specify a\n   * `fragmentName`.\n   *\n   * @param optimistic - Set to `true` to allow `readFragment` to return\n   * optimistic results. Is `false` by default.\n   */\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadFragmentOptions<TData, TVariables>\n  ): Unmasked<TData> | null;\n  /**\n   * {@inheritDoc @apollo/client!ApolloClient#readFragment:member(1)}\n   *\n   * @deprecated Pass the `optimistic` argument as part of the first argument\n   * instead of passing it as a separate option.\n   */\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadFragmentOptions<TData, TVariables>,\n    optimistic: boolean\n  ): Unmasked<TData> | null;\n\n  public readFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.ReadFragmentOptions<TData, TVariables>,\n    optimistic: boolean = false\n  ): Unmasked<TData> | null {\n    return this.cache.readFragment<TData, TVariables>(\n      { ...options, fragment: this.transform(options.fragment) },\n      optimistic\n    );\n  }\n\n  /**\n   * Writes some data in the shape of the provided GraphQL query directly to\n   * the store. This method will start at the root query. To start at a\n   * specific id returned by `cache.identify` then use `writeFragment`.\n   */\n  public writeQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WriteQueryOptions<TData, TVariables>\n  ): Reference | undefined {\n    const ref = this.cache.writeQuery<TData, TVariables>(options);\n\n    if (options.broadcast !== false) {\n      this.queryManager.broadcastQueries();\n    }\n\n    return ref;\n  }\n\n  /**\n   * Writes some data in the shape of the provided GraphQL fragment directly to\n   * the store. This method will write to a GraphQL fragment from any arbitrary\n   * id that is currently cached, unlike `writeQuery` which will only write\n   * from the root query.\n   *\n   * You must pass in a GraphQL document with a single fragment or a document\n   * with multiple fragments that represent what you are writing. If you pass\n   * in a document with multiple fragments then you must also specify a\n   * `fragmentName`.\n   */\n  public writeFragment<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WriteFragmentOptions<TData, TVariables>\n  ): Reference | undefined {\n    const ref = this.cache.writeFragment<TData, TVariables>(options);\n\n    if (options.broadcast !== false) {\n      this.queryManager.broadcastQueries();\n    }\n\n    return ref;\n  }\n\n  public __actionHookForDevTools(cb: () => any) {\n    this.devToolsHookCb = cb;\n  }\n\n  public __requestRaw(\n    request: ApolloLink.Request\n  ): Observable<ApolloLink.Result<unknown>> {\n    return execute(this.link, request, { client: this });\n  }\n\n  /**\n   * Resets your entire store by clearing out your cache and then re-executing\n   * all of your active queries. This makes it so that you may guarantee that\n   * there is no data left in your store from a time before you called this\n   * method.\n   *\n   * `resetStore()` is useful when your user just logged out. You’ve removed the\n   * user session, and you now want to make sure that any references to data you\n   * might have fetched while the user session was active is gone.\n   *\n   * It is important to remember that `resetStore()` _will_ refetch any active\n   * queries. This means that any components that might be mounted will execute\n   * their queries again using your network interface. If you do not want to\n   * re-execute any queries then you should make sure to stop watching any\n   * active queries.\n   */\n  public resetStore(): Promise<ApolloClient.QueryResult<any>[] | null> {\n    return Promise.resolve()\n      .then(() =>\n        this.queryManager.clearStore({\n          discardWatches: false,\n        })\n      )\n      .then(() => Promise.all(this.resetStoreCallbacks.map((fn) => fn())))\n      .then(() => this.refetchObservableQueries());\n  }\n\n  /**\n   * Remove all data from the store. Unlike `resetStore`, `clearStore` will\n   * not refetch any active queries.\n   */\n  public clearStore(): Promise<any[]> {\n    return Promise.resolve()\n      .then(() =>\n        this.queryManager.clearStore({\n          discardWatches: true,\n        })\n      )\n      .then(() => Promise.all(this.clearStoreCallbacks.map((fn) => fn())));\n  }\n\n  /**\n   * Allows callbacks to be registered that are executed when the store is\n   * reset. `onResetStore` returns an unsubscribe function that can be used\n   * to remove registered callbacks.\n   */\n  public onResetStore(cb: () => Promise<any>): () => void {\n    this.resetStoreCallbacks.push(cb);\n    return () => {\n      this.resetStoreCallbacks = this.resetStoreCallbacks.filter(\n        (c) => c !== cb\n      );\n    };\n  }\n\n  /**\n   * Allows callbacks to be registered that are executed when the store is\n   * cleared. `onClearStore` returns an unsubscribe function that can be used\n   * to remove registered callbacks.\n   */\n  public onClearStore(cb: () => Promise<any>): () => void {\n    this.clearStoreCallbacks.push(cb);\n    return () => {\n      this.clearStoreCallbacks = this.clearStoreCallbacks.filter(\n        (c) => c !== cb\n      );\n    };\n  }\n\n  /**\n   * Refetches all of your active queries.\n   *\n   * `reFetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage\n   *\n   * It is important to remember that `reFetchObservableQueries()` _will_ refetch any active\n   * queries. This means that any components that might be mounted will execute\n   * their queries again using your network interface. If you do not want to\n   * re-execute any queries then you should make sure to stop watching any\n   * active queries.\n   * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.\n   *\n   * Note: `cache-only` queries are not refetched by this function.\n   *\n   * @deprecated Please use `refetchObservableQueries` instead.\n   */\n  public reFetchObservableQueries: (\n    includeStandby?: boolean\n  ) => Promise<ApolloClient.QueryResult<any>[]>;\n\n  /**\n   * Refetches all of your active queries.\n   *\n   * `refetchObservableQueries()` is useful if you want to bring the client back to proper state in case of a network outage\n   *\n   * It is important to remember that `refetchObservableQueries()` _will_ refetch any active\n   * queries. This means that any components that might be mounted will execute\n   * their queries again using your network interface. If you do not want to\n   * re-execute any queries then you should make sure to stop watching any\n   * active queries.\n   * Takes optional parameter `includeStandby` which will include queries in standby-mode when refetching.\n   *\n   * Note: `cache-only` queries are not refetched by this function.\n   */\n  public refetchObservableQueries(\n    includeStandby?: boolean\n  ): Promise<ApolloClient.QueryResult<any>[]> {\n    return this.queryManager.refetchObservableQueries(includeStandby);\n  }\n\n  /**\n   * Refetches specified active queries. Similar to \"refetchObservableQueries()\" but with a specific list of queries.\n   *\n   * `refetchQueries()` is useful for use cases to imperatively refresh a selection of queries.\n   *\n   * It is important to remember that `refetchQueries()` _will_ refetch specified active\n   * queries. This means that any components that might be mounted will execute\n   * their queries again using your network interface. If you do not want to\n   * re-execute any queries then you should make sure to stop watching any\n   * active queries.\n   */\n  public refetchQueries<\n    TCache extends ApolloCache = ApolloCache,\n    TResult = Promise<ApolloClient.QueryResult<any>>,\n  >(\n    options: ApolloClient.RefetchQueriesOptions<TCache, TResult>\n  ): ApolloClient.RefetchQueriesResult<TResult> {\n    const map = this.queryManager.refetchQueries(\n      options as ApolloClient.RefetchQueriesOptions<ApolloCache, TResult>\n    );\n    const queries: ObservableQuery<any>[] = [];\n    const results: InternalRefetchQueriesResult<TResult>[] = [];\n\n    map.forEach((result, obsQuery) => {\n      queries.push(obsQuery);\n      results.push(result);\n    });\n\n    const result = Promise.all<TResult>(\n      results as TResult[]\n    ) as ApolloClient.RefetchQueriesResult<TResult>;\n\n    // In case you need the raw results immediately, without awaiting\n    // Promise.all(results):\n    result.queries = queries;\n    result.results = results;\n\n    // If you decide to ignore the result Promise because you're using\n    // result.queries and result.results instead, you shouldn't have to worry\n    // about preventing uncaught rejections for the Promise.all result.\n    result.catch((error) => {\n      invariant.debug(\n        `In client.refetchQueries, Promise.all promise rejected with error %o`,\n        error\n      );\n    });\n\n    return result;\n  }\n\n  /**\n   * Get all currently active `ObservableQuery` objects, in a `Set`.\n   *\n   * An \"active\" query is one that has observers and a `fetchPolicy` other than\n   * \"standby\" or \"cache-only\".\n   *\n   * You can include all `ObservableQuery` objects (including the inactive ones)\n   * by passing \"all\" instead of \"active\", or you can include just a subset of\n   * active queries by passing an array of query names or DocumentNode objects.\n   *\n   * Note: This method only returns queries that have active subscribers. Queries\n   * without subscribers are not tracked by the client.\n   */\n  public getObservableQueries(\n    include: RefetchQueriesInclude = \"active\"\n  ): Set<ObservableQuery<any>> {\n    return this.queryManager.getObservableQueries(include);\n  }\n\n  /**\n   * Exposes the cache's complete state, in a serializable format for later restoration.\n   *\n   * @remarks\n   *\n   * This can be useful for debugging in order to inspect the full state of the\n   * cache.\n   *\n   * @param optimistic - Determines whether the result contains data from the\n   * optimistic layer\n   */\n  public extract(optimistic?: boolean) {\n    return this.cache.extract(optimistic);\n  }\n\n  /**\n   * Replaces existing state in the cache (if any) with the values expressed by\n   * `serializedState`.\n   *\n   * Called when hydrating a cache (server side rendering, or offline storage),\n   * and also (potentially) during hot reloads.\n   */\n  public restore(serializedState: unknown) {\n    return this.cache.restore(serializedState);\n  }\n\n  /**\n   * Define a new ApolloLink (or link chain) that Apollo Client will use.\n   */\n  public setLink(newLink: ApolloLink) {\n    this.link = newLink;\n  }\n\n  public get defaultContext() {\n    return this.queryManager.defaultContext;\n  }\n\n  private maskedFragmentTransform = new DocumentTransform(\n    removeMaskedFragmentSpreads\n  );\n\n  private transform(document: DocumentNode, dataMasking = false) {\n    const transformed = this.queryManager.transform(document);\n    return dataMasking ?\n        this.maskedFragmentTransform.transformDocument(transformed)\n      : transformed;\n  }\n\n  /**\n   * @experimental\n   * This is not a stable API - it is used in development builds to expose\n   * information to the DevTools.\n   * Use at your own risk!\n   * For more details, see [Memory Management](https://www.apollographql.com/docs/react/caching/memory-management/#measuring-cache-usage)\n   *\n   * @example\n   *\n   * ```ts\n   * console.log(client.getMemoryInternals());\n   * ```\n   *\n   * Logs output in the following JSON format:\n   * @example\n   *\n   * ```json\n   * {\n   *   \"limits\": {\n   *     \"canonicalStringify\": 1000,\n   *     \"print\": 2000,\n   *     \"documentTransform.cache\": 2000,\n   *     \"queryManager.getDocumentInfo\": 2000,\n   *     \"PersistedQueryLink.persistedQueryHashes\": 2000,\n   *     \"fragmentRegistry.transform\": 2000,\n   *     \"fragmentRegistry.lookup\": 1000,\n   *     \"fragmentRegistry.findFragmentSpreads\": 4000,\n   *     \"cache.fragmentQueryDocuments\": 1000,\n   *     \"removeTypenameFromVariables.getVariableDefinitions\": 2000,\n   *     \"inMemoryCache.maybeBroadcastWatch\": 5000,\n   *     \"inMemoryCache.executeSelectionSet\": 10000,\n   *     \"inMemoryCache.executeSubSelectedArray\": 5000\n   *   },\n   *   \"sizes\": {\n   *     \"canonicalStringify\": 4,\n   *     \"print\": 14,\n   *     \"addTypenameDocumentTransform\": [\n   *       {\n   *         \"cache\": 14\n   *       }\n   *     ],\n   *     \"queryManager\": {\n   *       \"getDocumentInfo\": 14,\n   *       \"documentTransforms\": [\n   *         {\n   *           \"cache\": 14\n   *         },\n   *         {\n   *           \"cache\": 14\n   *         }\n   *       ]\n   *     },\n   *     \"fragmentRegistry\": {\n   *       \"findFragmentSpreads\": 34,\n   *       \"lookup\": 20,\n   *       \"transform\": 14\n   *     },\n   *     \"cache\": {\n   *       \"fragmentQueryDocuments\": 22\n   *     },\n   *     \"inMemoryCache\": {\n   *       \"executeSelectionSet\": 4345,\n   *       \"executeSubSelectedArray\": 1206,\n   *       \"maybeBroadcastWatch\": 32\n   *     },\n   *     \"links\": [\n   *       {\n   *         \"PersistedQueryLink\": {\n   *           \"persistedQueryHashes\": 14\n   *         }\n   *       },\n   *       {\n   *         \"removeTypenameFromVariables\": {\n   *           \"getVariableDefinitions\": 14\n   *         }\n   *       }\n   *     ]\n   *   }\n   * }\n   * ```\n   */\n  public declare getMemoryInternals?: typeof getApolloClientMemoryInternals;\n}\n\nif (__DEV__) {\n  ApolloClient.prototype.getMemoryInternals = getApolloClientMemoryInternals;\n}\n"
  },
  {
    "path": "src/core/ObservableQuery.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { DocumentNode } from \"graphql\";\nimport type {\n  InteropObservable,\n  MonoTypeOperatorFunction,\n  Observer,\n  OperatorFunction,\n  Subscribable,\n  Subscription,\n} from \"rxjs\";\nimport { BehaviorSubject, filter, Observable, share, Subject, tap } from \"rxjs\";\n\nimport type { Cache, MissingFieldError } from \"@apollo/client/cache\";\nimport type { MissingTree } from \"@apollo/client/cache\";\nimport type { MaybeMasked, Unmasked } from \"@apollo/client/masking\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  isNetworkRequestInFlight,\n  isNetworkRequestSettled,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  compact,\n  equalByQuery,\n  extensionsSymbol,\n  filterMap,\n  getOperationDefinition,\n  getOperationName,\n  getQueryDefinition,\n  preventUnhandledRejection,\n  toQueryResult,\n  variablesUnknownSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport { NetworkStatus } from \"./networkStatus.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type {\n  DataState,\n  DefaultContext,\n  ErrorLike,\n  GetDataState,\n  OperationVariables,\n  QueryNotification,\n  TypedDocumentNode,\n} from \"./types.js\";\nimport type {\n  ErrorPolicy,\n  NextFetchPolicyContext,\n  RefetchWritePolicy,\n  SubscribeToMoreUpdateQueryFn,\n  UpdateQueryMapFn,\n  UpdateQueryOptions,\n  WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\n\nconst { assign, hasOwnProperty } = Object;\n\ninterface TrackedOperation {\n  /**\n   * This NetworkStatus will be used to override the current networkStatus\n   */\n  override?: NetworkStatus;\n  /**\n   * Will abort tracking the operation from this ObservableQuery and remove it from `activeOperations`\n   */\n  abort: () => void;\n  /**\n   * `query` that was used by the `ObservableQuery` as the \"main query\" at the time the operation was started\n   * This is not necessarily the same query as the query the operation itself is doing.\n   */\n  query: DocumentNode;\n  variables: OperationVariables;\n}\n\nconst uninitialized: ObservableQuery.Result<any> = {\n  loading: true,\n  networkStatus: NetworkStatus.loading,\n  data: undefined,\n  dataState: \"empty\",\n  partial: true,\n};\n\nconst empty: ObservableQuery.Result<any> = {\n  loading: false,\n  networkStatus: NetworkStatus.ready,\n  data: undefined,\n  dataState: \"empty\",\n  partial: true,\n};\n\nconst enum EmitBehavior {\n  /**\n   * Emit will be calculated by the normal rules. (`undefined` will be treated the same as this)\n   */\n  default = 0,\n  /**\n   * This result should always be emitted, even if the result is equal to the\n   * previous result. (e.g. the first value after a `refetch`)\n   */\n  force = 1,\n  /**\n   * Never emit this result, it is only used to update `currentResult`.\n   */\n  never = 2,\n  /**\n   * This is a result carrying only a \"network status change\"/loading state update,\n   * emit according to the `notifyOnNetworkStatusChange` option.\n   */\n  networkStatusChange = 3,\n}\ninterface Meta {\n  shouldEmit?: EmitBehavior;\n  /** can be used to override `ObservableQuery.options.fetchPolicy` for this notification */\n  fetchPolicy?: WatchQueryFetchPolicy;\n}\n\nexport declare namespace ObservableQuery {\n  export type Options<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy: WatchQueryFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */\n    nextFetchPolicy?:\n      | WatchQueryFetchPolicy\n      | ((\n          this: ApolloClient.WatchQueryOptions<TData, TVariables>,\n          currentFetchPolicy: WatchQueryFetchPolicy,\n          context: NextFetchPolicyContext<TData, TVariables>\n        ) => WatchQueryFetchPolicy);\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#initialFetchPolicy:member} */\n    initialFetchPolicy: WatchQueryFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n    refetchWritePolicy?: RefetchWritePolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */\n    pollInterval?: number;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */\n    notifyOnNetworkStatusChange?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n    returnPartialData?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */\n    skipPollAttempt?: () => boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n    variables: TVariables;\n  };\n\n  export type FetchMoreOptions<\n    TData,\n    TVariables extends OperationVariables,\n    TFetchData = TData,\n    TFetchVars extends OperationVariables = TVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#query:member} */\n    query?: DocumentNode | TypedDocumentNode<TFetchData, TFetchVars>;\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n    variables?: Partial<NoInfer<TFetchVars>>;\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n    updateQuery?: (\n      previousQueryResult: Unmasked<TData>,\n      options: {\n        fetchMoreResult: Unmasked<TFetchData>;\n        variables: TFetchVars;\n      }\n    ) => Unmasked<TData>;\n  };\n\n  export interface SubscribeToMoreOptions<\n    // eslint-disable-next-line local-rules/tdata-tvariables-order\n    TData = unknown,\n    TSubscriptionVariables extends OperationVariables = OperationVariables,\n    TSubscriptionData = TData,\n    TVariables extends OperationVariables = TSubscriptionVariables,\n  > {\n    document:\n      | DocumentNode\n      | TypedDocumentNode<TSubscriptionData, TSubscriptionVariables>;\n    variables?: TSubscriptionVariables;\n    updateQuery?: SubscribeToMoreUpdateQueryFn<\n      TData,\n      TVariables,\n      TSubscriptionData\n    >;\n    onError?: (error: ErrorLike) => void;\n    context?: DefaultContext;\n  }\n\n  /**\n   * @internal\n   * This describes the `WatchOptions` used by `ObservableQuery` to\n   * subscribe to the cache.\n   */\n  interface CacheWatchOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > extends Cache.WatchOptions<TData, TVariables> {\n    /**\n     * @internal\n     * We cannot suppress the broadcast completely, since that would\n     * result in external updates to be lost if we go from\n     * (external A) -> (own B) -> (external C) when A and C have the same\n     * value.\n     * Without the `own B` being broadcast, the `cache.watch` would swallow\n     * C.\n     * So instead we track the last \"own diff\" and suppress further processing\n     * in the callback.\n     */\n    lastOwnDiff?: Cache.DiffResult<TData>;\n  }\n\n  export type Result<\n    TData,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = {\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n    error?: ErrorLike;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */\n    loading: boolean;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n    networkStatus: NetworkStatus;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#partial:member} */\n    partial: boolean;\n  } & GetDataState<TData, TStates>;\n\n  /**\n   * Promise returned by `reobserve` and `refetch` methods.\n   *\n   * By default, if the `ObservableQuery` is not interested in the result\n   * of this operation anymore, the network operation will be cancelled.\n   *\n   * This has an additional `retain` method that can be used to keep the\n   * network operation running until it is finished nonetheless.\n   */\n  interface ResultPromise<T> extends Promise<T> {\n    /**\n     * Keep the network operation running until it is finished, even if\n     * `ObservableQuery` unsubscribed from the operation.\n     */\n    retain(): this;\n  }\n\n  export namespace DocumentationTypes {\n    type OperatorFunctionChain<From, To> = [];\n    interface ObservableMethods<TData, OperatorResult> {\n      /** {@inheritDoc @apollo/client!ObservableQuery#pipe:member} */\n      pipe(\n        ...operators: OperatorFunctionChain<\n          ObservableQuery.Result<TData>,\n          OperatorResult\n        >\n      ): Observable<OperatorResult>;\n\n      /** {@inheritDoc @apollo/client!ObservableQuery#subscribe:member} */\n      subscribe(\n        observerOrNext:\n          | Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>>\n          | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)\n      ): Subscription;\n    }\n  }\n}\n\ninterface SubjectValue<TData, TVariables extends OperationVariables> {\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  variables: TVariables;\n  result: ObservableQuery.Result<TData>;\n  meta: Meta;\n}\n\nexport class ObservableQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >\n  implements\n    Subscribable<ObservableQuery.Result<MaybeMasked<TData>>>,\n    InteropObservable<ObservableQuery.Result<MaybeMasked<TData>>>\n{\n  public readonly options: ObservableQuery.Options<TData, TVariables>;\n  public readonly queryName?: string;\n  private variablesUnknown: boolean = false;\n\n  /** @internal will be read and written from `QueryInfo` */\n  public _lastWrite?: unknown;\n\n  // The `query` computed property will always reflect the document transformed\n  // by the last run query. `this.options.query` will always reflect the raw\n  // untransformed query to ensure document transforms with runtime conditionals\n  // are run on the original document.\n  public get query(): TypedDocumentNode<TData, TVariables> {\n    return this.lastQuery;\n  }\n\n  /**\n   * An object containing the variables that were provided for the query.\n   */\n  public get variables(): TVariables {\n    return this.options.variables;\n  }\n\n  private unsubscribeFromCache?: {\n    (): void;\n    query: TypedDocumentNode<TData, TVariables>;\n    variables: TVariables;\n  };\n  private input!: Subject<\n    QueryNotification.Value<TData> & {\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n      variables: TVariables;\n      meta: Meta;\n    }\n  >;\n  private subject!: BehaviorSubject<\n    SubjectValue<MaybeMasked<TData>, TVariables>\n  >;\n\n  private isTornDown: boolean;\n  private queryManager: QueryManager;\n  private subscriptions = new Set<Subscription>();\n\n  /**\n   * If an `ObservableQuery` is created with a `network-only` fetch policy,\n   * it should actually start receiving cache updates, but not before it has\n   * received the first result from the network.\n   */\n  private waitForNetworkResult: boolean;\n  private lastQuery: DocumentNode;\n\n  private linkSubscription?: Subscription;\n\n  private pollingInfo?: {\n    interval: number;\n    timeout: ReturnType<typeof setTimeout>;\n  };\n\n  private get networkStatus(): NetworkStatus {\n    return this.subject.getValue().result.networkStatus;\n  }\n\n  private get cache() {\n    return this.queryManager.cache;\n  }\n\n  constructor({\n    queryManager,\n    options,\n    transformedQuery = queryManager.transform(options.query),\n  }: {\n    queryManager: QueryManager;\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n    transformedQuery?: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    queryId?: string;\n  }) {\n    this.queryManager = queryManager;\n\n    // active state\n    this.waitForNetworkResult = options.fetchPolicy === \"network-only\";\n    this.isTornDown = false;\n\n    this.subscribeToMore = this.subscribeToMore.bind(this);\n    this.maskResult = this.maskResult.bind(this);\n\n    const {\n      watchQuery: { fetchPolicy: defaultFetchPolicy = \"cache-first\" } = {},\n    } = queryManager.defaultOptions;\n\n    const {\n      fetchPolicy = defaultFetchPolicy,\n      // Make sure we don't store \"standby\" as the initialFetchPolicy.\n      initialFetchPolicy = fetchPolicy === \"standby\" ? defaultFetchPolicy : (\n        fetchPolicy\n      ),\n    } = options;\n\n    if (options[variablesUnknownSymbol]) {\n      invariant(\n        fetchPolicy === \"standby\",\n        \"The `variablesUnknown` option can only be used together with a `standby` fetch policy.\"\n      );\n      this.variablesUnknown = true;\n    }\n\n    this.lastQuery = transformedQuery;\n\n    this.options = {\n      ...options,\n\n      // Remember the initial options.fetchPolicy so we can revert back to this\n      // policy when variables change. This information can also be specified\n      // (or overridden) by providing options.initialFetchPolicy explicitly.\n      initialFetchPolicy,\n\n      // This ensures this.options.fetchPolicy always has a string value, in\n      // case options.fetchPolicy was not provided.\n      fetchPolicy,\n      variables: this.getVariablesWithDefaults(options.variables),\n    };\n\n    this.initializeObservablesQueue();\n\n    this[\"@@observable\"] = () => this;\n    if (Symbol.observable) {\n      this[Symbol.observable] = () => this;\n    }\n\n    const opDef = getOperationDefinition(this.query);\n    this.queryName = opDef && opDef.name && opDef.name.value;\n  }\n\n  private initializeObservablesQueue() {\n    this.subject = new BehaviorSubject<\n      SubjectValue<MaybeMasked<TData>, TVariables>\n    >({\n      query: this.query,\n      variables: this.variables,\n      result: uninitialized,\n      meta: {},\n    });\n    const observable = this.subject.pipe(\n      tap({\n        subscribe: () => {\n          if (!this.subject.observed) {\n            this.reobserve();\n\n            // TODO: See if we can rework updatePolling to better handle this.\n            // reobserve calls updatePolling but this `subscribe` callback is\n            // called before the subject is subscribed to so `updatePolling`\n            // can't accurately detect if there is an active subscription.\n            // Calling it again here ensures that it can detect if it can poll\n            setTimeout(() => this.updatePolling());\n          }\n        },\n        unsubscribe: () => {\n          if (!this.subject.observed) {\n            this.tearDownQuery();\n          }\n        },\n      }),\n      filterMap(\n        (\n          { query, variables, result: current, meta },\n          context: {\n            previous?: ObservableQuery.Result<TData>;\n            previousVariables?: TVariables;\n          }\n        ) => {\n          const { shouldEmit } = meta;\n\n          if (current === uninitialized) {\n            // reset internal state after `ObservableQuery.reset()`\n            context.previous = undefined;\n            context.previousVariables = undefined;\n          }\n          if (\n            this.options.fetchPolicy === \"standby\" ||\n            shouldEmit === EmitBehavior.never\n          )\n            return;\n          if (shouldEmit === EmitBehavior.force) return emit();\n\n          const { previous, previousVariables } = context;\n\n          if (previous) {\n            const documentInfo = this.queryManager.getDocumentInfo(query);\n            const dataMasking = this.queryManager.dataMasking;\n            const maskedQuery =\n              dataMasking ? documentInfo.nonReactiveQuery : query;\n\n            const resultIsEqual =\n              dataMasking || documentInfo.hasNonreactiveDirective ?\n                equalByQuery(maskedQuery, previous, current, variables)\n              : equal(previous, current);\n\n            if (resultIsEqual && equal(previousVariables, variables)) {\n              return;\n            }\n          }\n\n          if (\n            shouldEmit === EmitBehavior.networkStatusChange &&\n            (!this.options.notifyOnNetworkStatusChange ||\n              equal(previous, current))\n          ) {\n            return;\n          }\n          return emit();\n\n          function emit() {\n            context.previous = current;\n            context.previousVariables = variables;\n            return current;\n          }\n        },\n        () => ({})\n      )\n    );\n\n    this.pipe = observable.pipe.bind(observable);\n    this.subscribe = observable.subscribe.bind(observable);\n\n    this.input = new Subject();\n    // we want to feed many streams into `this.subject`, but none of them should\n    // be able to close `this.input`\n    this.input.complete = () => {};\n    this.input.pipe(this.operator).subscribe(this.subject);\n  }\n\n  // We can't use Observable['subscribe'] here as the type as it conflicts with\n  // the ability to infer T from Subscribable<T>. This limits the surface area\n  // to the non-deprecated signature which works properly with type inference.\n  /**\n   * Subscribes to the `ObservableQuery`.\n   * @param observerOrNext - Either an RxJS `Observer` with some or all callback methods,\n   * or the `next` handler that is called for each value emitted from the subscribed Observable.\n   * @returns A subscription reference to the registered handlers.\n   */\n  public subscribe!: (\n    observerOrNext:\n      | Partial<Observer<ObservableQuery.Result<MaybeMasked<TData>>>>\n      | ((value: ObservableQuery.Result<MaybeMasked<TData>>) => void)\n  ) => Subscription;\n\n  /**\n   * Used to stitch together functional operators into a chain.\n   *\n   * @example\n   *\n   * ```ts\n   * import { filter, map } from 'rxjs';\n   *\n   * observableQuery\n   *   .pipe(\n   *     filter(...),\n   *     map(...),\n   *   )\n   *   .subscribe(x => console.log(x));\n   * ```\n   *\n   * @returns The Observable result of all the operators having been called\n   * in the order they were passed in.\n   */\n  public pipe!: Observable<ObservableQuery.Result<MaybeMasked<TData>>>[\"pipe\"];\n\n  public [Symbol.observable]!: () => Subscribable<\n    ObservableQuery.Result<MaybeMasked<TData>>\n  >;\n  public [\"@@observable\"]: () => Subscribable<\n    ObservableQuery.Result<MaybeMasked<TData>>\n  >;\n\n  /**\n   * @internal\n   */\n  public getCacheDiff({ optimistic = true } = {}) {\n    return this.cache.diff<TData>({\n      query: this.query,\n      variables: this.variables,\n      returnPartialData: true,\n      optimistic,\n    });\n  }\n\n  private getInitialResult(\n    initialFetchPolicy?: WatchQueryFetchPolicy\n  ): ObservableQuery.Result<MaybeMasked<TData>> {\n    let fetchPolicy = initialFetchPolicy || this.options.fetchPolicy;\n    if (\n      this.queryManager.prioritizeCacheValues &&\n      (fetchPolicy === \"network-only\" || fetchPolicy === \"cache-and-network\")\n    ) {\n      fetchPolicy = \"cache-first\";\n    }\n\n    const cacheResult = (): ObservableQuery.Result<TData> => {\n      const diff = this.getCacheDiff();\n      // TODO: queryInfo.getDiff should handle this since cache.diff returns a\n      // null when returnPartialData is false\n      const data =\n        this.options.returnPartialData || diff.complete ?\n          (diff.result as TData) ?? undefined\n        : undefined;\n\n      return this.maskResult({\n        data,\n        dataState:\n          diff.complete ? \"complete\"\n          : data === undefined ? \"empty\"\n          : \"partial\",\n        loading: !diff.complete,\n        networkStatus:\n          diff.complete ? NetworkStatus.ready : NetworkStatus.loading,\n        partial: !diff.complete,\n      } as ObservableQuery.Result<TData>);\n    };\n\n    switch (fetchPolicy) {\n      case \"cache-only\": {\n        return {\n          ...cacheResult(),\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n        };\n      }\n      case \"cache-first\":\n        return cacheResult();\n      case \"cache-and-network\":\n        return {\n          ...cacheResult(),\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n        };\n      case \"standby\":\n        return empty;\n\n      default:\n        return uninitialized;\n    }\n  }\n\n  private resubscribeCache() {\n    const { variables, fetchPolicy } = this.options;\n    const query = this.query;\n\n    const shouldUnsubscribe =\n      fetchPolicy === \"standby\" ||\n      fetchPolicy === \"no-cache\" ||\n      this.waitForNetworkResult;\n\n    const shouldResubscribe =\n      !isEqualQuery({ query, variables }, this.unsubscribeFromCache) &&\n      !this.waitForNetworkResult;\n\n    if (shouldUnsubscribe || shouldResubscribe) {\n      this.unsubscribeFromCache?.();\n    }\n\n    if (shouldUnsubscribe || !shouldResubscribe) {\n      return;\n    }\n\n    const watch: ObservableQuery.CacheWatchOptions<TData, TVariables> = {\n      query,\n      variables,\n      optimistic: true,\n      watcher: this,\n      callback: (diff) => {\n        const info = this.queryManager.getDocumentInfo(query);\n        if (info.hasClientExports || info.hasForcedResolvers) {\n          // If this is not set to something different than `diff`, we will\n          // not be notified about future cache changes with an equal `diff`.\n          // That would be the case if we are working with client-only fields\n          // that are forced or with `exports` fields that might change, causing\n          // local resolvers to return a new result.\n          // This is based on an implementation detail of `InMemoryCache`, which\n          // is not optimal - but the only alternative to this would be to\n          // resubscribe to the cache asynchonouly, which would bear the risk of\n          // missing further synchronous updates.\n          watch.lastDiff = undefined;\n        }\n        if (watch.lastOwnDiff === diff) {\n          // skip cache updates that were caused by our own writes\n          return;\n        }\n\n        const { result: previousResult } = this.subject.getValue();\n\n        if (\n          !diff.complete &&\n          // If we are trying to deliver an incomplete cache result, we avoid\n          // reporting it if the query has errored, otherwise we let the broadcast try\n          // and repair the partial result by refetching the query. This check avoids\n          // a situation where a query that errors and another succeeds with\n          // overlapping data does not report the partial data result to the errored\n          // query.\n          //\n          // See https://github.com/apollographql/apollo-client/issues/11400 for more\n          // information on this issue.\n          (previousResult.error ||\n            // Prevent to schedule a notify directly after the `ObservableQuery`\n            // has been `reset` (which will set the `previousResult` to `uninitialized` or `empty`)\n            // as in those cases, `resetCache` will manually call `refetch` with more intentional timing.\n            previousResult === uninitialized ||\n            previousResult === empty)\n        ) {\n          return;\n        }\n\n        if (!equal(previousResult.data, diff.result)) {\n          this.scheduleNotify();\n        }\n      },\n    };\n    const cancelWatch = this.cache.watch(watch);\n\n    this.unsubscribeFromCache = Object.assign(\n      () => {\n        this.unsubscribeFromCache = undefined;\n        cancelWatch();\n      },\n      { query, variables }\n    );\n  }\n\n  private stableLastResult?: ObservableQuery.Result<MaybeMasked<TData>>;\n  public getCurrentResult(): ObservableQuery.Result<MaybeMasked<TData>> {\n    const { result: current } = this.subject.getValue();\n    let value =\n      (\n        // if the `current` result is in an error state, we will always return that\n        // error state, even if we have no observers\n        current.networkStatus === NetworkStatus.error ||\n        // if we have observers, we are watching the cache and\n        // this.subject.getValue() will always be up to date\n        this.hasObservers() ||\n        // if we are using a `no-cache` fetch policy in which case this\n        // `ObservableQuery` cannot have been updated from the outside - in\n        // that case, we prefer to keep the current value\n        this.options.fetchPolicy === \"no-cache\"\n      ) ?\n        current\n        // otherwise, the `current` value might be outdated due to missed\n        // external updates - calculate it again\n      : this.getInitialResult();\n\n    if (value === uninitialized) {\n      value = this.getInitialResult();\n    }\n    if (!equal(this.stableLastResult, value)) {\n      this.stableLastResult = value;\n    }\n    return this.stableLastResult!;\n  }\n\n  /**\n   * Update the variables of this observable query, and fetch the new results.\n   * This method should be preferred over `setVariables` in most use cases.\n   *\n   * Returns a `ResultPromise` with an additional `.retain()` method. Calling\n   * `.retain()` keeps the network operation running even if the `ObservableQuery`\n   * no longer requires the result.\n   *\n   * Note: `refetch()` guarantees that a value will be emitted from the\n   * observable, even if the result is deep equal to the previous value.\n   *\n   * @param variables - The new set of variables. If there are missing variables,\n   * the previous values of those variables will be used.\n   */\n  public refetch(\n    variables?: Partial<TVariables>\n  ): ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>> {\n    const { fetchPolicy } = this.options;\n\n    const reobserveOptions: Partial<\n      ObservableQuery.Options<TData, TVariables>\n    > = {\n      // Always disable polling for refetches.\n      pollInterval: 0,\n    };\n\n    // Unless the provided fetchPolicy always consults the network\n    // (no-cache, network-only, or cache-and-network), override it with\n    // network-only to force the refetch for this fetchQuery call.\n    if (fetchPolicy === \"no-cache\") {\n      reobserveOptions.fetchPolicy = \"no-cache\";\n    } else {\n      reobserveOptions.fetchPolicy = \"network-only\";\n    }\n\n    if (__DEV__ && variables && hasOwnProperty.call(variables, \"variables\")) {\n      const queryDef = getQueryDefinition(this.query);\n      const vars = queryDef.variableDefinitions;\n      if (!vars || !vars.some((v) => v.variable.name.value === \"variables\")) {\n        invariant.warn(\n          `Called refetch(%o) for query %o, which does not declare a $variables variable.\nDid you mean to call refetch(variables) instead of refetch({ variables })?`,\n          variables,\n          queryDef.name?.value || queryDef\n        );\n      }\n    }\n\n    if (variables && !equal(this.variables, variables)) {\n      // Update the existing options with new variables\n      reobserveOptions.variables = this.options.variables =\n        this.getVariablesWithDefaults({ ...this.variables, ...variables });\n    }\n\n    this._lastWrite = undefined;\n    return this._reobserve(reobserveOptions, {\n      newNetworkStatus: NetworkStatus.refetch,\n    });\n  }\n\n  /**\n   * A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).\n   */\n  public fetchMore<\n    TFetchData = TData,\n    TFetchVars extends OperationVariables = TVariables,\n  >(\n    options: ObservableQuery.FetchMoreOptions<\n      TData,\n      TVariables,\n      TFetchData,\n      TFetchVars\n    >\n  ): Promise<ApolloClient.QueryResult<TFetchData>>;\n\n  public fetchMore<\n    TFetchData = TData,\n    TFetchVars extends OperationVariables = TVariables,\n  >({\n    query,\n    variables,\n    context,\n    errorPolicy,\n    updateQuery,\n  }: ObservableQuery.FetchMoreOptions<\n    TData,\n    TVariables,\n    TFetchData,\n    TFetchVars\n  >): Promise<ApolloClient.QueryResult<TFetchData>> {\n    invariant(\n      this.options.fetchPolicy !== \"cache-only\",\n      \"Cannot execute `fetchMore` for 'cache-only' query '%s'. Please use a different fetch policy.\",\n      getOperationName(this.query, \"(anonymous)\")\n    );\n    const combinedOptions = {\n      ...compact(\n        this.options,\n        { errorPolicy: \"none\" },\n        {\n          query,\n          context,\n          errorPolicy,\n        }\n      ),\n      variables: (query ? variables : (\n        {\n          ...this.variables,\n          ...variables,\n        }\n      )) as TFetchVars,\n      // The fetchMore request goes immediately to the network and does\n      // not automatically write its result to the cache (hence no-cache\n      // instead of network-only), because we allow the caller of\n      // fetchMore to provide an updateQuery callback that determines how\n      // the data gets written to the cache.\n      fetchPolicy: \"no-cache\",\n      notifyOnNetworkStatusChange: this.options.notifyOnNetworkStatusChange,\n    } as ApolloClient.QueryOptions<TFetchData, TFetchVars>;\n\n    combinedOptions.query = this.transformDocument(combinedOptions.query);\n\n    // If a temporary query is passed to `fetchMore`, we don't want to store\n    // it as the last query result since it may be an optimized query for\n    // pagination. We will however run the transforms on the original document\n    // as well as the document passed in `fetchMoreOptions` to ensure the cache\n    // uses the most up-to-date document which may rely on runtime conditionals.\n    this.lastQuery =\n      query ?\n        this.transformDocument(this.options.query)\n      : combinedOptions.query;\n\n    let wasUpdated = false;\n    const isCached = this.options.fetchPolicy !== \"no-cache\";\n\n    if (!isCached) {\n      invariant(\n        updateQuery,\n        \"You must provide an `updateQuery` function when using `fetchMore` with a `no-cache` fetch policy.\"\n      );\n    }\n\n    const { finalize, pushNotification } = this.pushOperation(\n      NetworkStatus.fetchMore\n    );\n\n    pushNotification(\n      {\n        source: \"newNetworkStatus\",\n        kind: \"N\",\n        value: {},\n      },\n      { shouldEmit: EmitBehavior.networkStatusChange }\n    );\n\n    const { promise, operator } = getTrackingOperatorPromise<TFetchData>();\n\n    const { observable } = this.queryManager.fetchObservableWithInfo(\n      combinedOptions,\n      { networkStatus: NetworkStatus.fetchMore, exposeExtensions: true }\n    );\n\n    const subscription = observable\n      .pipe(\n        operator,\n        filter(\n          (\n            notification\n          ): notification is Extract<\n            QueryNotification.FromNetwork<TFetchData>,\n            { kind: \"N\" }\n          > => notification.kind === \"N\" && notification.source === \"network\"\n        )\n      )\n      .subscribe({\n        next: (notification) => {\n          wasUpdated = false;\n          const fetchMoreResult: QueryManager.Result<TFetchData> =\n            notification.value;\n          const extensions = fetchMoreResult[extensionsSymbol];\n\n          if (isNetworkRequestSettled(notification.value.networkStatus)) {\n            finalize();\n          }\n\n          if (isCached) {\n            // Separately getting a diff here before the batch - `onWatchUpdated` might be\n            // called with an `undefined` `lastDiff` on the watcher if the cache was just subscribed to.\n            const lastDiff = this.getCacheDiff();\n            // Performing this cache update inside a cache.batch transaction ensures\n            // any affected cache.watch watchers are notified at most once about any\n            // updates. Most watchers will be using the QueryInfo class, which\n            // responds to notifications by calling reobserveCacheFirst to deliver\n            // fetchMore cache results back to this ObservableQuery.\n            this.cache.batch({\n              update: (cache) => {\n                if (updateQuery) {\n                  cache.updateQuery(\n                    {\n                      query: this.query,\n                      variables: this.variables,\n                      returnPartialData: true,\n                      optimistic: false,\n                      extensions,\n                    },\n                    (previous) =>\n                      updateQuery(previous! as any, {\n                        fetchMoreResult: fetchMoreResult.data as any,\n                        variables: combinedOptions.variables as TFetchVars,\n                      })\n                  );\n                } else {\n                  // If we're using a field policy instead of updateQuery, the only\n                  // thing we need to do is write the new data to the cache using\n                  // combinedOptions.variables (instead of this.variables, which is\n                  // what this.updateQuery uses, because it works by abusing the\n                  // original field value, keyed by the original variables).\n                  cache.writeQuery({\n                    query: combinedOptions.query,\n                    variables: combinedOptions.variables,\n                    data: fetchMoreResult.data as Unmasked<any>,\n                    extensions,\n                  });\n                }\n              },\n\n              onWatchUpdated: (watch, diff) => {\n                if (\n                  watch.watcher === this &&\n                  !equal(diff.result, lastDiff.result)\n                ) {\n                  wasUpdated = true;\n                  const lastResult = this.getCurrentResult();\n\n                  // Let the cache watch from resubscribeCache handle the final\n                  // result\n                  if (isNetworkRequestInFlight(fetchMoreResult.networkStatus)) {\n                    pushNotification({\n                      kind: \"N\",\n                      source: \"network\",\n                      value: {\n                        ...lastResult,\n                        networkStatus:\n                          (\n                            fetchMoreResult.networkStatus ===\n                            NetworkStatus.error\n                          ) ?\n                            NetworkStatus.ready\n                          : fetchMoreResult.networkStatus,\n                        // will be overwritten anyways, just here for types sake\n                        loading: false,\n                        data: diff.result,\n                        dataState:\n                          fetchMoreResult.dataState === \"streaming\" ?\n                            \"streaming\"\n                          : \"complete\",\n                      },\n                    });\n                  }\n                }\n              },\n            });\n          } else {\n            // There is a possibility `lastResult` may not be set when\n            // `fetchMore` is called which would cause this to crash. This should\n            // only happen if we haven't previously reported a result. We don't\n            // quite know what the right behavior should be here since this block\n            // of code runs after the fetch result has executed on the network.\n            // We plan to let it crash in the meantime.\n            //\n            // If we get bug reports due to the `data` property access on\n            // undefined, this should give us a real-world scenario that we can\n            // use to test against and determine the right behavior. If we do end\n            // up changing this behavior, this may require, for example, an\n            // adjustment to the types on `updateQuery` since that function\n            // expects that the first argument always contains previous result\n            // data, but not `undefined`.\n            const lastResult = this.getCurrentResult();\n            const data = updateQuery!(lastResult.data as Unmasked<TData>, {\n              fetchMoreResult: fetchMoreResult.data as Unmasked<TFetchData>,\n              variables: combinedOptions.variables as TFetchVars,\n            });\n\n            pushNotification({\n              kind: \"N\",\n              value: {\n                ...lastResult,\n                networkStatus: NetworkStatus.ready,\n                // will be overwritten anyways, just here for types sake\n                loading: false,\n                data: data as any,\n                dataState:\n                  lastResult.dataState === \"streaming\" ?\n                    \"streaming\"\n                  : \"complete\",\n              },\n              source: \"network\",\n            });\n          }\n        },\n      });\n\n    return preventUnhandledRejection(\n      promise\n        .then((result) => toQueryResult(this.maskResult(result)))\n        .finally(() => {\n          subscription.unsubscribe();\n          finalize();\n\n          if (isCached && !wasUpdated) {\n            const lastResult = this.getCurrentResult();\n\n            if (lastResult.dataState === \"streaming\") {\n              pushNotification({\n                kind: \"N\",\n                source: \"network\",\n                value: {\n                  ...lastResult,\n                  dataState: \"complete\",\n                  networkStatus: NetworkStatus.ready,\n                } as any,\n              });\n            } else {\n              pushNotification(\n                {\n                  kind: \"N\",\n                  source: \"newNetworkStatus\",\n                  value: {},\n                },\n                { shouldEmit: EmitBehavior.force }\n              );\n            }\n          }\n        })\n    );\n  }\n\n  // XXX the subscription variables are separate from the query variables.\n  // if you want to update subscription variables, right now you have to do that separately,\n  // and you can only do it by stopping the subscription and then subscribing again with new variables.\n  /**\n   * A function that enables you to execute a [subscription](https://www.apollographql.com/docs/react/data/subscriptions/), usually to subscribe to specific fields that were included in the query.\n   *\n   * This function returns _another_ function that you can call to terminate the subscription.\n   */\n  public subscribeToMore<\n    TSubscriptionData = TData,\n    TSubscriptionVariables extends OperationVariables = TVariables,\n  >(\n    options: ObservableQuery.SubscribeToMoreOptions<\n      TData,\n      TSubscriptionVariables,\n      TSubscriptionData,\n      TVariables\n    >\n  ): () => void {\n    const subscription = this.queryManager\n      .startGraphQLSubscription({\n        query: options.document,\n        variables: options.variables,\n        context: options.context,\n      })\n      .subscribe({\n        next: (subscriptionData) => {\n          const { updateQuery, onError } = options;\n          const { error } = subscriptionData;\n\n          if (error) {\n            if (onError) {\n              onError(error);\n            } else {\n              invariant.error(\"Unhandled GraphQL subscription error\", error);\n            }\n\n            return;\n          }\n\n          if (updateQuery) {\n            this.updateQuery((previous, updateOptions) =>\n              updateQuery(previous, {\n                subscriptionData: subscriptionData as {\n                  data: Unmasked<TSubscriptionData>;\n                },\n                ...updateOptions,\n              })\n            );\n          }\n        },\n      });\n\n    this.subscriptions.add(subscription);\n\n    return () => {\n      if (this.subscriptions.delete(subscription)) {\n        subscription.unsubscribe();\n      }\n    };\n  }\n\n  /** @internal */\n  public applyOptions(\n    newOptions: Partial<ObservableQuery.Options<TData, TVariables>>\n  ): void {\n    const mergedOptions = compact(this.options, newOptions || {});\n    assign(this.options, mergedOptions);\n    this.updatePolling();\n  }\n\n  /**\n   * Update the variables of this observable query, and fetch the new results\n   * if they've changed. Most users should prefer `refetch` instead of\n   * `setVariables` in order to to be properly notified of results even when\n   * they come from the cache.\n   *\n   * Note: `setVariables()` guarantees that a value will be emitted from the\n   * observable, even if the result is deeply equal to the previous value.\n   *\n   * Note: the promise will resolve with the last emitted result\n   * when either the variables match the current variables or there\n   * are no subscribers to the query.\n   *\n   * @param variables - The new set of variables. If there are missing variables,\n   * the previous values of those variables will be used.\n   */\n  public async setVariables(\n    variables: TVariables\n  ): Promise<ApolloClient.QueryResult<TData>> {\n    variables = this.getVariablesWithDefaults(variables);\n\n    if (equal(this.variables, variables)) {\n      // If we have no observers, then we don't actually want to make a network\n      // request. As soon as someone observes the query, the request will kick\n      // off. For now, we just store any changes. (See #1077)\n      return toQueryResult(this.getCurrentResult());\n    }\n\n    this.options.variables = variables;\n\n    // See comment above\n    if (!this.hasObservers()) {\n      return toQueryResult(this.getCurrentResult());\n    }\n\n    return this._reobserve(\n      {\n        // Reset options.fetchPolicy to its original value.\n        fetchPolicy: this.options.initialFetchPolicy,\n        variables,\n      },\n      { newNetworkStatus: NetworkStatus.setVariables }\n    );\n  }\n\n  /**\n   * A function that enables you to update the query's cached result without executing a followup GraphQL operation.\n   *\n   * See [using updateQuery and updateFragment](https://www.apollographql.com/docs/react/caching/cache-interaction/#using-updatequery-and-updatefragment) for additional information.\n   */\n  public updateQuery(mapFn: UpdateQueryMapFn<TData, TVariables>): void {\n    const { queryManager } = this;\n    const { result, complete } = this.getCacheDiff({ optimistic: false });\n\n    const newResult = mapFn(\n      result! as DeepPartial<Unmasked<TData>>,\n      {\n        variables: this.variables,\n        complete: !!complete,\n        previousData: result,\n      } as UpdateQueryOptions<TData, TVariables>\n    );\n\n    if (newResult) {\n      this.cache.writeQuery({\n        query: this.options.query,\n        data: newResult,\n        variables: this.variables,\n      });\n\n      queryManager.broadcastQueries();\n    }\n  }\n\n  /**\n   * A function that instructs the query to begin re-executing at a specified interval (in milliseconds).\n   */\n  public startPolling(pollInterval: number) {\n    this.options.pollInterval = pollInterval;\n    this.updatePolling();\n  }\n\n  /**\n   * A function that instructs the query to stop polling after a previous call to `startPolling`.\n   */\n  public stopPolling() {\n    this.options.pollInterval = 0;\n    this.updatePolling();\n  }\n\n  // Update options.fetchPolicy according to options.nextFetchPolicy.\n  private applyNextFetchPolicy(\n    reason: NextFetchPolicyContext<TData, TVariables>[\"reason\"],\n    // It's possible to use this method to apply options.nextFetchPolicy to\n    // options.fetchPolicy even if options !== this.options, though that happens\n    // most often when the options are temporary, used for only one request and\n    // then thrown away, so nextFetchPolicy may not end up mattering.\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>\n  ) {\n    if (options.nextFetchPolicy) {\n      const { fetchPolicy = \"cache-first\", initialFetchPolicy = fetchPolicy } =\n        options;\n\n      if (fetchPolicy === \"standby\") {\n        // Do nothing, leaving options.fetchPolicy unchanged.\n      } else if (typeof options.nextFetchPolicy === \"function\") {\n        // When someone chooses \"cache-and-network\" or \"network-only\" as their\n        // initial FetchPolicy, they often do not want future cache updates to\n        // trigger unconditional network requests, which is what repeatedly\n        // applying the \"cache-and-network\" or \"network-only\" policies would\n        // seem to imply. Instead, when the cache reports an update after the\n        // initial network request, it may be desirable for subsequent network\n        // requests to be triggered only if the cache result is incomplete. To\n        // that end, the options.nextFetchPolicy option provides an easy way to\n        // update options.fetchPolicy after the initial network request, without\n        // having to call observableQuery.reobserve.\n        options.fetchPolicy = options.nextFetchPolicy.call(\n          options as any,\n          fetchPolicy,\n          { reason, options, observable: this, initialFetchPolicy }\n        );\n      } else if (reason === \"variables-changed\") {\n        options.fetchPolicy = initialFetchPolicy;\n      } else {\n        options.fetchPolicy = options.nextFetchPolicy;\n      }\n    }\n\n    return options.fetchPolicy;\n  }\n\n  private fetch(\n    options: ObservableQuery.Options<TData, TVariables>,\n    networkStatus: NetworkStatus,\n    fetchQuery: DocumentNode,\n    operator: MonoTypeOperatorFunction<QueryNotification.Value<TData>>\n  ) {\n    // TODO Make sure we update the networkStatus (and infer fetchVariables)\n    // before actually committing to the fetch.\n    const initialFetchPolicy = this.options.fetchPolicy;\n    options.context ??= {};\n\n    let synchronouslyEmitted = false;\n    const onCacheHit = () => {\n      synchronouslyEmitted = true;\n    };\n    const fetchQueryOperator = // we cannot use `tap` here, since it allows only for a \"before subscription\"\n      // hook with `subscribe` and we care for \"directly before and after subscription\"\n      <T>(source: Observable<T>) =>\n        new Observable<T>((subscriber) => {\n          try {\n            return source.subscribe({\n              next(value) {\n                synchronouslyEmitted = true;\n                subscriber.next(value);\n              },\n              error: (error) => subscriber.error(error),\n              complete: () => subscriber.complete(),\n            });\n          } finally {\n            if (!synchronouslyEmitted) {\n              operation.override = networkStatus;\n              this.input.next({\n                kind: \"N\",\n                source: \"newNetworkStatus\",\n                value: {\n                  resetError: true,\n                },\n                query,\n                variables,\n                meta: {\n                  shouldEmit: EmitBehavior.networkStatusChange,\n                  /*\n                   * The moment this notification is emitted, `nextFetchPolicy`\n                   * might already have switched from a `network-only` to a\n                   * `cache-something` policy, so we want to ensure that the\n                   * loading state emit doesn't accidentally read from the cache\n                   * in those cases.\n                   */\n                  fetchPolicy: initialFetchPolicy,\n                },\n              });\n            }\n          }\n        });\n\n    let { observable, fromLink } = this.queryManager.fetchObservableWithInfo(\n      options,\n      {\n        networkStatus,\n        query: fetchQuery,\n        onCacheHit,\n        fetchQueryOperator,\n        observableQuery: this,\n      }\n    );\n\n    // track query and variables from the start of the operation\n    const { query, variables } = this;\n    const operation: TrackedOperation = {\n      abort: () => {\n        subscription.unsubscribe();\n      },\n      query,\n      variables,\n    };\n    this.activeOperations.add(operation);\n\n    let forceFirstValueEmit =\n      networkStatus == NetworkStatus.refetch ||\n      networkStatus == NetworkStatus.setVariables;\n    observable = observable.pipe(operator, share());\n    const subscription = observable\n      .pipe(\n        tap({\n          next: (notification) => {\n            if (\n              notification.source === \"newNetworkStatus\" ||\n              (notification.kind === \"N\" && notification.value.loading)\n            ) {\n              operation.override = networkStatus;\n            } else {\n              delete operation.override;\n            }\n          },\n          finalize: () => this.activeOperations.delete(operation),\n        })\n      )\n      .subscribe({\n        next: (value) => {\n          const meta: Meta = {};\n\n          if (\n            forceFirstValueEmit &&\n            value.kind === \"N\" &&\n            \"loading\" in value.value &&\n            !value.value.loading\n          ) {\n            forceFirstValueEmit = false;\n            meta.shouldEmit = EmitBehavior.force;\n          }\n\n          this.input.next({ ...value, query, variables, meta });\n        },\n      });\n\n    return { fromLink, subscription, observable };\n  }\n\n  // Turns polling on or off based on this.options.pollInterval.\n  private didWarnCacheOnlyPolling = false;\n  private updatePolling() {\n    // Avoid polling in SSR mode\n    if (this.queryManager.ssrMode) {\n      return;\n    }\n\n    const {\n      pollingInfo,\n      options: { fetchPolicy, pollInterval },\n    } = this;\n\n    const shouldCancelPolling = () => {\n      const { options } = this;\n\n      return (\n        !options.pollInterval ||\n        !this.hasObservers() ||\n        options.fetchPolicy === \"cache-only\" ||\n        options.fetchPolicy === \"standby\"\n      );\n    };\n\n    if (shouldCancelPolling()) {\n      if (__DEV__) {\n        if (\n          !this.didWarnCacheOnlyPolling &&\n          pollInterval &&\n          fetchPolicy === \"cache-only\"\n        ) {\n          invariant.warn(\n            \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n            getOperationName(this.query, \"(anonymous)\")\n          );\n          this.didWarnCacheOnlyPolling = true;\n        }\n      }\n\n      this.cancelPolling();\n      return;\n    }\n\n    if (pollingInfo?.interval === pollInterval) {\n      return;\n    }\n\n    const info = pollingInfo || (this.pollingInfo = {} as any);\n    info.interval = pollInterval;\n\n    const maybeFetch = () => {\n      // defense against options changing after the setTimeout changes in case\n      // the call site forgets to call cancelPolling\n      if (shouldCancelPolling()) {\n        return this.cancelPolling();\n      }\n\n      if (this.pollingInfo) {\n        if (\n          !isNetworkRequestInFlight(this.networkStatus) &&\n          !this.options.skipPollAttempt?.()\n        ) {\n          this._reobserve(\n            {\n              // Most fetchPolicy options don't make sense to use in a polling context, as\n              // users wouldn't want to be polling the cache directly. However, network-only and\n              // no-cache are both useful for when the user wants to control whether or not the\n              // polled results are written to the cache.\n              fetchPolicy:\n                this.options.initialFetchPolicy === \"no-cache\" ?\n                  \"no-cache\"\n                : \"network-only\",\n            },\n            {\n              newNetworkStatus: NetworkStatus.poll,\n            }\n          ).then(poll, poll);\n        } else {\n          poll();\n        }\n      }\n    };\n\n    const poll = () => {\n      const info = this.pollingInfo;\n      if (info) {\n        clearTimeout(info.timeout);\n        info.timeout = setTimeout(maybeFetch, info.interval);\n      }\n    };\n\n    poll();\n  }\n\n  // This differs from stopPolling in that it does not set pollInterval to 0\n  private cancelPolling() {\n    if (this.pollingInfo) {\n      clearTimeout(this.pollingInfo.timeout);\n      delete this.pollingInfo;\n    }\n  }\n\n  /**\n   * Reevaluate the query, optionally against new options. New options will be\n   * merged with the current options when given.\n   *\n   * Note: `variables` can be reset back to their defaults (typically empty) by calling `reobserve` with\n   * `variables: undefined`.\n   */\n  public reobserve(\n    newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>\n  ): ObservableQuery.ResultPromise<\n    ApolloClient.QueryResult<MaybeMasked<TData>>\n  > {\n    return this._reobserve(newOptions);\n  }\n  private _reobserve(\n    newOptions?: Partial<ObservableQuery.Options<TData, TVariables>>,\n    internalOptions?: {\n      newNetworkStatus?: NetworkStatus;\n    }\n  ): ObservableQuery.ResultPromise<\n    ApolloClient.QueryResult<MaybeMasked<TData>>\n  > {\n    this.isTornDown = false;\n    let { newNetworkStatus } = internalOptions || {};\n\n    this.queryManager.obsQueries.add(this);\n\n    const useDisposableObservable =\n      // Refetching uses a disposable Observable to allow refetches using different\n      // options, without permanently altering the options of the\n      // original ObservableQuery.\n      newNetworkStatus === NetworkStatus.refetch ||\n      // Polling uses a disposable Observable so the polling options (which force\n      // fetchPolicy to be \"network-only\" or \"no-cache\") won't override the original options.\n      newNetworkStatus === NetworkStatus.poll;\n\n    // Save the old variables, since Object.assign may modify them below.\n    const oldVariables = this.variables;\n    const oldFetchPolicy = this.options.fetchPolicy;\n\n    const mergedOptions = compact(this.options, newOptions || {});\n\n    // This request will hit the network, so even if there are no variables,\n    // we now know that's intentional. (see #12996)\n    // Even if that happens only once, we want `variablesUnknown` to stay false permanently.\n    this.variablesUnknown &&= mergedOptions.fetchPolicy === \"standby\";\n\n    const options =\n      useDisposableObservable ?\n        // Disposable Observable fetches receive a shallow copy of this.options\n        // (merged with newOptions), leaving this.options unmodified.\n        mergedOptions\n      : assign(this.options, mergedOptions);\n\n    // Don't update options.query with the transformed query to avoid\n    // overwriting this.options.query when we aren't using a disposable concast.\n    // We want to ensure we can re-run the custom document transforms the next\n    // time a request is made against the original query.\n    const query = this.transformDocument(options.query);\n\n    this.lastQuery = query;\n\n    // Reevaluate variables to allow resetting variables with variables: undefined,\n    // otherwise `compact` will ignore the `variables` key in `newOptions`. We\n    // do this after we run the query transform to ensure we get default\n    // variables from the transformed query.\n    //\n    // Note: updating options.variables may mutate this.options.variables\n    // in the case of a non-disposable query. This is intentional.\n    if (newOptions && \"variables\" in newOptions) {\n      options.variables = this.getVariablesWithDefaults(newOptions.variables);\n    }\n\n    if (!useDisposableObservable) {\n      // We can skip calling updatePolling if we're not changing this.options.\n      this.updatePolling();\n\n      // Reset options.fetchPolicy to its original value when variables change,\n      // unless a new fetchPolicy was provided by newOptions.\n      if (\n        newOptions &&\n        newOptions.variables &&\n        !equal(newOptions.variables, oldVariables) &&\n        // Don't mess with the fetchPolicy if it's currently \"standby\".\n        options.fetchPolicy !== \"standby\" &&\n        // If we're changing the fetchPolicy anyway, don't try to change it here\n        // using applyNextFetchPolicy. The explicit options.fetchPolicy wins.\n        (options.fetchPolicy === oldFetchPolicy ||\n          // A `nextFetchPolicy` function has even higher priority, though,\n          // so in that case `applyNextFetchPolicy` must be called.\n          typeof options.nextFetchPolicy === \"function\")\n      ) {\n        // This might mutate options.fetchPolicy\n        this.applyNextFetchPolicy(\"variables-changed\", options);\n        if (newNetworkStatus === void 0) {\n          newNetworkStatus = NetworkStatus.setVariables;\n        }\n      }\n    }\n\n    const oldNetworkStatus = this.networkStatus;\n\n    if (!newNetworkStatus) {\n      newNetworkStatus = NetworkStatus.loading;\n\n      if (\n        oldNetworkStatus !== NetworkStatus.loading &&\n        newOptions?.variables &&\n        !equal(newOptions.variables, oldVariables)\n      ) {\n        newNetworkStatus = NetworkStatus.setVariables;\n      }\n\n      // QueryManager does not emit any values for standby fetch policies so we\n      // want ensure that the networkStatus remains ready.\n      if (options.fetchPolicy === \"standby\") {\n        newNetworkStatus = NetworkStatus.ready;\n      }\n    }\n\n    if (options.fetchPolicy === \"standby\") {\n      this.cancelPolling();\n    }\n\n    this.resubscribeCache();\n    const { promise, operator: promiseOperator } = getTrackingOperatorPromise(\n      // This default value should only be used when using a `fetchPolicy` of\n      // `standby` since that fetch policy completes without emitting a\n      // result. Since we are converting this to a QueryResult type, we\n      // omit the extra fields from ApolloQueryResult in the default value.\n      options.fetchPolicy === \"standby\" ?\n        ({ data: undefined } as ObservableQuery.Result<TData>)\n      : undefined\n    );\n    const { subscription, observable, fromLink } = this.fetch(\n      options,\n      newNetworkStatus,\n      query,\n      promiseOperator\n    );\n\n    if (!useDisposableObservable && (fromLink || !this.linkSubscription)) {\n      if (this.linkSubscription) {\n        this.linkSubscription.unsubscribe();\n      }\n\n      this.linkSubscription = subscription;\n    }\n\n    const ret = Object.assign(\n      preventUnhandledRejection(\n        promise\n          .then((result) => toQueryResult(this.maskResult(result)))\n          .finally(() => {\n            if (!this.hasObservers() && this.activeOperations.size === 0) {\n              // If `reobserve` was called on a query without any observers,\n              // the teardown logic would never be called, so we need to\n              // call it here to ensure the query is properly torn down.\n              this.tearDownQuery();\n            }\n          })\n      ),\n      {\n        retain: () => {\n          const subscription = observable.subscribe({});\n          const unsubscribe = () => subscription.unsubscribe();\n          promise.then(unsubscribe, unsubscribe);\n          return ret;\n        },\n      }\n    );\n    return ret;\n  }\n\n  public hasObservers() {\n    return this.subject.observed;\n  }\n\n  /**\n   * Tears down the `ObservableQuery` and stops all active operations by sending a `complete` notification.\n   */\n  public stop() {\n    this.subject.complete();\n    this.initializeObservablesQueue();\n    this.tearDownQuery();\n  }\n\n  private tearDownQuery() {\n    if (this.isTornDown) return;\n\n    this.resetNotifications();\n    this.unsubscribeFromCache?.();\n    if (this.linkSubscription) {\n      this.linkSubscription.unsubscribe();\n      delete this.linkSubscription;\n    }\n\n    this.stopPolling();\n    // stop all active GraphQL subscriptions\n    this.subscriptions.forEach((sub) => sub.unsubscribe());\n    this.subscriptions.clear();\n    this.queryManager.obsQueries.delete(this);\n    this.isTornDown = true;\n    this.abortActiveOperations();\n    this._lastWrite = undefined;\n  }\n\n  private transformDocument(document: DocumentNode) {\n    return this.queryManager.transform(document);\n  }\n\n  private maskResult<T extends { data: any }>(result: T): T {\n    const masked = this.queryManager.maskOperation({\n      document: this.query,\n      data: result.data,\n      fetchPolicy: this.options.fetchPolicy,\n      cause: this,\n    });\n\n    // Maintain object identity as much as possible\n    return masked === result.data ? result : { ...result, data: masked };\n  }\n\n  private dirty: boolean = false;\n\n  private notifyTimeout?: ReturnType<typeof setTimeout>;\n\n  /** @internal */\n  private resetNotifications() {\n    if (this.notifyTimeout) {\n      clearTimeout(this.notifyTimeout);\n      this.notifyTimeout = void 0;\n    }\n    this.dirty = false;\n  }\n\n  /** @internal */\n  private scheduleNotify() {\n    if (this.dirty) return;\n    this.dirty = true;\n    if (!this.notifyTimeout) {\n      this.notifyTimeout = setTimeout(() => this.notify(true), 0);\n    }\n  }\n\n  /** @internal */\n  public notify(scheduled = false) {\n    if (!scheduled) {\n      // For queries with client exports or forced resolvers, we don't want to\n      // synchronously reobserve the cache on broadcast,\n      // but actually wait for the `scheduleNotify` timeout triggered by the\n      // `cache.watch` callback from `resubscribeCache`.\n      const info = this.queryManager.getDocumentInfo(this.query);\n      if (info.hasClientExports || info.hasForcedResolvers) {\n        return;\n      }\n    }\n\n    const { dirty } = this;\n    this.resetNotifications();\n\n    if (\n      dirty &&\n      (this.options.fetchPolicy === \"cache-only\" ||\n        this.options.fetchPolicy === \"cache-and-network\" ||\n        !this.activeOperations.size)\n    ) {\n      const diff = this.getCacheDiff();\n      if (\n        // `fromOptimisticTransaction` is not available through the `cache.diff`\n        // code path, so we need to check it this way\n        equal(diff.result, this.getCacheDiff({ optimistic: false }).result)\n      ) {\n        //If this diff did not come from an optimistic transaction\n        // make the ObservableQuery \"reobserve\" the latest data\n        // using a temporary fetch policy of \"cache-first\", so complete cache\n        // results have a chance to be delivered without triggering additional\n        // network requests, even when options.fetchPolicy is \"network-only\"\n        // or \"cache-and-network\". All other fetch policies are preserved by\n        // this method, and are handled by calling oq.reobserve(). If this\n        // reobservation is spurious, distinctUntilChanged still has a\n        // chance to catch it before delivery to ObservableQuery subscribers.\n        this.reobserveCacheFirst();\n      } else {\n        // If this diff came from an optimistic transaction, deliver the\n        // current cache data to the ObservableQuery, but don't perform a\n        // reobservation, since oq.reobserveCacheFirst might make a network\n        // request, and we never want to trigger network requests in the\n        // middle of optimistic updates.\n        this.input.next({\n          kind: \"N\",\n          value: {\n            data: diff.result,\n            dataState:\n              diff.complete ? \"complete\"\n              : diff.result ? \"partial\"\n              : \"empty\",\n            networkStatus: NetworkStatus.ready,\n            loading: false,\n            error: undefined,\n            partial: !diff.complete,\n          } as ObservableQuery.Result<TData>,\n          source: \"cache\",\n          query: this.query,\n          variables: this.variables,\n          meta: {},\n        });\n      }\n    }\n  }\n\n  private activeOperations = new Set<TrackedOperation>();\n  private pushOperation(networkStatus: NetworkStatus): {\n    finalize: () => void;\n    pushNotification: (\n      notification: QueryNotification.Value<TData>,\n      additionalMeta?: Omit<Meta, \"query\" | \"variables\">\n    ) => void;\n  } {\n    let aborted = false;\n    // track query and variables from the start of the operation\n    const { query, variables } = this;\n    const finalize = () => {\n      this.activeOperations.delete(operation);\n    };\n    const operation: TrackedOperation = {\n      override: networkStatus,\n      abort: () => {\n        aborted = true;\n        finalize();\n      },\n      query,\n      variables,\n    };\n    this.activeOperations.add(operation);\n    return {\n      finalize,\n      pushNotification: (\n        notification: QueryNotification.Value<TData>,\n        additionalMeta?: Meta\n      ) => {\n        if (!aborted) {\n          this.input.next({\n            ...notification,\n            query,\n            variables,\n            meta: { ...additionalMeta },\n          });\n        }\n      },\n    };\n  }\n\n  private calculateNetworkStatus(baseNetworkStatus: NetworkStatus) {\n    if (baseNetworkStatus === NetworkStatus.streaming) {\n      return baseNetworkStatus;\n    }\n    // in the future, this could be more complex logic, e.g. \"refetch\" and\n    // \"fetchMore\" having priority over \"polling\" or \"loading\" network statuses\n    // as for now we just take the \"latest\" operation that is still active,\n    // as that lines up best with previous behavior[]\n\n    const operation = Array.from(this.activeOperations.values())\n      .reverse()\n      .find(\n        (operation) =>\n          isEqualQuery(operation, this) && operation.override !== undefined\n      );\n    return operation?.override ?? baseNetworkStatus;\n  }\n\n  private abortActiveOperations() {\n    this.activeOperations.forEach((operation) => operation.abort());\n  }\n\n  /**\n   * @internal\n   * Called from `clearStore`.\n   *\n   * - resets the query to its initial state\n   * - cancels all active operations and their subscriptions\n   */\n  public reset() {\n    // exception for cache-only queries - we reset them into a \"ready\" state\n    // as we won't trigger a refetch for them\n    const resetToEmpty = this.options.fetchPolicy === \"cache-only\";\n    this.setResult(resetToEmpty ? empty : uninitialized, {\n      shouldEmit: resetToEmpty ? EmitBehavior.force : EmitBehavior.never,\n    });\n\n    this.abortActiveOperations();\n  }\n\n  /** @internal */\n  private setResult(\n    result: ObservableQuery.Result<TData>,\n    additionalMeta?: Meta\n  ) {\n    this.input.next({\n      source: \"setResult\",\n      kind: \"N\",\n      value: result,\n      query: this.query,\n      variables: this.variables,\n      meta: { ...additionalMeta },\n    });\n  }\n\n  private operator: OperatorFunction<\n    QueryNotification.Value<TData> & {\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n      variables: TVariables;\n      meta: Meta;\n    },\n    SubjectValue<TData, TVariables>\n  > = filterMap((notification) => {\n    const { query, variables, meta } = notification;\n\n    if (notification.source === \"setResult\") {\n      return { query, variables, result: notification.value, meta };\n    }\n\n    if (notification.kind === \"C\" || !isEqualQuery(notification, this)) {\n      return;\n    }\n\n    let result: ObservableQuery.Result<TData>;\n    const previous = this.subject.getValue();\n\n    if (notification.source === \"cache\") {\n      result = notification.value;\n      if (\n        result.networkStatus === NetworkStatus.ready &&\n        result.partial &&\n        (!this.options.returnPartialData ||\n          previous.result.networkStatus === NetworkStatus.error) &&\n        this.options.fetchPolicy !== \"cache-only\"\n      ) {\n        return;\n      }\n    } else if (notification.source === \"network\") {\n      if (this.waitForNetworkResult) {\n        this.waitForNetworkResult = false;\n        this.resubscribeCache();\n      }\n      result =\n        notification.kind === \"E\" ?\n          ({\n            ...(isEqualQuery(previous, notification) ?\n              previous.result\n            : { data: undefined, dataState: \"empty\", partial: true }),\n            error: notification.error,\n            networkStatus: NetworkStatus.error,\n            loading: false,\n          } as ObservableQuery.Result<TData>)\n        : notification.value;\n\n      if (notification.kind === \"E\" && result.dataState === \"streaming\") {\n        result.dataState = \"complete\" as any;\n      }\n\n      if (result.error) {\n        meta.shouldEmit = EmitBehavior.force;\n      }\n    } else if (notification.source === \"newNetworkStatus\") {\n      const baseResult =\n        isEqualQuery(previous, notification) ?\n          previous.result\n        : this.getInitialResult(meta.fetchPolicy);\n      const { resetError } = notification.value;\n      const error = resetError ? undefined : baseResult.error;\n      const networkStatus = error ? NetworkStatus.error : NetworkStatus.ready;\n      result = {\n        ...baseResult,\n        error,\n        networkStatus,\n      };\n    }\n    // every code path until here should have either returned or set a result,\n    // but typescript needs a little help\n    invariant(result!);\n\n    // normalize result shape\n    if (!result.error) delete result.error;\n    result.networkStatus = this.calculateNetworkStatus(result.networkStatus);\n    result.loading = isNetworkRequestInFlight(result.networkStatus);\n    result = this.maskResult(result);\n\n    return { query, variables, result, meta };\n  });\n\n  // Reobserve with fetchPolicy effectively set to \"cache-first\", triggering\n  // delivery of any new data from the cache, possibly falling back to the network\n  // if any cache data are missing. This allows _complete_ cache results to be\n  // delivered without also kicking off unnecessary network requests when\n  // this.options.fetchPolicy is \"cache-and-network\" or \"network-only\". When\n  // this.options.fetchPolicy is any other policy (\"cache-first\", \"cache-only\",\n  // \"standby\", or \"no-cache\"), we call this.reobserve() as usual.\n  private reobserveCacheFirst(): void {\n    const { fetchPolicy, nextFetchPolicy } = this.options;\n\n    if (fetchPolicy === \"cache-and-network\" || fetchPolicy === \"network-only\") {\n      this.reobserve({\n        fetchPolicy: \"cache-first\",\n        // Use a temporary nextFetchPolicy function that replaces itself with the\n        // previous nextFetchPolicy value and returns the original fetchPolicy.\n        nextFetchPolicy(\n          this: ApolloClient.WatchQueryOptions<TData, TVariables>,\n          currentFetchPolicy: WatchQueryFetchPolicy,\n          context: NextFetchPolicyContext<TData, TVariables>\n        ) {\n          // Replace this nextFetchPolicy function in the options object with the\n          // original this.options.nextFetchPolicy value.\n          this.nextFetchPolicy = nextFetchPolicy;\n          // If the original nextFetchPolicy value was a function, give it a\n          // chance to decide what happens here.\n          if (typeof this.nextFetchPolicy === \"function\") {\n            return this.nextFetchPolicy(currentFetchPolicy, context);\n          }\n          // Otherwise go back to the original this.options.fetchPolicy.\n          return fetchPolicy!;\n        },\n      });\n    } else {\n      this.reobserve();\n    }\n  }\n\n  private getVariablesWithDefaults(variables: TVariables | undefined) {\n    return this.queryManager.getVariables(this.query, variables);\n  }\n}\n\nexport function logMissingFieldErrors(\n  missing: MissingFieldError | MissingTree | undefined\n) {\n  if (__DEV__ && missing) {\n    invariant.debug(`Missing cache result fields: %o`, missing);\n  }\n}\n\nfunction isEqualQuery(\n  a?: { query: DocumentNode; variables: OperationVariables },\n  b?: { query: DocumentNode; variables: OperationVariables }\n) {\n  return !!(a && b && a.query === b.query && equal(a.variables, b.variables));\n}\n\nfunction getTrackingOperatorPromise<TData>(\n  defaultValue?: ObservableQuery.Result<TData>\n) {\n  let lastValue = defaultValue,\n    resolve: (value: ObservableQuery.Result<TData>) => void,\n    reject: (error: unknown) => void;\n  const promise = new Promise<ObservableQuery.Result<TData>>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n  const operator: MonoTypeOperatorFunction<QueryNotification.Value<TData>> =\n    tap({\n      next(value) {\n        if (value.kind === \"E\") {\n          return reject(value.error);\n        }\n\n        if (\n          value.kind === \"N\" &&\n          value.source !== \"newNetworkStatus\" &&\n          !value.value.loading\n        ) {\n          lastValue = value.value;\n        }\n      },\n      finalize: () => {\n        if (lastValue) {\n          resolve(lastValue);\n        } else {\n          const message = \"The operation was aborted.\";\n          const name = \"AbortError\";\n          reject(\n            typeof DOMException !== \"undefined\" ?\n              new DOMException(message, name)\n              // some environments do not have `DOMException`, e.g. node\n              // uses a normal `Error` with a `name` property instead: https://github.com/phryneas/node/blob/d0579b64f0f6b722f8e49bf8a471dd0d0604a21e/lib/internal/errors.js#L964\n              // error.code is a legacy property that is not used anymore,\n              // and also inconsistent across environments (in supporting\n              // browsers it is `20`, in node `'ABORT_ERR'`) so we omit that.\n            : Object.assign(new Error(message), { name })\n          );\n        }\n      },\n    });\n  return { promise, operator };\n}\n"
  },
  {
    "path": "src/core/QueryInfo.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { DocumentNode, FormattedExecutionResult } from \"graphql\";\n\nimport type { ApolloCache, Cache } from \"@apollo/client/cache\";\nimport type { IgnoreModifier } from \"@apollo/client/cache\";\nimport type { Incremental } from \"@apollo/client/incremental\";\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport type { ExtensionsWithStreamInfo } from \"@apollo/client/utilities/internal\";\nimport {\n  getOperationName,\n  graphQLResultHasError,\n  streamInfoSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type {\n  DataValue,\n  DefaultContext,\n  InternalRefetchQueriesInclude,\n  MutationQueryReducer,\n  MutationUpdaterFunction,\n  NormalizedExecutionResult,\n  OnQueryUpdated,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"./types.js\";\nimport type { ErrorPolicy } from \"./watchQueryOptions.js\";\n\ntype UpdateQueries<TData> = ApolloClient.MutateOptions<\n  TData,\n  any,\n  any\n>[\"updateQueries\"];\n\nconst IGNORE = {} as IgnoreModifier;\n\nexport const enum CacheWriteBehavior {\n  FORBID,\n  OVERWRITE,\n  MERGE,\n}\n\ninterface LastWrite {\n  result: FormattedExecutionResult<any, ExtensionsWithStreamInfo>;\n  variables: ApolloClient.WatchQueryOptions[\"variables\"];\n  dmCount: number | undefined;\n}\n\nconst destructiveMethodCounts = new WeakMap<ApolloCache, number>();\n\ninterface OperationInfo<\n  TData,\n  TVariables extends OperationVariables,\n  AllowedCacheWriteBehavior = CacheWriteBehavior,\n> {\n  document: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  variables: TVariables;\n  errorPolicy: ErrorPolicy;\n  cacheWriteBehavior: AllowedCacheWriteBehavior;\n}\n\nfunction wrapDestructiveCacheMethod(\n  cache: ApolloCache,\n  methodName: \"evict\" | \"modify\" | \"reset\"\n) {\n  const original = cache[methodName];\n  if (typeof original === \"function\") {\n    // @ts-expect-error this is just too generic to be typed correctly\n    cache[methodName] = function () {\n      destructiveMethodCounts.set(\n        cache,\n        // The %1e15 allows the count to wrap around to 0 safely every\n        // quadrillion evictions, so there's no risk of overflow. To be\n        // clear, this is more of a pedantic principle than something\n        // that matters in any conceivable practical scenario.\n        (destructiveMethodCounts.get(cache)! + 1) % 1e15\n      );\n      // @ts-expect-error this is just too generic to be typed correctly\n      return original.apply(this, arguments);\n    };\n  }\n}\n\nconst queryInfoIds = new WeakMap<QueryManager, number>();\n\n// A QueryInfo object represents a single network request, either initiated\n// from the QueryManager or from an ObservableQuery.\n// It will only ever be used for a single network call.\n// It is responsible for reporting results to the cache, merging and in a no-cache\n// scenario accumulating the response.\nexport class QueryInfo<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n  TCache extends ApolloCache = ApolloCache,\n> {\n  // TODO remove soon - this should be able to be handled by cancelling old operations before starting new ones\n  lastRequestId = 1;\n\n  private cache: TCache;\n  private queryManager: Pick<\n    QueryManager,\n    | \"getObservableQueries\"\n    | \"refetchQueries\"\n    | \"getDocumentInfo\"\n    | \"broadcastQueries\"\n    | \"incrementalHandler\"\n  >;\n  public readonly id: string;\n  private readonly observableQuery?: ObservableQuery<any, any>;\n  private incremental?: Incremental.IncrementalRequest<\n    Record<string, unknown>,\n    DataValue.Complete<TData> | DataValue.Streaming<TData>\n  >;\n\n  constructor(\n    queryManager: QueryManager,\n    observableQuery?: ObservableQuery<any, any>\n  ) {\n    const cache = (this.cache = queryManager.cache as TCache);\n    const id = (queryInfoIds.get(queryManager) || 0) + 1;\n    queryInfoIds.set(queryManager, id);\n    this.id = id + \"\";\n    this.observableQuery = observableQuery;\n    this.queryManager = queryManager;\n\n    // Track how often cache.evict is called, since we want eviction to\n    // override the feud-stopping logic in the markQueryResult method, by\n    // causing shouldWrite to return true. Wrapping the cache.evict method\n    // is a bit of a hack, but it saves us from having to make eviction\n    // counting an official part of the ApolloCache API.\n    if (!destructiveMethodCounts.has(cache)) {\n      destructiveMethodCounts.set(cache, 0);\n      wrapDestructiveCacheMethod(cache, \"evict\");\n      wrapDestructiveCacheMethod(cache, \"modify\");\n      wrapDestructiveCacheMethod(cache, \"reset\");\n    }\n  }\n\n  /**\n   * @internal\n   * For feud-preventing behaviour, `lastWrite` should be shared by all `QueryInfo` instances of an `ObservableQuery`.\n   * In the case of a standalone `QueryInfo`, we will keep a local version.\n   */\n  public _lastWrite?: LastWrite;\n  private get lastWrite(): LastWrite | undefined {\n    return (this.observableQuery || this)._lastWrite as LastWrite | undefined;\n  }\n  private set lastWrite(value: LastWrite | undefined) {\n    (this.observableQuery || this)._lastWrite = value;\n  }\n\n  public resetLastWrite() {\n    this.lastWrite = void 0;\n  }\n\n  private shouldWrite(\n    result: FormattedExecutionResult<any, ExtensionsWithStreamInfo>,\n    variables: ApolloClient.WatchQueryOptions[\"variables\"]\n  ) {\n    const { lastWrite } = this;\n    return !(\n      lastWrite &&\n      // If cache.evict has been called since the last time we wrote this\n      // data into the cache, there's a chance writing this result into\n      // the cache will repair what was evicted.\n      lastWrite.dmCount === destructiveMethodCounts.get(this.cache) &&\n      equal(variables, lastWrite.variables) &&\n      equal(result.data, lastWrite.result.data) &&\n      // We have to compare these values because its possible the final chunk\n      // emitted in the incremental result is just `hasNext: false`. This\n      // ensures we trigger a cache write when we get `isLastChunk: true`.\n      result.extensions?.[streamInfoSymbol] ===\n        lastWrite.result.extensions?.[streamInfoSymbol]\n    );\n  }\n\n  get hasNext() {\n    return this.incremental ? this.incremental.hasNext : false;\n  }\n\n  private maybeHandleIncrementalResult(\n    cacheData: TData | DeepPartial<TData> | undefined | null,\n    incoming: ApolloLink.Result<TData>,\n    query: DocumentNode\n  ): FormattedExecutionResult<\n    DataValue.Complete<TData> | DataValue.Streaming<TData>,\n    ExtensionsWithStreamInfo\n  > {\n    const { incrementalHandler } = this.queryManager;\n\n    if (incrementalHandler.isIncrementalResult(incoming)) {\n      this.incremental ||= incrementalHandler.startRequest<\n        TData & Record<string, unknown>\n      >({\n        query,\n      }) as Incremental.IncrementalRequest<\n        Record<string, unknown>,\n        DataValue.Complete<TData> | DataValue.Streaming<TData>\n      >;\n\n      return this.incremental.handle(cacheData, incoming);\n    }\n    return incoming;\n  }\n\n  public markQueryResult(\n    incoming: ApolloLink.Result<TData>,\n    {\n      document: query,\n      variables,\n      errorPolicy,\n      cacheWriteBehavior,\n    }: OperationInfo<TData, TVariables>\n  ): FormattedExecutionResult<\n    DataValue.Complete<TData> | DataValue.Streaming<TData>,\n    ExtensionsWithStreamInfo\n  > {\n    const diffOptions = {\n      query,\n      variables,\n      returnPartialData: true,\n      optimistic: true,\n    };\n\n    // Cancel the pending notify timeout (if it exists) to prevent extraneous network\n    // requests. To allow future notify timeouts, diff and dirty are reset as well.\n    this.observableQuery?.[\"resetNotifications\"]();\n\n    const skipCache = cacheWriteBehavior === CacheWriteBehavior.FORBID;\n    const lastDiff =\n      skipCache ? undefined : this.cache.diff<TData>(diffOptions);\n\n    let result = this.maybeHandleIncrementalResult(\n      lastDiff?.result,\n      incoming,\n      query\n    );\n    if (skipCache) {\n      return result;\n    }\n\n    if (shouldWriteResult(result, errorPolicy)) {\n      // Using a transaction here so we have a chance to read the result\n      // back from the cache before the watch callback fires as a result\n      // of writeQuery, so we can store the new diff quietly and ignore\n      // it when we receive it redundantly from the watch callback.\n      this.cache.batch({\n        onWatchUpdated: (\n          // all additional options on ObservableQuery.CacheWatchOptions are\n          // optional so we can use the type here\n          watch: ObservableQuery.CacheWatchOptions,\n          diff\n        ) => {\n          if (watch.watcher === this.observableQuery) {\n            // see comment on `lastOwnDiff` for explanation\n            watch.lastOwnDiff = diff;\n          }\n        },\n        update: (cache) => {\n          if (this.shouldWrite(result, variables)) {\n            cache.writeQuery({\n              query,\n              data: result.data as Unmasked<any>,\n              variables,\n              overwrite: cacheWriteBehavior === CacheWriteBehavior.OVERWRITE,\n              extensions: result.extensions,\n            });\n\n            this.lastWrite = {\n              result,\n              variables,\n              dmCount: destructiveMethodCounts.get(this.cache),\n            };\n          } else {\n            // If result is the same as the last result we received from\n            // the network (and the variables match too), avoid writing\n            // result into the cache again. The wisdom of skipping this\n            // cache write is far from obvious, since any cache write\n            // could be the one that puts the cache back into a desired\n            // state, fixing corruption or missing data. However, if we\n            // always write every network result into the cache, we enable\n            // feuds between queries competing to update the same data in\n            // incompatible ways, which can lead to an endless cycle of\n            // cache broadcasts and useless network requests. As with any\n            // feud, eventually one side must step back from the brink,\n            // letting the other side(s) have the last word(s). There may\n            // be other points where we could break this cycle, such as\n            // silencing the broadcast for cache.writeQuery (not a good\n            // idea, since it just delays the feud a bit) or somehow\n            // avoiding the network request that just happened (also bad,\n            // because the server could return useful new data). All\n            // options considered, skipping this cache write seems to be\n            // the least damaging place to break the cycle, because it\n            // reflects the intuition that we recently wrote this exact\n            // result into the cache, so the cache *should* already/still\n            // contain this data. If some other query has clobbered that\n            // data in the meantime, that's too bad, but there will be no\n            // winners if every query blindly reverts to its own version\n            // of the data. This approach also gives the network a chance\n            // to return new data, which will be written into the cache as\n            // usual, notifying only those queries that are directly\n            // affected by the cache updates, as usual. In the future, an\n            // even more sophisticated cache could perhaps prevent or\n            // mitigate the clobbering somehow, but that would make this\n            // particular cache write even less important, and thus\n            // skipping it would be even safer than it is today.\n            if (lastDiff && lastDiff.complete) {\n              // Reuse data from the last good (complete) diff that we\n              // received, when possible.\n              result = { ...result, data: lastDiff.result };\n              return;\n            }\n            // If the previous this.diff was incomplete, fall through to\n            // re-reading the latest data with cache.diff, below.\n          }\n\n          const diff = cache.diff<TData>(diffOptions);\n\n          // If we're allowed to write to the cache, and we can read a\n          // complete result from the cache, update result.data to be the\n          // result from the cache, rather than the raw network result.\n          // Set without setDiff to avoid triggering a notify call, since\n          // we have other ways of notifying for this result.\n          if (diff.complete) {\n            result = { ...result, data: diff.result };\n          }\n        },\n      });\n    } else {\n      this.lastWrite = void 0;\n    }\n\n    return result;\n  }\n\n  public markMutationResult(\n    incoming: ApolloLink.Result<TData>,\n    mutation: OperationInfo<\n      TData,\n      TVariables,\n      CacheWriteBehavior.FORBID | CacheWriteBehavior.MERGE\n    > & {\n      context?: DefaultContext;\n      updateQueries: UpdateQueries<TData>;\n      update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n      awaitRefetchQueries?: boolean;\n      refetchQueries?:\n        | ((\n            result: NormalizedExecutionResult<Unmasked<TData>>\n          ) => InternalRefetchQueriesInclude)\n        | InternalRefetchQueriesInclude;\n      removeOptimistic?: string;\n      onQueryUpdated?: OnQueryUpdated<any>;\n      keepRootFields?: boolean;\n    },\n    cache = this.cache\n  ): Promise<\n    FormattedExecutionResult<\n      DataValue.Complete<TData> | DataValue.Streaming<TData>,\n      ExtensionsWithStreamInfo\n    >\n  > {\n    const cacheWrites: Cache.WriteOptions[] = [];\n    const skipCache = mutation.cacheWriteBehavior === CacheWriteBehavior.FORBID;\n\n    let result = this.maybeHandleIncrementalResult(\n      skipCache ? undefined : (\n        cache.diff<TData>({\n          id: \"ROOT_MUTATION\",\n          // The cache complains if passed a mutation where it expects a\n          // query, so we transform mutations and subscriptions to queries\n          // (only once, thanks to this.transformCache).\n          query: this.queryManager.getDocumentInfo(mutation.document).asQuery,\n          variables: mutation.variables,\n          optimistic: false,\n          returnPartialData: true,\n        }).result\n      ),\n      incoming,\n      mutation.document\n    );\n\n    if (mutation.errorPolicy === \"ignore\") {\n      result = { ...result, errors: [] };\n    }\n\n    if (graphQLResultHasError(result) && mutation.errorPolicy === \"none\") {\n      return Promise.resolve(result);\n    }\n\n    const getResultWithDataState = () =>\n      ({\n        ...result,\n        dataState: this.hasNext ? \"streaming\" : \"complete\",\n      }) as NormalizedExecutionResult<Unmasked<TData>>;\n\n    if (!skipCache && shouldWriteResult(result, mutation.errorPolicy)) {\n      cacheWrites.push({\n        result: result.data,\n        dataId: \"ROOT_MUTATION\",\n        query: mutation.document,\n        variables: mutation.variables,\n        extensions: result.extensions,\n      });\n\n      const { updateQueries } = mutation;\n      if (updateQueries) {\n        this.queryManager\n          .getObservableQueries(\"all\")\n          .forEach((observableQuery) => {\n            const queryName = observableQuery && observableQuery.queryName;\n            if (\n              !queryName ||\n              !Object.hasOwnProperty.call(updateQueries, queryName)\n            ) {\n              return;\n            }\n            const updater = updateQueries[queryName];\n            const { query: document, variables } = observableQuery;\n\n            // Read the current query result from the store.\n            const { result: currentQueryResult, complete } =\n              observableQuery.getCacheDiff({ optimistic: false });\n\n            if (complete && currentQueryResult) {\n              // Run our reducer using the current query result and the mutation result.\n              const nextQueryResult = (updater as MutationQueryReducer<any>)(\n                currentQueryResult,\n                {\n                  mutationResult: getResultWithDataState(),\n                  queryName: (document && getOperationName(document)) || void 0,\n                  queryVariables: variables!,\n                }\n              );\n\n              // Write the modified result back into the store if we got a new result.\n              if (nextQueryResult) {\n                cacheWrites.push({\n                  result: nextQueryResult,\n                  dataId: \"ROOT_QUERY\",\n                  query: document!,\n                  variables,\n                });\n              }\n            }\n          });\n      }\n    }\n\n    let refetchQueries = mutation.refetchQueries;\n    if (typeof refetchQueries === \"function\") {\n      refetchQueries = refetchQueries(getResultWithDataState());\n    }\n\n    if (\n      cacheWrites.length > 0 ||\n      (refetchQueries || \"\").length > 0 ||\n      mutation.update ||\n      mutation.onQueryUpdated ||\n      mutation.removeOptimistic\n    ) {\n      const results: any[] = [];\n\n      this.queryManager\n        .refetchQueries({\n          updateCache: (cache) => {\n            if (!skipCache) {\n              cacheWrites.forEach((write) => cache.write(write));\n            }\n\n            // If the mutation has some writes associated with it then we need to\n            // apply those writes to the store by running this reducer again with\n            // a write action.\n            const { update } = mutation;\n            // Determine whether result is a SingleExecutionResult,\n            // or the final ExecutionPatchResult.\n\n            if (update) {\n              if (!skipCache) {\n                // Re-read the ROOT_MUTATION data we just wrote into the cache\n                // (the first cache.write call in the cacheWrites.forEach loop\n                // above), so field read functions have a chance to run for\n                // fields within mutation result objects.\n                const diff = cache.diff<TData>({\n                  id: \"ROOT_MUTATION\",\n                  // The cache complains if passed a mutation where it expects a\n                  // query, so we transform mutations and subscriptions to queries\n                  // (only once, thanks to this.transformCache).\n                  query: this.queryManager.getDocumentInfo(mutation.document)\n                    .asQuery,\n                  variables: mutation.variables,\n                  optimistic: false,\n                  returnPartialData: true,\n                });\n\n                if (diff.complete) {\n                  result = {\n                    ...result,\n                    data: diff.result,\n                  };\n                }\n              }\n\n              // If we've received the whole response, call the update function.\n              if (!this.hasNext) {\n                update(\n                  cache as TCache,\n                  result as FormattedExecutionResult<Unmasked<TData>>,\n                  {\n                    context: mutation.context,\n                    variables: mutation.variables,\n                  }\n                );\n              }\n            }\n\n            // TODO Do this with cache.evict({ id: 'ROOT_MUTATION' }) but make it\n            // shallow to allow rolling back optimistic evictions.\n            if (!skipCache && !mutation.keepRootFields && !this.hasNext) {\n              cache.modify({\n                id: \"ROOT_MUTATION\",\n                fields(value, { fieldName, DELETE }) {\n                  return fieldName === \"__typename\" ? value : DELETE;\n                },\n              });\n            }\n          },\n\n          include: refetchQueries,\n\n          // Write the final mutation.result to the root layer of the cache.\n          optimistic: false,\n\n          // Remove the corresponding optimistic layer at the same time as we\n          // write the final non-optimistic result.\n          removeOptimistic: mutation.removeOptimistic,\n\n          // Let the caller of client.mutate optionally determine the refetching\n          // behavior for watched queries after the mutation.update function runs.\n          // If no onQueryUpdated function was provided for this mutation, pass\n          // null instead of undefined to disable the default refetching behavior.\n          onQueryUpdated: mutation.onQueryUpdated || null,\n        })\n        .forEach((result) => results.push(result));\n\n      if (mutation.awaitRefetchQueries || mutation.onQueryUpdated) {\n        // Returning a promise here makes the mutation await that promise, so we\n        // include results in that promise's work if awaitRefetchQueries or an\n        // onQueryUpdated function was specified.\n        return Promise.all(results).then(() => result);\n      }\n    }\n\n    return Promise.resolve(result);\n  }\n\n  public markMutationOptimistic(\n    optimisticResponse: any,\n    mutation: OperationInfo<\n      TData,\n      TVariables,\n      CacheWriteBehavior.FORBID | CacheWriteBehavior.MERGE\n    > & {\n      context?: DefaultContext;\n      updateQueries: UpdateQueries<TData>;\n      update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n      keepRootFields?: boolean;\n    }\n  ) {\n    const data =\n      typeof optimisticResponse === \"function\" ?\n        optimisticResponse(mutation.variables, { IGNORE })\n      : optimisticResponse;\n\n    if (data === IGNORE) {\n      return false;\n    }\n\n    this.cache.recordOptimisticTransaction((cache) => {\n      try {\n        this.markMutationResult({ data }, mutation, cache as TCache);\n      } catch (error) {\n        invariant.error(error);\n      }\n    }, this.id);\n\n    return true;\n  }\n\n  public markSubscriptionResult(\n    result: FormattedExecutionResult<TData>,\n    {\n      document,\n      variables,\n      errorPolicy,\n      cacheWriteBehavior,\n    }: OperationInfo<\n      TData,\n      TVariables,\n      CacheWriteBehavior.FORBID | CacheWriteBehavior.MERGE\n    >\n  ) {\n    if (cacheWriteBehavior !== CacheWriteBehavior.FORBID) {\n      if (shouldWriteResult(result, errorPolicy)) {\n        this.cache.write({\n          query: document,\n          result: result.data as any,\n          dataId: \"ROOT_SUBSCRIPTION\",\n          variables: variables,\n          extensions: result.extensions,\n        });\n      }\n\n      this.queryManager.broadcastQueries();\n    }\n  }\n}\n\nfunction shouldWriteResult<T>(\n  result: FormattedExecutionResult<T>,\n  errorPolicy: ErrorPolicy = \"none\"\n) {\n  const ignoreErrors = errorPolicy === \"ignore\" || errorPolicy === \"all\";\n  let writeWithErrors = !graphQLResultHasError(result);\n  if (!writeWithErrors && ignoreErrors && result.data) {\n    writeWithErrors = true;\n  }\n  return writeWithErrors;\n}\n"
  },
  {
    "path": "src/core/QueryManager.ts",
    "content": "import { Trie } from \"@wry/trie\";\nimport type {\n  DirectiveNode,\n  DocumentNode,\n  FormattedExecutionResult,\n} from \"graphql\";\nimport { BREAK, Kind, OperationTypeNode, visit } from \"graphql\";\nimport { Observable, throwError } from \"rxjs\";\nimport {\n  catchError,\n  concat,\n  EMPTY,\n  filter,\n  finalize,\n  from,\n  lastValueFrom,\n  map,\n  materialize,\n  mergeMap,\n  of,\n  share,\n  shareReplay,\n  Subject,\n  tap,\n} from \"rxjs\";\n\nimport type { ApolloCache, Cache } from \"@apollo/client/cache\";\nimport { canonicalStringify } from \"@apollo/client/cache\";\nimport {\n  CombinedGraphQLErrors,\n  graphQLResultHasProtocolErrors,\n  registerLinkError,\n  toErrorLike,\n} from \"@apollo/client/errors\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"@apollo/client/errors\";\nimport type { Incremental } from \"@apollo/client/incremental\";\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport { execute } from \"@apollo/client/link\";\nimport type { LocalState } from \"@apollo/client/local-state\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport { maskFragment, maskOperation } from \"@apollo/client/masking\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  cacheSizes,\n  DocumentTransform,\n  isNetworkRequestInFlight,\n  print,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ExtensionsWithStreamInfo } from \"@apollo/client/utilities/internal\";\nimport {\n  AutoCleanedWeakCache,\n  checkDocument,\n  extensionsSymbol,\n  filterMap,\n  getDefaultValues,\n  getOperationDefinition,\n  getOperationName,\n  graphQLResultHasError,\n  hasDirectives,\n  hasForcedResolvers,\n  isDocumentNode,\n  isNonNullObject,\n  makeUniqueId,\n  mergeOptions,\n  removeDirectivesFromDocument,\n  streamInfoSymbol,\n  toQueryResult,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../utilities/caching/sizes.js\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport { NetworkStatus } from \"./networkStatus.js\";\nimport { logMissingFieldErrors, ObservableQuery } from \"./ObservableQuery.js\";\nimport { CacheWriteBehavior, QueryInfo } from \"./QueryInfo.js\";\nimport type {\n  DataState,\n  DefaultContext,\n  InternalRefetchQueriesInclude,\n  InternalRefetchQueriesMap,\n  InternalRefetchQueriesOptions,\n  InternalRefetchQueriesResult,\n  OperationVariables,\n  QueryNotification,\n  SubscriptionObservable,\n  TypedDocumentNode,\n} from \"./types.js\";\nimport type {\n  ErrorPolicy,\n  MutationFetchPolicy,\n  WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\n\ninterface MutationStoreValue {\n  mutation: DocumentNode;\n  variables: Record<string, any>;\n  loading: boolean;\n  error: Error | null;\n}\n\ninterface TransformCacheEntry {\n  hasClientExports: boolean;\n  hasForcedResolvers: boolean;\n  hasNonreactiveDirective: boolean;\n  hasIncrementalDirective: boolean;\n  nonReactiveQuery: DocumentNode;\n  clientQuery: DocumentNode | null;\n  serverQuery: DocumentNode | null;\n  defaultVars: OperationVariables;\n  asQuery: DocumentNode;\n  operationType: OperationTypeNode | undefined;\n  violation?: Error | undefined;\n}\n\ninterface MaskFragmentOptions<TData> {\n  fragment: DocumentNode;\n  data: TData;\n  fragmentName?: string;\n}\n\ninterface MaskOperationOptions<TData> {\n  document: DocumentNode;\n  data: TData;\n  /**\n   * Can be used to identify the cause to prevent warning for the same cause twice.\n   * This would be an object like e.g. an `ObervableQuery`.\n   * If the `cause` is not provided, we will warn every time.\n   */\n  cause?: object;\n  fetchPolicy?: WatchQueryFetchPolicy;\n}\n\ninterface QueryManagerOptions {\n  client: ApolloClient;\n  clientOptions: ApolloClient.Options;\n  defaultOptions: ApolloClient.DefaultOptions;\n  documentTransform: DocumentTransform | null | undefined;\n  queryDeduplication: boolean;\n  onBroadcast: undefined | (() => void);\n  ssrMode: boolean;\n  assumeImmutableResults: boolean;\n  defaultContext: Partial<DefaultContext> | undefined;\n  dataMasking: boolean;\n  localState: LocalState | undefined;\n  incrementalHandler: Incremental.Handler;\n}\n\nexport declare namespace QueryManager {\n  export type Result<\n    TData,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = ObservableQuery.Result<TData, TStates> & {\n    [extensionsSymbol]?: ExtensionsWithStreamInfo;\n  };\n}\n\nexport class QueryManager {\n  public defaultOptions: ApolloClient.DefaultOptions;\n\n  public readonly client: ApolloClient;\n  /**\n   * The options that were passed to the ApolloClient constructor.\n   */\n  public readonly clientOptions: ApolloClient.Options;\n  public readonly assumeImmutableResults: boolean;\n  public readonly documentTransform: DocumentTransform;\n  public readonly ssrMode: boolean;\n  public readonly defaultContext: Partial<DefaultContext>;\n  public readonly dataMasking: boolean;\n  public readonly incrementalHandler: Incremental.Handler;\n  public localState: LocalState | undefined;\n\n  private queryDeduplication: boolean;\n\n  /**\n   * Whether to prioritize cache values over network results when\n   * `fetchObservableWithInfo` is called.\n   * This will essentially turn a `\"network-only\"` or `\"cache-and-network\"`\n   * fetchPolicy into a `\"cache-first\"` fetchPolicy, but without influencing\n   * the `fetchPolicy` of the `ObservableQuery`.\n   *\n   * This can e.g. be used to prioritize the cache during the first render after\n   * SSR.\n   */\n  public prioritizeCacheValues: boolean = false;\n\n  private onBroadcast?: () => void;\n  public mutationStore?: {\n    [mutationId: string]: MutationStoreValue;\n  };\n\n  /**\n   * All ObservableQueries that currently have at least one subscriber.\n   */\n  public obsQueries = new Set<ObservableQuery<any, any>>();\n\n  // Maps from queryInfo.id strings to Promise rejection functions for\n  // currently active queries and fetches.\n  // Use protected instead of private field so\n  // @apollo/experimental-nextjs-app-support can access type info.\n  protected fetchCancelFns = new Map<string, (error: any) => any>();\n\n  constructor(options: QueryManagerOptions) {\n    const defaultDocumentTransform = new DocumentTransform(\n      (document) => this.cache.transformDocument(document),\n      // Allow the apollo cache to manage its own transform caches\n      { cache: false }\n    );\n\n    this.client = options.client;\n    this.defaultOptions = options.defaultOptions;\n    this.queryDeduplication = options.queryDeduplication;\n    this.clientOptions = options.clientOptions;\n    this.ssrMode = options.ssrMode;\n    this.assumeImmutableResults = options.assumeImmutableResults;\n    this.dataMasking = options.dataMasking;\n    this.localState = options.localState;\n    this.incrementalHandler = options.incrementalHandler;\n    const documentTransform = options.documentTransform;\n    this.documentTransform =\n      documentTransform ?\n        defaultDocumentTransform\n          .concat(documentTransform)\n          // The custom document transform may add new fragment spreads or new\n          // field selections, so we want to give the cache a chance to run\n          // again. For example, the InMemoryCache adds __typename to field\n          // selections and fragments from the fragment registry.\n          .concat(defaultDocumentTransform)\n      : defaultDocumentTransform;\n    this.defaultContext = options.defaultContext || {};\n\n    if ((this.onBroadcast = options.onBroadcast)) {\n      this.mutationStore = {};\n    }\n  }\n\n  get link() {\n    return this.client.link;\n  }\n\n  get cache() {\n    return this.client.cache;\n  }\n\n  /**\n   * Call this method to terminate any active query processes, making it safe\n   * to dispose of this QueryManager instance.\n   */\n  public stop() {\n    this.obsQueries.forEach((oq) => oq.stop());\n\n    this.cancelPendingFetches(\n      newInvariantError(\"QueryManager stopped while query was in flight\")\n    );\n  }\n\n  private cancelPendingFetches(error: Error) {\n    this.fetchCancelFns.forEach((cancel) => cancel(error));\n    this.fetchCancelFns.clear();\n  }\n\n  public async mutate<\n    TData,\n    TVariables extends OperationVariables,\n    TCache extends ApolloCache,\n  >({\n    mutation,\n    variables,\n    optimisticResponse,\n    updateQueries,\n    refetchQueries = [],\n    awaitRefetchQueries = false,\n    update: updateWithProxyFn,\n    onQueryUpdated,\n    fetchPolicy,\n    errorPolicy,\n    keepRootFields,\n    context,\n  }: ApolloClient.MutateOptions<TData, TVariables, TCache> & {\n    errorPolicy: ErrorPolicy;\n    fetchPolicy: MutationFetchPolicy;\n  }): Promise<ApolloClient.MutateResult<MaybeMasked<TData>>> {\n    const queryInfo = new QueryInfo<TData, TVariables, TCache>(this);\n\n    mutation = this.cache.transformForLink(this.transform(mutation));\n    const { hasClientExports } = this.getDocumentInfo(mutation);\n\n    variables = this.getVariables(mutation, variables);\n\n    if (hasClientExports) {\n      if (__DEV__) {\n        invariant(\n          this.localState,\n          \"Mutation '%s' contains `@client` fields with variables provided by `@export` but local state has not been configured.\",\n          getOperationName(mutation, \"(anonymous)\")\n        );\n      }\n\n      variables = await this.localState!.getExportedVariables<TVariables>({\n        client: this.client,\n        document: mutation,\n        variables,\n        context,\n      });\n    }\n\n    const mutationStoreValue =\n      this.mutationStore &&\n      (this.mutationStore[queryInfo.id] = {\n        mutation,\n        variables,\n        loading: true,\n        error: null,\n      } as MutationStoreValue);\n\n    const isOptimistic =\n      optimisticResponse &&\n      queryInfo.markMutationOptimistic(optimisticResponse, {\n        document: mutation,\n        variables,\n        cacheWriteBehavior:\n          fetchPolicy === \"no-cache\" ?\n            CacheWriteBehavior.FORBID\n          : CacheWriteBehavior.MERGE,\n        errorPolicy,\n        context,\n        updateQueries,\n        update: updateWithProxyFn,\n        keepRootFields,\n      });\n\n    this.broadcastQueries();\n\n    return new Promise((resolve, reject) => {\n      const cause = {};\n      return this.getObservableFromLink<TData>(\n        mutation,\n        {\n          ...context,\n          optimisticResponse: isOptimistic ? optimisticResponse : void 0,\n        },\n        variables,\n        fetchPolicy,\n        {},\n        false\n      )\n        .observable.pipe(\n          validateDidEmitValue(),\n          mergeMap((result) => {\n            const storeResult: typeof result = { ...result };\n\n            return from(\n              queryInfo.markMutationResult(storeResult, {\n                document: mutation,\n                variables,\n                cacheWriteBehavior:\n                  fetchPolicy === \"no-cache\" ?\n                    CacheWriteBehavior.FORBID\n                  : CacheWriteBehavior.MERGE,\n                errorPolicy,\n                context,\n                update: updateWithProxyFn,\n                updateQueries,\n                awaitRefetchQueries,\n                refetchQueries,\n                removeOptimistic: isOptimistic ? queryInfo.id : void 0,\n                onQueryUpdated,\n                keepRootFields,\n              })\n            );\n          })\n        )\n        .pipe(\n          map((storeResult) => {\n            const hasErrors = graphQLResultHasError(storeResult);\n            if (hasErrors && errorPolicy === \"none\") {\n              throw new CombinedGraphQLErrors(\n                removeStreamDetailsFromExtensions(storeResult)\n              );\n            }\n\n            if (mutationStoreValue) {\n              mutationStoreValue.loading = false;\n              mutationStoreValue.error = null;\n            }\n\n            return storeResult;\n          })\n        )\n        .subscribe({\n          next: (storeResult) => {\n            this.broadcastQueries();\n\n            // Since mutations might receive multiple payloads from the\n            // ApolloLink chain (e.g. when used with @defer),\n            // we resolve with a SingleExecutionResult or after the final\n            // ExecutionPatchResult has arrived and we have assembled the\n            // multipart response into a single result.\n            if (!queryInfo.hasNext) {\n              const result: ApolloClient.MutateResult<TData> = {\n                data: this.maskOperation({\n                  document: mutation,\n                  data: storeResult.data,\n                  fetchPolicy,\n                  cause,\n                }) as any,\n              };\n\n              if (graphQLResultHasError(storeResult)) {\n                result.error = new CombinedGraphQLErrors(storeResult);\n              }\n\n              if (Object.keys(storeResult.extensions || {}).length) {\n                result.extensions = storeResult.extensions;\n              }\n\n              resolve(result);\n            }\n          },\n\n          error: (error) => {\n            if (mutationStoreValue) {\n              mutationStoreValue.loading = false;\n              mutationStoreValue.error = error;\n            }\n\n            if (isOptimistic) {\n              this.cache.removeOptimistic(queryInfo.id);\n            }\n\n            this.broadcastQueries();\n\n            if (errorPolicy === \"ignore\") {\n              return resolve({ data: undefined });\n            }\n\n            if (errorPolicy === \"all\") {\n              return resolve({ data: undefined, error });\n            }\n\n            reject(error);\n          },\n        });\n    });\n  }\n\n  public fetchQuery<TData, TVariables extends OperationVariables>(\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>,\n    networkStatus?: NetworkStatus\n  ): Promise<ApolloClient.QueryResult<TData>> {\n    checkDocument(options.query, OperationTypeNode.QUERY);\n\n    // do the rest asynchronously to keep the same rejection timing as\n    // checks further in `.mutate`\n    return (async () =>\n      lastValueFrom(\n        this.fetchObservableWithInfo(options, {\n          networkStatus,\n        }).observable.pipe(\n          filterMap((value) => {\n            switch (value.kind) {\n              case \"E\":\n                throw value.error;\n              case \"N\": {\n                if (value.source !== \"newNetworkStatus\")\n                  return toQueryResult(value.value);\n              }\n            }\n          })\n        ),\n        {\n          // This default is needed when a `standby` fetch policy is used to avoid\n          // an EmptyError from rejecting this promise.\n          defaultValue: { data: undefined },\n        }\n      ))();\n  }\n\n  public transform(document: DocumentNode) {\n    return this.documentTransform.transformDocument(document);\n  }\n\n  private transformCache = new AutoCleanedWeakCache<\n    DocumentNode,\n    TransformCacheEntry\n  >(\n    cacheSizes[\"queryManager.getDocumentInfo\"] ||\n      defaultCacheSizes[\"queryManager.getDocumentInfo\"]\n  );\n\n  public getDocumentInfo(document: DocumentNode) {\n    const { transformCache } = this;\n\n    if (!transformCache.has(document)) {\n      const operationDefinition = getOperationDefinition(document);\n\n      const cacheEntry: TransformCacheEntry = {\n        // TODO These three calls (hasClientExports, shouldForceResolvers, and\n        // usesNonreactiveDirective) are performing independent full traversals\n        // of the transformed document. We should consider merging these\n        // traversals into a single pass in the future, though the work is\n        // cached after the first time.\n        hasClientExports: hasDirectives([\"client\", \"export\"], document, true),\n        hasForcedResolvers: hasForcedResolvers(document),\n        hasNonreactiveDirective: hasDirectives([\"nonreactive\"], document),\n        hasIncrementalDirective: hasDirectives([\"defer\"], document),\n        nonReactiveQuery: addNonReactiveToNamedFragments(document),\n        clientQuery: hasDirectives([\"client\"], document) ? document : null,\n        serverQuery: removeDirectivesFromDocument(\n          [\n            { name: \"client\", remove: true },\n            { name: \"connection\" },\n            { name: \"nonreactive\" },\n            { name: \"unmask\" },\n          ],\n          document\n        ),\n        operationType: operationDefinition?.operation,\n        defaultVars: getDefaultValues(\n          operationDefinition\n        ) as OperationVariables,\n        // Transform any mutation or subscription operations to query operations\n        // so we can read/write them from/to the cache.\n        asQuery: {\n          ...document,\n          definitions: document.definitions.map((def) => {\n            if (\n              def.kind === \"OperationDefinition\" &&\n              def.operation !== \"query\"\n            ) {\n              return { ...def, operation: \"query\" as OperationTypeNode };\n            }\n            return def;\n          }),\n        },\n      };\n\n      transformCache.set(document, cacheEntry);\n    }\n\n    const entry = transformCache.get(document)!;\n    if (entry.violation) {\n      throw entry.violation;\n    }\n    return entry;\n  }\n\n  public getVariables<TVariables extends OperationVariables>(\n    document: DocumentNode,\n    variables?: TVariables\n  ): TVariables {\n    const defaultVars = this.getDocumentInfo(document).defaultVars;\n    const varsWithDefaults = Object.entries(variables ?? {}).map(\n      ([key, value]) => [key, value === undefined ? defaultVars[key] : value]\n    );\n\n    return {\n      ...defaultVars,\n      ...Object.fromEntries(varsWithDefaults),\n    };\n  }\n\n  public watchQuery<\n    TData,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>\n  ): ObservableQuery<TData, TVariables> {\n    checkDocument(options.query, OperationTypeNode.QUERY);\n\n    const query = this.transform(options.query);\n\n    // assign variable default values if supplied\n    // NOTE: We don't modify options.query here with the transformed query to\n    // ensure observable.options.query is set to the raw untransformed query.\n    options = {\n      ...options,\n      variables: this.getVariables(query, options.variables) as TVariables,\n    };\n\n    if (typeof options.notifyOnNetworkStatusChange === \"undefined\") {\n      options.notifyOnNetworkStatusChange = true;\n    }\n\n    const observable = new ObservableQuery<TData, TVariables>({\n      queryManager: this,\n      options,\n      transformedQuery: query,\n    });\n\n    return observable;\n  }\n\n  public query<\n    TData,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    options: ApolloClient.QueryOptions<TData, TVariables>\n  ): Promise<ApolloClient.QueryResult<MaybeMasked<TData>>> {\n    const query = this.transform(options.query);\n\n    return this.fetchQuery<TData, TVariables>({\n      ...(options as any),\n      query,\n    }).then((value) => ({\n      ...value,\n      data: this.maskOperation({\n        document: query,\n        data: value?.data,\n        fetchPolicy: options.fetchPolicy,\n      }),\n    }));\n  }\n\n  private requestIdCounter = 1;\n  public generateRequestId() {\n    return this.requestIdCounter++;\n  }\n\n  public clearStore(\n    options: Cache.ResetOptions = {\n      discardWatches: true,\n    }\n  ): Promise<void> {\n    // Before we have sent the reset action to the store, we can no longer\n    // rely on the results returned by in-flight requests since these may\n    // depend on values that previously existed in the data portion of the\n    // store. So, we cancel the promises and observers that we have issued\n    // so far and not yet resolved (in the case of queries).\n    this.cancelPendingFetches(\n      newInvariantError(\n        \"Store reset while query was in flight (not completed in link chain)\"\n      )\n    );\n\n    this.obsQueries.forEach((observableQuery) => {\n      // Set loading to true so listeners don't trigger unless they want\n      // results with partial data.\n      observableQuery.reset();\n    });\n\n    if (this.mutationStore) {\n      this.mutationStore = {};\n    }\n\n    // begin removing data from the store\n    return this.cache.reset(options);\n  }\n\n  public getObservableQueries(\n    include: InternalRefetchQueriesInclude = \"active\"\n  ) {\n    const queries = new Set<ObservableQuery<any>>();\n    const queryNames = new Map<string, string | undefined>();\n    const queryNamesAndQueryStrings = new Map<string, boolean>();\n    const legacyQueryOptions = new Set<ApolloClient.QueryOptions>();\n\n    if (Array.isArray(include)) {\n      include.forEach((desc) => {\n        if (typeof desc === \"string\") {\n          queryNames.set(desc, desc);\n          queryNamesAndQueryStrings.set(desc, false);\n        } else if (isDocumentNode(desc)) {\n          const queryString = print(this.transform(desc));\n          queryNames.set(queryString, getOperationName(desc));\n          queryNamesAndQueryStrings.set(queryString, false);\n        } else if (isNonNullObject(desc) && desc.query) {\n          legacyQueryOptions.add(desc);\n        }\n      });\n    }\n\n    this.obsQueries.forEach((oq) => {\n      const document = print(this.transform(oq.options.query));\n      if (include === \"all\") {\n        queries.add(oq);\n        return;\n      }\n\n      const {\n        queryName,\n        options: { fetchPolicy },\n      } = oq;\n\n      if (include === \"active\" && fetchPolicy === \"standby\") {\n        return;\n      }\n\n      if (\n        include === \"active\" ||\n        (queryName && queryNamesAndQueryStrings.has(queryName)) ||\n        (document && queryNamesAndQueryStrings.has(document))\n      ) {\n        queries.add(oq);\n        if (queryName) queryNamesAndQueryStrings.set(queryName, true);\n        if (document) queryNamesAndQueryStrings.set(document, true);\n      }\n    });\n\n    if (legacyQueryOptions.size) {\n      legacyQueryOptions.forEach((options) => {\n        const oq = new ObservableQuery({\n          queryManager: this,\n          options: {\n            ...mergeOptions(this.defaultOptions.watchQuery, options),\n            fetchPolicy: \"network-only\",\n          },\n        });\n        queries.add(oq);\n      });\n    }\n\n    if (__DEV__ && queryNamesAndQueryStrings.size) {\n      queryNamesAndQueryStrings.forEach((included, nameOrQueryString) => {\n        if (!included) {\n          const queryName = queryNames.get(nameOrQueryString);\n\n          if (queryName) {\n            invariant.warn(\n              `Unknown query named \"%s\" requested in refetchQueries options.include array`,\n              queryName\n            );\n          } else {\n            invariant.warn(\n              `Unknown anonymous query requested in refetchQueries options.include array`\n            );\n          }\n        }\n      });\n    }\n\n    return queries;\n  }\n\n  public refetchObservableQueries(\n    includeStandby: boolean = false\n  ): Promise<ApolloClient.QueryResult<any>[]> {\n    const observableQueryPromises: Promise<ApolloClient.QueryResult<any>>[] =\n      [];\n\n    this.getObservableQueries(includeStandby ? \"all\" : \"active\").forEach(\n      (observableQuery) => {\n        const { fetchPolicy } = observableQuery.options;\n        if (\n          (includeStandby || fetchPolicy !== \"standby\") &&\n          fetchPolicy !== \"cache-only\"\n        ) {\n          observableQueryPromises.push(observableQuery.refetch());\n        }\n      }\n    );\n\n    this.broadcastQueries();\n\n    return Promise.all(observableQueryPromises);\n  }\n\n  public startGraphQLSubscription<TData = unknown>(\n    options: ApolloClient.SubscribeOptions<TData>\n  ): SubscriptionObservable<ApolloClient.SubscribeResult<TData>> {\n    let { query, variables } = options;\n    const {\n      fetchPolicy = \"cache-first\",\n      errorPolicy = \"none\",\n      context = {},\n      extensions = {},\n    } = options;\n\n    checkDocument(query, OperationTypeNode.SUBSCRIPTION);\n\n    query = this.transform(query);\n    variables = this.getVariables(query, variables);\n\n    let restart: (() => void) | undefined;\n\n    if (__DEV__) {\n      invariant(\n        !this.getDocumentInfo(query).hasClientExports || this.localState,\n        \"Subscription '%s' contains `@client` fields with variables provided by `@export` but local state has not been configured.\",\n        getOperationName(query, \"(anonymous)\")\n      );\n    }\n\n    const observable = (\n      this.getDocumentInfo(query).hasClientExports ?\n        from(\n          this.localState!.getExportedVariables({\n            client: this.client,\n            document: query,\n            variables,\n            context,\n          })\n        )\n      : of(variables)).pipe(\n      mergeMap((variables) => {\n        const { observable, restart: res } = this.getObservableFromLink<TData>(\n          query,\n          context,\n          variables,\n          fetchPolicy,\n          extensions\n        );\n\n        const queryInfo = new QueryInfo<TData>(this);\n\n        restart = res;\n        return (observable as Observable<FormattedExecutionResult<TData>>).pipe(\n          map((rawResult): ApolloClient.SubscribeResult<TData> => {\n            queryInfo.markSubscriptionResult(rawResult, {\n              document: query,\n              variables,\n              errorPolicy,\n              cacheWriteBehavior:\n                fetchPolicy === \"no-cache\" ?\n                  CacheWriteBehavior.FORBID\n                : CacheWriteBehavior.MERGE,\n            });\n\n            const result: ApolloClient.SubscribeResult<TData> = {\n              data: rawResult.data ?? undefined,\n            };\n\n            if (graphQLResultHasError(rawResult)) {\n              result.error = new CombinedGraphQLErrors(rawResult);\n            } else if (graphQLResultHasProtocolErrors(rawResult)) {\n              result.error = rawResult.extensions[PROTOCOL_ERRORS_SYMBOL];\n              // Don't emit protocol errors added by HttpLink\n              delete rawResult.extensions[PROTOCOL_ERRORS_SYMBOL];\n            }\n\n            if (\n              rawResult.extensions &&\n              Object.keys(rawResult.extensions).length\n            ) {\n              result.extensions = rawResult.extensions;\n            }\n\n            if (result.error && errorPolicy === \"none\") {\n              result.data = undefined;\n            }\n\n            if (errorPolicy === \"ignore\") {\n              delete result.error;\n            }\n\n            return result;\n          }),\n          catchError((error) => {\n            if (errorPolicy === \"ignore\") {\n              return of({\n                data: undefined,\n              } as ApolloClient.SubscribeResult<TData>);\n            }\n\n            return of({ data: undefined, error });\n          }),\n          filter((result) => !!(result.data || result.error))\n        );\n      })\n    );\n\n    return Object.assign(observable, { restart: () => restart?.() });\n  }\n\n  public broadcastQueries() {\n    if (this.onBroadcast) this.onBroadcast();\n    this.obsQueries.forEach((observableQuery) => observableQuery.notify());\n  }\n\n  // Use protected instead of private field so\n  // @apollo/experimental-nextjs-app-support can access type info.\n  protected inFlightLinkObservables = new Trie<{\n    observable?: Observable<ApolloLink.Result<any>>;\n    restart?: () => void;\n  }>(false);\n\n  private getObservableFromLink<TData = unknown>(\n    query: DocumentNode,\n    context: DefaultContext | undefined,\n    variables: OperationVariables,\n    fetchPolicy: WatchQueryFetchPolicy,\n    extensions?: Record<string, any>,\n    // Prefer context.queryDeduplication if specified.\n    deduplication: boolean = context?.queryDeduplication ??\n      this.queryDeduplication\n  ): {\n    restart: () => void;\n    observable: Observable<ApolloLink.Result<TData>>;\n  } {\n    let entry: {\n      observable?: Observable<ApolloLink.Result<TData>>;\n      // The restart function has to be on a mutable object that way if multiple\n      // client.subscribe() calls are made before the first one subscribes to\n      // the observable, the `restart` function can be updated for all\n      // deduplicated client.subscribe() calls.\n      restart?: () => void;\n    } = {};\n\n    const { serverQuery, clientQuery, operationType, hasIncrementalDirective } =\n      this.getDocumentInfo(query);\n\n    const operationName = getOperationName(query);\n    const executeContext: ApolloLink.ExecuteContext = {\n      client: this.client,\n    };\n\n    if (serverQuery) {\n      const { inFlightLinkObservables, link } = this;\n\n      try {\n        const operation = this.incrementalHandler.prepareRequest({\n          query: serverQuery,\n          variables,\n          context: {\n            ...this.defaultContext,\n            ...context,\n            queryDeduplication: deduplication,\n          },\n          extensions,\n        });\n\n        context = operation.context;\n\n        function withRestart(source: Observable<ApolloLink.Result>) {\n          return new Observable<ApolloLink.Result>((observer) => {\n            function subscribe() {\n              return source.subscribe({\n                next: observer.next.bind(observer),\n                complete: observer.complete.bind(observer),\n                error: observer.error.bind(observer),\n              });\n            }\n            let subscription = subscribe();\n\n            entry.restart ||= () => {\n              subscription.unsubscribe();\n              subscription = subscribe();\n            };\n\n            return () => {\n              subscription.unsubscribe();\n              entry.restart = undefined;\n            };\n          });\n        }\n\n        if (deduplication) {\n          const printedServerQuery = print(serverQuery);\n          const varJson = canonicalStringify(variables);\n\n          entry = inFlightLinkObservables.lookup(printedServerQuery, varJson);\n\n          if (!entry.observable) {\n            entry.observable = execute(link, operation, executeContext).pipe(\n              withRestart,\n              finalize(() => {\n                if (\n                  inFlightLinkObservables.peek(printedServerQuery, varJson) ===\n                  entry\n                ) {\n                  inFlightLinkObservables.remove(printedServerQuery, varJson);\n                }\n              }),\n              // We don't want to replay the last emitted value for\n              // subscriptions and instead opt to wait to receive updates until\n              // the subscription emits new values.\n              operationType === OperationTypeNode.SUBSCRIPTION ?\n                share()\n              : shareReplay({ refCount: true })\n            ) as Observable<ApolloLink.Result<TData>>;\n          }\n        } else {\n          entry.observable = execute(link, operation, executeContext).pipe(\n            withRestart\n          ) as Observable<ApolloLink.Result<TData>>;\n        }\n      } catch (error) {\n        entry.observable = throwError(() => error);\n      }\n    } else {\n      entry.observable = of({ data: {} } as ApolloLink.Result<TData>);\n    }\n\n    if (clientQuery) {\n      const { operation } = getOperationDefinition(query)!;\n      if (__DEV__) {\n        invariant(\n          this.localState,\n          \"%s '%s' contains `@client` fields but local state has not been configured.\",\n          operation[0].toUpperCase() + operation.slice(1),\n          operationName ?? \"(anonymous)\"\n        );\n      }\n\n      invariant(\n        !hasIncrementalDirective,\n        \"%s '%s' contains `@client` and `@defer` directives. These cannot be used together.\",\n        operation[0].toUpperCase() + operation.slice(1),\n        operationName ?? \"(anonymous)\"\n      );\n\n      entry.observable = entry.observable.pipe(\n        mergeMap((result) => {\n          return from(\n            this.localState!.execute<TData>({\n              client: this.client,\n              document: clientQuery,\n              remoteResult: result as FormattedExecutionResult<TData>,\n              context,\n              variables,\n              fetchPolicy,\n            })\n          );\n        })\n      );\n    }\n\n    return {\n      restart: () => entry.restart?.(),\n      observable: entry.observable.pipe(\n        catchError((error) => {\n          error = toErrorLike(error);\n          registerLinkError(error);\n          throw error;\n        })\n      ),\n    };\n  }\n\n  private getResultsFromLink<TData, TVariables extends OperationVariables>(\n    options: {\n      query: DocumentNode;\n      variables: TVariables;\n      context: DefaultContext | undefined;\n      fetchPolicy: WatchQueryFetchPolicy;\n      errorPolicy: ErrorPolicy;\n    },\n    {\n      queryInfo,\n      cacheWriteBehavior,\n      observableQuery,\n      exposeExtensions,\n    }: {\n      queryInfo: QueryInfo<TData, TVariables>;\n      cacheWriteBehavior: CacheWriteBehavior;\n      observableQuery: ObservableQuery<TData, TVariables> | undefined;\n      exposeExtensions?: boolean;\n    }\n  ): Observable<ObservableQuery.Result<TData>> {\n    const requestId = (queryInfo.lastRequestId = this.generateRequestId());\n    const { errorPolicy } = options;\n\n    // Performing transformForLink here gives this.cache a chance to fill in\n    // missing fragment definitions (for example) before sending this document\n    // through the link chain.\n    const linkDocument = this.cache.transformForLink(options.query);\n\n    return this.getObservableFromLink<TData>(\n      linkDocument,\n      options.context,\n      options.variables,\n      options.fetchPolicy\n    ).observable.pipe(\n      map((incoming) => {\n        // Use linkDocument rather than queryInfo.document so the\n        // operation/fragments used to write the result are the same as the\n        // ones used to obtain it from the link.\n        const result = queryInfo.markQueryResult(incoming, {\n          ...options,\n          document: linkDocument,\n          cacheWriteBehavior,\n        });\n        const hasErrors = graphQLResultHasError(result);\n\n        if (hasErrors && errorPolicy === \"none\") {\n          queryInfo.resetLastWrite();\n          observableQuery?.[\"resetNotifications\"]();\n          throw new CombinedGraphQLErrors(\n            removeStreamDetailsFromExtensions(result)\n          );\n        }\n\n        const aqr: QueryManager.Result<TData> = {\n          data: result.data as TData,\n          ...(queryInfo.hasNext ?\n            {\n              loading: true,\n              networkStatus: NetworkStatus.streaming,\n              dataState: \"streaming\",\n              partial: true,\n            }\n          : {\n              dataState: result.data ? \"complete\" : \"empty\",\n              loading: false,\n              networkStatus: NetworkStatus.ready,\n              partial: !result.data,\n            }),\n        } as ObservableQuery.Result<TData>;\n\n        if (exposeExtensions && \"extensions\" in result) {\n          aqr[extensionsSymbol] = result.extensions;\n        }\n\n        // In the case we start multiple network requests simultaneously, we\n        // want to ensure we properly set `data` if we're reporting on an old\n        // result which will not be caught by the conditional above that ends up\n        // throwing the markError result.\n        if (hasErrors) {\n          if (errorPolicy === \"none\") {\n            aqr.data = void 0 as TData;\n            aqr.dataState = \"empty\";\n          }\n          if (errorPolicy !== \"ignore\") {\n            aqr.error = new CombinedGraphQLErrors(\n              removeStreamDetailsFromExtensions(result)\n            );\n            if (aqr.dataState !== \"streaming\") {\n              aqr.networkStatus = NetworkStatus.error;\n            }\n          }\n        }\n\n        return aqr;\n      }),\n      catchError((error) => {\n        // Avoid storing errors from older interrupted queries.\n        if (requestId >= queryInfo.lastRequestId && errorPolicy === \"none\") {\n          queryInfo.resetLastWrite();\n          observableQuery?.[\"resetNotifications\"]();\n          throw error;\n        }\n\n        const aqr: ObservableQuery.Result<TData> = {\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        };\n\n        if (errorPolicy !== \"ignore\") {\n          aqr.error = error;\n          aqr.networkStatus = NetworkStatus.error;\n        }\n\n        return of(aqr);\n      })\n    );\n  }\n\n  public fetchObservableWithInfo<TData, TVariables extends OperationVariables>(\n    options: ApolloClient.WatchQueryOptions<TData, TVariables>,\n    {\n      // The initial networkStatus for this fetch, most often\n      // NetworkStatus.loading, but also possibly fetchMore, poll, refetch,\n      // or setVariables.\n      networkStatus = NetworkStatus.loading,\n      query = options.query,\n      fetchQueryOperator = (x) => x,\n      onCacheHit = () => {},\n      observableQuery,\n      exposeExtensions,\n    }: {\n      networkStatus?: NetworkStatus;\n      query?: DocumentNode;\n      fetchQueryOperator?: <T>(source: Observable<T>) => Observable<T>;\n      onCacheHit?: () => void;\n      observableQuery?: ObservableQuery<TData, TVariables> | undefined;\n      /**\n       * Attach `extensions` to the result object so that it is accessible by\n       * the calling code without being exposed to the emitted result.\n       *\n       * @remarks\n       * Used by e.g. `fetchMore` to add `extensions` to the `cache.writeQuery`\n       * call since it uses a `no-cache` query and cannot be written in\n       * `QueryInfo`.\n       */\n      exposeExtensions?: boolean;\n    }\n  ): ObservableAndInfo<TData> {\n    const variables = this.getVariables(query, options.variables) as TVariables;\n\n    let {\n      fetchPolicy = \"cache-first\",\n      errorPolicy = \"none\",\n      returnPartialData = false,\n      notifyOnNetworkStatusChange = true,\n      context = {},\n    } = options;\n\n    if (\n      this.prioritizeCacheValues &&\n      (fetchPolicy === \"network-only\" || fetchPolicy === \"cache-and-network\")\n    ) {\n      fetchPolicy = \"cache-first\";\n    }\n\n    const normalized = Object.assign({}, options, {\n      query,\n      variables,\n      fetchPolicy,\n      errorPolicy,\n      returnPartialData,\n      notifyOnNetworkStatusChange,\n      context,\n    });\n\n    const queryInfo = new QueryInfo<TData, TVariables>(this, observableQuery);\n\n    const fromVariables = (variables: TVariables) => {\n      // Since normalized is always a fresh copy of options, it's safe to\n      // modify its properties here, rather than creating yet another new\n      // WatchQueryOptions object.\n      normalized.variables = variables;\n\n      const cacheWriteBehavior =\n        fetchPolicy === \"no-cache\" ? CacheWriteBehavior.FORBID\n          // Watched queries must opt into overwriting existing data on refetch,\n          // by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n        : (\n          networkStatus === NetworkStatus.refetch &&\n          normalized.refetchWritePolicy !== \"merge\"\n        ) ?\n          CacheWriteBehavior.OVERWRITE\n        : CacheWriteBehavior.MERGE;\n      const observableWithInfo = this.fetchQueryByPolicy<TData, TVariables>(\n        normalized,\n        {\n          queryInfo,\n          cacheWriteBehavior,\n          onCacheHit,\n          observableQuery,\n          exposeExtensions,\n        }\n      );\n      observableWithInfo.observable =\n        observableWithInfo.observable.pipe(fetchQueryOperator);\n\n      if (\n        // If we're in standby, postpone advancing options.fetchPolicy using\n        // applyNextFetchPolicy.\n        normalized.fetchPolicy !== \"standby\"\n      ) {\n        observableQuery?.[\"applyNextFetchPolicy\"](\n          \"after-fetch\",\n          options as any\n        );\n      }\n\n      return observableWithInfo;\n    };\n\n    // This cancel function needs to be set before the concast is created,\n    // in case concast creation synchronously cancels the request.\n    const cleanupCancelFn = () => {\n      this.fetchCancelFns.delete(queryInfo.id);\n    };\n    this.fetchCancelFns.set(queryInfo.id, (error) => {\n      fetchCancelSubject.next({\n        kind: \"E\",\n        error,\n        source: \"network\",\n      });\n    });\n\n    const fetchCancelSubject = new Subject<QueryNotification.Value<TData>>();\n    let observable: Observable<QueryNotification.Value<TData>>,\n      containsDataFromLink: boolean;\n\n    // If the query has @export(as: ...) directives, then we need to\n    // process those directives asynchronously. When there are no\n    // @export directives (the common case), we deliberately avoid\n    // wrapping the result of this.fetchQueryByPolicy in a Promise,\n    // since the timing of result delivery is (unfortunately) important\n    // for backwards compatibility. TODO This code could be simpler if\n    // we deprecated and removed LocalState.\n    if (this.getDocumentInfo(normalized.query).hasClientExports) {\n      if (__DEV__) {\n        invariant(\n          this.localState,\n          \"Query '%s' contains `@client` fields with variables provided by `@export` but local state has not been configured.\",\n          getOperationName(normalized.query, \"(anonymous)\")\n        );\n      }\n\n      observable = from(\n        this.localState!.getExportedVariables({\n          client: this.client,\n          document: normalized.query,\n          variables: normalized.variables,\n          context: normalized.context,\n        })\n      ).pipe(mergeMap((variables) => fromVariables(variables).observable));\n\n      // there is just no way we can synchronously get the *right* value here,\n      // so we will assume `true`, which is the behaviour before the bug fix in\n      // #10597. This means that bug is not fixed in that case, and is probably\n      // un-fixable with reasonable effort for the edge case of @export as\n      // directives.\n      containsDataFromLink = true;\n    } else {\n      const sourcesWithInfo = fromVariables(normalized.variables);\n      containsDataFromLink = sourcesWithInfo.fromLink;\n      observable = sourcesWithInfo.observable;\n    }\n\n    return {\n      // Merge `observable` with `fetchCancelSubject`, in a way that completing or\n      // erroring either of them will complete the merged obserable.\n      observable: new Observable<QueryNotification.Value<TData>>((observer) => {\n        observer.add(cleanupCancelFn);\n        observable.subscribe(observer);\n        fetchCancelSubject.subscribe(observer);\n      }).pipe(share()),\n      fromLink: containsDataFromLink,\n    };\n  }\n\n  public refetchQueries<TResult>({\n    updateCache,\n    include,\n    optimistic = false,\n    removeOptimistic = optimistic ? makeUniqueId(\"refetchQueries\") : void 0,\n    onQueryUpdated,\n  }: InternalRefetchQueriesOptions<\n    ApolloCache,\n    TResult\n  >): InternalRefetchQueriesMap<TResult> {\n    const includedQueriesByOq = new Map<\n      ObservableQuery<any>,\n      {\n        oq: ObservableQuery<any>;\n        lastDiff?: Cache.DiffResult<any>;\n        diff?: Cache.DiffResult<any>;\n      }\n    >();\n\n    if (include) {\n      this.getObservableQueries(include).forEach((oq) => {\n        if (oq.options.fetchPolicy === \"cache-only\" || oq[\"variablesUnknown\"]) {\n          return;\n        }\n\n        const current = oq.getCurrentResult();\n        includedQueriesByOq.set(oq, {\n          oq,\n          lastDiff: {\n            result: current?.data,\n            complete: !current?.partial,\n          },\n        });\n      });\n    }\n\n    const results: InternalRefetchQueriesMap<TResult> = new Map();\n\n    if (updateCache) {\n      const handled = new Set<ObservableQuery<any>>();\n      this.cache.batch({\n        update: updateCache,\n\n        // Since you can perform any combination of cache reads and/or writes in\n        // the cache.batch update function, its optimistic option can be either\n        // a boolean or a string, representing three distinct modes of\n        // operation:\n        //\n        // * false: read/write only the root layer\n        // * true: read/write the topmost layer\n        // * string: read/write a fresh optimistic layer with that ID string\n        //\n        // When typeof optimistic === \"string\", a new optimistic layer will be\n        // temporarily created within cache.batch with that string as its ID. If\n        // we then pass that same string as the removeOptimistic option, we can\n        // make cache.batch immediately remove the optimistic layer after\n        // running the updateCache function, triggering only one broadcast.\n        //\n        // However, the refetchQueries method accepts only true or false for its\n        // optimistic option (not string). We interpret true to mean a temporary\n        // optimistic layer should be created, to allow efficiently rolling back\n        // the effect of the updateCache function, which involves passing a\n        // string instead of true as the optimistic option to cache.batch, when\n        // refetchQueries receives optimistic: true.\n        //\n        // In other words, we are deliberately not supporting the use case of\n        // writing to an *existing* optimistic layer (using the refetchQueries\n        // updateCache function), since that would potentially interfere with\n        // other optimistic updates in progress. Instead, you can read/write\n        // only the root layer by passing optimistic: false to refetchQueries,\n        // or you can read/write a brand new optimistic layer that will be\n        // automatically removed by passing optimistic: true.\n        optimistic: (optimistic && removeOptimistic) || false,\n\n        // The removeOptimistic option can also be provided by itself, even if\n        // optimistic === false, to remove some previously-added optimistic\n        // layer safely and efficiently, like we do in markMutationResult.\n        //\n        // If an explicit removeOptimistic string is provided with optimistic:\n        // true, the removeOptimistic string will determine the ID of the\n        // temporary optimistic layer, in case that ever matters.\n        removeOptimistic,\n\n        onWatchUpdated(watch, diff, lastDiff) {\n          const oq = watch.watcher;\n\n          if (oq instanceof ObservableQuery && !handled.has(oq)) {\n            handled.add(oq);\n            if (onQueryUpdated) {\n              // Since we're about to handle this query now, remove it from\n              // includedQueriesById, in case it was added earlier because of\n              // options.include.\n              includedQueriesByOq.delete(oq);\n\n              let result:\n                | TResult\n                | boolean\n                | Promise<ApolloClient.QueryResult<any>> = onQueryUpdated(\n                oq,\n                diff,\n                lastDiff\n              );\n\n              if (result === true) {\n                // The onQueryUpdated function requested the default refetching\n                // behavior by returning true.\n                result = oq\n                  .refetch()\n                  .retain(/* create a persistent subscription on the query */);\n              }\n\n              // Record the result in the results Map, as long as onQueryUpdated\n              // did not return false to skip/ignore this result.\n              if (result !== false) {\n                results.set(\n                  oq,\n                  result as InternalRefetchQueriesResult<TResult>\n                );\n              }\n\n              // Allow the default cache broadcast to happen, except when\n              // onQueryUpdated returns false.\n              return result;\n            }\n\n            if (\n              onQueryUpdated !== null &&\n              oq.options.fetchPolicy !== \"cache-only\"\n            ) {\n              // If we don't have an onQueryUpdated function, and onQueryUpdated\n              // was not disabled by passing null, make sure this query is\n              // \"included\" like any other options.include-specified query.\n              includedQueriesByOq.set(oq, { oq, lastDiff, diff });\n            }\n          }\n        },\n      });\n    }\n\n    if (includedQueriesByOq.size) {\n      includedQueriesByOq.forEach(({ oq, lastDiff, diff }) => {\n        let result:\n          | TResult\n          | boolean\n          | Promise<ApolloClient.QueryResult<any>>\n          | undefined;\n\n        // If onQueryUpdated is provided, we want to use it for all included\n        // queries, even the QueryOptions ones.\n        if (onQueryUpdated) {\n          if (!diff) {\n            diff = oq.getCacheDiff();\n          }\n          result = onQueryUpdated(oq, diff, lastDiff);\n        }\n\n        // Otherwise, we fall back to refetching.\n        if (!onQueryUpdated || result === true) {\n          result = oq\n            .refetch()\n            .retain(/* create a persistent subscription on the query */);\n        }\n\n        if (result !== false) {\n          results.set(oq, result as InternalRefetchQueriesResult<TResult>);\n        }\n      });\n    }\n\n    if (removeOptimistic) {\n      // In case no updateCache callback was provided (so cache.batch was not\n      // called above, and thus did not already remove the optimistic layer),\n      // remove it here. Since this is a no-op when the layer has already been\n      // removed, we do it even if we called cache.batch above, since it's\n      // possible this.cache is an instance of some ApolloCache subclass other\n      // than InMemoryCache, and does not fully support the removeOptimistic\n      // option for cache.batch.\n      this.cache.removeOptimistic(removeOptimistic);\n    }\n\n    return results;\n  }\n\n  private noCacheWarningsByCause = new WeakSet<object>();\n\n  public maskOperation<TData = unknown>(\n    options: MaskOperationOptions<TData>\n  ): MaybeMasked<TData> {\n    const { document, data } = options;\n\n    if (__DEV__) {\n      const { fetchPolicy, cause = {} } = options;\n      const operationType = getOperationDefinition(document)?.operation;\n\n      if (\n        this.dataMasking &&\n        fetchPolicy === \"no-cache\" &&\n        !isFullyUnmaskedOperation(document) &&\n        !this.noCacheWarningsByCause.has(cause)\n      ) {\n        this.noCacheWarningsByCause.add(cause);\n\n        invariant.warn(\n          '[%s]: Fragments masked by data masking are inaccessible when using fetch policy \"no-cache\". Please add `@unmask` to each fragment spread to access the data.',\n          getOperationName(document, `Unnamed ${operationType ?? \"operation\"}`)\n        );\n      }\n    }\n\n    return (\n      this.dataMasking ?\n        maskOperation(data, document, this.cache)\n      : data) as MaybeMasked<TData>;\n  }\n\n  public maskFragment<TData = unknown>(options: MaskFragmentOptions<TData>) {\n    const { data, fragment, fragmentName } = options;\n\n    return this.dataMasking ?\n        maskFragment(data, fragment, this.cache, fragmentName)\n      : data;\n  }\n\n  private fetchQueryByPolicy<TData, TVariables extends OperationVariables>(\n    {\n      query,\n      variables,\n      fetchPolicy,\n      errorPolicy,\n      returnPartialData,\n      context,\n    }: {\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n      variables: TVariables;\n      fetchPolicy: WatchQueryFetchPolicy;\n      errorPolicy: ErrorPolicy;\n      returnPartialData?: boolean;\n      context?: DefaultContext;\n    },\n    {\n      cacheWriteBehavior,\n      onCacheHit,\n      queryInfo,\n      observableQuery,\n      exposeExtensions,\n    }: {\n      cacheWriteBehavior: CacheWriteBehavior;\n      onCacheHit: () => void;\n      queryInfo: QueryInfo<TData, TVariables>;\n      observableQuery: ObservableQuery<TData, TVariables> | undefined;\n      exposeExtensions?: boolean;\n    }\n  ): ObservableAndInfo<TData> {\n    const readCache = () =>\n      this.cache.diff<any>({\n        query,\n        variables,\n        returnPartialData: true,\n        optimistic: true,\n      });\n\n    const resultsFromCache = (\n      diff: Cache.DiffResult<TData>,\n      networkStatus: NetworkStatus\n    ): Observable<QueryNotification.FromCache<TData>> => {\n      const data = diff.result;\n\n      if (__DEV__ && !returnPartialData && data !== null) {\n        logMissingFieldErrors(diff.missing);\n      }\n\n      const toResult = (\n        data: TData | DeepPartial<TData> | undefined\n      ): ObservableQuery.Result<TData> => {\n        // TODO: Eventually we should move this handling into\n        // queryInfo.getDiff() directly. Since getDiff is updated to return null\n        // on returnPartialData: false, we should take advantage of that instead\n        // of having to patch it elsewhere.\n        if (!diff.complete && !returnPartialData) {\n          data = undefined;\n        }\n\n        return {\n          // TODO: Handle partial data\n          data: data as TData | undefined,\n          dataState:\n            diff.complete ? \"complete\"\n            : data ? \"partial\"\n            : \"empty\",\n          loading: isNetworkRequestInFlight(networkStatus),\n          networkStatus,\n          partial: !diff.complete,\n        } as ObservableQuery.Result<TData>;\n      };\n\n      const fromData = (\n        data: TData | DeepPartial<TData> | undefined\n      ): Observable<QueryNotification.FromCache<TData>> => {\n        return of({\n          kind: \"N\",\n          value: toResult(data),\n          source: \"cache\",\n        });\n      };\n\n      if (\n        // Don't attempt to run forced resolvers if we have incomplete cache\n        // data and partial isn't allowed since this result would get set to\n        // `undefined` anyways in `toResult`.\n        (diff.complete || returnPartialData) &&\n        this.getDocumentInfo(query).hasForcedResolvers\n      ) {\n        if (__DEV__) {\n          invariant(\n            this.localState,\n            \"Query '%s' contains `@client` fields but local state has not been configured.\",\n            getOperationName(query, \"(anonymous)\")\n          );\n        }\n        onCacheHit();\n\n        return from(\n          this.localState!.execute<TData>({\n            client: this.client,\n            document: query,\n            remoteResult: data ? { data } : undefined,\n            context,\n            variables,\n            onlyRunForcedResolvers: true,\n            returnPartialData: true,\n            fetchPolicy,\n          }).then(\n            (resolved): QueryNotification.FromCache<TData> => ({\n              kind: \"N\",\n              value: toResult(resolved.data || void 0),\n              source: \"cache\",\n            })\n          )\n        );\n      }\n\n      // Resolves https://github.com/apollographql/apollo-client/issues/10317.\n      // If errorPolicy is 'none' and notifyOnNetworkStatusChange is true,\n      // data was incorrectly returned from the cache on refetch:\n      // if diff.missing exists, we should not return cache data.\n      if (\n        errorPolicy === \"none\" &&\n        networkStatus === NetworkStatus.refetch &&\n        diff.missing\n      ) {\n        return fromData(void 0);\n      }\n\n      return fromData(data || undefined);\n    };\n\n    const resultsFromLink = () =>\n      this.getResultsFromLink<TData, TVariables>(\n        {\n          query,\n          variables,\n          context,\n          fetchPolicy,\n          errorPolicy,\n        },\n        {\n          cacheWriteBehavior,\n          queryInfo,\n          observableQuery,\n          exposeExtensions,\n        }\n      ).pipe(\n        validateDidEmitValue(),\n        materialize(),\n        map(\n          (result): QueryNotification.FromNetwork<TData> => ({\n            ...result,\n            source: \"network\",\n          })\n        )\n      );\n\n    switch (fetchPolicy) {\n      default:\n      case \"cache-first\": {\n        const diff = readCache();\n\n        if (diff.complete) {\n          return {\n            fromLink: false,\n            observable: resultsFromCache(diff, NetworkStatus.ready),\n          };\n        }\n\n        if (returnPartialData) {\n          return {\n            fromLink: true,\n            observable: concat(\n              resultsFromCache(diff, NetworkStatus.loading),\n              resultsFromLink()\n            ),\n          };\n        }\n\n        return { fromLink: true, observable: resultsFromLink() };\n      }\n\n      case \"cache-and-network\": {\n        const diff = readCache();\n\n        if (diff.complete || returnPartialData) {\n          return {\n            fromLink: true,\n            observable: concat(\n              resultsFromCache(diff, NetworkStatus.loading),\n              resultsFromLink()\n            ),\n          };\n        }\n\n        return { fromLink: true, observable: resultsFromLink() };\n      }\n\n      case \"cache-only\":\n        return {\n          fromLink: false,\n          observable: concat(\n            resultsFromCache(readCache(), NetworkStatus.ready)\n          ),\n        };\n\n      case \"network-only\":\n        return { fromLink: true, observable: resultsFromLink() };\n\n      case \"no-cache\":\n        return { fromLink: true, observable: resultsFromLink() };\n\n      case \"standby\":\n        return { fromLink: false, observable: EMPTY };\n    }\n  }\n}\n\nfunction validateDidEmitValue<T>() {\n  let didEmitValue = false;\n\n  return tap<T>({\n    next() {\n      didEmitValue = true;\n    },\n    complete() {\n      invariant(\n        didEmitValue,\n        \"The link chain completed without emitting a value. This is likely unintentional and should be updated to emit a value before completing.\"\n      );\n    },\n  });\n}\n\n// Return types used by fetchQueryByPolicy and other private methods above.\ninterface ObservableAndInfo<TData> {\n  // Metadata properties that can be returned in addition to the Observable.\n  fromLink: boolean;\n  observable: Observable<QueryNotification.Value<TData>>;\n}\n\nfunction isFullyUnmaskedOperation(document: DocumentNode) {\n  let isUnmasked = true;\n\n  visit(document, {\n    FragmentSpread: (node) => {\n      isUnmasked =\n        !!node.directives &&\n        node.directives.some((directive) => directive.name.value === \"unmask\");\n\n      if (!isUnmasked) {\n        return BREAK;\n      }\n    },\n  });\n\n  return isUnmasked;\n}\n\nfunction addNonReactiveToNamedFragments(document: DocumentNode) {\n  return visit(document, {\n    FragmentSpread: (node) => {\n      // Do not add `@nonreactive` if the fragment is marked with `@unmask`\n      // since we want to react to changes in this fragment.\n      if (\n        node.directives?.some((directive) => directive.name.value === \"unmask\")\n      ) {\n        return;\n      }\n\n      return {\n        ...node,\n        directives: [\n          ...(node.directives || []),\n          {\n            kind: Kind.DIRECTIVE,\n            name: { kind: Kind.NAME, value: \"nonreactive\" },\n          } satisfies DirectiveNode,\n        ],\n      };\n    },\n  });\n}\n\nfunction removeStreamDetailsFromExtensions(\n  original: FormattedExecutionResult<any, ExtensionsWithStreamInfo>\n): FormattedExecutionResult<any> {\n  if (original.extensions?.[streamInfoSymbol] == null) {\n    return original;\n  }\n\n  const {\n    extensions: { [streamInfoSymbol]: _, ...extensions },\n    ...result\n  } = original;\n\n  if (Object.keys(extensions).length > 0) {\n    (result as FormattedExecutionResult<any>).extensions = extensions;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "src/core/__tests__/ApolloClient/general.test.ts",
    "content": "// externals\nimport type { DocumentNode } from \"graphql\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Observer } from \"rxjs\";\nimport { Observable, Subject } from \"rxjs\";\n\nimport type { ObservableQuery, TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { addTypenameToDocument, print } from \"@apollo/client/utilities\";\nimport { variablesUnknownSymbol } from \"@apollo/client/utilities/internal\";\nimport {\n  InvariantError,\n  setVerbosity,\n} from \"@apollo/client/utilities/invariant\";\n\nimport type { MockApolloLink } from \"../../../testing/core/mocking/mockLink.js\";\nimport type { WatchQueryFetchPolicy } from \"../../watchQueryOptions.js\";\n\ndescribe(\"ApolloClient\", () => {\n  const getObservableStream = ({\n    query,\n    variables = {},\n    queryOptions = {},\n    result,\n    error,\n    delay,\n  }: {\n    query: DocumentNode;\n    variables?: Object;\n    queryOptions?: Object;\n    error?: Error;\n    result?: ApolloLink.Result;\n    delay?: number;\n  }) => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request: { query, variables }, result, error, delay },\n      ]),\n    });\n\n    return new ObservableStream(\n      client.watchQuery({ query, variables, ...queryOptions })\n    );\n  };\n\n  it(\"handles GraphQL errors\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      variables: {},\n      result: {\n        errors: [new GraphQLError(\"This is an error message.\")],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        errors: [{ message: \"This is an error message.\" }],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"handles GraphQL errors as data\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      variables: {},\n      queryOptions: {\n        errorPolicy: \"all\",\n      },\n      result: {\n        errors: [new GraphQLError(\"This is an error message.\")],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      error: new CombinedGraphQLErrors({\n        errors: [{ message: \"This is an error message.\" }],\n      }),\n      networkStatus: 8,\n      partial: true,\n    });\n  });\n\n  it(\"handles GraphQL errors with data returned\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      result: {\n        data: {\n          allPeople: {\n            people: {\n              name: \"Ada Lovelace\",\n            },\n          },\n        },\n        errors: [new GraphQLError(\"This is an error message.\")],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        data: { allPeople: { people: { name: \"Ada Lovelace\" } } },\n        errors: [{ message: \"This is an error message.\" }],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"empty error array (handle non-spec-compliant server) #156\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      result: {\n        data: {\n          allPeople: {\n            people: {\n              name: \"Ada Lovelace\",\n            },\n          },\n        },\n        errors: [],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        allPeople: {\n          people: {\n            name: \"Ada Lovelace\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      loading: false,\n      partial: false,\n    });\n  });\n\n  // Easy to get into this state if you write an incorrect `formatError`\n  // function with graphql-server or express-graphql\n  it(\"error array with nulls (handle non-spec-compliant server) #1185\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      result: {\n        errors: [null as any],\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({ errors: [null as any] }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"handles network errors\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      error: new Error(\"Network error\"),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new Error(\"Network error\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"handles network errors with errorPolicy: 'all'\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      queryOptions: {\n        errorPolicy: \"all\",\n      },\n      error: new Error(\"Network error\"),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      error: new Error(\"Network error\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"handles network errors with errorPolicy: 'ignore'\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      queryOptions: {\n        errorPolicy: \"ignore\",\n      },\n      error: new Error(\"Network error\"),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  // Determine how/if we want to change this at all. ObservableQuery no longer\n  // emits errors to its observers and instead emits a `next` event with an\n  // `error` property.\n  it.skip(\"uses console.error to log unhandled errors\", async () => {\n    using _ = spyOnConsole(\"error\");\n    const query = gql`\n      query people {\n        allPeople(first: 1) {\n          people {\n            name\n          }\n        }\n      }\n    `;\n    const error = new Error(\"Network error\");\n\n    const client = new ApolloClient({\n      link: new MockLink([{ request: { query }, error }]),\n      cache: new InMemoryCache(),\n    });\n\n    const observable = client.watchQuery({ query });\n    observable.subscribe({\n      next: () => {\n        throw new Error(\"Should not have been called\");\n      },\n    });\n\n    await wait(10);\n\n    expect(console.error).toHaveBeenCalledTimes(1);\n    expect(console.error).toHaveBeenCalledWith(\n      \"Unhandled error\",\n      \"Network error\",\n      expect.anything()\n    );\n  });\n\n  it(\"handles an unsubscribe action that happens before data returns\", async () => {\n    const stream = getObservableStream({\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      delay: Infinity,\n    });\n\n    expect(stream.unsubscribe).not.toThrow();\n  });\n\n  it(\"causes link unsubscription if unsubscribed\", async () => {\n    const expResult = {\n      data: {\n        allPeople: {\n          people: [\n            {\n              name: \"Luke Skywalker\",\n            },\n          ],\n        },\n      },\n    };\n\n    const request = {\n      query: gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      variables: undefined,\n    };\n\n    const mockedResponse = {\n      request,\n      result: expResult,\n    };\n\n    const onRequestSubscribe = jest.fn();\n    const onRequestUnsubscribe = jest.fn();\n\n    const mockedSingleLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        onRequestSubscribe();\n\n        // Delay (100ms) must be bigger than unsubscribe await (5ms)\n        // to show clearly that the connection was aborted before completing\n        const timer = setTimeout(() => {\n          observer.next(mockedResponse.result);\n          observer.complete();\n        }, 100);\n\n        return () => {\n          onRequestUnsubscribe();\n          clearTimeout(timer);\n        };\n      });\n    });\n\n    const client = new ApolloClient({\n      link: mockedSingleLink,\n      cache: new InMemoryCache(),\n    });\n\n    const observableQuery = client.watchQuery({\n      query: request.query,\n      variables: request.variables,\n      notifyOnNetworkStatusChange: false,\n    });\n\n    const stream = new ObservableStream(observableQuery);\n\n    stream.unsubscribe();\n\n    await wait(10);\n\n    expect(onRequestUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onRequestSubscribe).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"causes link unsubscription after reobserve\", async () => {\n    const expResult = {\n      data: {\n        allPeople: {\n          people: [\n            {\n              name: \"Luke Skywalker\",\n            },\n          ],\n        },\n      },\n    };\n\n    const request = {\n      query: gql`\n        query people($offset: Int) {\n          allPeople(first: $offset) {\n            people {\n              name\n            }\n          }\n        }\n      `,\n      variables: undefined,\n    };\n\n    const mockedResponse = {\n      request,\n      result: expResult,\n    };\n\n    const onRequestSubscribe = jest.fn();\n    const onRequestUnsubscribe = jest.fn();\n    let counter = 0;\n    const mockedSingleLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        const id = ++counter;\n        onRequestSubscribe(id);\n\n        // Delay (100ms) must be bigger than sum of reobserve and unsubscribe awaits (5ms each)\n        // to show clearly that the connection was aborted before completing\n        const timer = setTimeout(() => {\n          observer.next(mockedResponse.result);\n          observer.complete();\n        }, 100);\n\n        return () => {\n          onRequestUnsubscribe(id);\n          clearTimeout(timer);\n        };\n      });\n    });\n\n    const client = new ApolloClient({\n      link: mockedSingleLink,\n      cache: new InMemoryCache(),\n      defaultOptions: {\n        watchQuery: {\n          fetchPolicy: \"cache-and-network\",\n          returnPartialData: false,\n        },\n        query: {\n          fetchPolicy: \"network-only\",\n        },\n      },\n      queryDeduplication: false,\n    });\n\n    const observableQuery = client.watchQuery<\n      (typeof expResult)[\"data\"],\n      { offset?: number | undefined }\n    >({\n      query: request.query,\n      variables: request.variables,\n    });\n\n    const stream = new ObservableStream(observableQuery);\n\n    expect(onRequestSubscribe.mock.calls).toStrictEqual([[1]]);\n\n    await wait(50);\n\n    // This is the most important part of this test\n    // Check that reobserve cancels the previous connection while watchQuery remains active\n    void observableQuery.reobserve({ variables: { offset: 20 } });\n\n    await wait(10);\n\n    stream.unsubscribe();\n\n    await wait(10);\n\n    expect(onRequestSubscribe.mock.calls).toStrictEqual([[1], [2]]);\n    expect(onRequestUnsubscribe.mock.calls).toStrictEqual([[1], [2]]);\n  });\n  test(\"handles race conditions when changing variables\", async () => {\n    const query = gql`\n      query GetPerson($id: ID!) {\n        person(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: 1 } },\n        result: {\n          data: {\n            person: {\n              __typename: \"Person\",\n              id: 1,\n              name: \"Luke Skywalker\",\n            },\n          },\n        },\n        // Ensure the first request takes longer than the 2nd to execute\n        delay: 50,\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: {\n          data: {\n            person: {\n              __typename: \"Person\",\n              id: 2,\n              name: \"Leia Skywalker\",\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    const observableQuery = client.watchQuery({\n      query,\n      variables: { id: 1 },\n      fetchPolicy: \"network-only\",\n    });\n\n    const stream = new ObservableStream(observableQuery);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    // Kick off another request while the other is still pending\n    await wait(10);\n    void observableQuery.reobserve({ variables: { id: 2 } });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        person: {\n          __typename: \"Person\",\n          id: 2,\n          name: \"Leia Skywalker\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"allows you to subscribe twice to one query\", async () => {\n    const request = {\n      query: gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `,\n      variables: {\n        id: \"1\",\n      },\n    };\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const data3 = {\n      people_one: {\n        name: \"Luke Skywalker has another name\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request,\n          result: { data: data1 },\n        },\n        {\n          request,\n          result: { data: data2 },\n\n          // Wait for both to subscribe\n          delay: 100,\n        },\n        {\n          request,\n          result: { data: data3 },\n        },\n      ]),\n    });\n\n    // pre populate data to avoid contention\n    await client.query(request);\n\n    const observable = client.watchQuery(request);\n\n    const stream1 = new ObservableStream(observable);\n    const stream2 = new ObservableStream(observable);\n\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream1).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    stream1.unsubscribe();\n    void observable.refetch();\n\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream2).toEmitTypedValue({\n      data: data3,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"resolves all queries when one finishes after another\", async () => {\n    const request = {\n      query: gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `,\n      variables: {\n        id: \"1\",\n      },\n    };\n    const request2 = {\n      query: gql`\n        query fetchLeia($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `,\n      variables: {\n        id: \"2\",\n      },\n    };\n    const request3 = {\n      query: gql`\n        query fetchHan($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `,\n      variables: {\n        id: \"3\",\n      },\n    };\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n    const data2 = {\n      people_one: {\n        name: \"Leia Skywalker\",\n      },\n    };\n    const data3 = {\n      people_one: {\n        name: \"Han Solo\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request,\n          result: { data: data1 },\n          delay: 10,\n        },\n        {\n          request: request2,\n          result: { data: data2 },\n          // make the second request the slower one\n          delay: 100,\n        },\n        {\n          request: request3,\n          result: { data: data3 },\n          delay: 10,\n        },\n      ]),\n    });\n\n    const ob1 = client.watchQuery(request);\n    const ob2 = client.watchQuery(request2);\n    const ob3 = client.watchQuery(request3);\n\n    const stream1 = new ObservableStream(ob1);\n    const stream2 = new ObservableStream(ob2);\n    const stream3 = new ObservableStream(ob3);\n\n    await expect(stream1).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream3).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream3).toEmitTypedValue({\n      data: data3,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"allows you to refetch queries\", async () => {\n    const request = {\n      query: gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `,\n      variables: {\n        id: \"1\",\n      },\n      notifyOnNetworkStatusChange: false,\n    };\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request, result: { data: data1 } },\n        { request, result: { data: data2 } },\n      ]),\n    });\n\n    const observable = client.watchQuery(request);\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    void observable.refetch();\n    await expect(stream).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"will return referentially equivalent data in getCurrentResult if nothing changed\", async () => {\n    const request = {\n      query: gql`\n        {\n          a\n          b {\n            c\n          }\n          d {\n            e\n            f {\n              g\n            }\n          }\n        }\n      `,\n      notifyOnNetworkStatusChange: false,\n    };\n\n    const data1 = {\n      a: 1,\n      b: { c: 2 },\n      d: { e: 3, f: { g: 4 } },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([{ request, result: { data: data1 } }]),\n    });\n\n    const observable = client.watchQuery(request);\n    const stream = new ObservableStream(observable);\n\n    const { data } = await stream.takeNext();\n\n    expect(data).toEqual(data1);\n    expect(data).toBe(observable.getCurrentResult().data);\n  });\n\n  {\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n    it.each<\n      [\n        notifyOnNetworkStatusChange: boolean,\n        fetchPolicy: WatchQueryFetchPolicy,\n        expectedInitialResults: ObservableQuery.Result<typeof data1>[],\n        expectedRefetchedResults: ObservableQuery.Result<typeof data1>[],\n      ]\n    >([\n      [\n        false,\n        \"cache-first\",\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n      [\n        false,\n        \"network-only\",\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n      [\n        false,\n        \"cache-and-network\",\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          // {\n          //   data: data1,\n          //   loading: true,\n          //   networkStatus: NetworkStatus.refetch,\n          //   partial: false,\n          // },\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n      [\n        true,\n        \"cache-first\",\n        [\n          {\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: true,\n            networkStatus: NetworkStatus.refetch,\n            partial: false,\n          },\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n      [\n        true,\n        \"network-only\",\n        [\n          {\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: true,\n            networkStatus: NetworkStatus.refetch,\n            partial: false,\n          },\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n      [\n        true,\n        \"cache-and-network\",\n        [\n          {\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        [\n          {\n            data: data1,\n            dataState: \"complete\",\n            loading: true,\n            networkStatus: NetworkStatus.refetch,\n            partial: false,\n          },\n          {\n            data: data2,\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n      ],\n    ])(\n      \"networkStatus changes (notifyOnNetworkStatusChange: %s, fetchPolicy %s)\",\n      async (\n        notifyOnNetworkStatusChange,\n        fetchPolicy,\n        expectedInitialResults,\n        expectedRefetchedResults\n      ) => {\n        const request: ApolloClient.WatchQueryOptions = {\n          query: gql`\n            query fetchLuke($id: String) {\n              people_one(id: $id) {\n                name\n              }\n            }\n          `,\n          variables: {\n            id: \"1\",\n          },\n          notifyOnNetworkStatusChange,\n          fetchPolicy,\n        };\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            { request, result: { data: data1 } },\n            { request, result: { data: data2 } },\n          ]),\n        });\n\n        const observable = client.watchQuery(request);\n        const stream = new ObservableStream(observable);\n        for (const expected of expectedInitialResults) {\n          await expect(stream).toEmitTypedValue(expected);\n        }\n        void observable.refetch();\n        for (const expected of expectedRefetchedResults) {\n          await expect(stream).toEmitTypedValue(expected);\n        }\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n  }\n\n  it(\"allows you to refetch queries with promises\", async () => {\n    const request = {\n      query: gql`\n        {\n          people_one(id: 1) {\n            name\n          }\n        }\n      `,\n    };\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request, result: { data: data1 } },\n        { request, result: { data: data2 } },\n      ]),\n    });\n\n    const observable = client.watchQuery(request);\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const result = await observable.refetch();\n\n    expect(result).toStrictEqualTyped({ data: data2 });\n  });\n\n  it(\"allows you to refetch queries with new variables\", async () => {\n    const query = gql`\n      {\n        people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const data3 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name and age\",\n      },\n    };\n\n    const data4 = {\n      people_one: {\n        name: \"Luke Skywalker has a whole new bag\",\n      },\n    };\n\n    const variables1 = {\n      test: \"I am your father\",\n    };\n\n    const variables2 = {\n      test: \"No. No! That's not true! That's impossible!\",\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: query },\n          result: { data: data1 },\n        },\n        {\n          request: { query: query },\n          result: { data: data2 },\n        },\n        {\n          request: { query: query, variables: variables1 },\n          result: { data: data3 },\n        },\n        {\n          request: { query: query, variables: variables2 },\n          result: { data: data4 },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch(variables1);\n\n    await expect(stream).toEmitTypedValue({\n      data: data3,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch(variables2);\n\n    await expect(stream).toEmitTypedValue({\n      data: data4,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"only modifies variables when refetching\", async () => {\n    const query = gql`\n      {\n        people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: query },\n          result: { data: data1 },\n        },\n        {\n          request: { query: query },\n          result: { data: data2 },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n    const originalOptions = { ...observable.options } as Record<string, any>;\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const updatedOptions = { ...observable.options } as Record<string, any>;\n    delete originalOptions.variables;\n    delete updatedOptions.variables;\n    expect(updatedOptions).toEqual(originalOptions);\n  });\n\n  it(\"continues to poll after refetch\", async () => {\n    const query = gql`\n      {\n        people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const data3 = {\n      people_one: {\n        name: \"Patsy\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data: data1 },\n        },\n        {\n          request: { query },\n          result: { data: data2 },\n        },\n        {\n          request: { query },\n          result: { data: data3 },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      pollInterval: 200,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue(\n      {\n        data: data3,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      },\n      { timeout: 250 }\n    );\n\n    observable.stopPolling();\n  });\n\n  it(\"sets networkStatus to `poll` if a polling query is in flight\", async () => {\n    const query = gql`\n      {\n        people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const data2 = {\n      people_one: {\n        name: \"Luke Skywalker has a new name\",\n      },\n    };\n\n    const data3 = {\n      people_one: {\n        name: \"Patsy\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data: data1 },\n        },\n        {\n          request: { query },\n          result: { data: data2 },\n        },\n        {\n          request: { query },\n          result: { data: data3 },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      pollInterval: 30,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.poll,\n      partial: false,\n    });\n\n    stream.unsubscribe();\n  });\n\n  it(\"can handle null values in arrays (#1551)\", async () => {\n    const query = gql`\n      {\n        list {\n          value\n        }\n      }\n    `;\n    const data = { list: [null, { value: 1 }] };\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([{ request: { query }, result: { data } }]),\n    });\n    const observable = client.watchQuery({ query });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.getCurrentResult().data).toEqual(data);\n  });\n\n  it(\"supports cache-only fetchPolicy fetching only cached data\", async () => {\n    const query = gql`\n      query complexQuery {\n        luke: people_one(id: 1) {\n          name\n        }\n        vader: people_one(id: 4) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      luke: {\n        __typename: \"Person\",\n        name: \"Luke Skywalker\",\n      },\n      vader: {\n        __typename: \"Person\",\n        name: \"Darth Vader\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([{ request: { query }, result: { data: data1 } }]),\n    });\n\n    // First, prime the cache\n    await client.query({ query });\n\n    const observable = client.watchQuery({\n      query: query,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"returns partial cache data when using cache-only with returnPartialData: true\", async () => {\n    const primeQuery = gql`\n      query primeQuery {\n        luke: people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const complexQuery = gql`\n      query complexQuery {\n        luke: people_one(id: 1) {\n          name\n        }\n        vader: people_one(id: 4) {\n          name\n        }\n      }\n    `;\n\n    const partialData = {\n      luke: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request: { query: primeQuery }, result: { data: partialData } },\n      ]),\n    });\n\n    // First, prime the cache\n    await client.query({ query: primeQuery });\n\n    const observable = client.watchQuery({\n      query: complexQuery,\n      fetchPolicy: \"cache-only\",\n      returnPartialData: true,\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: partialData,\n      dataState: \"partial\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"does not return partial cache data for cache-only query without returnPartialData\", async () => {\n    const primeQuery = gql`\n      query primeQuery {\n        luke: people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const complexQuery = gql`\n      query complexQuery {\n        luke: people_one(id: 1) {\n          name\n        }\n        vader: people_one(id: 4) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      luke: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request: { query: primeQuery }, result: { data: data1 } },\n      ]),\n    });\n\n    // First, prime the cache\n    await client.query({ query: primeQuery });\n\n    const observable = client.watchQuery({\n      query: complexQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"`cache-only` reverts to an empty but successful result if data was previously there and suddenly went missing\", async () => {\n    const complexQuery = gql`\n      query complexQuery {\n        luke: people_one(id: 1) {\n          id\n          name\n        }\n        vader: people_one(id: 4) {\n          id\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      luke: {\n        __typename: \"Person\",\n        id: 1,\n        name: \"Luke Skywalker\",\n      },\n      vader: {\n        __typename: \"Person\",\n        id: 4,\n        name: \"Darth Vader\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request: { query: complexQuery }, result: { data: data1 } },\n      ]),\n    });\n\n    // First, prime the cache\n    await client.query({ query: complexQuery });\n\n    const observable = client.watchQuery({\n      query: complexQuery,\n      fetchPolicy: \"cache-only\",\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    client.cache.evict({ id: \"Person:4\" }); // Ensure 'vader' is not in cache\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"runs a mutation\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(id: \"5\")\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data: { makeListPrivate: true } },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({ mutation });\n\n    expect(result).toStrictEqualTyped({ data: { makeListPrivate: true } });\n  });\n\n  it(\"runs a mutation even when errors is empty array #2912\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(id: \"5\")\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data: { makeListPrivate: true }, errors: [] },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({ mutation });\n\n    expect(result).toStrictEqualTyped({ data: { makeListPrivate: true } });\n  });\n\n  it('runs a mutation with default errorPolicy equal to \"none\"', async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(id: \"5\")\n      }\n    `;\n    const errors = [new GraphQLError(\"foo\")];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { errors },\n        },\n      ]),\n    });\n\n    await expect(client.mutate({ mutation })).rejects.toThrow(\n      new CombinedGraphQLErrors({ errors })\n    );\n  });\n\n  it(\"runs a mutation with variables\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate($listId: ID!) {\n        makeListPrivate(id: $listId)\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: mutation, variables: { listId: \"1\" } },\n          result: { data: { makeListPrivate: true } },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({\n      mutation,\n      variables: { listId: \"1\" },\n    });\n\n    expect(result).toStrictEqualTyped({ data: { makeListPrivate: true } });\n  });\n\n  const getIdField = (obj: any) => obj.id;\n\n  it(\"runs a mutation with object parameters and puts the result in the store\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(input: { id: \"5\" }) {\n          id\n          isPrivate\n        }\n      }\n    `;\n    const data = {\n      makeListPrivate: {\n        id: \"5\",\n        isPrivate: true,\n      },\n    };\n\n    const cache = new InMemoryCache({\n      dataIdFromObject: getIdField,\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({ mutation });\n\n    expect(result).toStrictEqualTyped({ data });\n\n    // Make sure we updated the store with the new data\n    expect(cache.extract()[\"5\"]).toEqual({\n      id: \"5\",\n      isPrivate: true,\n    });\n  });\n\n  it(\"runs a mutation and puts the result in the store\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(id: \"5\") {\n          id\n          isPrivate\n        }\n      }\n    `;\n    const data = {\n      makeListPrivate: {\n        id: \"5\",\n        isPrivate: true,\n      },\n    };\n    const cache = new InMemoryCache({\n      dataIdFromObject: getIdField,\n    });\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({ mutation });\n\n    expect(result).toStrictEqualTyped({ data });\n\n    // Make sure we updated the store with the new data\n    expect(cache.extract()[\"5\"]).toEqual({\n      id: \"5\",\n      isPrivate: true,\n    });\n  });\n\n  it(\"runs a mutation and puts the result in the store with root key\", async () => {\n    const mutation = gql`\n      mutation makeListPrivate {\n        makeListPrivate(id: \"5\") {\n          id\n          isPrivate\n        }\n      }\n    `;\n\n    const data = {\n      makeListPrivate: {\n        id: \"5\",\n        isPrivate: true,\n      },\n    };\n\n    const cache = new InMemoryCache({\n      dataIdFromObject: getIdField,\n    });\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data },\n        },\n      ]),\n    });\n\n    const result = await client.mutate({ mutation });\n\n    expect(result).toStrictEqualTyped({ data });\n\n    // Make sure we updated the store with the new data\n    expect(cache.extract()[\"5\"]).toEqual({\n      id: \"5\",\n      isPrivate: true,\n    });\n  });\n\n  it(`doesn't return data while query is loading`, async () => {\n    const query1 = gql`\n      {\n        people_one(id: 1) {\n          name\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        name: \"Luke Skywalker\",\n      },\n    };\n\n    const query2 = gql`\n      {\n        people_one(id: 5) {\n          name\n        }\n      }\n    `;\n\n    const data2 = {\n      people_one: {\n        name: \"Darth Vader\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: query1 },\n          result: { data: data1 },\n          delay: 10,\n        },\n        {\n          request: { query: query2 },\n          result: { data: data2 },\n        },\n      ]),\n    });\n\n    const observable1 = client.watchQuery({ query: query1 });\n    const observable2 = client.watchQuery({ query: query2 });\n\n    const stream1 = new ObservableStream(observable1);\n    const stream2 = new ObservableStream(observable2);\n\n    await expect(stream1).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"updates result of previous query if the result of a new query overlaps\", async () => {\n    const query1 = gql`\n      {\n        people_one(id: 1) {\n          __typename\n          id\n          name\n          age\n        }\n      }\n    `;\n\n    const data1 = {\n      people_one: {\n        // Correctly identifying this entity is necessary so that fields\n        // from query1 and query2 can be safely merged in the cache.\n        __typename: \"Human\",\n        id: 1,\n        name: \"Luke Skywalker\",\n        age: 50,\n      },\n    };\n\n    const query2 = gql`\n      {\n        people_one(id: 1) {\n          __typename\n          id\n          name\n          username\n        }\n      }\n    `;\n\n    const data2 = {\n      people_one: {\n        __typename: \"Human\",\n        id: 1,\n        name: \"Luke Skywalker has a new name\",\n        username: \"luke\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: query1 },\n          result: { data: data1 },\n        },\n        {\n          request: { query: query2 },\n          result: { data: data2 },\n          delay: 10,\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({ query: query1 });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await client.query({ query: query2 });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        people_one: {\n          __typename: \"Human\",\n          id: 1,\n          name: \"Luke Skywalker has a new name\",\n          age: 50,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"warns if you forget the template literal tag\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    expect(() => {\n      void client.query({\n        // Bamboozle TypeScript into letting us do this\n        query: \"string\" as any as DocumentNode,\n      });\n    }).toThrow(/wrap the query string in a \"gql\" tag/);\n\n    await expect(() =>\n      client.mutate({\n        // Bamboozle TypeScript into letting us do this\n        mutation: \"string\" as any as DocumentNode,\n      })\n    ).toThrow(/wrap the query string in a \"gql\" tag/);\n\n    expect(() => {\n      client.watchQuery({\n        // Bamboozle TypeScript into letting us do this\n        query: \"string\" as any as DocumentNode,\n      });\n    }).toThrow(/wrap the query string in a \"gql\" tag/);\n  });\n\n  it(\"should transform queries correctly when given a QueryTransformer\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const transformedQuery = gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n\n    const transformedQueryResult = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n        __typename: \"Author\",\n      },\n    };\n\n    //make sure that the query is transformed within the query\n    //manager\n    const result = await new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: transformedQuery },\n          result: { data: transformedQueryResult },\n        },\n      ]),\n    }).query({ query });\n\n    expect(result).toStrictEqualTyped({ data: transformedQueryResult });\n  });\n\n  it(\"should transform mutations correctly\", async () => {\n    const mutation = gql`\n      mutation {\n        createAuthor(firstName: \"John\", lastName: \"Smith\") {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const transformedMutation = gql`\n      mutation {\n        createAuthor(firstName: \"John\", lastName: \"Smith\") {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n\n    const transformedMutationResult = {\n      createAuthor: {\n        firstName: \"It works!\",\n        lastName: \"It works!\",\n        __typename: \"Author\",\n      },\n    };\n\n    const result = await new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: transformedMutation },\n          result: { data: transformedMutationResult },\n        },\n      ]),\n    }).mutate({ mutation: mutation });\n\n    expect(result).toStrictEqualTyped({ data: transformedMutationResult });\n  });\n\n  it(\"should reject a query promise given a network error\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const networkError = new Error(\"Network error\");\n\n    await expect(\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([{ request: { query }, error: networkError }]),\n      }).query({ query })\n    ).rejects.toEqual(networkError);\n  });\n\n  it(\"should reject a query promise given a GraphQL error\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const graphQLErrors = [new GraphQLError(\"GraphQL error\")];\n    await expect(\n      new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { errors: graphQLErrors },\n          },\n        ]),\n      }).query({ query })\n    ).rejects.toEqual(new CombinedGraphQLErrors({ errors: graphQLErrors }));\n  });\n\n  it(\"should not empty the store when a non-polling query fails due to a network error\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const data = {\n      author: {\n        firstName: \"Dhaivat\",\n        lastName: \"Pandya\",\n      },\n    };\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n        {\n          request: { query },\n          error: new Error(\"Network error occurred\"),\n        },\n      ]),\n    });\n    const result = await client.query({ query });\n\n    expect(result).toStrictEqualTyped({ data });\n\n    await expect(\n      client.query({ query, fetchPolicy: \"network-only\" })\n    ).rejects.toThrow();\n\n    expect(cache.extract().ROOT_QUERY!.author).toEqual(data.author);\n  });\n\n  it(\"should be able to unsubscribe from a polling query subscription\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const data = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const observable = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n        {\n          request: { query },\n          result: () => {\n            throw new Error(\"Should not again\");\n          },\n        },\n      ]),\n    }).watchQuery({ query, pollInterval: 20 });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    stream.unsubscribe();\n\n    // Ensure polling has stopped by ensuring the error is not thrown from the mocks\n    await wait(30);\n  });\n\n  it(\"should not empty the store when a polling query fails due to a network error\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const data = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n        {\n          request: { query },\n          error: new Error(\"Network error occurred.\"),\n        },\n      ]),\n    });\n    const observable = client.watchQuery({\n      query,\n      pollInterval: 20,\n      notifyOnNetworkStatusChange: false,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(cache.extract().ROOT_QUERY!.author).toEqual(data.author);\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      error: new Error(\"Network error occurred.\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    });\n    expect(cache.extract().ROOT_QUERY!.author).toEqual(data.author);\n\n    observable.stopPolling();\n  });\n\n  it(\"should not fire next on an observer if there is no change in the result\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const data = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data },\n          maxUsageCount: 2,\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({ query });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(client.query({ query })).resolves.toStrictEqualTyped({ data });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"should not return stale data when we orphan a real-id node in the store with a real-id node\", async () => {\n    const query1 = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n          }\n          age\n          id\n          __typename\n        }\n      }\n    `;\n    const query2 = gql`\n      query {\n        author {\n          name {\n            firstName\n          }\n          id\n          __typename\n        }\n      }\n    `;\n    const data1 = {\n      author: {\n        name: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n        age: 18,\n        id: \"187\",\n        __typename: \"Author\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: {\n          firstName: \"John\",\n        },\n        id: \"197\",\n        __typename: \"Author\",\n      },\n    };\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        dataIdFromObject: (object) => {\n          if (object.__typename && object.id) {\n            return object.__typename + \"__\" + object.id;\n          }\n          return undefined;\n        },\n      }),\n      link: new MockLink([\n        {\n          request: { query: query1 },\n          result: { data: data1 },\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n        {\n          request: { query: query2 },\n          result: { data: data2 },\n        },\n      ]),\n    });\n\n    const observable1 = client.watchQuery({ query: query1 });\n    const observable2 = client.watchQuery({ query: query2 });\n\n    const stream1 = new ObservableStream(observable1);\n    const stream2 = new ObservableStream(observable2);\n\n    await expect(stream1).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"should return partial data when configured when we orphan a real-id node in the store with a real-id node\", async () => {\n    const query1 = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n          }\n          age\n          id\n          __typename\n        }\n      }\n    `;\n    const query2 = gql`\n      query {\n        author {\n          name {\n            firstName\n          }\n          id\n          __typename\n        }\n      }\n    `;\n    const data1 = {\n      author: {\n        name: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n        age: 18,\n        id: \"187\",\n        __typename: \"Author\",\n      },\n    };\n    const data2 = {\n      author: {\n        name: {\n          firstName: \"John\",\n        },\n        id: \"197\",\n        __typename: \"Author\",\n      },\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: query1 },\n          result: { data: data1 },\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n        {\n          request: { query: query2 },\n          result: { data: data2 },\n        },\n      ]),\n    });\n\n    const observable1 = client.watchQuery({\n      query: query1,\n      returnPartialData: true,\n    });\n    const observable2 = client.watchQuery({ query: query2 });\n\n    const stream1 = new ObservableStream(observable1);\n    const stream2 = new ObservableStream(observable2);\n\n    await expect(stream1).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream1).toEmitTypedValue({\n      data: data1,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: data2,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"should not write unchanged network results to cache\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            info: {\n              merge: false,\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            // Deliver the results async so we can observe the loading state\n            setTimeout(() => {\n              switch (operation.operationName) {\n                case \"A\":\n                  observer.next({ data: { info: { a: \"ay\" } } });\n                  break;\n                case \"B\":\n                  observer.next({ data: { info: { b: \"bee\" } } });\n                  break;\n              }\n              observer.complete!();\n            });\n          })\n      ),\n    });\n\n    const queryA = gql`\n      query A {\n        info {\n          a\n        }\n      }\n    `;\n    const queryB = gql`\n      query B {\n        info {\n          b\n        }\n      }\n    `;\n\n    const obsA = client.watchQuery({\n      query: queryA,\n      returnPartialData: true,\n    });\n\n    const obsB = client.watchQuery({\n      query: queryB,\n      returnPartialData: true,\n    });\n\n    const aStream = new ObservableStream(obsA);\n    const bStream = new ObservableStream(obsB);\n\n    await expect(aStream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n\n    await expect(bStream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n\n    await expect(aStream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          a: \"ay\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(bStream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          b: \"bee\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(aStream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: {\n        info: {},\n      },\n      dataState: \"partial\",\n      partial: true,\n    });\n\n    await expect(aStream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          a: \"ay\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(aStream).not.toEmitAnything();\n    await expect(bStream).not.toEmitAnything();\n  });\n\n  it(\"should disable feud-stopping logic after evict or modify\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            info: {\n              merge: false,\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        () =>\n          new Observable((observer: Observer<ApolloLink.Result>) => {\n            setTimeout(() => {\n              observer.next!({ data: { info: { c: \"see\" } } });\n              observer.complete!();\n            });\n          })\n      ),\n    });\n\n    const query = gql`\n      query {\n        info {\n          c\n        }\n      }\n    `;\n\n    const obs = client.watchQuery({\n      query,\n      returnPartialData: true,\n    });\n\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          c: \"see\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    cache.evict({ fieldName: \"info\" });\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          c: \"see\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    cache.modify({\n      fields: {\n        info(_, { DELETE }) {\n          return DELETE;\n        },\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        info: {\n          c: \"see\",\n        },\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  it(\"should not error when replacing unidentified data with a normalized ID\", async () => {\n    const queryWithoutId = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n          }\n          age\n          __typename\n        }\n      }\n    `;\n\n    const queryWithId = gql`\n      query {\n        author {\n          name {\n            firstName\n          }\n          id\n          __typename\n        }\n      }\n    `;\n\n    const dataWithoutId = {\n      author: {\n        name: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n        age: \"124\",\n        __typename: \"Author\",\n      },\n    };\n\n    const dataWithId = {\n      author: {\n        name: {\n          firstName: \"Jane\",\n        },\n        id: \"129\",\n        __typename: \"Author\",\n      },\n    };\n\n    let mergeCount = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              author: {\n                merge(existing, incoming, { isReference, readField }) {\n                  switch (++mergeCount) {\n                    case 1:\n                      expect(existing).toBeUndefined();\n                      expect(isReference(incoming)).toBe(false);\n                      expect(incoming).toEqual(dataWithoutId.author);\n                      break;\n                    case 2:\n                      expect(existing).toEqual(dataWithoutId.author);\n                      expect(isReference(incoming)).toBe(true);\n                      expect(readField(\"id\", incoming)).toBe(\"129\");\n                      expect(readField(\"name\", incoming)).toEqual(\n                        dataWithId.author.name\n                      );\n                      break;\n                    default:\n                      fail(\"unreached\");\n                  }\n                  return incoming;\n                },\n              },\n            },\n          },\n        },\n      }),\n      link: new MockLink(\n        [\n          {\n            request: { query: queryWithoutId },\n            result: { data: dataWithoutId },\n            maxUsageCount: Number.POSITIVE_INFINITY,\n          },\n          {\n            request: { query: queryWithId },\n            result: { data: dataWithId },\n            maxUsageCount: Number.POSITIVE_INFINITY,\n          },\n        ],\n        { defaultOptions: { delay: 0 } }\n      ),\n    });\n\n    const observableWithId = client.watchQuery({ query: queryWithId });\n    const observableWithoutId = client.watchQuery({ query: queryWithoutId });\n\n    const stream1 = new ObservableStream(observableWithoutId);\n    const stream2 = new ObservableStream(observableWithId);\n\n    await expect(stream1).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream1).toEmitTypedValue({\n      data: dataWithoutId,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    await expect(stream2).toEmitTypedValue({\n      data: dataWithId,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  it(\"exposes errors on a refetch as a rejection\", async () => {\n    const request = {\n      query: gql`\n        {\n          people_one(id: 1) {\n            name\n          }\n        }\n      `,\n    };\n    const firstResult = {\n      data: {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      },\n    };\n    const secondResult = {\n      errors: [new GraphQLError(\"This is not the person you are looking for.\")],\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        { request, result: firstResult },\n        { request, result: secondResult },\n      ]),\n    });\n\n    const handle = client.watchQuery(request);\n    const stream = new ObservableStream(handle);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: firstResult.data,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const expectedError = new CombinedGraphQLErrors({\n      errors: secondResult.errors,\n    });\n\n    await expect(handle.refetch()).rejects.toThrow(expectedError);\n\n    await expect(stream).toEmitTypedValue({\n      data: firstResult.data,\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: firstResult.data,\n      dataState: \"complete\",\n      error: expectedError,\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    });\n  });\n\n  it(\"does not return incomplete data when two queries for the same item are executed\", async () => {\n    const queryA = gql`\n      query queryA {\n        person(id: \"abc\") {\n          __typename\n          id\n          firstName\n          lastName\n        }\n      }\n    `;\n    const queryB = gql`\n      query queryB {\n        person(id: \"abc\") {\n          __typename\n          id\n          lastName\n          age\n        }\n      }\n    `;\n    const dataA = {\n      person: {\n        __typename: \"Person\",\n        id: \"abc\",\n        firstName: \"Luke\",\n        lastName: \"Skywalker\",\n      },\n    };\n    const dataB = {\n      person: {\n        __typename: \"Person\",\n        id: \"abc\",\n        lastName: \"Skywalker\",\n        age: \"32\",\n      },\n    };\n    const client = new ApolloClient({\n      cache: new InMemoryCache({}),\n      link: new MockLink([\n        { request: { query: queryA }, result: { data: dataA }, delay: 10 },\n        { request: { query: queryB }, result: { data: dataB }, delay: 20 },\n      ]),\n      ssrMode: true,\n    });\n\n    const observableA = client.watchQuery({ query: queryA });\n    const observableB = client.watchQuery({ query: queryB });\n    const streamA = new ObservableStream(observableA);\n    const streamB = new ObservableStream(observableB);\n\n    await expect(streamA).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(streamA).toEmitTypedValue({\n      data: dataA,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observableA.getCurrentResult()).toStrictEqualTyped({\n      data: dataA,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observableB.getCurrentResult()).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(streamB).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    await expect(streamB).toEmitTypedValue({\n      data: dataB,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observableA.getCurrentResult()).toStrictEqualTyped({\n      data: dataA,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observableB.getCurrentResult()).toStrictEqualTyped({\n      data: dataB,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  describe(\"polling queries\", () => {\n    it(\"allows you to poll queries\", async () => {\n      const query = gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"1\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Luke Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(\n          [\n            {\n              request: { query, variables },\n              result: { data: data1 },\n            },\n            {\n              request: { query, variables },\n              result: { data: data2 },\n            },\n          ],\n          { showWarnings: false }\n        ),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 50,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"does not poll during SSR\", async () => {\n      const query = gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"1\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Luke Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        ssrMode: true,\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: data1 },\n          },\n          {\n            request: { query, variables },\n            result: { data: data2 },\n            maxUsageCount: Number.POSITIVE_INFINITY,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 10,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"should let you handle multiple polled queries and unsubscribe from one of them\", async () => {\n      const query1 = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const query2 = gql`\n        query {\n          person {\n            name\n          }\n        }\n      `;\n      const data11 = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const data12 = {\n        author: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const data13 = {\n        author: {\n          firstName: \"Jolly\",\n          lastName: \"Smith\",\n        },\n      };\n      const data14 = {\n        author: {\n          firstName: \"Jared\",\n          lastName: \"Smith\",\n        },\n      };\n      const data21 = {\n        person: {\n          name: \"Jane Smith\",\n        },\n      };\n      const data22 = {\n        person: {\n          name: \"Josey Smith\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: query1 },\n            result: { data: data11 },\n          },\n          {\n            request: { query: query1 },\n            result: { data: data12 },\n          },\n          {\n            request: { query: query1 },\n            result: { data: data13 },\n          },\n          {\n            request: { query: query1 },\n            result: { data: data14 },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data21 },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data22 },\n          },\n        ]),\n      });\n      let handle1Count = 0;\n      let handleCount = 0;\n      let setMilestone = false;\n\n      const subscription1 = client\n        .watchQuery({\n          query: query1,\n          pollInterval: 150,\n          notifyOnNetworkStatusChange: false,\n        })\n        .subscribe({\n          next() {\n            handle1Count++;\n            handleCount++;\n            if (handle1Count > 1 && !setMilestone) {\n              subscription1.unsubscribe();\n              setMilestone = true;\n            }\n          },\n        });\n\n      const subscription2 = client\n        .watchQuery({\n          query: query2,\n          pollInterval: 2000,\n          notifyOnNetworkStatusChange: false,\n        })\n        .subscribe({\n          next() {\n            handleCount++;\n          },\n        });\n\n      await wait(400);\n\n      expect(handleCount).toBe(3);\n      subscription1.unsubscribe();\n      subscription2.unsubscribe();\n    });\n\n    it(\"allows you to unsubscribe from polled queries\", async () => {\n      const query = gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"1\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Luke Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: data1 },\n          },\n          {\n            request: { query, variables },\n            result: { data: data2 },\n          },\n          {\n            request: { query, variables },\n            result: () => {\n              throw new Error(\"Should not fetch again\");\n            },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 50,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      stream.unsubscribe();\n\n      // Ensure polling has stopped by ensuring the error is not thrown from the mocks\n      await wait(60);\n    });\n\n    it(\"allows you to unsubscribe from polled query errors\", async () => {\n      const query = gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"1\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Luke Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: data1 },\n          },\n          {\n            request: { query, variables },\n            error: new Error(\"Network error\"),\n          },\n          {\n            request: { query, variables },\n            result: { data: data2 },\n          },\n          {\n            request: { query, variables },\n            result: () => {\n              throw new Error(\"Should not fetch again\");\n            },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 50,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        error: new Error(\"Network error\"),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n\n      stream.unsubscribe();\n\n      // Ensure polling has stopped by ensuring the error is not thrown from the mocks\n      await wait(200);\n    });\n\n    it(\"exposes a way to start a polling query\", async () => {\n      const query = gql`\n        query fetchLuke($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"1\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Luke Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Luke Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(\n          [\n            {\n              request: { query, variables },\n              result: { data: data1 },\n            },\n            {\n              request: { query, variables },\n              result: { data: data2 },\n            },\n          ],\n          { showWarnings: false }\n        ),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      observable.startPolling(50);\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"exposes a way to stop a polling query\", async () => {\n      const query = gql`\n        query fetchLeia($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"2\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Leia Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Leia Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: data1 },\n          },\n          {\n            request: { query, variables },\n            result: { data: data2 },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 50,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      observable.stopPolling();\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"stopped polling queries still get updates\", async () => {\n      const query = gql`\n        query fetchLeia($id: String) {\n          people_one(id: $id) {\n            name\n          }\n        }\n      `;\n\n      const variables = {\n        id: \"2\",\n      };\n\n      const data1 = {\n        people_one: {\n          name: \"Leia Skywalker\",\n        },\n      };\n\n      const data2 = {\n        people_one: {\n          name: \"Leia Skywalker has a new name\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(\n          [\n            {\n              request: { query, variables },\n              result: { data: data1 },\n            },\n            {\n              request: { query, variables },\n              result: { data: data2 },\n            },\n          ],\n          { showWarnings: false }\n        ),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        pollInterval: 50,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      observable.stopPolling();\n\n      const result = await client.query({\n        query,\n        variables,\n        fetchPolicy: \"network-only\",\n      });\n\n      expect(result).toStrictEqualTyped({ data: data2 });\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n  });\n\n  describe(\"store resets\", () => {\n    it(\"returns a promise resolving when all queries have been refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const dataChanged = {\n        author: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const query2 = gql`\n        query {\n          author2 {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data2 = {\n        author2: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const data2Changed = {\n        author2: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2 },\n          },\n          {\n            request: { query },\n            result: { data: dataChanged },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2Changed },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const observable2 = client.watchQuery({ query: query2 });\n\n      const stream = new ObservableStream(observable);\n      const stream2 = new ObservableStream(observable2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.resetStore();\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataChanged,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable2.getCurrentResult()).toStrictEqualTyped({\n        data: data2Changed,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should change the store state to an empty state\", () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      void client.resetStore();\n\n      expect(client.cache.extract()).toEqual({});\n      // TODO: Determine if we can drop this check against internal state and\n      // replace it with something user-facing.\n      expect(client[\"queryManager\"].mutationStore).toEqual({});\n    });\n\n    it(\"should only refetch once when we store reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const data2 = {\n        author: {\n          firstName: \"Johnny\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link: ApolloLink = new ApolloLink(\n        (op) =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              timesFired += 1;\n              if (timesFired > 1) {\n                observer.next({ data: data2 });\n              } else {\n                observer.next({ data });\n              }\n              observer.complete();\n            });\n          })\n      );\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      // reset the store after data has returned\n      void client.resetStore();\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      // only refetch once and make sure data has changed\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(2);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"should not refetch torn-down queries\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link: ApolloLink = ApolloLink.from([\n        new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              timesFired += 1;\n              observer.next({ data });\n            })\n        ),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      stream.unsubscribe();\n\n      expect(timesFired).toBe(1);\n\n      void client.resetStore();\n      await wait(50);\n\n      expect(timesFired).toBe(1);\n    });\n\n    it(\"should not error when resetStore called\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              timesFired += 1;\n              observer.next({ data });\n              observer.complete();\n              return;\n            })\n        ),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      const observable = client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      void client.resetStore();\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(2);\n    });\n\n    it(\"should throw an error on an inflight fetch query if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n            delay: 10000, //i.e. forever\n          },\n        ]),\n      });\n      // TODO: Determine if there is a better way to test this.\n      const promise = client[\"queryManager\"].fetchQuery({\n        query,\n      });\n\n      // Need to delay the reset at least until the fetchRequest method\n      // has had a chance to enter this request into fetchQueryRejectFns.\n      await wait(100);\n      void client.resetStore();\n\n      await expect(promise).rejects.toThrow(\n        new InvariantError(\n          \"Store reset while query was in flight (not completed in link chain)\"\n        )\n      );\n    });\n\n    it(\"should call refetch on a mocked Observable if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n        ]),\n      });\n      const obs = client.watchQuery({ query });\n      obs.subscribe({});\n      obs.refetch = jest.fn();\n\n      void client.resetStore();\n\n      await wait(0);\n\n      expect(obs.refetch).toHaveBeenCalledTimes(1);\n    });\n\n    it(\"should not call refetch on a cache-only Observable if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"cache-only\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.resetStore();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should not call refetch on a standby Observable if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"standby\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.resetStore();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should not call refetch on a non-subscribed Observable if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.resetStore();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should throw an error on an inflight query() if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const link = new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            // reset the store as soon as we hear about the query\n            void client.resetStore();\n            observer.next({ data });\n            return;\n          })\n      );\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      await expect(client.query({ query })).rejects.toThrow(\n        new InvariantError(\n          \"Store reset while query was in flight (not completed in link chain)\"\n        )\n      );\n    });\n\n    it(\"should throw an error on an inflight ObservableQuery if the store is reset\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const link = new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            // reset the store as soon as we hear about the query\n            void client.resetStore();\n            observer.next({ data });\n            return;\n          })\n      );\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      await expect(client.watchQuery({ query }).reobserve()).rejects.toThrow(\n        new InvariantError(\n          \"Store reset while query was in flight (not completed in link chain)\"\n        )\n      );\n    });\n  });\n\n  describe(\"refetching observed queries\", () => {\n    it(\"returns a promise resolving when all queries have been refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const dataChanged = {\n        author: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const query2 = gql`\n        query {\n          author2 {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data2 = {\n        author2: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const data2Changed = {\n        author2: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2 },\n          },\n          {\n            request: { query },\n            result: { data: dataChanged },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2Changed },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const observable2 = client.watchQuery({ query: query2 });\n\n      const stream = new ObservableStream(observable);\n      const stream2 = new ObservableStream(observable2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.refetchObservableQueries();\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataChanged,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable2.getCurrentResult()).toStrictEqualTyped({\n        data: data2Changed,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should only refetch once when we refetch observable queries\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const data2 = {\n        author: {\n          firstName: \"Johnny\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = new ApolloLink(\n        (op) =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              timesFired += 1;\n              if (timesFired > 1) {\n                observer.next({ data: data2 });\n              } else {\n                observer.next({ data });\n              }\n              observer.complete();\n            });\n          })\n      );\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      // refetch the observed queries after data has returned\n      void client.refetchObservableQueries();\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(2);\n    });\n\n    it(\"should not refetch torn-down queries\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              timesFired += 1;\n              observer.next({ data });\n              return;\n            })\n        ),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      stream.unsubscribe();\n      void client.refetchObservableQueries();\n\n      await wait(50);\n\n      expect(timesFired).toBe(1);\n    });\n\n    it(\"should not error after refetchObservableQueries\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              timesFired += 1;\n              observer.next({ data });\n              observer.complete();\n            })\n        ),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      const observable = client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      void client.refetchObservableQueries();\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(2);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"should NOT throw an error on an inflight fetch query if the observable queries are refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n            delay: 100,\n          },\n        ]),\n      });\n      // TODO: Determine if there is a better way to test this\n      const promise = client[\"queryManager\"].fetchQuery({\n        query,\n      });\n      void client.refetchObservableQueries();\n\n      await expect(promise).resolves.toBeTruthy();\n    });\n\n    it(\"should call refetch on a mocked Observable if the observed queries are refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n        ]),\n      });\n\n      const obs = client.watchQuery({ query });\n      obs.subscribe({});\n      obs.refetch = jest.fn();\n\n      void client.refetchObservableQueries();\n\n      await wait(0);\n\n      expect(obs.refetch).toHaveBeenCalledTimes(1);\n    });\n\n    it(\"should not call refetch on a cache-only Observable if the observed queries are refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"cache-only\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.refetchObservableQueries();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should not call refetch on a standby Observable if the observed queries are refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"standby\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.refetchObservableQueries();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should refetch on a standby Observable if the observed queries are refetched and the includeStandby parameter is set to true\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"standby\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      const includeStandBy = true;\n      void client.refetchObservableQueries(includeStandBy);\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(1);\n    });\n\n    it(\"should not call refetch on a cache-only Observable if the observed queries are refetched and the includeStandby parameter is set to true\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n        fetchPolicy: \"cache-only\",\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.subscribe({});\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      const includeStandBy = true;\n      void client.refetchObservableQueries(includeStandBy);\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should not call refetch on a non-subscribed Observable\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([]),\n      });\n\n      const options = {\n        query,\n      } as ApolloClient.WatchQueryOptions;\n\n      let refetchCount = 0;\n\n      const obs = client.watchQuery(options);\n      obs.refetch = () => {\n        ++refetchCount;\n        return null as never;\n      };\n\n      void client.refetchObservableQueries();\n\n      await wait(50);\n\n      expect(refetchCount).toEqual(0);\n    });\n\n    it(\"should NOT throw an error on an inflight query() if the observed queries are refetched\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const link = new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            // refetch observed queries as soon as we hear about the query\n            void client.refetchObservableQueries();\n            observer.next({ data });\n            observer.complete();\n          })\n      );\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      await expect(client.query({ query })).resolves.toBeTruthy();\n    });\n  });\n\n  describe(\"refetching specified queries\", () => {\n    it(\"returns a promise resolving when all queries have been refetched\", async () => {\n      const query = gql`\n        query GetAuthor {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const dataChanged = {\n        author: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const query2 = gql`\n        query GetAuthor2 {\n          author2 {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data2 = {\n        author2: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const data2Changed = {\n        author2: {\n          firstName: \"John changed\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2 },\n          },\n          {\n            request: { query },\n            result: { data: dataChanged },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2Changed },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const observable2 = client.watchQuery({ query: query2 });\n\n      const stream = new ObservableStream(observable);\n      const stream2 = new ObservableStream(observable2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      await expect(stream2).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.refetchQueries({\n        include: [\"GetAuthor\", \"GetAuthor2\"],\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataChanged,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable2.getCurrentResult()).toStrictEqualTyped({\n        data: data2Changed,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n  });\n\n  describe(\"loading state\", () => {\n    it(\"should be passed as false if we are not watching a query\", async () => {\n      const query = gql`\n        query {\n          fortuneCookie\n        }\n      `;\n      const data = {\n        fortuneCookie: \"Buy it\",\n      };\n      const result = await new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n        ]),\n      }).query({ query });\n\n      expect(result).toStrictEqualTyped({ data });\n    });\n\n    it(\"should be passed to the observer as true if we are returning partial data\", async () => {\n      const fortuneCookie =\n        \"You must stick to your goal but rethink your approach\";\n      const primeQuery = gql`\n        query {\n          fortuneCookie\n        }\n      `;\n      const primeData = { fortuneCookie };\n\n      const author = { name: \"John\" };\n      const query = gql`\n        query {\n          fortuneCookie\n          author {\n            name\n          }\n        }\n      `;\n      const fullData = { fortuneCookie, author };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data: fullData },\n            delay: 5,\n          },\n          {\n            request: { query: primeQuery },\n            result: { data: primeData },\n          },\n        ]),\n      });\n\n      await client.query({ query: primeQuery });\n\n      const observable = client.watchQuery({\n        query,\n        returnPartialData: true,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: primeData,\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: fullData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should be passed to the observer as false if we are returning all the data\", async () => {\n      const stream = getObservableStream({\n        query: gql`\n          query {\n            author {\n              firstName\n              lastName\n            }\n          }\n        `,\n        result: {\n          data: {\n            author: {\n              firstName: \"John\",\n              lastName: \"Smith\",\n            },\n          },\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { author: { firstName: \"John\", lastName: \"Smith\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"will update on `resetStore`\", async () => {\n      const testQuery = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data1 = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const data2 = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith 2\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: testQuery },\n            result: { data: data1 },\n          },\n          {\n            request: { query: testQuery },\n            result: { data: data2 },\n          },\n        ]),\n      });\n\n      const stream = new ObservableStream(\n        client.watchQuery({\n          query: testQuery,\n          notifyOnNetworkStatusChange: false,\n        })\n      );\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await wait(0);\n      void client.resetStore();\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"will be true when partial data may be returned\", async () => {\n      const query1 = gql`\n        {\n          a {\n            x1\n            y1\n            z1\n          }\n        }\n      `;\n      const query2 = gql`\n        {\n          a {\n            x1\n            y1\n            z1\n          }\n          b {\n            x2\n            y2\n            z2\n          }\n        }\n      `;\n      const data1 = {\n        a: { x1: 1, y1: 2, z1: 3 },\n      };\n      const data2 = {\n        a: { x1: 1, y1: 2, z1: 3 },\n        b: { x2: 3, y2: 2, z2: 1 },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: query1 },\n            result: { data: data1 },\n          },\n          {\n            request: { query: query2 },\n            result: { data: data2 },\n            delay: 5,\n          },\n        ]),\n      });\n\n      const result1 = await client.query({ query: query1 });\n      expect(result1).toStrictEqualTyped({ data: data1 });\n\n      const observable = client.watchQuery({\n        query: query2,\n        returnPartialData: true,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: data1,\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"refetchQueries\", () => {\n    it(\"should refetch the right query when a result is successfully returned\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const variables = { id: \"1234\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void client.mutate({ mutation, refetchQueries: [\"getAuthors\"] });\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should not warn and continue when an unknown query name is asked to refetch\", async () => {\n      using _ = spyOnConsole(\"warn\");\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(\n          [\n            {\n              request: { query },\n              result: { data },\n            },\n            {\n              request: { query },\n              result: { data: secondReqData },\n            },\n            {\n              request: { query: mutation },\n              result: { data: mutationData },\n            },\n          ],\n          { showWarnings: false }\n        ),\n      });\n      const observable = client.watchQuery({\n        query,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void client.mutate({\n        mutation,\n        refetchQueries: [\"fakeQuery\", \"getAuthors\"],\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(console.warn).toHaveBeenCalledWith(\n        'Unknown query named \"%s\" requested in refetchQueries options.include array',\n        \"fakeQuery\"\n      );\n    });\n\n    it(\"should ignore (with warning) a query named in refetchQueries that has no active subscriptions\", async () => {\n      using _ = spyOnConsole(\"warn\");\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      stream.unsubscribe();\n      await client.mutate({\n        mutation,\n        refetchQueries: [\"getAuthors\"],\n      });\n\n      expect(console.warn).toHaveBeenLastCalledWith(\n        'Unknown query named \"%s\" requested in refetchQueries options.include array',\n        \"getAuthors\"\n      );\n    });\n\n    it(\"should ignore (with warning) a document node in refetchQueries that has no active subscriptions\", async () => {\n      using _ = spyOnConsole(\"warn\");\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      stream.unsubscribe();\n\n      // The subscription has been stopped already\n      await client.mutate({\n        mutation,\n        refetchQueries: [query],\n      });\n\n      expect(console.warn).toHaveBeenLastCalledWith(\n        'Unknown query named \"%s\" requested in refetchQueries options.include array',\n        \"getAuthors\"\n      );\n    });\n\n    it(\"should ignore (with warning) a document node containing an anonymous query in refetchQueries that has no active subscriptions\", async () => {\n      using _ = spyOnConsole(\"warn\");\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      stream.unsubscribe();\n\n      // The subscription has been stopped already\n      await client.mutate({\n        mutation,\n        refetchQueries: [query],\n      });\n\n      expect(console.warn).toHaveBeenLastCalledWith(\n        \"Unknown anonymous query requested in refetchQueries options.include array\"\n      );\n    });\n\n    it(\"also works with a query document and variables\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName($id: ID!) {\n          changeAuthorName(newName: \"Jack Smith\", id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n      const mutationVariables = { id: \"2345\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n            delay: 10,\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n            delay: 100,\n          },\n          {\n            request: { query: mutation, variables: mutationVariables },\n            result: { data: mutationData },\n            delay: 10,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n        variables: mutationVariables,\n        refetchQueries: [{ query, variables }],\n      });\n\n      await expect(stream).toEmitTypedValue(\n        {\n          data: secondReqData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        { timeout: 150 }\n      );\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"also works with a query document node\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName($id: ID!) {\n          changeAuthorName(newName: \"Jack Smith\", id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n      const mutationVariables = { id: \"2345\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n            delay: 10,\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n            delay: 100,\n          },\n          {\n            request: { query: mutation, variables: mutationVariables },\n            result: { data: mutationData },\n            delay: 10,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n        variables: mutationVariables,\n        refetchQueries: [query],\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue(\n        {\n          data: secondReqData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        { timeout: 150 }\n      );\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"also works with different references of a same query document node\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName($id: ID!) {\n          changeAuthorName(newName: \"Jack Smith\", id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n      const mutationVariables = { id: \"2345\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n            delay: 10,\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n            delay: 100,\n          },\n          {\n            request: { query: mutation, variables: mutationVariables },\n            result: { data: mutationData },\n            delay: 10,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n        variables: mutationVariables,\n        // spread the query into a new object to simulate multiple instances\n        refetchQueries: [{ ...query }],\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue(\n        {\n          data: secondReqData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        { timeout: 150 }\n      );\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"also works with a conditional function that returns false\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const conditional = jest.fn(() => []);\n      await client.mutate({ mutation, refetchQueries: conditional });\n\n      expect(conditional).toHaveBeenCalledTimes(1);\n      expect(conditional).toHaveBeenCalledWith(\n        expect.objectContaining({ data: mutationData })\n      );\n    });\n\n    it(\"also works with a conditional function that returns an array of refetches\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n          {\n            request: { query },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const conditional = jest.fn(() => [{ query }]);\n      await client.mutate({ mutation, refetchQueries: conditional });\n\n      expect(conditional).toHaveBeenCalledTimes(1);\n      expect(conditional).toHaveBeenCalledWith(\n        expect.objectContaining({ data: mutationData })\n      );\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should refetch using the original query context (if any)\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const variables = { id: \"1234\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n\n      const headers = {\n        someHeader: \"some value\",\n      };\n      const observable = client.watchQuery({\n        query,\n        variables,\n        context: {\n          headers,\n        },\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitNext();\n\n      void client.mutate({\n        mutation,\n        refetchQueries: [\"getAuthors\"],\n      });\n\n      await expect(stream).toEmitNext();\n\n      const context = (client.link as MockApolloLink).operation!.getContext();\n      expect(context.headers).not.toBeUndefined();\n      expect(context.headers.someHeader).toEqual(headers.someHeader);\n    });\n\n    it(\"should refetch using the specified context, if provided\", async () => {\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const variables = { id: \"1234\" };\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      const headers = {\n        someHeader: \"some value\",\n      };\n\n      await expect(stream).toEmitNext();\n\n      await client.mutate({\n        mutation,\n        refetchQueries: [\n          {\n            query,\n            variables,\n            context: {\n              headers,\n            },\n          },\n        ],\n      });\n\n      await expect(stream).toEmitNext();\n\n      const context = (client.link as MockApolloLink).operation!.getContext();\n      expect(context.headers).not.toBeUndefined();\n      expect(context.headers.someHeader).toEqual(headers.someHeader);\n    });\n\n    it(\"should not refetch queries with variablesUnknown: true until they have been executed (via reobserve with new fetchPolicy)\", async () => {\n      const query = gql`\n        query getAuthor($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const variables = { id: \"1234\" };\n\n      const operationSubject = new Subject<ApolloLink.Operation>();\n      const link = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          operationSubject.next(operation);\n          return forward(operation);\n        }).concat(link),\n      });\n\n      const operationStream = new ObservableStream(operationSubject);\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"standby\",\n        [variablesUnknownSymbol]: true,\n      });\n      const stream = new ObservableStream(observable);\n      await expect(stream).not.toEmitAnything();\n      await expect(operationStream).not.toEmitAnything();\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      await client.refetchQueries({ include: [query] });\n      await expect(stream).not.toEmitAnything();\n      await expect(operationStream).not.toEmitAnything();\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      void observable.reobserve({ fetchPolicy: \"cache-first\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      await expect(operationStream).toEmitNext();\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      link.simulateResult({ result: { data } }, true);\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void client.refetchQueries({ include: [query] });\n      await expect(stream).toEmitSimilarValue({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n        }),\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n      await expect(operationStream).toEmitNext();\n\n      link.simulateResult({ result: { data: secondReqData } }, true);\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should not refetch queries with variablesUnknown: true until they have been executed (via manual refetch)\", async () => {\n      const query = gql`\n        query getAuthor($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n      const variables = { id: \"1234\" };\n\n      const operationSubject = new Subject<ApolloLink.Operation>();\n      const link = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          operationSubject.next(operation);\n          return forward(operation);\n        }).concat(link),\n      });\n\n      const operationStream = new ObservableStream(operationSubject);\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"standby\",\n        [variablesUnknownSymbol]: true,\n      });\n\n      // since a `standby` query never emits anything, even when refetched manually,\n      // we just use this to subscribe but don't consume values\n      using stream = new ObservableStream(observable);\n      await expect(operationStream).not.toEmitAnything();\n\n      await client.refetchQueries({ include: [query] });\n      await expect(operationStream).not.toEmitAnything();\n\n      void observable.refetch();\n      await expect(operationStream).toEmitNext();\n      link.simulateResult({ result: { data } }, true);\n\n      // wait a tick to avoid query deduplication\n      await wait(0);\n\n      void client.refetchQueries({ include: [query] });\n      await expect(operationStream).toEmitNext();\n      link.simulateResult({ result: { data: secondReqData } }, true);\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"onQueryUpdated\", () => {\n    const mutation = gql`\n      mutation changeAuthorName {\n        changeAuthorName(newName: \"Jack Smith\") {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const mutationData = {\n      changeAuthorName: {\n        firstName: \"Jack\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const query = gql`\n      query getAuthors($id: ID!) {\n        author(id: $id) {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const data = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n\n    const secondReqData = {\n      author: {\n        firstName: \"Jane\",\n        lastName: \"Johnson\",\n      },\n    };\n\n    const variables = { id: \"1234\" };\n\n    function makeClient() {\n      return new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n        ]),\n      });\n    }\n\n    it(\"should refetch the right query when a result is successfully returned\", async () => {\n      const client = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      let finishedRefetch = false;\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n\n        update(cache) {\n          cache.modify({\n            fields: {\n              author(_, { INVALIDATE }) {\n                return INVALIDATE;\n              },\n            },\n          });\n        },\n\n        async onQueryUpdated(obsQuery) {\n          expect(obsQuery.options.query).toBe(query);\n          const result = await obsQuery.refetch();\n\n          // Wait a bit to make sure the mutation really awaited the\n          // refetching of the query.\n          await wait(100);\n          finishedRefetch = true;\n          return result;\n        },\n      });\n\n      expect(finishedRefetch).toBe(true);\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should refetch using the original query context (if any)\", async () => {\n      const client = makeClient();\n\n      const headers = {\n        someHeader: \"some value\",\n      };\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        context: {\n          headers,\n        },\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void client.mutate({\n        mutation,\n\n        update(cache) {\n          cache.modify({\n            fields: {\n              author(_, { INVALIDATE }) {\n                return INVALIDATE;\n              },\n            },\n          });\n        },\n\n        onQueryUpdated(obsQuery) {\n          expect(obsQuery.options.query).toBe(query);\n          return obsQuery.refetch();\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const context = (client.link as MockApolloLink).operation!.getContext();\n      expect(context.headers).not.toBeUndefined();\n      expect(context.headers.someHeader).toEqual(headers.someHeader);\n    });\n\n    it(\"should refetch using the specified context, if provided\", async () => {\n      const client = makeClient();\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      const headers = {\n        someHeader: \"some value\",\n      };\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void client.mutate({\n        mutation,\n\n        update(cache) {\n          cache.evict({ fieldName: \"author\" });\n        },\n\n        onQueryUpdated(obsQuery) {\n          expect(obsQuery.options.query).toBe(query);\n          return obsQuery.reobserve({\n            fetchPolicy: \"network-only\",\n            context: {\n              ...obsQuery.options.context,\n              headers,\n            },\n          });\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const context = (client.link as MockApolloLink).operation!.getContext();\n      expect(context.headers).not.toBeUndefined();\n      expect(context.headers.someHeader).toEqual(headers.someHeader);\n    });\n  });\n\n  describe(\"awaitRefetchQueries\", () => {\n    it(\"should not wait for `refetchQueries` to complete before resolving the mutation, when `awaitRefetchQueries` is undefined\", async () => {\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const queryData = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: queryData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: queryData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({ mutation, refetchQueries: [\"getAuthors\"] });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: queryData,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n    });\n\n    it(\"should not wait for `refetchQueries` to complete before resolving the mutation, when `awaitRefetchQueries` is false\", async () => {\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const queryData = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: queryData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: queryData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n        refetchQueries: [\"getAuthors\"],\n        awaitRefetchQueries: false,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: queryData,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n    });\n\n    it(\"should wait for `refetchQueries` to complete before resolving the mutation, when `awaitRefetchQueries` is `true`\", async () => {\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const queryData = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: queryData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: queryData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await client.mutate({\n        mutation,\n        refetchQueries: [\"getAuthors\"],\n        awaitRefetchQueries: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"should allow catching errors from `refetchQueries` when `awaitRefetchQueries` is `true`\", async () => {\n      const query = gql`\n        query getAuthors($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const queryData = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const mutation = gql`\n        mutation changeAuthorName {\n          changeAuthorName(newName: \"Jack Smith\") {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const mutationData = {\n        changeAuthorName: {\n          firstName: \"Jack\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const variables = { id: \"1234\" };\n      const refetchError = new Error(\"Refetch failed\");\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: queryData },\n          },\n          {\n            request: { query: mutation },\n            result: { data: mutationData },\n          },\n          {\n            request: { query, variables },\n            result: { data: secondReqData },\n            error: refetchError,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        notifyOnNetworkStatusChange: false,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: queryData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        client.mutate({\n          mutation,\n          refetchQueries: [\"getAuthors\"],\n          awaitRefetchQueries: true,\n        })\n      ).rejects.toThrow(refetchError);\n\n      await expect(stream).toEmitTypedValue({\n        data: queryData,\n        dataState: \"complete\",\n        error: refetchError,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n    });\n  });\n\n  describe(\"store watchers\", () => {\n    it(\"does not fill up the store on resolved queries\", async () => {\n      const query1 = gql`\n        query One {\n          one\n        }\n      `;\n      const query2 = gql`\n        query Two {\n          two\n        }\n      `;\n      const query3 = gql`\n        query Three {\n          three\n        }\n      `;\n      const query4 = gql`\n        query Four {\n          four\n        }\n      `;\n\n      const link = new MockLink([\n        { request: { query: query1 }, result: { data: { one: 1 } } },\n        { request: { query: query2 }, result: { data: { two: 2 } } },\n        { request: { query: query3 }, result: { data: { three: 3 } } },\n        { request: { query: query4 }, result: { data: { four: 4 } } },\n      ]);\n      const cache = new InMemoryCache();\n\n      const client = new ApolloClient({ cache, link });\n\n      await client.query({ query: query1 });\n      await client.query({ query: query2 });\n      await client.query({ query: query3 });\n      await client.query({ query: query4 });\n      await wait(10);\n\n      expect(cache[\"watches\"].size).toBe(0);\n    });\n  });\n\n  describe(\"`no-cache` handling\", () => {\n    it(\"should return a query result (if one exists) when a `no-cache` fetch policy is used\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"no-cache\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n  });\n\n  describe(\"client awareness\", () => {\n    it(\"ClientAwarenessLink should pick up configuration on `ApolloClientOptions`\", async () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data },\n        },\n      ]);\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ClientAwarenessLink().concat(link),\n        clientAwareness: {\n          name: \"Test\",\n          version: \"1.0.0\",\n        },\n      });\n\n      const observable = client.watchQuery({\n        query,\n        fetchPolicy: \"no-cache\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitNext();\n\n      const context = link.operation!.getContext();\n      expect(context.headers).toStrictEqual({\n        \"apollographql-client-name\": \"Test\",\n        \"apollographql-client-version\": \"1.0.0\",\n      });\n    });\n  });\n\n  describe(\"queryDeduplication\", () => {\n    it(\"should be true when context is true, default is false and argument not provided\", () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n          }\n        }\n      `;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: {\n              data: {\n                author: { __typename: \"Author\", firstName: \"John\" },\n              },\n            },\n          },\n        ]),\n      });\n\n      void client.query({ query, context: { queryDeduplication: true } });\n\n      // TODO: Determine if there is a better way to assert this behavior\n      // without reaching into internal state\n      expect(\n        client[\"queryManager\"][\"inFlightLinkObservables\"].peek(\n          print(addTypenameToDocument(query)),\n          \"{}\"\n        )\n      ).toEqual({\n        observable: expect.any(Observable),\n        restart: expect.any(Function),\n      });\n    });\n\n    it(\"should allow overriding global queryDeduplication: true to false\", () => {\n      const query = gql`\n        query {\n          author {\n            firstName\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: {\n              data: {\n                author: { firstName: \"John\" },\n              },\n            },\n          },\n        ]),\n        queryDeduplication: true,\n      });\n\n      void client.query({ query, context: { queryDeduplication: false } });\n\n      // TODO: Determine if there is a better way to assert this behavior\n      // without checking internal state\n      expect(\n        client[\"queryManager\"][\"inFlightLinkObservables\"].peek(\n          print(addTypenameToDocument(query)),\n          \"{}\"\n        )\n      ).toBeUndefined();\n    });\n  });\n\n  describe(\"missing cache field warnings\", () => {\n    let verbosity: ReturnType<typeof setVerbosity>;\n    let spy: any;\n    beforeEach(() => {\n      verbosity = setVerbosity(\"debug\");\n      spy = jest.spyOn(console, \"debug\").mockImplementation();\n    });\n\n    afterEach(() => {\n      setVerbosity(verbosity);\n      spy.mockRestore();\n    });\n\n    it(\"should show missing cache result fields warning when returnPartialData is false\", async () => {\n      const query1 = gql`\n        query {\n          car {\n            make\n            model\n            id\n            __typename\n          }\n        }\n      `;\n\n      const query2 = gql`\n        query {\n          car {\n            make\n            model\n            vin\n            id\n            __typename\n          }\n        }\n      `;\n\n      const data1 = {\n        car: {\n          make: \"Ford\",\n          model: \"Pinto\",\n          id: 123,\n          __typename: \"Car\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: query1 },\n            result: { data: data1 },\n          },\n        ]),\n      });\n\n      const observable1 = client.watchQuery({ query: query1 });\n      const observable2 = client.watchQuery({\n        query: query2,\n        fetchPolicy: \"cache-only\",\n        returnPartialData: false,\n      });\n\n      const stream1 = new ObservableStream(observable1);\n\n      await expect(stream1).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream1).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      stream1.unsubscribe();\n\n      const stream2 = new ObservableStream(observable2);\n\n      await expect(stream2).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(spy).toHaveBeenCalledTimes(1);\n    });\n\n    it(\"should not show missing cache result fields warning when returnPartialData is true\", async () => {\n      const query1 = gql`\n        query {\n          car {\n            make\n            model\n            id\n            __typename\n          }\n        }\n      `;\n\n      const query2 = gql`\n        query {\n          car {\n            make\n            model\n            vin\n            id\n            __typename\n          }\n        }\n      `;\n\n      const data1 = {\n        car: {\n          make: \"Ford\",\n          model: \"Pinto\",\n          id: 123,\n          __typename: \"Car\",\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: query1 },\n            result: { data: data1 },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable1 = client.watchQuery({ query: query1 });\n      const observable2 = client.watchQuery({\n        query: query2,\n        fetchPolicy: \"cache-only\",\n        returnPartialData: true,\n      });\n\n      const stream1 = new ObservableStream(observable1);\n\n      await expect(stream1).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream1).toEmitTypedValue({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      stream1.unsubscribe();\n\n      const stream2 = new ObservableStream(observable2);\n\n      await expect(stream2).toEmitTypedValue({\n        data: data1,\n        dataState: \"partial\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(spy).toHaveBeenCalledTimes(0);\n    });\n  });\n\n  describe(\"defaultContext\", () => {\n    let _: any; // trash variable to throw away values when destructuring\n    _ = _; // omit \"'_' is declared but its value is never read.\" compiler warning\n\n    it(\"ApolloClient and QueryManager share a `defaultContext` instance (default empty object)\", () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      expect(client.defaultContext).toBe(client[\"queryManager\"].defaultContext);\n    });\n\n    it(\"ApolloClient and QueryManager share a `defaultContext` instance (provided option)\", () => {\n      const defaultContext = {};\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n        defaultContext,\n      });\n\n      expect(client.defaultContext).toBe(defaultContext);\n      expect(client[\"queryManager\"].defaultContext).toBe(defaultContext);\n    });\n\n    it(\"`defaultContext` cannot be reassigned on the user-facing `ApolloClient`\", () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      expect(() => {\n        // @ts-ignore\n        client.defaultContext = { query: { fetchPolicy: \"cache-only\" } };\n      }).toThrow(/Cannot set property defaultContext/);\n    });\n\n    it.each([\n      [\n        \"query\",\n        {\n          method: \"query\",\n          option: \"query\",\n          document: gql`\n            query {\n              foo\n            }\n          `,\n        },\n      ],\n      [\n        \"mutation\",\n        {\n          method: \"mutate\",\n          option: \"mutation\",\n          document: gql`\n            mutation {\n              foo\n            }\n          `,\n        },\n      ],\n    ] as const)(\n      \"`defaultContext` will be applied to the context of a %s\",\n      async (_, { method, option, document }) => {\n        let context: any;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new ApolloLink(\n            (operation) =>\n              new Observable((observer) => {\n                ({ cache: _, ...context } = operation.getContext());\n                observer.complete();\n              })\n          ),\n          defaultContext: {\n            foo: \"bar\",\n          },\n        });\n\n        // @ts-ignore a bit too generic for TS\n        client[method]({ [option]: document }).catch(() => {});\n\n        expect(context.foo).toBe(\"bar\");\n      }\n    );\n\n    it(\"`defaultContext` will be applied to the context of a subscription\", async () => {\n      let context: any;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              ({ cache: _, ...context } = operation.getContext());\n              observer.complete();\n            })\n        ),\n        defaultContext: {\n          foo: \"bar\",\n        },\n      });\n\n      client\n        .subscribe({\n          query: gql`\n            subscription {\n              foo\n            }\n          `,\n        })\n        .subscribe(() => {});\n\n      expect(context.foo).toBe(\"bar\");\n    });\n\n    it(\"`ApolloClient.defaultContext` can be modified and changes will show up in future queries\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              observer.next({ data: { foo: operation.getContext().foo } });\n              observer.complete();\n            })\n        ),\n        defaultContext: {\n          foo: \"bar\",\n        },\n      });\n\n      // one query to \"warm up\" with an old value to make sure the value\n      // isn't locked in at the first query or something\n      await expect(\n        client.query({\n          query: gql`\n            query {\n              foo\n            }\n          `,\n          fetchPolicy: \"no-cache\",\n        })\n      ).resolves.toStrictEqualTyped({ data: { foo: \"bar\" } });\n\n      client.defaultContext.foo = \"changed\";\n\n      await expect(\n        client.query({\n          query: gql`\n            query {\n              foo\n            }\n          `,\n          fetchPolicy: \"no-cache\",\n        })\n      ).resolves.toStrictEqualTyped({ data: { foo: \"changed\" } });\n    });\n\n    it(\"`defaultContext` will be shallowly merged with explicit context\", async () => {\n      let context: any;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              ({ cache: _, ...context } = operation.getContext());\n              observer.next({ data: null });\n              observer.complete();\n            })\n        ),\n        defaultContext: {\n          foo: { bar: \"baz\" },\n          a: { b: \"c\" },\n        },\n      });\n\n      await client.query({\n        query: gql`\n          query {\n            foo\n          }\n        `,\n        fetchPolicy: \"no-cache\",\n        context: {\n          a: { x: \"y\" },\n        },\n      });\n\n      expect(context).toEqual(\n        expect.objectContaining({\n          foo: { bar: \"baz\" },\n          a: { b: undefined, x: \"y\" },\n        })\n      );\n    });\n\n    it(\"`defaultContext` will be shallowly merged with context from `defaultOptions.query.context\", async () => {\n      let context: any;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              ({ cache: _, ...context } = operation.getContext());\n              observer.next({ data: null });\n              observer.complete();\n            })\n        ),\n        defaultContext: {\n          foo: { bar: \"baz\" },\n          a: { b: \"c\" },\n        },\n        defaultOptions: {\n          query: {\n            context: {\n              a: { x: \"y\" },\n            },\n          },\n        },\n      });\n\n      await client.query({\n        query: gql`\n          query {\n            foo\n          }\n        `,\n        fetchPolicy: \"no-cache\",\n      });\n\n      expect(context.foo).toStrictEqual({ bar: \"baz\" });\n      expect(context.a).toStrictEqual({ x: \"y\" });\n    });\n\n    it(\n      \"document existing behavior: `defaultOptions.query.context` will be \" +\n        \"completely overwritten by, not merged with, explicit context\",\n      async () => {\n        let context: any;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new ApolloLink(\n            (operation) =>\n              new Observable((observer) => {\n                ({ cache: _, ...context } = operation.getContext());\n                observer.next({ data: null });\n                observer.complete();\n              })\n          ),\n          defaultOptions: {\n            query: {\n              context: {\n                foo: { bar: \"baz\" },\n              },\n            },\n          },\n        });\n\n        await client.query({\n          query: gql`\n            query {\n              foo\n            }\n          `,\n          fetchPolicy: \"no-cache\",\n          context: {\n            a: { x: \"y\" },\n          },\n        });\n\n        expect(context.a).toStrictEqual({ x: \"y\" });\n        expect(context.foo).toBeUndefined();\n      }\n    );\n  });\n\n  describe(\"forbidden field alias names\", () => {\n    it(\"`ApolloClient.query` throws when encountering a query that aliases another field to `__typename`\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const query = gql`\n        query Test {\n          __typename: hello\n        }\n      `;\n      expect(() => client.query({ query })).toThrow(\n        new InvariantError(\n          '`__typename` is a forbidden field alias name in the selection set for field `hello` in query \"Test\".'\n        )\n      );\n    });\n\n    it(\"`ApolloClient.query` throws when encountering a query that aliases another field to `__ac_*`\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const query = gql`\n        query Test {\n          foo {\n            __ac_foo: hello\n          }\n        }\n      `;\n      expect(() => client.query({ query })).toThrow(\n        new InvariantError(\n          '`__ac_foo` is a forbidden field alias name in the selection set for field `foo.hello` in query \"Test\".'\n        )\n      );\n    });\n\n    it(\"Aliasing `__typename` to `__typename` is, while weird, not forbidden.\", async () => {\n      const query = gql`\n        query Test {\n          __typename: __typename\n        }\n      `;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data: {} },\n          },\n        ]),\n      });\n\n      expect(await client.query({ query })).toStrictEqualTyped({\n        data: { __typename: \"Query\" },\n      });\n    });\n\n    it(\"`ApolloClient.watchQuery` throws when encountering a query that aliases another field to `__typename`\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const query = gql`\n        query Test {\n          hello {\n            __typename: world\n          }\n        }\n      `;\n      expect(() => client.watchQuery({ query })).toThrow(\n        new InvariantError(\n          '`__typename` is a forbidden field alias name in the selection set for field `hello.world` in query \"Test\".'\n        )\n      );\n    });\n\n    it(\"calling `ObservableQuery.fetchMore` throws when encountering a query that aliases another field to `__typename`\", async () => {\n      const query = gql`\n        query Test {\n          hello {\n            __typename\n            world\n          }\n        }\n      `;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: {\n              data: { hello: { world: \"Hello World\", __typename: \"Hello\" } },\n            },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query });\n      observable.subscribe({});\n      expect(() =>\n        observable.fetchMore({\n          query: gql`\n            query Test {\n              hello {\n                __typename: fetchMore\n                world\n              }\n            }\n          `,\n        })\n      ).toThrow(\n        new InvariantError(\n          '`__typename` is a forbidden field alias name in the selection set for field `hello.fetchMore` in query \"Test\".'\n        )\n      );\n    });\n\n    it(\"`ApolloClient.mutate` throws when encountering a query that aliases another field to `__typename`\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const mutation = gql`\n        mutation AddTestUser {\n          addUser(id: 5) {\n            hello {\n              __typename: world\n            }\n          }\n        }\n      `;\n      expect(() => client.mutate({ mutation })).toThrow(\n        new InvariantError(\n          '`__typename` is a forbidden field alias name in the selection set for field `addUser.hello.world` in mutation \"AddTestUser\".'\n        )\n      );\n    });\n\n    it(\"`ApolloClient.subscribe` throws when encountering a query that aliases another field to `__typename`\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n      const query = gql`\n        subscription Test {\n          hello {\n            __typename: world\n          }\n        }\n      `;\n      expect(() => client.subscribe({ query })).toThrow(\n        new InvariantError(\n          '`__typename` is a forbidden field alias name in the selection set for field `hello.world` in subscription \"Test\".'\n        )\n      );\n    });\n  });\n\n  test(\"`client.watchQuery` should forward symbol keys on `options` even with `defaultOptions` present on `ApolloClient`\", () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n      defaultOptions: {\n        watchQuery: {},\n      },\n    });\n\n    const obsQuery = client.watchQuery({\n      query: gql`\n        query Test {\n          hello\n        }\n      `,\n      [variablesUnknownSymbol]: true,\n      fetchPolicy: \"standby\",\n    });\n\n    expect(obsQuery[\"variablesUnknown\"]).toBe(true);\n  });\n});\n\ndescribe.skip(\"type tests\", () => {\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const query = gql``;\n    const mutation = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.watchQuery({ query });\n    client.watchQuery({ query, variables: {} });\n    client.watchQuery({ query, variables: { foo: \"bar\" } });\n    client.watchQuery({ query, variables: { bar: \"baz\" } });\n\n    void client.query({ query });\n    void client.query({ query, variables: {} });\n    void client.query({ query, variables: { foo: \"bar\" } });\n    void client.query({ query, variables: { bar: \"baz\" } });\n\n    client.subscribe({ query });\n    client.subscribe({ query, variables: {} });\n    client.subscribe({ query, variables: { foo: \"bar\" } });\n    client.subscribe({ query, variables: { bar: \"baz\" } });\n\n    void client.mutate({ mutation });\n    void client.mutate({ mutation, variables: {} });\n    void client.mutate({ mutation, variables: { foo: \"bar\" } });\n    void client.mutate({ mutation, variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n    const mutation: TypedDocumentNode<{ greeting: string }> = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.watchQuery({ query });\n    client.watchQuery({ query, variables: {} });\n    client.watchQuery({ query, variables: undefined });\n    client.watchQuery({ query, variables: { foo: \"bar\" } });\n    client.watchQuery({ query, variables: { bar: \"baz\" } });\n\n    void client.query({ query });\n    void client.query({ query, variables: {} });\n    void client.query({ query, variables: undefined });\n    void client.query({ query, variables: { foo: \"bar\" } });\n    void client.query({ query, variables: { bar: \"baz\" } });\n\n    client.subscribe({ query });\n    client.subscribe({ query, variables: {} });\n    client.subscribe({ query, variables: undefined });\n    client.subscribe({ query, variables: { foo: \"bar\" } });\n    client.subscribe({ query, variables: { bar: \"baz\" } });\n\n    void client.mutate({ mutation });\n    void client.mutate({ mutation, variables: {} });\n    void client.mutate({ mutation, variables: undefined });\n    void client.mutate({ mutation, variables: { foo: \"bar\" } });\n    void client.mutate({ mutation, variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n    const mutation: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.watchQuery({ query });\n    client.watchQuery({ query, variables: {} });\n    client.watchQuery({ query, variables: undefined });\n    client.watchQuery({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        bar: \"baz\",\n      },\n    });\n\n    void client.query({ query });\n    void client.query({ query, variables: {} });\n    void client.query({ query, variables: undefined });\n    void client.query({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        bar: \"baz\",\n      },\n    });\n\n    client.subscribe({ query });\n    client.subscribe({ query, variables: {} });\n    client.subscribe({ query, variables: undefined });\n    client.subscribe({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        bar: \"baz\",\n      },\n    });\n\n    void client.mutate({ mutation });\n    void client.mutate({ mutation, variables: {} });\n    void client.mutate({ mutation, variables: undefined });\n    void client.mutate({\n      mutation,\n      variables: {\n        // @ts-expect-error unknown variables\n        bar: \"baz\",\n      },\n    });\n  });\n\n  test(\"is invalid when TVariables is never\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n    const mutation: TypedDocumentNode<{ greeting: string }, never> = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    // @ts-expect-error\n    client.watchQuery({ query });\n    client.watchQuery({\n      query,\n      // @ts-expect-error\n      variables: {},\n    });\n    client.watchQuery({\n      query,\n      // @ts-expect-error\n      variables: undefined,\n    });\n    client.watchQuery({\n      query,\n      // @ts-expect-error unknown variables\n      variables: { foo: \"bar\" },\n    });\n\n    // @ts-expect-error\n    void client.query({ query });\n    void client.query({\n      query,\n      // @ts-expect-error\n      variables: {},\n    });\n    void client.query({\n      query,\n      // @ts-expect-error\n      variables: undefined,\n    });\n    void client.query({\n      query,\n      // @ts-expect-error unknown variables\n      variables: { foo: \"bar\" },\n    });\n\n    // @ts-expect-error\n    client.subscribe({ query });\n    client.subscribe({\n      query,\n      // @ts-expect-error\n      variables: {},\n    });\n    client.subscribe({\n      query,\n      // @ts-expect-error\n      variables: undefined,\n    });\n    client.subscribe({\n      query,\n      // @ts-expect-error unknown variables\n      variables: { foo: \"bar\" },\n    });\n\n    // @ts-expect-error\n    void client.mutate({ mutation });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error\n      variables: {},\n    });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error\n      variables: undefined,\n    });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error unknown variables\n      variables: { foo: \"bar\" },\n    });\n  });\n\n  test(\"optional variables are optional\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n    const mutation: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.watchQuery({ query });\n    client.watchQuery({ query, variables: {} });\n    client.watchQuery({ query, variables: undefined });\n    client.watchQuery({ query, variables: { limit: 10 } });\n    client.watchQuery({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.watchQuery({\n      query,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void client.query({ query });\n    void client.query({ query, variables: {} });\n    void client.query({ query, variables: undefined });\n    void client.query({ query, variables: { limit: 10 } });\n    void client.query({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.query({\n      query,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    client.subscribe({ query });\n    client.subscribe({ query, variables: {} });\n    client.subscribe({ query, variables: undefined });\n    client.subscribe({ query, variables: { limit: 10 } });\n    client.subscribe({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.subscribe({\n      query,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void client.mutate({ mutation });\n    void client.mutate({ mutation, variables: {} });\n    void client.mutate({ mutation, variables: undefined });\n    void client.mutate({ mutation, variables: { limit: 10 } });\n    void client.mutate({\n      mutation,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.mutate({\n      mutation,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"enforced required variables when TVariables includes required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n    const mutation: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    // @ts-expect-error empty variables\n    client.watchQuery({ query });\n    client.watchQuery({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    client.watchQuery({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    client.watchQuery({ query, variables: { id: \"1\" } });\n    client.watchQuery({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.watchQuery({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    void client.query({ query });\n    void client.query({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    void client.query({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    void client.query({ query, variables: { id: \"1\" } });\n    void client.query({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.query({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    client.subscribe({ query });\n    client.subscribe({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    client.subscribe({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    client.subscribe({ query, variables: { id: \"1\" } });\n    client.subscribe({\n      query,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.subscribe({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    void client.mutate({ mutation });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    void client.mutate({ mutation, variables: { id: \"1\" } });\n    void client.mutate({\n      mutation,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.mutate({\n      mutation,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n    const mutation: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    // @ts-expect-error empty variables\n    client.watchQuery({ query });\n    client.watchQuery({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    client.watchQuery({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    client.watchQuery({ query, variables: { id: \"1\" } });\n    client.watchQuery({\n      query,\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    client.watchQuery({ query, variables: { id: \"1\", language: \"en\" } });\n    client.watchQuery({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.watchQuery({\n      query,\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    void client.query({ query });\n    void client.query({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    void client.query({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    void client.query({ query, variables: { id: \"1\" } });\n    void client.query({\n      query,\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    void client.query({ query, variables: { id: \"1\", language: \"en\" } });\n    void client.query({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.query({\n      query,\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    client.subscribe({ query });\n    client.subscribe({\n      query,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    client.subscribe({\n      query,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    client.subscribe({ query, variables: { id: \"1\" } });\n    client.subscribe({\n      query,\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    client.subscribe({ query, variables: { id: \"1\", language: \"en\" } });\n    client.subscribe({\n      query,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    client.subscribe({\n      query,\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    // @ts-expect-error empty variables\n    void client.mutate({ mutation });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error empty variables\n      variables: undefined,\n    });\n    void client.mutate({ mutation, variables: { id: \"1\" } });\n    void client.mutate({\n      mutation,\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    void client.mutate({ mutation, variables: { id: \"1\", language: \"en\" } });\n    void client.mutate({\n      mutation,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void client.mutate({\n      mutation,\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/ApolloClient/links.test.ts",
    "content": "import { type FormattedExecutionResult, OperationTypeNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Observable, Subscription } from \"rxjs\";\nimport { map, of } from \"rxjs\";\n\nimport type { Reference } from \"@apollo/client\";\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\n\ndescribe(\"Link interactions\", () => {\n  it(\"includes the client on the operation for eviction links\", (done) => {\n    expect.assertions(3);\n    const query = gql`\n      query CachedLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n\n    const evictionLink = new ApolloLink((operation, forward) => {\n      const { client } = operation;\n      expect(client).toBeDefined();\n      return (forward(operation) as Observable<FormattedExecutionResult>).pipe(\n        map((result) => {\n          setTimeout(() => {\n            const cacheResult = client.cache.read({\n              query,\n              optimistic: true,\n            });\n            expect(cacheResult).toEqual(initialData);\n            expect(cacheResult).toEqual(result.data);\n            if (count === 2) {\n              done();\n            }\n          }, 10);\n          return result;\n        })\n      );\n    });\n\n    const mockLink = new MockSubscriptionLink();\n    const link = ApolloLink.from([evictionLink, mockLink]);\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n    });\n\n    let count = 0;\n    observable.subscribe({\n      next: (result) => {\n        count++;\n      },\n      error: (e) => {\n        console.error(e);\n      },\n    });\n\n    // fire off first result\n    mockLink.simulateResult({ result: { data: initialData } });\n  });\n\n  it(\"cleans up all links on the final unsubscribe from watchQuery\", (done) => {\n    const query = gql`\n      query WatchedLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      notifyOnNetworkStatusChange: false,\n    });\n\n    let count = 0;\n    let four: Subscription;\n    // first watch\n    const one = observable.subscribe((result) => count++);\n    // second watch\n    const two = observable.subscribe((result) => count++);\n    // third watch (to be unsubscribed)\n    const three = observable.subscribe((result) => {\n      count++;\n      three.unsubscribe();\n      // fourth watch\n      four = observable.subscribe((x) => count++);\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n    setTimeout(() => {\n      one.unsubscribe();\n\n      link.simulateResult(\n        {\n          result: {\n            data: {\n              people_one: {\n                name: \"Luke Skywalker\",\n                friends: [{ name: \"R2D2\" }],\n              },\n            },\n          },\n        },\n        true\n      );\n      setTimeout(() => {\n        four.unsubscribe();\n        // final unsubscribe should be called now\n        two.unsubscribe();\n      }, 10);\n    }, 10);\n\n    link.onUnsubscribe(() => {\n      expect(count).toEqual(6);\n      done();\n    });\n  });\n\n  it(\"cleans up all links on the final unsubscribe from watchQuery [error]\", (done) => {\n    const query = gql`\n      query WatchedLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      notifyOnNetworkStatusChange: false,\n    });\n\n    let count = 0;\n    let four: Subscription;\n    // first watch\n    const one = observable.subscribe((result) => count++);\n    // second watch\n    observable.subscribe({\n      next: () => count++,\n      error: () => {\n        throw new Error(\"Error should not be called\");\n      },\n    });\n    // third watch (to be unsubscribed)\n    const three = observable.subscribe((result) => {\n      count++;\n      three.unsubscribe();\n      // fourth watch\n      four = observable.subscribe((x) => count++);\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n    setTimeout(() => {\n      one.unsubscribe();\n      four.unsubscribe();\n\n      // final unsubscribe should be called now\n      // since errors clean up subscriptions\n      link.simulateResult({ error: new Error(\"dang\") });\n    }, 10);\n\n    link.onUnsubscribe(() => {\n      expect(count).toEqual(5);\n      done();\n    });\n  });\n\n  it(\"includes the client on the operation for mutations\", (done) => {\n    const mutation = gql`\n      mutation UpdateLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const evictionLink = new ApolloLink((operation, forward) => {\n      const { client } = operation;\n      expect(client).toBeDefined();\n      done();\n      return forward(operation);\n    });\n\n    const mockLink = new MockSubscriptionLink();\n    const link = ApolloLink.from([evictionLink, mockLink]);\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    void client.mutate({ mutation });\n  });\n\n  it(\"includes passed context in the context for mutations\", (done) => {\n    const mutation = gql`\n      mutation UpdateLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const evictionLink = new ApolloLink((operation, forward) => {\n      const { planet } = operation.getContext();\n      expect(planet).toBe(\"Tatooine\");\n      done();\n      return forward(operation);\n    });\n\n    const mockLink = new MockSubscriptionLink();\n    const link = ApolloLink.from([evictionLink, mockLink]);\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    void client.mutate({ mutation, context: { planet: \"Tatooine\" } });\n  });\n\n  it(\"includes client on operation for cache resolvers\", async () => {\n    const query = gql`\n      {\n        books {\n          id\n          title\n        }\n      }\n    `;\n\n    const shouldHitCacheResolver = gql`\n      {\n        book(id: 1) {\n          title\n        }\n      }\n    `;\n\n    const bookData = {\n      books: [\n        { id: 1, title: \"Woo\", __typename: \"Book\" },\n        { id: 2, title: \"Foo\", __typename: \"Book\" },\n      ],\n    };\n\n    const link = new ApolloLink((operation, forward) => {\n      const { client } = operation;\n      expect(client).toBeDefined();\n      expect(client.cache.identify({ id: 1, __typename: \"Book\" })).toEqual(\n        \"Book:1\"\n      );\n      return of({ data: bookData });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              book(_, { args, toReference, readField }) {\n                if (!args) {\n                  throw new Error(\"arg must never be null\");\n                }\n\n                const ref = toReference({ __typename: \"Book\", id: args.id });\n                if (!ref) {\n                  throw new Error(\"ref must never be null\");\n                }\n\n                expect(ref).toEqual({ __ref: `Book:${args.id}` });\n                const found = readField<Reference[]>(\"books\")!.find(\n                  (book) => book.__ref === ref.__ref\n                );\n                expect(found).toBeTruthy();\n                return found;\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    await client.query({ query });\n\n    const { data } = await client.query({ query: shouldHitCacheResolver });\n    expect(data).toMatchObject({\n      book: { title: \"Woo\", __typename: \"Book\" },\n    });\n  });\n\n  it(\"removes @client fields from the query before it reaches the link\", async () => {\n    const result: { current: ApolloLink.Operation | undefined } = {\n      current: undefined,\n    };\n\n    const query = gql`\n      query {\n        books {\n          id\n          title\n          isRead @client\n        }\n      }\n    `;\n\n    const expectedQuery = gql`\n      query {\n        books {\n          id\n          title\n          __typename\n        }\n      }\n    `;\n\n    const link = new ApolloLink((operation) => {\n      result.current = operation;\n\n      return of({\n        data: {\n          books: [\n            { id: 1, title: \"Woo\", __typename: \"Book\" },\n            { id: 2, title: \"Foo\", __typename: \"Book\" },\n          ],\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      localState: new LocalState(),\n    });\n\n    await client.query({ query });\n\n    expect(result.current!.query).toMatchDocument(expectedQuery);\n  });\n\n  it(\"passes all expected properties into links\", async () => {\n    let operation!: ApolloLink.Operation;\n    const link = new ApolloLink((op) => {\n      operation = op;\n      return of({ data: { hello: \"world\" } });\n    });\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n    const query = gql`\n      query HelloWorld {\n        hello\n      }\n    `;\n    await client\n      .query({\n        query,\n      })\n      .catch(() => {});\n    expect(operation).toStrictEqualTyped({\n      variables: {},\n      extensions: {},\n      operationName: \"HelloWorld\",\n      operationType: OperationTypeNode.QUERY,\n      query,\n    });\n    expect(Object.keys(operation)).toEqual([\n      \"query\",\n      \"variables\",\n      \"extensions\",\n      \"operationName\",\n      \"operationType\",\n    ]);\n    expect(Object.getOwnPropertyNames(operation)).toEqual([\n      \"query\",\n      \"variables\",\n      \"extensions\",\n      \"operationName\",\n      \"operationType\",\n      \"setContext\",\n      \"getContext\",\n      \"client\",\n    ]);\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/ApolloClient/multiple-results.test.ts",
    "content": "import { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport { ObservableStream, wait } from \"@apollo/client/testing/internal\";\n\ndescribe(\"multiple results\", () => {\n  it(\"allows multiple query results from link\", async () => {\n    const query = gql`\n      query LazyLoadLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: null,\n      },\n    };\n\n    const laterData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    link.simulateResult({ result: { data: laterData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: laterData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  it(\"allows multiple query results from link with ignored errors\", async () => {\n    const query = gql`\n      query LazyLoadLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: null,\n      },\n    };\n\n    const laterData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      errorPolicy: \"ignore\",\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    link.simulateResult({\n      result: { errors: [new GraphQLError(\"defer failed\")] },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: 7,\n      partial: true,\n    });\n\n    await wait(20);\n    link.simulateResult({ result: { data: laterData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: laterData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  it(\"strips errors from a result if ignored\", async () => {\n    const query = gql`\n      query LazyLoadLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: null,\n      },\n    };\n\n    const laterData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      errorPolicy: \"ignore\",\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    // this should fire the `next` event without this error\n    link.simulateResult({\n      result: {\n        errors: [new GraphQLError(\"defer failed\")],\n        data: laterData,\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: laterData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  it.skip(\"allows multiple query results from link with all errors\", async () => {\n    const query = gql`\n      query LazyLoadLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: null,\n      },\n    };\n\n    const laterData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: [{ name: \"Leia Skywalker\" }],\n      },\n    };\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      errorPolicy: \"all\",\n    });\n    const stream = new ObservableStream(observable);\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    // this should fire the next event again\n    link.simulateResult({\n      error: new Error(\"defer failed\"),\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      error: new Error(\"defer failed\"),\n      partial: false,\n    });\n\n    link.simulateResult({ result: { data: laterData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: laterData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n  });\n\n  it(\"emits error if an error is set with the none policy\", async () => {\n    const query = gql`\n      query LazyLoadLuke {\n        people_one(id: 1) {\n          name\n          friends {\n            name\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      people_one: {\n        name: \"Luke Skywalker\",\n        friends: null,\n      },\n    };\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n      // errorPolicy: 'none', // this is the default\n    });\n    const stream = new ObservableStream(observable);\n\n    let count = 0;\n    observable.subscribe({\n      next: (result) => {\n        // errors should never be passed since they are ignored\n        count++;\n        // loading\n        if (count === 1) {\n          expect(result.error).toBeUndefined();\n        }\n        // first result\n        if (count === 2) {\n          expect(result.error).toBeUndefined();\n        }\n        // error\n        if (count === 3) {\n          expect(result.error).toBeDefined();\n        }\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    // fire off first result\n    link.simulateResult({ result: { data: initialData } });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: 7,\n      partial: false,\n    });\n\n    link.simulateResult({ error: new Error(\"defer failed\") });\n\n    await expect(stream).toEmitTypedValue({\n      data: initialData,\n      dataState: \"complete\",\n      error: new Error(\"defer failed\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/ObservableQuery.ts",
    "content": "import type {\n  ResultOf,\n  TypedDocumentNode,\n} from \"@graphql-typed-document-node/core\";\nimport { waitFor } from \"@testing-library/react\";\nimport { expectTypeOf } from \"expect-type\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { ObservedValueOf, Observer } from \"rxjs\";\nimport { delay, from, lastValueFrom, Observable, of, Subject } from \"rxjs\";\n\nimport type {\n  ObservableQuery,\n  OperationVariables,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  markAsStreaming,\n  ObservableStream,\n  setupVariablesCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  DocumentTransform,\n  relayStylePagination,\n} from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\n\ndescribe(\"ObservableQuery\", () => {\n  // Standard data for all these tests\n  const query: TypedDocumentNode<{\n    people_one: {\n      name: string;\n    };\n  }> = gql`\n    query query($id: ID!) {\n      people_one(id: $id) {\n        name\n      }\n    }\n  `;\n  const variables = { id: 1 };\n  const differentVariables = { id: 2 };\n  const dataOne = {\n    people_one: {\n      name: \"Luke Skywalker\",\n    },\n  };\n  const dataTwo = {\n    people_one: {\n      name: \"Leia Skywalker\",\n    },\n  };\n\n  const error = new GraphQLError(\"is offline.\", undefined, null, null, [\n    \"people_one\",\n  ]);\n  const wrappedError = new CombinedGraphQLErrors({\n    data: dataOne,\n    errors: [error],\n  });\n\n  describe(\"reobserve\", () => {\n    describe(\"to change pollInterval\", () => {\n      it(\"starts polling if goes from 0 -> something\", async () => {\n        const query = gql`\n          query {\n            count\n          }\n        `;\n        let count = 0;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query },\n              result: () => ({ data: { count: ++count } }),\n              maxUsageCount: Number.POSITIVE_INFINITY,\n              delay: 20,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({ query });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 1 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).not.toEmitAnything();\n\n        // The value is returned from the cache\n        await expect(\n          observable.reobserve({ pollInterval: 10 })\n        ).resolves.toStrictEqualTyped({ data: { count: 1 } });\n\n        // We don't expect to see a loading state from reobserve since it just\n        // read the value from the cache and did not fetch from the network. The\n        // poll state is the first loading state we will see\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 1 },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 2 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 2 },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 3 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        observable.stopPolling();\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"stops polling if goes from something -> 0\", async () => {\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query, variables },\n              result: { data: dataOne },\n              delay: 20,\n            },\n            {\n              request: { query, variables },\n              result: { data: dataTwo },\n              delay: 20,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          variables,\n          pollInterval: 10,\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataTwo,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await observable.reobserve({ pollInterval: 0 });\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"stops polling if goes from something -> fetchPolicy: standby\", async () => {\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query, variables },\n              result: { data: dataOne },\n              delay: 20,\n            },\n            {\n              request: { query, variables },\n              result: { data: dataTwo },\n              delay: 20,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          variables,\n          pollInterval: 10,\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataTwo,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await observable.reobserve({ fetchPolicy: \"standby\" });\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"resumes polling if goes from fetchPolicy: standby to non-standby\", async () => {\n        const query = gql`\n          query {\n            greeting\n          }\n        `;\n        let count = 0;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query },\n              result: () => ({ data: { greeting: `hello ${++count}` } }),\n              delay: 20,\n              maxUsageCount: Number.POSITIVE_INFINITY,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({ query, pollInterval: 10 });\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { greeting: \"hello 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { greeting: \"hello 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { greeting: \"hello 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(\n          observable.reobserve({ fetchPolicy: \"standby\" })\n        ).resolves.toStrictEqualTyped({ data: undefined });\n\n        await expect(stream).not.toEmitAnything();\n\n        await expect(\n          observable.reobserve({ fetchPolicy: \"cache-first\" })\n        ).resolves.toStrictEqualTyped({ data: { greeting: \"hello 2\" } });\n\n        await expect(stream).toEmitTypedValue({\n          data: { greeting: \"hello 2\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { greeting: \"hello 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        observable.stopPolling();\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"can change pollInterval from one value to another\", async () => {\n        const query = gql`\n          query {\n            count\n          }\n        `;\n        let count = 0;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query },\n              result: () => ({ data: { count: ++count } }),\n              maxUsageCount: Number.POSITIVE_INFINITY,\n              delay: 20,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({ query, pollInterval: 100 });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 1 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue(\n          {\n            data: { count: 1 },\n            dataState: \"complete\",\n            loading: true,\n            networkStatus: NetworkStatus.poll,\n            partial: false,\n          },\n          { timeout: 110 }\n        );\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 2 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        // Value is read from the cache\n        await expect(\n          observable.reobserve({ pollInterval: 10 })\n        ).resolves.toStrictEqualTyped({ data: { count: 2 } });\n\n        // We don't see a loading state from reobserve since it reread the value\n        // from the cache\n\n        await expect(stream).toEmitTypedValue(\n          {\n            data: { count: 2 },\n            dataState: \"complete\",\n            loading: true,\n            networkStatus: NetworkStatus.poll,\n            partial: false,\n          },\n          { timeout: 20 }\n        );\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 3 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        observable.stopPolling();\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"warns and does not start polling on a cache-only query when using reobserve to change poll interval\", async () => {\n        using _ = spyOnConsole(\"warn\");\n        const query = gql`\n          query CountQuery {\n            count\n          }\n        `;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: ApolloLink.empty(),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy: \"cache-only\",\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        });\n\n        await expect(\n          observable.reobserve({ pollInterval: 10 })\n        ).resolves.toStrictEqualTyped({ data: undefined });\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n          \"CountQuery\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"warns and does not start polling on a cache-only query when initializing with poll interval\", async () => {\n        using _ = spyOnConsole(\"warn\");\n        const query = gql`\n          query CountQuery {\n            count\n          }\n        `;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: ApolloLink.empty(),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy: \"cache-only\",\n          pollInterval: 10,\n        });\n\n        const stream = new ObservableStream(observable);\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n          \"CountQuery\"\n        );\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        });\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"warns and does not start polling on a cache-only query when calling startPolling\", async () => {\n        using _ = spyOnConsole(\"warn\");\n        const query = gql`\n          query CountQuery {\n            count\n          }\n        `;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: ApolloLink.empty(),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy: \"cache-only\",\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        });\n\n        observable.startPolling(10);\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n          \"CountQuery\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"does not warn about polling on cache-only query multiple times\", async () => {\n        using consoleSpy = spyOnConsole(\"warn\");\n        const query = gql`\n          query CountQuery {\n            count\n          }\n        `;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: ApolloLink.empty(),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy: \"cache-only\",\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        });\n\n        observable.startPolling(10);\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n          \"CountQuery\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n\n        consoleSpy.warn.mockClear();\n        observable.startPolling(10);\n\n        expect(console.warn).not.toHaveBeenCalled();\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"cancels polling when changing to a cache-only fetchPolicy\", async () => {\n        using _ = spyOnConsole(\"warn\");\n        const query = gql`\n          query CountQuery {\n            count\n          }\n        `;\n        let count = 0;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query },\n              result: () => ({ data: { count: ++count } }),\n              maxUsageCount: Number.POSITIVE_INFINITY,\n              delay: 20,\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({ query, pollInterval: 100 });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 1 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 1 },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { count: 2 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(\n          observable.reobserve({ fetchPolicy: \"cache-only\" })\n        ).resolves.toStrictEqualTyped({ data: { count: 2 } });\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"Cannot poll on 'cache-only' query '%s' and as such, polling is disabled. Please use a different fetch policy.\",\n          \"CountQuery\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n      });\n    });\n\n    it(\"does not break refetch\", async () => {\n      const query = gql`\n        query people($first: Int) {\n          allPeople(first: $first) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n      const variables1 = { first: 0 };\n\n      const data2 = { allPeople: { people: [{ name: \"Leia Skywalker\" }] } };\n      const variables2 = { first: 1 };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: query, variables: variables1 },\n            result: { data },\n            delay: 20,\n          },\n          {\n            request: { query: query, variables: variables2 },\n            result: { data: data2 },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query: query,\n        variables: variables1,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.refetch(variables2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"rerenders when refetch is called\", async () => {\n      const query = gql`\n        query people($first: Int) {\n          allPeople(first: $first) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n      const variables = { first: 0 };\n\n      const data2 = { allPeople: { people: [{ name: \"Leia Skywalker\" }] } };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n            delay: 20,\n          },\n          {\n            request: { query, variables },\n            result: { data: data2 },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.refetch();\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"rerenders with new variables then shows correct data for previous variables\", async () => {\n      const query = gql`\n        query people($first: Int) {\n          allPeople(first: $first) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n      const variables = { first: 0 };\n\n      const data2 = { allPeople: { people: [{ name: \"Leia Skywalker\" }] } };\n      const variables2 = { first: 1 };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data },\n          },\n          {\n            request: { query, variables: variables2 },\n            result: { data: data2 },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.reobserve({ variables: variables2 });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      // go back to first set of variables\n      const current = await observable.reobserve({ variables });\n      expect(current).toStrictEqualTyped({ data });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"if query is refetched, and an error is returned, can refetch again with successful result\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n          },\n          {\n            request: { query, variables },\n            result: { data: dataOne, errors: [error] },\n          },\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(observable.refetch()).rejects.toThrow(\n        new CombinedGraphQLErrors({ data: dataOne, errors: [error] })\n      );\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({ data: dataOne, errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n\n      await expect(observable.refetch()).resolves.toStrictEqualTyped({\n        data: dataOne,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does a network request if fetchPolicy becomes networkOnly\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n          },\n          {\n            request: { query, variables },\n            result: { data: dataTwo },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.reobserve({ fetchPolicy: \"network-only\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    // TODO: This test does not match the description since it never becomes\n    // \"not cache-only\" after it is set to cache-only.\n    it(\"does a network request if fetchPolicy is cache-only then store is reset then fetchPolicy becomes not cache-only\", async () => {\n      const testQuery = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(\n          () =>\n            new Observable((observer) => {\n              timesFired += 1;\n              observer.next({ data });\n              observer.complete();\n            })\n        ),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      // fetch first data from server\n      const observable = client.watchQuery({\n        query: testQuery,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(timesFired).toBe(1);\n\n      await expect(\n        observable.reobserve({ fetchPolicy: \"cache-only\" })\n      ).resolves.toStrictEqualTyped({ data });\n      await client.resetStore();\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      expect(timesFired).toBe(1);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does a network request if fetchPolicy changes from cache-only\", async () => {\n      const testQuery = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(() => {\n          return new Observable((observer) => {\n            setTimeout(() => {\n              timesFired += 1;\n              observer.next({ data });\n              observer.complete();\n            });\n          });\n        }),\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      const observable = client.watchQuery({\n        query: testQuery,\n        fetchPolicy: \"cache-only\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(timesFired).toBe(0);\n\n      await observable.reobserve({ fetchPolicy: \"cache-first\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(timesFired).toBe(1);\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"can set queries to standby and will not fetch when doing so\", async () => {\n      const testQuery = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(() => {\n          return new Observable((observer) => {\n            timesFired += 1;\n            setTimeout(() => {\n              observer.next({ data });\n              observer.complete();\n            }, 20);\n          });\n        }),\n      ]);\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n      const observable = client.watchQuery({\n        query: testQuery,\n        fetchPolicy: \"cache-first\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(timesFired).toBe(1);\n\n      await expect(\n        observable.reobserve({ query, fetchPolicy: \"standby\" })\n      ).resolves.toStrictEqualTyped({ data: undefined });\n\n      // make sure the query didn't get fired again.\n      await expect(stream).not.toEmitAnything();\n      expect(timesFired).toBe(1);\n    });\n\n    it(\"will not fetch when setting a cache-only query to standby\", async () => {\n      const testQuery = gql`\n        query {\n          author {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n\n      let timesFired = 0;\n      const link = ApolloLink.from([\n        new ApolloLink(() => {\n          return new Observable((observer) => {\n            timesFired += 1;\n            setTimeout(() => {\n              observer.next({ data });\n              observer.complete();\n            }, 20);\n          });\n        }),\n      ]);\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      client.writeQuery({ query: testQuery, data });\n\n      const observable = client.watchQuery({\n        query: testQuery,\n        fetchPolicy: \"cache-only\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(timesFired).toBe(0);\n\n      await expect(\n        observable.reobserve({ query, fetchPolicy: \"standby\" })\n      ).resolves.toStrictEqualTyped({ data: undefined });\n\n      // make sure the query didn't get fired again.\n      await expect(stream).not.toEmitAnything();\n      expect(timesFired).toBe(0);\n    });\n\n    it(\"returns a promise which eventually returns data\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n          {\n            request: { query, variables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const res = await observable.reobserve({\n        fetchPolicy: \"cache-and-network\",\n      });\n\n      expect(res).toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"registers and unregisters `ObservableQuery` even if it is not subscribed to\", async () => {\n      const link = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      const observable = client.watchQuery({ query, variables });\n      expect(client.getObservableQueries().size).toBe(0);\n      const promise = observable.reobserve();\n      expect(client.getObservableQueries().size).toBe(1);\n      link.simulateResult(\n        {\n          result: { data: dataOne },\n        },\n        true\n      );\n      await promise;\n      expect(client.getObservableQueries().size).toBe(0);\n    });\n  });\n\n  describe(\"setVariables\", () => {\n    it(\"reruns query if the variables change\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n          {\n            request: { query, variables: differentVariables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.setVariables(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does invalidate the currentResult data if the variables change\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n          {\n            request: { query, variables: differentVariables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.setVariables(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does not invalidate the currentResult errors if the variables change\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { errors: [error] },\n            delay: 20,\n          },\n          {\n            request: { query, variables: differentVariables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        errorPolicy: \"all\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      await expect(\n        observable.setVariables(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"sets networkStatus to `setVariables` when fetching\", async () => {\n      const mockedResponses = [\n        {\n          request: { query, variables },\n          result: { data: dataOne },\n          delay: 20,\n        },\n        {\n          request: { query, variables: differentVariables },\n          result: { data: dataTwo },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mockedResponses),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.setVariables(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"sets networkStatus to `refetch` when calling refetch with new variables\", async () => {\n      const mockedResponses = [\n        {\n          request: { query, variables },\n          result: { data: dataOne },\n          delay: 20,\n        },\n        {\n          request: { query, variables: differentVariables },\n          result: { data: dataTwo },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mockedResponses),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.refetch(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"does not rerun query if variables do not change\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n          {\n            request: { query, variables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.setVariables(variables)\n      ).resolves.toStrictEqualTyped({ data: dataOne });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"treats setVariables({}) as unchanged if previous variables are undefined\", async () => {\n      const query = gql`\n        query ($offset: Int) {\n          users(offset: $offset) {\n            id\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query },\n            result: { data: { users: [{ __typename: \"User\", id: 1 }] } },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        // Ensure we don't get another network request\n        fetchPolicy: \"network-only\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { users: [{ __typename: \"User\", id: 1 }] },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(observable.setVariables({})).resolves.toStrictEqualTyped({\n        data: { users: [{ __typename: \"User\", id: 1 }] },\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"treats setVariables as unchanged if passing variables with default in query\", async () => {\n      const query = gql`\n        query ($limit: Int = 5, $offset: Int) {\n          users(offset: $offset) {\n            id\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables: { limit: 5, offset: 0 } },\n            result: { data: { users: [{ __typename: \"User\", id: 1 }] } },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables: { limit: 5, offset: 0 },\n        // Ensure we don't get another network request\n        fetchPolicy: \"network-only\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: { users: [{ __typename: \"User\", id: 1 }] },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(\n        observable.setVariables({ offset: 0 })\n      ).resolves.toStrictEqualTyped({\n        data: { users: [{ __typename: \"User\", id: 1 }] },\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"handles variables changing while a query is in-flight\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n          {\n            request: { query, variables: differentVariables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n      // The expected behavior is that the original variables are forgotten\n      // and the query stays in loading state until the result for the new variables\n      // has returned.\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(\n        observable.setVariables(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      // Initial fetch\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      // setVariables\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n\n  describe(\"refetch\", () => {\n    // TODO: If updating this to include a cache result for the changed\n    // variables, a cache value is emitted for the refetch, but I believe this\n    // should be undefined.\n    it(\"calls fetchRequest with fetchPolicy `network-only` when using a non-networked fetch policy\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n          },\n          {\n            request: { query, variables: differentVariables },\n            result: { data: dataTwo },\n          },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"cache-first\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.refetch(differentVariables);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"calling refetch with different variables before the query itself resolved will only yield the result for the new variables\", async () => {\n      const observers: Observer<ApolloLink.Result<typeof dataOne>>[] = [];\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          return new Observable((observer) => {\n            observers.push(observer);\n          });\n        }),\n      });\n      const observableQuery = client.watchQuery({\n        query,\n        variables: { id: 1 },\n      });\n      const stream = new ObservableStream(observableQuery);\n\n      void observableQuery.refetch({ id: 2 });\n\n      observers[0].next({ data: dataOne });\n      observers[0].complete();\n\n      observers[1].next({ data: dataTwo });\n      observers[1].complete();\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"calling refetch multiple times with different variables will return only results for the most recent variables\", async () => {\n      const observers: Observer<ApolloLink.Result<typeof dataOne>>[] = [];\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          return new Observable((observer) => {\n            observers.push(observer);\n          });\n        }),\n      });\n      const observableQuery = client.watchQuery({\n        query,\n        variables: { id: 1 },\n      });\n      const stream = new ObservableStream(observableQuery);\n\n      observers[0].next({ data: dataOne });\n      observers[0].complete();\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void observableQuery.refetch({ id: 2 });\n      void observableQuery.refetch({ id: 3 });\n\n      observers[1].next({ data: dataTwo });\n      observers[1].complete();\n\n      observers[2].next({\n        data: {\n          people_one: {\n            name: \"SomeOneElse\",\n          },\n        },\n      });\n      observers[2].complete();\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          people_one: {\n            name: \"SomeOneElse\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"if an ObservableQuery is unsubscribed while `refetch` is running, the promise returned by `refetch` rejects with an `AbortError`.\", async () => {\n      const observers: Observer<ApolloLink.Result<typeof dataOne>>[] = [];\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          return new Observable((observer) => {\n            observers.push(observer);\n          });\n        }),\n      });\n      const observableQuery = client.watchQuery({\n        query,\n        variables: { id: 1 },\n      });\n\n      const stream = new ObservableStream(observableQuery);\n\n      observers[0].next({ data: dataOne });\n      observers[0].complete();\n\n      const promise = observableQuery.refetch({ id: 2 });\n\n      stream.unsubscribe();\n\n      observers[1].next({ data: dataTwo });\n      observers[1].complete();\n\n      await expect(promise).rejects.toEqual(\n        new DOMException(\"The operation was aborted.\", \"AbortError\")\n      );\n    });\n\n    it(\"handles `no-cache` fetchPolicy with refetch\", async () => {\n      const mockedResponses = [\n        {\n          request: { query, variables },\n          result: { data: dataOne },\n        },\n        {\n          request: { query, variables: differentVariables },\n          result: { data: dataTwo },\n        },\n      ];\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mockedResponses),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"no-cache\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(client.extract()).toEqual({});\n\n      await expect(\n        observable.refetch(differentVariables)\n      ).resolves.toStrictEqualTyped({ data: dataTwo });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(client.extract()).toEqual({});\n\n      // Unlike network-only or cache-and-network, the no-cache\n      // FetchPolicy does not switch to cache-first after the first\n      // network request.\n      expect(observable.options.fetchPolicy).toBe(\"no-cache\");\n    });\n\n    it(\"allows refetch on cache-only query\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          { request: { query, variables }, result: { data: dataOne } },\n        ]),\n      });\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"cache-only\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      await expect(observable.refetch()).resolves.toStrictEqualTyped({\n        data: dataOne,\n      });\n\n      await expect(stream).toEmitSimilarValue({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n        }),\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns cached results after refetch when changing variables using a cache-and-network fetch policy\", async () => {\n      const query = gql`\n        query people($first: Int) {\n          allPeople(first: $first) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n      const variables1 = { first: 0 };\n\n      const data2 = { allPeople: { people: [{ name: \"Leia Skywalker\" }] } };\n      const variables2 = { first: 1 };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables: variables1 },\n            result: { data },\n            delay: 20,\n          },\n          {\n            request: { query, variables: variables2 },\n            result: { data: data2 },\n            delay: 20,\n          },\n          {\n            request: { query, variables: variables1 },\n            result: { data },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables: variables1,\n        fetchPolicy: \"cache-and-network\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.refetch(variables2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await observable.refetch(variables1);\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"resets fetchPolicy when variables change when using nextFetchPolicy\", async () => {\n      // This query and variables are copied from react-apollo\n      const queryWithVars = gql`\n        query people($first: Int) {\n          allPeople(first: $first) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const data = { allPeople: { people: [{ name: \"Luke Skywalker\" }] } };\n      const variables1 = { first: 0 };\n\n      const data2 = { allPeople: { people: [{ name: \"Leia Skywalker\" }] } };\n      const variables2 = { first: 1 };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: {\n              query: queryWithVars,\n              variables: variables1,\n            },\n            result: { data },\n            delay: 20,\n          },\n          {\n            request: {\n              query: queryWithVars,\n              variables: variables2,\n            },\n            result: { data: data2 },\n            delay: 20,\n          },\n          {\n            request: {\n              query: queryWithVars,\n              variables: variables1,\n            },\n            result: { data },\n            delay: 20,\n          },\n          {\n            request: {\n              query: queryWithVars,\n              variables: variables2,\n            },\n            result: { data: data2 },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const usedFetchPolicies: WatchQueryFetchPolicy[] = [];\n      const observable = client.watchQuery({\n        query: queryWithVars,\n        variables: variables1,\n        fetchPolicy: \"cache-and-network\",\n        nextFetchPolicy(currentFetchPolicy, info) {\n          if (info.reason === \"variables-changed\") {\n            return info.initialFetchPolicy;\n          }\n          usedFetchPolicies.push(currentFetchPolicy);\n          if (info.reason === \"after-fetch\") {\n            return \"cache-first\";\n          }\n          return currentFetchPolicy;\n        },\n      });\n\n      expect(observable.options.fetchPolicy).toBe(\"cache-and-network\");\n      expect(observable.options.initialFetchPolicy).toBe(\"cache-and-network\");\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      await observable.refetch(variables2);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      {\n        const result = await observable.reobserve({ variables: variables1 });\n\n        expect(result).toStrictEqualTyped({ data });\n        expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      await expect(stream).toEmitTypedValue({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      {\n        const result = await observable.reobserve({ variables: variables2 });\n\n        expect(result).toStrictEqualTyped({ data: data2 });\n        expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      await expect(stream).toEmitTypedValue({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n      expect(usedFetchPolicies).toEqual([\n        \"cache-and-network\",\n        \"network-only\",\n        \"cache-and-network\",\n        \"cache-and-network\",\n      ]);\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    // TODO: Revisit what this will look like when we move local resolvers to\n    // the link chain. This is not something that will work if its combined with\n    // other cached data.\n    it.failing(\n      \"cache-and-network refetch should run @client(always: true) resolvers when network request fails\",\n      async () => {\n        const query = gql`\n          query MixedQuery {\n            counter @client(always: true)\n            name\n          }\n        `;\n\n        let count = 0;\n\n        let linkObservable = of({\n          data: {\n            name: \"Ben\",\n          },\n        }).pipe(delay(20));\n\n        const intentionalNetworkFailure = new Error(\n          \"intentional network failure\"\n        );\n\n        const errorObservable: typeof linkObservable = new Observable(\n          (observer) => {\n            observer.error(intentionalNetworkFailure);\n          }\n        );\n\n        const client = new ApolloClient({\n          link: new ApolloLink(() => linkObservable),\n          cache: new InMemoryCache(),\n          localState: new LocalState({\n            resolvers: {\n              Query: {\n                counter() {\n                  return ++count;\n                },\n              },\n            },\n          }),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy: \"cache-and-network\",\n          returnPartialData: true,\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 1 },\n          dataState: \"partial\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 2, name: \"Ben\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        const oldLinkObs = linkObservable;\n        // Make the next network request fail.\n        linkObservable = errorObservable;\n\n        await expect(() => observable.refetch()).rejects.toThrow(\n          intentionalNetworkFailure\n        );\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 3, name: \"Ben\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 3, name: \"Ben\" },\n          dataState: \"complete\",\n          error: intentionalNetworkFailure,\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          partial: false,\n        });\n\n        // Switch back from errorObservable.\n        linkObservable = oldLinkObs;\n\n        const result = await observable.refetch();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            counter: 5,\n            name: \"Ben\",\n          },\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 4, name: \"Ben\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: { counter: 5, name: \"Ben\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).not.toEmitAnything();\n      }\n    );\n\n    describe(\"warnings about refetch({ variables })\", () => {\n      it(\"should warn if passed { variables } and query does not declare any variables\", async () => {\n        using _ = spyOnConsole(\"warn\");\n\n        const queryWithoutVariables = gql`\n          query QueryWithoutVariables {\n            getVars {\n              __typename\n              name\n            }\n          }\n        `;\n\n        function makeMock(...vars: string[]) {\n          const requestWithoutVariables = {\n            query: queryWithoutVariables,\n            variables: {\n              variables: vars,\n            },\n          };\n\n          const resultWithVariables = {\n            data: {\n              getVars: vars.map((name) => ({\n                __typename: \"Var\",\n                name,\n              })),\n            },\n          };\n\n          return {\n            request: requestWithoutVariables,\n            result: resultWithVariables,\n            delay: 20,\n          };\n        }\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([makeMock(\"a\", \"b\", \"c\"), makeMock(\"d\", \"e\")]),\n        });\n        const observableWithoutVariables = client.watchQuery({\n          query: queryWithoutVariables,\n          variables: { variables: [\"a\", \"b\", \"c\"] },\n        });\n\n        const stream = new ObservableStream(observableWithoutVariables);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await observableWithoutVariables.refetch({\n          variables: [\"d\", \"e\"],\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"d\" },\n              { __typename: \"Var\", name: \"e\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          [\n            \"Called refetch(%o) for query %o, which does not declare a $variables variable.\",\n            \"Did you mean to call refetch(variables) instead of refetch({ variables })?\",\n          ].join(\"\\n\"),\n          { variables: [\"d\", \"e\"] },\n          \"QueryWithoutVariables\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"should warn if passed { variables } and query does not declare $variables\", async () => {\n        using _ = spyOnConsole(\"warn\");\n\n        const queryWithVarsVar: TypedDocumentNode<\n          { getVars: Array<{ __typename: \"Var\"; name: string }> },\n          { vars: string[] }\n        > = gql`\n          query QueryWithVarsVar($vars: [String!]) {\n            getVars(variables: $vars) {\n              __typename\n              name\n            }\n          }\n        `;\n\n        function makeMock(...vars: string[]) {\n          const requestWithVarsVar = {\n            query: queryWithVarsVar,\n            variables: { vars },\n          };\n\n          const resultWithVarsVar = {\n            data: {\n              getVars: vars.map((name) => ({\n                __typename: \"Var\",\n                name,\n              })),\n            },\n          };\n\n          return {\n            request: requestWithVarsVar,\n            result: resultWithVarsVar,\n          };\n        }\n\n        const mocks = [makeMock(\"a\", \"b\", \"c\"), makeMock(\"d\", \"e\")];\n        const firstRequest = mocks[0].request;\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink(mocks, { showWarnings: false }),\n        });\n\n        const observableWithVarsVar = client.watchQuery({\n          query: firstRequest.query,\n          variables: firstRequest.variables,\n        });\n\n        const stream = new ObservableStream(observableWithVarsVar);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        // It's a common mistake to call refetch({ variables }) when you meant\n        // to call refetch(variables).\n        const promise = observableWithVarsVar.refetch({\n          // @ts-expect-error\n          variables: { vars: [\"d\", \"e\"] },\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          error: expect.objectContaining({\n            message: expect.stringMatching(\n              /No more mocked responses for the query:\\s+query QueryWithVarsVar\\(\\$vars: \\[String!\\]\\)/\n            ),\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          partial: false,\n        });\n\n        await expect(promise).rejects.toEqual(\n          expect.objectContaining({\n            message: expect.stringMatching(\n              /No more mocked responses for the query:\\s+query QueryWithVarsVar\\(\\$vars: \\[String!\\]\\)/\n            ),\n          })\n        );\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          [\n            \"Called refetch(%o) for query %o, which does not declare a $variables variable.\",\n            \"Did you mean to call refetch(variables) instead of refetch({ variables })?\",\n          ].join(\"\\n\"),\n          { variables: { vars: [\"d\", \"e\"] } },\n          \"QueryWithVarsVar\"\n        );\n\n        await expect(stream).not.toEmitAnything();\n      });\n\n      it(\"should not warn if passed { variables } and query declares $variables\", async () => {\n        using _ = spyOnConsole(\"warn\");\n\n        const queryWithVariablesVar: TypedDocumentNode<\n          { getVars: Array<{ __typename: \"Var\"; name: string }> },\n          { variables: string[] }\n        > = gql`\n          query QueryWithVariablesVar($variables: [String!]) {\n            getVars(variables: $variables) {\n              __typename\n              name\n            }\n          }\n        `;\n\n        function makeMock(...variables: string[]) {\n          const requestWithVariablesVar = {\n            query: queryWithVariablesVar,\n            variables: {\n              variables,\n            },\n          };\n\n          const resultWithVariablesVar = {\n            data: {\n              getVars: variables.map((name) => ({\n                __typename: \"Var\",\n                name,\n              })),\n            },\n          };\n\n          return {\n            request: requestWithVariablesVar,\n            result: resultWithVariablesVar,\n          };\n        }\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([makeMock(\"a\", \"b\", \"c\"), makeMock(\"d\", \"e\")]),\n        });\n\n        const observableWithVariablesVar = client.watchQuery({\n          query: queryWithVariablesVar,\n          variables: { variables: [\"a\", \"b\", \"c\"] },\n        });\n\n        const stream = new ObservableStream(observableWithVariablesVar);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"a\" },\n              { __typename: \"Var\", name: \"b\" },\n              { __typename: \"Var\", name: \"c\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await observableWithVariablesVar.refetch({ variables: [\"d\", \"e\"] });\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            getVars: [\n              { __typename: \"Var\", name: \"d\" },\n              { __typename: \"Var\", name: \"e\" },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        expect(console.warn).not.toHaveBeenCalled();\n\n        await expect(stream).not.toEmitAnything();\n      });\n    });\n  });\n\n  describe(\"currentResult\", () => {\n    it(\"returns the same value as observableQuery.next got\", async () => {\n      const queryWithFragment = gql`\n        fragment CatInfo on Cat {\n          isTabby\n          __typename\n        }\n\n        fragment DogInfo on Dog {\n          hasBrindleCoat\n          __typename\n        }\n\n        fragment PetInfo on Pet {\n          id\n          name\n          age\n          ... on Cat {\n            ...CatInfo\n            __typename\n          }\n          ... on Dog {\n            ...DogInfo\n            __typename\n          }\n          __typename\n        }\n\n        {\n          pets {\n            ...PetInfo\n            __typename\n          }\n        }\n      `;\n\n      const petData = [\n        {\n          id: 1,\n          name: \"Phoenix\",\n          age: 6,\n          isTabby: true,\n          __typename: \"Cat\",\n        },\n        {\n          id: 2,\n          name: \"Tempe\",\n          age: 3,\n          isTabby: false,\n          __typename: \"Cat\",\n        },\n        {\n          id: 3,\n          name: \"Robin\",\n          age: 10,\n          hasBrindleCoat: true,\n          __typename: \"Dog\",\n        },\n      ];\n\n      const dataOneWithTypename = {\n        pets: petData.slice(0, 2),\n      };\n\n      const dataTwoWithTypename = {\n        pets: petData.slice(0, 3),\n      };\n\n      const client = new ApolloClient({\n        link: new MockLink([\n          {\n            request: { query: queryWithFragment, variables },\n            result: { data: dataOneWithTypename },\n          },\n          {\n            request: { query: queryWithFragment, variables },\n            result: { data: dataTwoWithTypename },\n          },\n        ]),\n        cache: new InMemoryCache({\n          possibleTypes: {\n            Creature: [\"Pet\"],\n            Pet: [\"Dog\", \"Cat\"],\n          },\n        }),\n      });\n\n      const observable = client.watchQuery({\n        query: queryWithFragment,\n        variables,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOneWithTypename,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOneWithTypename,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      void observable.refetch();\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOneWithTypename,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOneWithTypename,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwoWithTypename,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        dataState: \"complete\",\n        data: dataTwoWithTypename,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns results from the store immediately\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n            delay: 20,\n          },\n        ]),\n      });\n\n      client.writeQuery({ query, variables, data: dataOne });\n\n      const observable = client.watchQuery({ query, variables });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns errors from the store immediately\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { errors: [error] },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n    });\n\n    it(\"returns referentially equal errors\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { errors: [error] },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({ query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      const currentResult = observable.getCurrentResult();\n      const currentResult2 = observable.getCurrentResult();\n\n      expect(currentResult).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(currentResult.error === currentResult2.error).toBe(true);\n    });\n\n    it(\"returns errors with data if errorPolicy is all\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne, errors: [error] },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        errorPolicy: \"all\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({ data: dataOne, errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({ data: dataOne, errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: false,\n      });\n    });\n\n    it(\"errors out if errorPolicy is none\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne, errors: [error] },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        errorPolicy: \"none\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: wrappedError,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(observable.getCurrentResult().error).toEqual(wrappedError);\n    });\n\n    it(\"errors out if errorPolicy is none and the observable has completed\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne, errors: [error] },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        errorPolicy: \"none\",\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ data: dataOne, errors: [error] }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: wrappedError,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toMatchObject({\n        data: undefined,\n        error: wrappedError,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n    });\n\n    it(\"ignores errors with data if errorPolicy is ignore\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { errors: [error], data: dataOne },\n            delay: 20,\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        errorPolicy: \"ignore\",\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n    });\n\n    it(\"returns partial data from the store immediately\", async () => {\n      const superQuery = gql`\n        query superQuery($id: ID!) {\n          people_one(id: $id) {\n            name\n            age\n          }\n        }\n      `;\n\n      const superDataOne = {\n        people_one: {\n          name: \"Luke Skywalker\",\n          age: 21,\n        },\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query: superQuery, variables },\n            result: { data: superDataOne },\n            delay: 20,\n          },\n        ]),\n      });\n\n      client.writeQuery({ query, variables, data: dataOne });\n\n      const observable = client.watchQuery({\n        query: superQuery,\n        variables,\n        returnPartialData: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: dataOne,\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataOne,\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: superDataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: superDataOne,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns loading even if full data is available when using network-only fetchPolicy\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n\n      client.writeQuery({ query, variables, data: dataOne });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"network-only\",\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns loading on no-cache fetchPolicy queries when calling getCurrentResult\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataTwo },\n            delay: 20,\n          },\n        ]),\n      });\n\n      client.writeQuery({ query, variables, data: dataOne });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"no-cache\",\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: dataTwo,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(client.readQuery({ query, variables })).toStrictEqualTyped(\n        dataOne\n      );\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns loading: false on cache-only queries when calling getCurrentResult with no data in the cache\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"cache-only\",\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns loading: false on cache-only queries with returnPartialData: true when calling getCurrentResult with partial data in the cache\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"cache-only\",\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"returns loading: false on cache-only queries when calling getCurrentResult with data in the cache\", async () => {\n      const query = gql`\n        query {\n          user {\n            id\n            name\n          }\n        }\n      `;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: ApolloLink.empty(),\n      });\n\n      client.writeQuery({\n        query: gql`\n          query {\n            user {\n              id\n            }\n          }\n        `,\n        variables,\n        data: { user: { __typename: \"User\", id: \"1\" } },\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n        fetchPolicy: \"cache-only\",\n        returnPartialData: true,\n      });\n\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: \"1\" } },\n        dataState: \"partial\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({\n        data: { user: { __typename: \"User\", id: \"1\" } },\n        dataState: \"partial\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n      expect(observable.getCurrentResult()).toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: \"1\" } },\n        dataState: \"partial\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: true,\n      });\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    it(\"handles multiple calls to getCurrentResult without losing data\", async () => {\n      const query = gql`\n        {\n          greeting {\n            message\n            ... on Greeting @defer {\n              recipient {\n                name\n              }\n            }\n          }\n        }\n      `;\n\n      const link = new MockSubscriptionLink();\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n        incrementalHandler: new Defer20220824Handler(),\n      });\n\n      const obs = client.watchQuery({ query });\n      const stream = new ObservableStream(obs);\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n\n      link.simulateResult({\n        result: {\n          data: {\n            greeting: {\n              message: \"Hello world\",\n              __typename: \"Greeting\",\n            },\n          },\n          hasNext: true,\n        },\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: markAsStreaming({\n          greeting: {\n            message: \"Hello world\",\n            __typename: \"Greeting\",\n          },\n        }),\n        dataState: \"streaming\",\n        loading: true,\n        networkStatus: NetworkStatus.streaming,\n        partial: true,\n      });\n\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n\n      link.simulateResult(\n        {\n          result: {\n            incremental: [\n              {\n                data: {\n                  recipient: {\n                    name: \"Alice\",\n                    __typename: \"Person\",\n                  },\n                  __typename: \"Greeting\",\n                },\n                path: [\"greeting\"],\n              },\n            ],\n            hasNext: false,\n          },\n        },\n        true\n      );\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          greeting: {\n            message: \"Hello world\",\n            recipient: {\n              name: \"Alice\",\n              __typename: \"Person\",\n            },\n            __typename: \"Greeting\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n      // This 2nd identical check is intentional to ensure calling this function\n      // more than once returns the right value.\n      expect(obs.getCurrentResult()).toBe(stream.getCurrent());\n\n      await expect(stream).not.toEmitAnything();\n    });\n\n    {\n      type Result =\n        // wait for the emit of a new value\n        | { emit: ObservableQuery.Result<{ hello: string }> }\n        // don't expect an emit, but `currentResult` should change\n        | { currentResult: ObservableQuery.Result<{ hello: string }> }\n        // `currentResult` should stay the same\n        | undefined;\n\n      const cacheValues = {\n        initial: { hello: \"world (initial)\" },\n        link: { hello: \"world (from link)\" },\n        refetch: { hello: \"world (from link again)\" },\n        update1: { hello: \"world (from cache again, 1)\" },\n        update2: { hello: \"world (from cache again, 2)\" },\n        update3: { hello: \"world (from cache again, 3)\" },\n        update4: { hello: \"world (from cache again, 4)\" },\n      } as const;\n\n      const loadingStates = {\n        loading: {\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n        },\n        done: {\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n        },\n        refetching: {\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n        },\n      } as const;\n\n      type TestDetails = {\n        // writeCache: cacheValues.initial\n        resultBeforeSubscribe: Exclude<Result, { emit: any }>;\n        // observableQuery.subscribe\n        resultAfterSubscribe: Result;\n        // writeCache:  cacheValues.update1\n        resultAfterCacheUpdate1: Result;\n        // incoming result: cacheValues.link\n        resultAfterLinkNext: Result;\n        // writeCache:  cacheValues.update2\n        resultAfterCacheUpdate2: Result;\n        // observableQuery.refetch\n        resultAfterRefetchCall: Result;\n        // writeCache:  cacheValues.update3\n        resultAfterCacheUpdate3: Result;\n        // incoming result:  cacheValues.refetch\n        resultAfterRefetchNext: Result;\n        // writeCache:  cacheValues.update4\n        resultAfterCacheUpdate4: Result;\n      };\n\n      it.each<\n        [\n          initialFetchPolicy: WatchQueryFetchPolicy,\n          nextFetchPolicy: WatchQueryFetchPolicy,\n          notifyOnNetworkStatusChange: boolean,\n          testDetails: TestDetails,\n        ]\n      >([\n        [\n          \"cache-and-network\",\n          \"cache-and-network\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.loading,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.loading,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-and-network\",\n          \"cache-and-network\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.loading,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.loading,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-first\",\n          \"cache-first\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-first\",\n          \"cache-first\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-first\",\n          \"cache-and-network\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-first\",\n          \"cache-and-network\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"no-cache\",\n          \"no-cache\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"no-cache\",\n          \"no-cache\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"no-cache\",\n          \"cache-and-network\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"no-cache\",\n          \"cache-and-network\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.loading,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.link,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"standby\",\n          \"standby\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              // TODO: this seems to be wrong behavior\n              currentResult: {\n                ...loadingStates.refetching,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"standby\",\n          \"standby\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              // TODO: this seems to be wrong behavior\n              currentResult: {\n                ...loadingStates.refetching,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"standby\",\n          \"cache-and-network\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              // TODO: this seems to be wrong behavior\n              currentResult: {\n                ...loadingStates.refetching,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"standby\",\n          \"cache-and-network\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate1: undefined,\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: undefined,\n            resultAfterRefetchCall: {\n              // TODO: this seems to be wrong behavior\n              currentResult: {\n                ...loadingStates.refetching,\n                data: undefined,\n                dataState: \"empty\",\n                partial: true,\n              },\n            },\n            resultAfterCacheUpdate3: undefined,\n            resultAfterRefetchNext: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: undefined,\n          },\n        ],\n        [\n          \"cache-only\",\n          \"cache-only\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-only\",\n          \"cache-only\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-only\",\n          \"cache-and-network\",\n          true,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n        [\n          \"cache-only\",\n          \"cache-and-network\",\n          false,\n          {\n            resultBeforeSubscribe: {\n              currentResult: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterSubscribe: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.initial,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate1: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update1,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterLinkNext: undefined,\n            resultAfterCacheUpdate2: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchCall: {\n              currentResult: {\n                ...loadingStates.refetching,\n                data: cacheValues.update2,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate3: {\n              emit: {\n                ...loadingStates.refetching,\n                data: cacheValues.update3,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterRefetchNext: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.refetch,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n            resultAfterCacheUpdate4: {\n              emit: {\n                ...loadingStates.done,\n                data: cacheValues.update4,\n                dataState: \"complete\",\n                partial: false,\n              },\n            },\n          },\n        ],\n      ])(\n        \"fetchPolicy %s -> %s (notifyOnNetworkStatusChange %s)\",\n        async (\n          fetchPolicy,\n          nextFetchPolicy,\n          notifyOnNetworkStatusChange,\n          {\n            resultBeforeSubscribe,\n            resultAfterSubscribe,\n            resultAfterCacheUpdate1,\n            resultAfterLinkNext,\n            resultAfterCacheUpdate2,\n            resultAfterRefetchCall,\n            resultAfterCacheUpdate3,\n            resultAfterRefetchNext,\n            resultAfterCacheUpdate4,\n          }\n        ) => {\n          const query = gql`\n            {\n              hello\n            }\n          `;\n          let subject = new Subject<ApolloLink.Result>();\n          const link = new ApolloLink(() => subject);\n          const cache = new InMemoryCache({});\n          cache.writeQuery({ query, data: cacheValues.initial });\n\n          const client = new ApolloClient({ link, cache });\n          const observableQuery = client.watchQuery({\n            query,\n            fetchPolicy,\n            nextFetchPolicy,\n            notifyOnNetworkStatusChange,\n          });\n\n          let lastCurrentResult = observableQuery.getCurrentResult();\n          async function check(result: Result, expectedName: string) {\n            if (!result) {\n              expect(observableQuery.getCurrentResult()).toStrictEqualTyped(\n                lastCurrentResult,\n                {\n                  received: \"observableQuery.getCurrentResult()\",\n                  expected: expectedName,\n                  hintOptions: {\n                    comment: \"should not change from previous comparison\",\n                  },\n                }\n              );\n            } else if (\"emit\" in result) {\n              await expect(stream).toEmitTypedValue(result.emit, {\n                expected: expectedName,\n              });\n              expect(observableQuery.getCurrentResult()).toStrictEqualTyped(\n                result.emit,\n                {\n                  expected: expectedName,\n                  received: \"observableQuery.getCurrentResult()\",\n                  hintOptions: {\n                    comment:\n                      \"observableQuery.getCurrentResult() should equal emitted value immediately after emit\",\n                  },\n                }\n              );\n            } else {\n              await waitFor(() => {\n                expect(observableQuery.getCurrentResult()).toStrictEqualTyped(\n                  result.currentResult,\n                  {\n                    expected: expectedName,\n                    received: \"observableQuery.getCurrentResult()\",\n                    hintOptions: {\n                      comment:\n                        \"waiting for `getCurrentResult` to change to expected value\",\n                    },\n                  }\n                );\n              });\n            }\n            lastCurrentResult = observableQuery.getCurrentResult();\n          }\n\n          await check(resultBeforeSubscribe, \"resultBeforeSubscribe\");\n\n          const stream = new ObservableStream(observableQuery);\n          await check(resultAfterSubscribe, \"resultAfterSubscribe\");\n\n          cache.writeQuery({ query, data: cacheValues.update1 });\n\n          await check(resultAfterCacheUpdate1, \"resultAfterCacheUpdate1\");\n\n          setTimeout(() => {\n            subject.next({ data: cacheValues.link });\n            subject.complete();\n          });\n          await check(resultAfterLinkNext, \"resultAfterLinkNext\");\n\n          cache.writeQuery({ query, data: cacheValues.update2 });\n          await check(resultAfterCacheUpdate2, \"resultAfterCacheUpdate2\");\n\n          await lastValueFrom(subject, { defaultValue: undefined });\n          subject = new Subject();\n          void observableQuery.refetch().catch(() => {});\n          await check(resultAfterRefetchCall, \"resultAfterRefetchCall\");\n\n          cache.writeQuery({ query, data: cacheValues.update3 });\n\n          await check(resultAfterCacheUpdate3, \"resultAfterCacheUpdate3\");\n\n          setTimeout(() => {\n            subject.next({ data: cacheValues.refetch });\n            subject.complete();\n          });\n          await check(resultAfterRefetchNext, \"resultAfterRefetchNext\");\n\n          cache.writeQuery({ query, data: cacheValues.update4 });\n          await check(resultAfterCacheUpdate4, \"resultAfterCacheUpdate4\");\n\n          await expect(stream).not.toEmitAnything();\n        }\n      );\n    }\n\n    describe(\"mutations\", () => {\n      const mutation = gql`\n        mutation setName {\n          name\n        }\n      `;\n\n      const mutationData = {\n        name: \"Leia Skywalker\",\n      };\n\n      const optimisticResponse = {\n        name: \"Leia Skywalker (optimistic)\",\n      };\n\n      const updateQueries = {\n        query: (_: any, { mutationResult }: any) => {\n          return {\n            people_one: { name: mutationResult.data.name },\n          };\n        },\n      };\n\n      it(\"returns optimistic mutation results from the store\", async () => {\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([\n            {\n              request: { query, variables },\n              result: { data: dataOne },\n            },\n            {\n              request: { query: mutation },\n              result: { data: mutationData },\n            },\n          ]),\n        });\n\n        const observable = client.watchQuery({\n          query,\n          variables,\n        });\n\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n        expect(observable.getCurrentResult()).toStrictEqualTyped({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        void client.mutate({\n          mutation,\n          optimisticResponse,\n          updateQueries,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            people_one: optimisticResponse,\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n        expect(observable.getCurrentResult()).toStrictEqualTyped({\n          data: {\n            people_one: optimisticResponse,\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).toEmitTypedValue({\n          data: {\n            people_one: mutationData,\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n        expect(observable.getCurrentResult()).toStrictEqualTyped({\n          data: {\n            people_one: mutationData,\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n\n        await expect(stream).not.toEmitAnything();\n      });\n    });\n  });\n\n  describe(\"prioritizeCacheValues interaction with fetchPolicy\", () => {\n    it.each([\n      // `standby` should never show a loading state or cause network requests\n      {\n        fetchPolicy: \"standby\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        },\n        expectedEmits: [],\n        expectedFetchCount: 0,\n      },\n      {\n        fetchPolicy: \"standby\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        },\n        expectedEmits: [],\n        expectedFetchCount: 0,\n      },\n      // `network-only` should return a loading result and make a network request\n      // if values are missing from cache, but if cache values are present,\n      // during `prioritizeCacheValues` it is actually allowed to immediately\n      // read from the cache and avoid a network request\n      {\n        fetchPolicy: \"network-only\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: { field: \"network\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"network-only\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: { field: \"cached\" },\n          dataState: \"complete\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        expectedEmits: [\n          {\n            data: { field: \"cached\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // cache-only should never cause network requests\n      {\n        fetchPolicy: \"cache-only\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: true,\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      {\n        fetchPolicy: \"cache-only\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: { field: \"cached\" },\n          dataState: \"complete\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        expectedEmits: [\n          {\n            data: { field: \"cached\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // cache-first is the default behavior with `prioritizeCacheValues`\n      {\n        fetchPolicy: \"cache-first\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: { field: \"network\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"cache-first\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: { field: \"cached\" },\n          dataState: \"complete\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        expectedEmits: [\n          {\n            data: { field: \"cached\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // no-cache should always fetch and never read from the cache\n      {\n        fetchPolicy: \"no-cache\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: { field: \"network\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"no-cache\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: { field: \"network\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      // cache-and-network should avoid fetching if cache is populated\n      {\n        fetchPolicy: \"cache-and-network\" as const,\n        populateCache: false,\n        expectedInitialCurrentResult: {\n          data: undefined,\n          dataState: \"empty\" as const,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          partial: true,\n        },\n        expectedEmits: [\n          {\n            data: undefined,\n            dataState: \"empty\" as const,\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            partial: true,\n          },\n          {\n            data: { field: \"network\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"cache-and-network\" as const,\n        populateCache: true,\n        expectedInitialCurrentResult: {\n          data: { field: \"cached\" },\n          dataState: \"complete\" as const,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        },\n        expectedEmits: [\n          {\n            data: { field: \"cached\" },\n            dataState: \"complete\" as const,\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            partial: false,\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n    ])(\n      \"fetchPolicy: '$fetchPolicy' with prioritizeCacheValues (cache populated: $populateCache)\",\n      async ({\n        populateCache,\n        fetchPolicy,\n        expectedInitialCurrentResult,\n        expectedEmits,\n        expectedFetchCount,\n      }) => {\n        const query = gql`\n          {\n            field\n          }\n        `;\n        const link = new MockLink([\n          { request: { query }, result: { data: { field: \"network\" } } },\n        ]);\n        const linkSpy = jest.spyOn(link, \"request\");\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link,\n        });\n\n        if (populateCache) {\n          client.writeQuery({ query, data: { field: \"cached\" } });\n        }\n\n        client.prioritizeCacheValues = true;\n\n        const observable = client.watchQuery({\n          query,\n          fetchPolicy,\n        });\n\n        const result = observable.getCurrentResult();\n        expect(result).toStrictEqualTyped(expectedInitialCurrentResult);\n\n        const stream = new ObservableStream(observable);\n\n        for (const expectedEmit of expectedEmits) {\n          await expect(stream).toEmitTypedValue(expectedEmit);\n        }\n\n        await expect(stream).not.toEmitAnything();\n\n        // Check whether network request was made based on expected behavior\n        expect(linkSpy).toHaveBeenCalledTimes(expectedFetchCount);\n      }\n    );\n  });\n\n  describe(\"assumeImmutableResults\", () => {\n    // Need to handle loading state or notifyOnNetworkStatusChange: false\n    // properly\n    it.skip(\"should prevent costly (but safe) cloneDeep calls\", async () => {\n      const queryOptions = {\n        query: gql`\n          query {\n            value\n          }\n        `,\n        pollInterval: 20,\n      };\n\n      function check({\n        assumeImmutableResults = true,\n        assertFrozenResults = false,\n      }) {\n        const cache = new InMemoryCache();\n        const client = new ApolloClient({\n          link: new MockLink([\n            { request: queryOptions, result: { data: { value: 1 } } },\n            { request: queryOptions, result: { data: { value: 2 } } },\n            { request: queryOptions, result: { data: { value: 3 } } },\n          ]),\n          assumeImmutableResults,\n          cache,\n        });\n\n        const observable = client.watchQuery<any>(queryOptions);\n        const values: any[] = [];\n\n        return new Promise<any[]>((resolve, reject) => {\n          observable.subscribe({\n            next({ data }) {\n              values.push(data.value);\n              if (assertFrozenResults) {\n                try {\n                  data.value = \"oyez\";\n                } catch (error) {\n                  observable.stopPolling();\n                  reject(error);\n                }\n              } else {\n                data = {\n                  ...data,\n                  value: \"oyez\",\n                };\n              }\n              client.writeQuery({\n                query: queryOptions.query,\n                data,\n              });\n            },\n            error(err) {\n              expect(err.message).toMatch(/No more mocked responses/);\n              resolve(values);\n            },\n          });\n        });\n      }\n\n      async function checkThrows(assumeImmutableResults: boolean) {\n        try {\n          await check({\n            assumeImmutableResults,\n            // No matter what value we provide for assumeImmutableResults, if we\n            // tell the InMemoryCache to deep-freeze its results, destructive\n            // modifications of the result objects will become fatal. Once you\n            // start enforcing immutability in this way, you might as well pass\n            // assumeImmutableResults: true, to prevent calling cloneDeep.\n            assertFrozenResults: true,\n          });\n          throw new Error(\"not reached\");\n        } catch (error) {\n          expect(error).toBeInstanceOf(TypeError);\n          expect((error as Error).message).toMatch(\n            /Cannot assign to read only property 'value'/\n          );\n        }\n      }\n      await checkThrows(true);\n      await checkThrows(false);\n    });\n  });\n\n  describe(\".query computed property\", () => {\n    it(\"is equal to transformed query when instantiating via `watchQuery`\", () => {\n      const query = gql`\n        query {\n          currentUser {\n            id\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      const observable = client.watchQuery({ query });\n\n      expect(observable.query).toMatchDocument(gql`\n        query {\n          currentUser {\n            id\n            __typename\n          }\n        }\n      `);\n    });\n\n    it(\"is referentially stable\", () => {\n      const query = gql`\n        query {\n          currentUser {\n            id\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      const observable = client.watchQuery({ query });\n      const result = observable.query;\n\n      expect(observable.query).toBe(result);\n    });\n\n    it(\"is updated with transformed query when `reobserve` changes the query\", async () => {\n      const query = gql`\n        query {\n          currentUser {\n            id\n          }\n        }\n      `;\n\n      const updatedQuery = gql`\n        query {\n          product {\n            id\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: new ApolloLink(() => of({ data: {} })),\n        cache: new InMemoryCache(),\n      });\n\n      // Don't write results to the cache to prevent cache write warnings on\n      // missing data\n      const observable = client.watchQuery({ query, fetchPolicy: \"no-cache\" });\n\n      expect(observable.query).toMatchDocument(gql`\n        query {\n          currentUser {\n            id\n            __typename\n          }\n        }\n      `);\n\n      await observable.reobserve({ query: updatedQuery });\n\n      expect(observable.query).toMatchDocument(gql`\n        query {\n          product {\n            id\n            __typename\n          }\n        }\n      `);\n    });\n\n    it(\"reflects query run through custom transforms\", () => {\n      const query = gql`\n        query {\n          currentUser {\n            id\n            name @client\n          }\n        }\n      `;\n\n      const documentTransform = new DocumentTransform((document) => {\n        return removeDirectivesFromDocument([{ name: \"client\" }], document)!;\n      });\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        documentTransform,\n      });\n\n      const observable = client.watchQuery({ query });\n\n      expect(observable.query).toMatchDocument(gql`\n        query {\n          currentUser {\n            id\n            name\n            __typename\n          }\n        }\n      `);\n    });\n  });\n\n  describe(\"updateQuery\", () => {\n    it(\"should be able to determine if the previous result is complete\", async () => {\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink([\n          {\n            request: { query, variables },\n            result: { data: dataOne },\n          },\n        ]),\n      });\n\n      const observable = client.watchQuery({\n        query,\n        variables,\n      });\n\n      let updateQuerySpy = jest.fn();\n      observable.updateQuery((previous, { complete, previousData }) => {\n        updateQuerySpy();\n        expect(previous).toEqual(null);\n        expect(complete).toBe(false);\n        expect(previousData).toStrictEqual(previous);\n\n        if (complete) {\n          expectTypeOf(previousData).toEqualTypeOf<typeof dataOne>();\n        } else {\n          expectTypeOf(previousData).toEqualTypeOf<\n            DeepPartial<typeof previous> | undefined\n          >();\n        }\n      });\n\n      observable.subscribe(jest.fn());\n\n      await waitFor(() => {\n        expect(observable.getCurrentResult()).toStrictEqualTyped({\n          data: dataOne,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          partial: false,\n        });\n      });\n\n      observable.updateQuery((previous, { complete, previousData }) => {\n        updateQuerySpy();\n        expect(previous).toEqual(dataOne);\n        expect(complete).toBe(true);\n        expect(previousData).toStrictEqual(previous);\n\n        if (complete) {\n          expectTypeOf(previousData).toEqualTypeOf<typeof dataOne>();\n        } else {\n          expectTypeOf(previousData).toEqualTypeOf<\n            DeepPartial<typeof previous> | undefined\n          >();\n        }\n      });\n\n      expect(updateQuerySpy).toHaveBeenCalledTimes(2);\n    });\n  });\n\n  it(\"QueryInfo does not notify for !== but deep-equal results\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query, variables },\n          result: { data: dataOne },\n        },\n      ]),\n    });\n\n    const observable = client.watchQuery({ query, variables });\n\n    const cache = client.cache;\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: dataOne,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    let invalidateCount = 0;\n    let onWatchUpdatedCount = 0;\n\n    cache.batch({\n      optimistic: true,\n      update(cache) {\n        cache.modify({\n          fields: {\n            people_one(value, { INVALIDATE }) {\n              expect(value).toEqual(dataOne.people_one);\n              ++invalidateCount;\n              return INVALIDATE;\n            },\n          },\n        });\n      },\n      // Verify that the cache.modify operation did trigger a cache broadcast.\n      onWatchUpdated(watch, diff) {\n        expect(watch.watcher).toBe(observable);\n        expect(diff).toEqual({\n          complete: true,\n          result: {\n            people_one: {\n              name: \"Luke Skywalker\",\n            },\n          },\n        });\n        ++onWatchUpdatedCount;\n      },\n    });\n\n    await wait(100);\n\n    expect(invalidateCount).toBe(1);\n    expect(onWatchUpdatedCount).toBe(1);\n    client.stop();\n\n    await expect(stream).toComplete();\n  });\n});\n\ntest(\"regression test for #10587\", async () => {\n  let observers: Record<string, Observer<ApolloLink.Result>> = {};\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      observers[operation.operationName!] = observer;\n    });\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        SchemaType: {\n          merge: true,\n        },\n      },\n    }).restore({\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        schemaType: { __typename: \"SchemaType\", a: \"\", b: \"\" },\n      },\n    }),\n    defaultOptions: {\n      watchQuery: {\n        fetchPolicy: \"cache-and-network\",\n        nextFetchPolicy: \"cache-and-network\",\n      },\n    },\n    link,\n  });\n\n  const query1 = client.watchQuery({\n    query: gql`\n      query query1 {\n        schemaType {\n          a\n        }\n      }\n    `,\n  });\n  const query2 = client.watchQuery({\n    query: gql`\n      query query2 {\n        schemaType {\n          a\n          b\n        }\n      }\n    `,\n  });\n  const query1Spy = jest.fn();\n  const query2Spy = jest.fn();\n\n  query1.subscribe(query1Spy);\n  query2.subscribe(query2Spy);\n\n  const finalExpectedCalls = {\n    query1: [\n      [\n        {\n          data: {\n            schemaType: {\n              __typename: \"SchemaType\",\n              a: \"\",\n            },\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: 1,\n          partial: false,\n        },\n      ],\n      [\n        {\n          data: {\n            schemaType: {\n              __typename: \"SchemaType\",\n              a: \"a\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: 7,\n          partial: false,\n        },\n      ],\n    ],\n    query2: [\n      [\n        {\n          data: {\n            schemaType: {\n              __typename: \"SchemaType\",\n              a: \"\",\n              b: \"\",\n            },\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: 1,\n          partial: false,\n        },\n      ],\n      [\n        {\n          data: {\n            schemaType: {\n              __typename: \"SchemaType\",\n              a: \"a\",\n              b: \"\",\n            },\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: 1,\n          partial: false,\n        },\n      ],\n      [\n        {\n          data: {\n            schemaType: {\n              __typename: \"SchemaType\",\n              a: \"a\",\n              b: \"b\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: 7,\n          partial: false,\n        },\n      ],\n    ],\n  } as const;\n\n  await waitFor(() =>\n    expect(query1Spy.mock.calls).toEqual(finalExpectedCalls.query1.slice(0, 1))\n  );\n  expect(query2Spy.mock.calls).toEqual(finalExpectedCalls.query2.slice(0, 1));\n\n  observers.query1.next({\n    data: { schemaType: { __typename: \"SchemaType\", a: \"a\" } },\n  });\n  observers.query1.complete();\n\n  await waitFor(() => {\n    expect(query1Spy.mock.calls).toEqual(finalExpectedCalls.query1);\n  });\n  expect(query2Spy.mock.calls).toEqual(finalExpectedCalls.query2.slice(0, 2));\n\n  observers.query2.next({\n    data: { schemaType: { __typename: \"SchemaType\", a: \"a\", b: \"b\" } },\n  });\n  observers.query2.complete();\n\n  await waitFor(() =>\n    expect(query2Spy.mock.calls).toEqual(finalExpectedCalls.query2)\n  );\n  expect(query1Spy.mock.calls).toEqual(finalExpectedCalls.query1);\n});\n\n// https://github.com/apollographql/apollo-client/issues/11184\ntest(\"handles changing variables in rapid succession before other request is completed\", async () => {\n  interface UserCountQuery {\n    userCount: number;\n  }\n  interface UserCountVariables {\n    department: \"HR\" | null;\n  }\n\n  const query: TypedDocumentNode<UserCountQuery, UserCountVariables> = gql`\n    query UserCountQuery($department: Department) {\n      userCount(department: $department)\n    }\n  `;\n  const mocks = [\n    {\n      request: { query, variables: { department: null } },\n      result: { data: { userCount: 10 } },\n    },\n    {\n      request: { query, variables: { department: \"HR\" } },\n      result: { data: { userCount: 5 } },\n      delay: 50,\n    },\n  ];\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery<UserCountQuery, UserCountVariables>({\n    query,\n    variables: { department: null },\n  });\n\n  observable.subscribe(jest.fn());\n\n  await waitFor(() => {\n    expect(observable.getCurrentResult()).toStrictEqualTyped({\n      data: { userCount: 10 },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n  });\n\n  void observable.reobserve({ variables: { department: \"HR\" } });\n  await wait(10);\n  void observable.reobserve({ variables: { department: null } });\n\n  // Wait for request to finish\n  await wait(50);\n\n  expect(observable.options.variables).toEqual({ department: null });\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { userCount: 10 },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"works with `from`\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const data = {\n    hello: \"world\",\n  };\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data },\n    },\n  ]);\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n  const observableQuery = client.watchQuery({\n    query,\n  });\n\n  const observable = from(observableQuery);\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"does not emit initial loading state with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const data = { hello: \"world\" };\n\n  const client = new ApolloClient({\n    link: new MockLink([{ request: { query }, result: { data } }]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit initial loading state using network-only fetch policy with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const data = { hello: \"world\" };\n\n  const client = new ApolloClient({\n    link: new MockLink([{ request: { query }, result: { data } }]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n    fetchPolicy: \"network-only\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit initial loading state using cache-and-network fetch policy with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const data = { hello: \"world\" };\n\n  const client = new ApolloClient({\n    link: new MockLink([{ request: { query }, result: { data } }]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n    fetchPolicy: \"cache-and-network\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"emits initial loading state using cache-and-network fetch policy with initial cached data with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: new MockLink([\n      { request: { query }, result: { data: { hello: \"world\" } }, delay: 20 },\n    ]),\n    cache: new InMemoryCache(),\n  });\n\n  client.writeQuery({ query, data: { hello: \"world (cached)\" } });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n    fetchPolicy: \"cache-and-network\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { hello: \"world (cached)\" },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { hello: \"world\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit initial loading state using no-cache fetch policy with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const data = { hello: \"world\" };\n\n  const client = new ApolloClient({\n    link: new MockLink([{ request: { query }, result: { data } }]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n    fetchPolicy: \"no-cache\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on refetch with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: new MockLink([\n      { request: { query }, result: { data: { hello: \"world\" } }, delay: 20 },\n      { request: { query }, result: { data: { hello: \"world 2\" } }, delay: 20 },\n    ]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { hello: \"world\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(observable.refetch()).resolves.toStrictEqualTyped({\n    data: { hello: \"world 2\" },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { hello: \"world 2\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on refetch with new variables with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query ($recipient: String!) {\n      greeting(recipient: $recipient)\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { greeting: `Hello, ${operation.variables.recipient}` },\n          });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { recipient: \"Test\" },\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(\n    observable.refetch({ recipient: \"Test 2\" })\n  ).resolves.toStrictEqualTyped({ data: { greeting: \"Hello, Test 2\" } });\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test 2\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on setVariables with notifyOnNetworkStatusChange: false\", async () => {\n  const query: TypedDocumentNode<{ greeting: string }, { recipient: string }> =\n    gql`\n      query ($recipient: String!) {\n        greeting(recipient: $recipient)\n      }\n    `;\n\n  const client = new ApolloClient({\n    link: new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { greeting: `Hello, ${operation.variables.recipient}` },\n          });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { recipient: \"Test\" },\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(\n    observable.setVariables({ recipient: \"Test 2\" })\n  ).resolves.toStrictEqualTyped({ data: { greeting: \"Hello, Test 2\" } });\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test 2\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on reobserve with notifyOnNetworkStatusChange: false\", async () => {\n  const query: TypedDocumentNode<{ greeting: string }, { recipient: string }> =\n    gql`\n      query ($recipient: String!) {\n        greeting(recipient: $recipient)\n      }\n    `;\n\n  const client = new ApolloClient({\n    link: new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { greeting: `Hello, ${operation.variables.recipient}` },\n          });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { recipient: \"Test\" },\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(\n    observable.reobserve({ variables: { recipient: \"Test 2\" } })\n  ).resolves.toStrictEqualTyped({ data: { greeting: \"Hello, Test 2\" } });\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"Hello, Test 2\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on fetchMore with notifyOnNetworkStatusChange: false\", async () => {\n  const query: TypedDocumentNode<\n    { comments: Array<{ __typename: \"Comment\"; id: number }> },\n    { limit: number; offset: number }\n  > = gql`\n    query ($limit: Int!, $offset: Int!) {\n      comments(limit: $limit, offset: $offset) {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: new MockLink([\n      {\n        request: { query, variables: { offset: 0, limit: 2 } },\n        result: {\n          data: {\n            comments: [\n              { __typename: \"Comment\", id: 1 },\n              { __typename: \"Comment\", id: 2 },\n            ],\n          },\n        },\n      },\n      {\n        request: { query, variables: { offset: 2, limit: 2 } },\n        result: {\n          data: {\n            comments: [\n              { __typename: \"Comment\", id: 3 },\n              { __typename: \"Comment\", id: 4 },\n            ],\n          },\n        },\n      },\n    ]),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { offset: 0, limit: 2 },\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      comments: [\n        { __typename: \"Comment\", id: 1 },\n        { __typename: \"Comment\", id: 2 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(\n    observable.fetchMore({\n      variables: { offset: 2, limit: 2 },\n      updateQuery: (_, { fetchMoreResult }) => fetchMoreResult,\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      comments: [\n        { __typename: \"Comment\", id: 3 },\n        { __typename: \"Comment\", id: 4 },\n      ],\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      comments: [\n        { __typename: \"Comment\", id: 3 },\n        { __typename: \"Comment\", id: 4 },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest.each([\"cache-first\", \"network-only\"] as const)(\n  \"`fetchMore` with `fetchPolicy` `%s` will leave `loading` even if a result doesn't trigger cache change\",\n  async (fetchPolicy) => {\n    const query: TypedDocumentNode<\n      {\n        items: {\n          __typename: \"ItemConnection\";\n          edges: {\n            __typename: \"ItemEdge\";\n            cursor: string;\n            node: { __typename: \"Item\"; id: string; attributes: string[] };\n          }[];\n          pageInfo: {\n            __typename: \"PageInfo\";\n            hasNextPage: boolean;\n            endCursor: string | null;\n          };\n        };\n      },\n      {\n        first?: number;\n        after?: string;\n      }\n    > = gql`\n      query Items($first: Int, $after: String) {\n        items(first: $first, after: $after) {\n          edges {\n            cursor\n            node {\n              id\n              attributes\n            }\n          }\n          pageInfo {\n            hasNextPage\n            endCursor\n          }\n        }\n      }\n    `;\n    const firstResult: ResultOf<typeof query> = {\n      items: {\n        edges: [\n          {\n            cursor: \"YXJyYXljb25uZWN0aW9uOjA=\",\n            node: {\n              id: \"0\",\n              attributes: [\"data\"],\n              __typename: \"Item\",\n            },\n            __typename: \"ItemEdge\",\n          },\n          {\n            cursor: \"YXJyYXljb25uZWN0aW9uOjk=\",\n            node: {\n              id: \"9\",\n              attributes: [\"data\"],\n              __typename: \"Item\",\n            },\n            __typename: \"ItemEdge\",\n          },\n        ],\n        pageInfo: {\n          hasNextPage: false,\n          endCursor: \"YXJyYXljb25uZWN0aW9uOjk=\",\n          __typename: \"PageInfo\",\n        },\n        __typename: \"ItemConnection\",\n      },\n    };\n\n    const secondResult: ResultOf<typeof query> = {\n      items: {\n        edges: [],\n        pageInfo: {\n          hasNextPage: false,\n          endCursor: null,\n          __typename: \"PageInfo\",\n        },\n        __typename: \"ItemConnection\",\n      },\n    };\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query, variables: { first: 2 } },\n          result: {\n            data: firstResult,\n          },\n        },\n        {\n          request: {\n            query,\n            variables: {\n              first: 10,\n              after: \"YXJyYXljb25uZWN0aW9uOjk=\",\n            },\n          },\n          result: {\n            data: secondResult,\n          },\n        },\n      ] satisfies MockLink.MockedResponse<ResultOf<typeof query>>[]),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              items: relayStylePagination(),\n            },\n          },\n        },\n      }),\n    });\n\n    const observable = client.watchQuery({\n      query,\n      variables: { first: 2 },\n      fetchPolicy,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        items: {\n          __typename: \"ItemConnection\",\n          edges: firstResult.items.edges,\n          pageInfo: {\n            __typename: \"PageInfo\",\n            hasNextPage: false,\n            endCursor: \"YXJyYXljb25uZWN0aW9uOjk=\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    const more = observable.fetchMore({\n      variables: {\n        first: 10,\n        after: \"YXJyYXljb25uZWN0aW9uOjk=\",\n      },\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected(previous) {\n        return {\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n        };\n      },\n    });\n\n    await expect(more).resolves.toStrictEqualTyped({\n      data: {\n        items: {\n          edges: [],\n          pageInfo: {\n            hasNextPage: false,\n            endCursor: null,\n            __typename: \"PageInfo\",\n          },\n          __typename: \"ItemConnection\",\n        },\n      },\n    });\n\n    await expect(stream).toEmitSimilarValue({\n      expected(previous) {\n        return {\n          ...previous,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n        };\n      },\n    });\n\n    await expect(stream).not.toEmitAnything();\n  }\n);\n\ntest(\"does not emit loading state on client.resetStore with notifyOnNetworkStatusChange: false\", async () => {\n  const query: TypedDocumentNode<\n    { count: number },\n    Record<string, never>\n  > = gql`\n    query {\n      count\n    }\n  `;\n\n  let count = 0;\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { count: ++count },\n          });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { count: 1 },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await client.resetStore();\n\n  await expect(stream).toEmitTypedValue({\n    data: { count: 2 },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state on when evicting fields with notifyOnNetworkStatusChange: false\", async () => {\n  const query = gql`\n    query {\n      user {\n        id\n        username\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink([\n      {\n        request: { query },\n        result: {\n          data: { user: { __typename: \"User\", id: 1, username: \"test1\" } },\n        },\n      },\n      {\n        request: { query },\n        result: {\n          data: { user: { __typename: \"User\", id: 1, username: \"test2\" } },\n        },\n      },\n    ]),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", id: 1, username: \"test1\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  client.cache.modify({\n    id: cache.identify({ __typename: \"User\", id: 1 }),\n    fields: {\n      username: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", id: 1, username: \"test2\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"emits proper cache result if cache changes between watchQuery initialization and subscription\", async () => {\n  const query = gql`\n    query {\n      value\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({ query, data: { value: \"initial\" } });\n  const observable = client.watchQuery({ query });\n  client.writeQuery({ query, data: { value: \"updated\" } });\n\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { value: \"updated\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"emits proper cache result if cache changes when subscribing after previously unsubscribing\", async () => {\n  const query = gql`\n    query {\n      value\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({ query, data: { value: \"initial\" } });\n  const observable = client.watchQuery({ query });\n\n  {\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { value: \"initial\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n\n    stream.unsubscribe();\n  }\n\n  client.writeQuery({ query, data: { value: \"updated\" } });\n\n  {\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { value: \"updated\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  }\n});\n\ntest(\"emits loading state when switching from standby to non-standby fetch policy\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"hello\" } },\n        delay: 20,\n      },\n    ]),\n  });\n\n  const observable = client.watchQuery({ query, fetchPolicy: \"standby\" });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).not.toEmitAnything();\n\n  await expect(\n    observable.reobserve({ fetchPolicy: \"cache-first\" })\n  ).resolves.toStrictEqualTyped({ data: { greeting: \"hello\" } });\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { greeting: \"hello\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"does not emit loading state when changing variables with standby fetch policy\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { id: 1 },\n    fetchPolicy: \"standby\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).not.toEmitAnything();\n\n  await expect(\n    observable.reobserve({ variables: { id: 2 } })\n  ).resolves.toStrictEqualTyped({ data: undefined });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(observable.options.variables).toStrictEqualTyped({ id: 2 });\n});\n\ntest(\"emits loading state when calling reobserve with new fetch policy after changing variables with standby fetch policy\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query, variables: { id: 2 } },\n        result: {\n          data: { user: { __typename: \"User\", id: 2, name: \"Test 2\" } },\n        },\n        delay: 20,\n      },\n    ]),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { id: 1 },\n    fetchPolicy: \"standby\",\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).not.toEmitAnything();\n\n  await expect(\n    observable.reobserve({ variables: { id: 2 } })\n  ).resolves.toStrictEqualTyped({ data: undefined });\n\n  await expect(stream).not.toEmitAnything();\n\n  await expect(\n    observable.reobserve({ fetchPolicy: \"cache-first\" })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 2, name: \"Test 2\" } },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", id: 2, name: \"Test 2\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest('completes open subscription when \"stop\" is called', async () => {\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link,\n  });\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const observable = client.watchQuery({ query });\n  const stream = new ObservableStream(observable);\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  expect(observable.hasObservers()).toBe(true);\n  observable.stop();\n  await expect(stream).toComplete();\n  expect(observable.hasObservers()).toBe(false);\n});\n\ntest('accepts new subscribers after \"stop\" is called', async () => {\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link,\n  });\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const observable = client.watchQuery({ query });\n  const stream = new ObservableStream(observable);\n  const firstOperation = link.operation;\n  expect(firstOperation).toBeDefined();\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  expect(observable.hasObservers()).toBe(true);\n  observable.stop();\n  await expect(stream).toComplete();\n  expect(observable.hasObservers()).toBe(false);\n\n  const stream2 = new ObservableStream(observable);\n  const secondOperation = link.operation;\n  expect(secondOperation).toBeDefined();\n  expect(secondOperation).not.toBe(firstOperation);\n  await expect(stream2).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  expect(observable.hasObservers()).toBe(true);\n});\n\ntest('completes open subscription when \"client.stop\" is called', async () => {\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link,\n  });\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const observable = client.watchQuery({ query });\n  const stream = new ObservableStream(observable);\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  expect(observable.hasObservers()).toBe(true);\n  client.stop();\n  await expect(stream).toComplete();\n  expect(observable.hasObservers()).toBe(false);\n});\n\ndescribe(\".variables\", () => {\n  test(\"returns empty object when no variables are passed\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql`\n      query {\n        greeting\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({ query });\n\n    expect(observable.variables).toStrictEqualTyped({});\n  });\n\n  test(\"returns configured variables\", () => {\n    const query: TypedDocumentNode<{ user: { name: string } }, { id: number }> =\n      gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            name\n          }\n        }\n      `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({ query, variables: { id: 1 } });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 1 });\n  });\n\n  test(\"contains default variables from query\", () => {\n    const query: TypedDocumentNode<\n      { user: { name: string } },\n      { id?: number }\n    > = gql`\n      query ($id: ID! = 1) {\n        user(id: $id) {\n          name\n        }\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({ query });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 1 });\n  });\n\n  test(\"contains combined default variables from query and configured variables\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset: number }\n    > = gql`\n      query ($limit: Int = 10, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({ query, variables: { offset: 0 } });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n  });\n\n  test(\"handles default variables in query overwritten by configured variables\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset: number }\n    > = gql`\n      query ($limit: Int = 10, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: 5, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n  });\n\n  test(\"returns updated variables set from setVariables\", () => {\n    const query: TypedDocumentNode<{ user: { name: string } }, { id: number }> =\n      gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            name\n          }\n        }\n      `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { id: 1 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 1 });\n\n    void observable.setVariables({ id: 2 });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 2 });\n  });\n\n  test(\"returns updated variables set from refetch\", () => {\n    const query: TypedDocumentNode<{ user: { name: string } }, { id: number }> =\n      gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            name\n          }\n        }\n      `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { id: 1 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 1 });\n\n    void observable.refetch({ id: 2 });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 2 });\n  });\n\n  test(\"returns updated variables set from reobserve\", () => {\n    const query: TypedDocumentNode<{ user: { name: string } }, { id: number }> =\n      gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            name\n          }\n        }\n      `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { id: 1 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ id: 1 });\n\n    void observable.reobserve({ variables: { id: 2 } }).catch(() => {});\n\n    expect(observable.variables).toStrictEqualTyped({ id: 2 });\n  });\n\n  test(\"does not return variables given to fetchMore\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit: number; offset: number }\n    > = gql`\n      query ($limit: Int!, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: 10, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.fetchMore({ variables: { offset: 5 } }).catch(() => {});\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n  });\n\n  test(\"handles undefined values\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset: number }\n    > = gql`\n      query ($limit: Int, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: undefined, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({\n      limit: undefined,\n      offset: 0,\n    });\n\n    void observable.setVariables({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable\n      .setVariables({ limit: undefined, offset: 0 })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({\n      limit: undefined,\n      offset: 0,\n    });\n\n    void observable.refetch({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.refetch({ limit: undefined, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({\n      limit: undefined,\n      offset: 0,\n    });\n\n    void observable\n      .reobserve({ variables: { limit: 10, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: undefined, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({\n      limit: undefined,\n      offset: 0,\n    });\n  });\n\n  test(\"handles undefined values with default variables in the query\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset: number }\n    > = gql`\n      query ($limit: Int = 5, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: undefined, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n\n    void observable.setVariables({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable\n      .setVariables({ limit: undefined, offset: 0 })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n\n    void observable.refetch({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.refetch({ limit: undefined, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: 10, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: undefined, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n  });\n\n  test(\"handles null values with default variables in the query\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number | null; offset: number }\n    > = gql`\n      query ($limit: Int = 5, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: null, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: null, offset: 0 });\n\n    void observable.setVariables({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.setVariables({ limit: null, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: null, offset: 0 });\n\n    void observable.refetch({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.refetch({ limit: null, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: null, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: 10, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: null, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: null, offset: 0 });\n  });\n\n  test(\"handles omitted keys with default variables in the query\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset: number }\n    > = gql`\n      query ($limit: Int = 5, $offset: Int!) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n\n    void observable.setVariables({ limit: 10, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.setVariables({ offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n\n    void observable.refetch({ limit: 8, offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 8, offset: 0 });\n\n    // Refetch does a merge of variables so we don't expect `limit` to change.\n    void observable.refetch({ offset: 0 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 8, offset: 0 });\n\n    void observable\n      .reobserve({ variables: { limit: 10, offset: 0 } })\n      .catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.reobserve({ variables: { offset: 0 } }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 5, offset: 0 });\n  });\n\n  test(\"resets variables to {} when passing variables as undefined\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset?: number }\n    > = gql`\n      query ($limit: Int, $offset: Int) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: { limit: 10, offset: 0 },\n    });\n\n    expect(observable.variables).toStrictEqualTyped({ limit: 10, offset: 0 });\n\n    void observable.reobserve({ variables: undefined }).catch(() => {});\n\n    expect(observable.variables).toStrictEqualTyped({});\n  });\n\n  test(\"sets variables as {} when using empty object as variables\", () => {\n    const query: TypedDocumentNode<\n      { users: Array<{ name: string }> },\n      { limit?: number; offset?: number }\n    > = gql`\n      query ($limit: Int, $offset: Int) {\n        users(limit: $limit, offset: $offset) {\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    const observable = client.watchQuery({\n      query,\n      variables: {},\n    });\n\n    expect(observable.variables).toStrictEqualTyped({});\n\n    void observable.setVariables({ limit: 10 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10 });\n\n    void observable.setVariables({}).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({});\n\n    void observable.refetch({ limit: 10 }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10 });\n\n    // Since `refetch` merges variables, we don't expect variables to change\n    void observable.refetch({}).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10 });\n\n    void observable.reobserve({ variables: { limit: 10 } }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({ limit: 10 });\n\n    void observable.reobserve({ variables: {} }).catch(() => {});\n    expect(observable.variables).toStrictEqualTyped({});\n  });\n});\n\ndescribe.skip(\"type tests\", () => {\n  test.skip(\"type test for `from`\", () => {\n    expectTypeOf<\n      ObservedValueOf<ObservableQuery<{ foo: string }, { bar: number }>>\n    >().toEqualTypeOf<ObservableQuery.Result<{ foo: string }>>();\n  });\n\n  test(\"variables with DocumentNode\", () => {\n    const query = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<OperationVariables>();\n\n    void observable.setVariables({});\n    void observable.setVariables({ foo: \"bar\" });\n    void observable.setVariables({ bar: \"baz\" });\n\n    void observable.refetch();\n    void observable.refetch({});\n    void observable.refetch({ foo: \"bar\" });\n    void observable.refetch({ foo: \"baz\" });\n\n    void observable.reobserve();\n    void observable.reobserve({ variables: {} });\n    void observable.reobserve({ variables: { foo: \"bar\" } });\n    void observable.reobserve({ variables: { foo: \"baz\" } });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({ variables: {} });\n    void observable.fetchMore({ variables: { foo: \"bar\" } });\n    void observable.fetchMore({ variables: { foo: \"baz\" } });\n  });\n\n  test(\"is invalid with variables as never\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    // @ts-expect-error expecting variables key\n    const observable = client.watchQuery({ query });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<never>();\n\n    // @ts-expect-error\n    void observable.setVariables({});\n    // @ts-expect-error\n    void observable.setVariables({ foo: \"bar\" });\n\n    void observable.refetch();\n    // @ts-expect-error\n    void observable.refetch({});\n    // @ts-expect-error\n    void observable.refetch({ foo: \"bar\" });\n\n    void observable.reobserve();\n    void observable.reobserve({\n      // @ts-expect-error variables is never\n      variables: {},\n    });\n    void observable.reobserve({ variables: undefined });\n    void observable.reobserve({\n      // @ts-expect-error\n      variables: { foo: \"bar\" },\n    });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({\n      // @ts-expect-error unknown variables\n      variables: {},\n    });\n    void observable.fetchMore({ variables: undefined });\n    void observable.fetchMore({\n      // @ts-expect-error variables is never\n      variables: { foo: \"bar\" },\n    });\n  });\n\n  test(\"variables with Record<string, never>\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<Record<string, never>>();\n\n    void observable.setVariables({});\n    void observable.setVariables({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.refetch();\n    void observable.refetch({});\n    void observable.refetch({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.reobserve();\n    void observable.reobserve({ variables: {} });\n    void observable.reobserve({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({\n      variables: {},\n    });\n    void observable.fetchMore({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"variables with optional variables\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const observable = client.watchQuery({ query });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<{ limit?: number }>();\n\n    void observable.setVariables({});\n    void observable.setVariables({ limit: 10 });\n    void observable.setVariables({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.setVariables({\n      limit: 10,\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.refetch();\n    void observable.refetch({});\n    void observable.refetch({ limit: 10 });\n    void observable.refetch({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.refetch({\n      limit: 10,\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.reobserve();\n    void observable.reobserve({ variables: {} });\n    void observable.reobserve({ variables: { limit: 10 } });\n    void observable.reobserve({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.reobserve({\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({ variables: {} });\n    void observable.fetchMore({ variables: { limit: 10 } });\n    void observable.fetchMore({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.fetchMore({\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"variables with required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: \"1\" } });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<{ id: string }>();\n\n    // @ts-expect-error missing required variable\n    void observable.setVariables({});\n    void observable.setVariables({ id: \"1\" });\n    void observable.setVariables({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.setVariables({\n      id: \"1\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.refetch();\n    void observable.refetch({});\n    void observable.refetch({ id: \"1\" });\n    void observable.refetch({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.refetch({\n      id: \"1\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.reobserve();\n    void observable.reobserve({\n      // @ts-expect-error missing required variable\n      variables: {},\n    });\n    void observable.reobserve({ variables: { id: \"1\" } });\n    void observable.reobserve({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.reobserve({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({ variables: {} });\n    void observable.fetchMore({ variables: { id: \"1\" } });\n    void observable.fetchMore({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.fetchMore({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"variables with mixed required and optional\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const observable = client.watchQuery({ query, variables: { id: \"1\" } });\n\n    expectTypeOf(observable.variables).toEqualTypeOf<{\n      id: string;\n      language?: string;\n    }>();\n\n    // @ts-expect-error missing required variable\n    void observable.setVariables({});\n    void observable.setVariables({ id: \"1\" });\n    // @ts-expect-error missing required variable\n    void observable.setVariables({ language: \"en\" });\n    void observable.setVariables({ id: \"1\", language: \"en\" });\n    void observable.setVariables({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.setVariables({\n      id: \"1\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.setVariables({\n      id: \"1\",\n      language: \"en\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.refetch();\n    void observable.refetch({});\n    void observable.refetch({ id: \"1\" });\n    void observable.refetch({ language: \"en\" });\n    void observable.refetch({ id: \"1\", language: \"en\" });\n    void observable.refetch({\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.refetch({\n      id: \"1\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n    void observable.refetch({\n      id: \"1\",\n      language: \"en\",\n      // @ts-expect-error unknown variables\n      foo: \"bar\",\n    });\n\n    void observable.reobserve();\n    void observable.reobserve({\n      // @ts-expect-error missing required variable\n      variables: {},\n    });\n    void observable.reobserve({ variables: { id: \"1\" } });\n    void observable.reobserve({\n      // @ts-expect-error missing required variable\n      variables: { language: \"en\" },\n    });\n    void observable.reobserve({ variables: { id: \"1\", language: \"en\" } });\n    void observable.reobserve({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.reobserve({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.reobserve({\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    void observable.fetchMore({});\n    void observable.fetchMore({ variables: {} });\n    void observable.fetchMore({ variables: { id: \"1\" } });\n    void observable.fetchMore({ variables: { language: \"en\" } });\n    void observable.fetchMore({ variables: { id: \"1\", language: \"en\" } });\n    void observable.fetchMore({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.fetchMore({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void observable.fetchMore({\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n});\n\ntest(\"does not return partial cache data when `returnPartialData` is false and new variables are passed in\", async () => {\n  const partialQuery = gql`\n    query MyCar($id: ID) {\n      car(id: $id) {\n        id\n        make\n      }\n    }\n  `;\n\n  const query = gql`\n    query MyCar($id: ID) {\n      car(id: $id) {\n        id\n        make\n        model\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink([\n      {\n        request: { query, variables: { id: 2 } },\n        result: {\n          data: {\n            car: { __typename: \"Car\", id: 2, make: \"Ford\", model: \"Bronco\" },\n          },\n        },\n        delay: 50,\n      },\n    ]),\n  });\n\n  cache.writeQuery({\n    query,\n    variables: { id: 1 },\n    data: {\n      car: {\n        __typename: \"Car\",\n        id: 1,\n        make: \"Ford\",\n        model: \"Pinto\",\n      },\n    },\n  });\n\n  cache.writeQuery({\n    query: partialQuery,\n    variables: { id: 2 },\n    data: {\n      car: {\n        __typename: \"Car\",\n        id: 2,\n        make: \"Ford\",\n        model: \"Bronco\",\n      },\n    },\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { id: 1 },\n    returnPartialData: false,\n  });\n\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      car: { __typename: \"Car\", id: 1, make: \"Ford\", model: \"Pinto\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  void observable.reobserve({ variables: { id: 2 } });\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.setVariables,\n    partial: true,\n  });\n\n  expect(observable.getCurrentResult()).toBe(stream.getCurrent());\n\n  await expect(stream).toEmitTypedValue({\n    data: { car: { __typename: \"Car\", id: 2, make: \"Ford\", model: \"Bronco\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  expect(observable.getCurrentResult()).toBe(stream.getCurrent());\n});\n\ntest(\"emits data: undefined when changing variables and an error is returned with notifyOnNetworkStatusChange: false\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      mocks[0],\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: { errors: [{ message: \"Something went wrong\" }] },\n      },\n    ]),\n  });\n\n  const observable = client.watchQuery({\n    query,\n    variables: { id: \"1\" },\n    notifyOnNetworkStatusChange: false,\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(\n    observable.reobserve({ variables: { id: \"2\" } })\n  ).rejects.toEqual(\n    new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    error: new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n"
  },
  {
    "path": "src/core/__tests__/client.mutate/refetchQueries.test.ts",
    "content": "import { ApolloClient, gql, InMemoryCache } from \"@apollo/client\";\nimport { MockLink } from \"@apollo/client/testing\";\n\ntest(\"applies defaultOptions.watchQuery to refetchQueries query objects\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n\n  const mutation = gql`\n    mutation {\n      updateGreeting\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query: mutation },\n        result: { data: { updateGreeting: true } },\n      },\n      {\n        request: { query },\n        result: { data: { greeting: null }, errors: [{ message: \"Oops\" }] },\n      },\n    ]),\n    defaultOptions: {\n      watchQuery: {\n        errorPolicy: \"all\",\n      },\n    },\n  });\n\n  // With defaultOptions.watchQuery.errorPolicy: \"all\", the refetch query\n  // should not cause the mutation to reject despite returning GraphQL errors.\n  await expect(\n    client.mutate({\n      mutation,\n      refetchQueries: [{ query }],\n      awaitRefetchQueries: true,\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { updateGreeting: true },\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/client.query/context.ts",
    "content": "import { of } from \"rxjs\";\n\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\n\ntest(\"can get the client from the operation\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const request = jest.fn((_: ApolloLink.Operation) => {\n    return of({ data: { greeting: \"Hello\" } });\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(request),\n  });\n\n  await client.query({ query });\n  const [operation] = request.mock.calls[0];\n\n  expect(operation.client).toBe(client);\n});\n\ntest(\"allows custom context\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const request = jest.fn((_: ApolloLink.Operation) => {\n    return of({ data: { greeting: \"Hello\" } });\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(request),\n  });\n\n  await client.query({ query, context: { foo: true } });\n  const [operation] = request.mock.calls[0];\n\n  expect(operation.getContext()).toStrictEqualTyped({\n    foo: true,\n    queryDeduplication: true,\n  });\n});\n\ntest(\"uses context from defaultContext\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const request = jest.fn((_: ApolloLink.Operation) => {\n    return of({ data: { greeting: \"Hello\" } });\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(request),\n    defaultContext: {\n      foo: true,\n    },\n  });\n\n  await client.query({ query });\n  const [operation] = request.mock.calls[0];\n\n  expect(operation.getContext()).toStrictEqualTyped({\n    foo: true,\n    queryDeduplication: true,\n  });\n});\n\ntest(\"can override global default\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n  const request = jest.fn((_: ApolloLink.Operation) => {\n    return of({ data: { greeting: \"Hello\" } });\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(request),\n    defaultContext: {\n      foo: true,\n    },\n  });\n\n  await client.query({ query, context: { foo: false } });\n  const [operation] = request.mock.calls[0];\n\n  expect(operation.getContext()).toStrictEqualTyped({\n    foo: false,\n    queryDeduplication: true,\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/client.query/defaultOptions.test.ts",
    "content": "import {\n  ApolloClient,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n} from \"@apollo/client\";\nimport { MockLink } from \"@apollo/client/testing\";\n\ntest(\"uses defaultOptions from `query` key\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: null }, errors: [{ message: \"Oops\" }] },\n      },\n    ]),\n    defaultOptions: {\n      query: {\n        errorPolicy: \"all\",\n      },\n    },\n  });\n\n  await expect(client.query({ query })).resolves.toStrictEqualTyped({\n    data: { greeting: null },\n    error: new CombinedGraphQLErrors({\n      data: { greeting: null },\n      errors: [{ message: \"Oops\" }],\n    }),\n  });\n});\n\ntest(\"does not use defaultOptions from `watchQuery` key\", async () => {\n  const query = gql`\n    query {\n      greeting\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: null }, errors: [{ message: \"Oops\" }] },\n      },\n    ]),\n    defaultOptions: {\n      watchQuery: {\n        errorPolicy: \"all\",\n      },\n    },\n  });\n\n  await expect(client.query({ query })).rejects.toThrow(\n    new CombinedGraphQLErrors({\n      data: { greeting: null },\n      errors: [{ message: \"Oops\" }],\n    })\n  );\n});\n"
  },
  {
    "path": "src/core/__tests__/client.readFragment/general.test.ts",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\n\ntest(\"can use `from` with readFragment\", async () => {\n  const fragment: TypedDocumentNode<\n    {\n      bar: boolean;\n      baz: boolean;\n      __typename: \"Foo\";\n    },\n    Record<string, never>\n  > = gql`\n    fragment FooFragment on Foo {\n      bar\n      baz\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: ApolloLink.empty(),\n    cache: new InMemoryCache().restore({\n      \"Foo:1\": {\n        __typename: \"Foo\",\n        id: 1,\n        bar: true,\n        baz: false,\n      },\n    }),\n  });\n\n  expect(\n    client.readFragment({\n      fragment,\n      from: { __typename: \"Foo\", id: 1 },\n    })\n  ).toStrictEqualTyped({ __typename: \"Foo\", bar: true, baz: false });\n\n  expect(\n    client.readFragment({\n      fragment,\n      from: { __ref: \"Foo:1\" },\n    })\n  ).toStrictEqualTyped({ __typename: \"Foo\", bar: true, baz: false });\n\n  expect(\n    client.readFragment({\n      fragment,\n      from: \"Foo:1\",\n    })\n  ).toStrictEqualTyped({ __typename: \"Foo\", bar: true, baz: false });\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchFragment/arrays.test.ts",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport { ObservableStream, wait } from \"@apollo/client/testing/internal\";\n\ntest(\"can use array for `from` to get array of items\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"allows mix of array identifiers\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [{ __typename: \"Item\", id: 1 }, \"Item:2\", { __ref: \"Item:3\" }],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 3, text: \"Item #3\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns empty array with empty from\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({ fragment, from: [] });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns result as partial when cache is empty\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [null, null, null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: \"Dangling reference to missing Item:1 object\",\n      1: \"Dangling reference to missing Item:2 object\",\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns as complete if all `from` items are null\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [null, null, null],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [null, null, null],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns as complete if all `from` items are complete or null\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [null, null, { __typename: \"Item\", id: 5 }],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [null, null, { __typename: \"Item\", id: 5, text: \"Item #5\" }],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"returns as partial if some `from` items are incomplete mixed with null\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [null, null, { __typename: \"Item\", id: 5 }],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [null, null, null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"can use static arrays with useFragment with partially fulfilled items\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 2; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: { 2: \"Dangling reference to missing Item:5 object\" },\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"updates items in the array with cache writes\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const { cache } = client;\n\n  for (let i = 1; i <= 2; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 2,\n      text: \"Item #2 updated\",\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  client.cache.batch({\n    update: (cache) => {\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 1,\n          text: \"Item #1 from batch\",\n        },\n      });\n\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 from batch\",\n        },\n      });\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 from batch\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5 from batch\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Item\", id: 1 }),\n    fields: {\n      text: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5 from batch\" },\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: {\n        text: \"Can't find field 'text' on Item:1 object\",\n      },\n    },\n  });\n\n  // should not cause rerender since its an item not watched\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 6,\n      text: \"Item #6 ignored\",\n    },\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"works with data masking\", async () => {\n  type ItemDetails = {\n    __typename: string;\n    text: string;\n  } & { \" $fragmentName\"?: \"ItemDetailsFragment\" };\n\n  type Item = {\n    __typename: string;\n    id: number;\n  } & {\n    \" $fragmentRefs\"?: { ItemDetailsFragment: ItemDetails };\n  };\n\n  const detailsFragment: TypedDocumentNode<ItemDetails> = gql`\n    fragment ItemDetailsFragment on Item {\n      text\n    }\n  `;\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      ...ItemDetailsFragment\n    }\n\n    ${detailsFragment}\n  `;\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const { cache } = client;\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      fragmentName: \"ItemFragment\",\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const parentObservable = client.watchFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const childObservable = client.watchFragment({\n    fragment: detailsFragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const parentStream = new ObservableStream(parentObservable);\n  const childStream = new ObservableStream(childObservable);\n\n  await expect(parentStream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(childStream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", text: \"Item #1\" },\n      { __typename: \"Item\", text: \"Item #2\" },\n      { __typename: \"Item\", text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: {\n      __typename: \"Item\",\n      id: 2,\n      text: \"Item #2 updated\",\n    },\n  });\n\n  await expect(childStream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", text: \"Item #1\" },\n      { __typename: \"Item\", text: \"Item #2 updated\" },\n      { __typename: \"Item\", text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(parentStream).not.toEmitAnything();\n\n  client.cache.batch({\n    update: (cache) => {\n      cache.writeFragment({\n        fragment,\n        fragmentName: \"ItemFragment\",\n        data: {\n          __typename: \"Item\",\n          id: 1,\n          text: \"Item #1 from batch\",\n        },\n      });\n\n      cache.writeFragment({\n        fragment,\n        fragmentName: \"ItemFragment\",\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 from batch\",\n        },\n      });\n    },\n  });\n\n  await expect(childStream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", text: \"Item #1 from batch\" },\n      { __typename: \"Item\", text: \"Item #2 updated\" },\n      { __typename: \"Item\", text: \"Item #5 from batch\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(parentStream).not.toEmitAnything();\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Item\", id: 1 }),\n    fields: {\n      text: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  await expect(childStream).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\" },\n      { __typename: \"Item\", text: \"Item #2 updated\" },\n      { __typename: \"Item\", text: \"Item #5 from batch\" },\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: {\n        text: \"Can't find field 'text' on Item:1 object\",\n      },\n    },\n  });\n  await expect(parentStream).not.toEmitAnything();\n\n  // should not cause rerender since its an item not watched\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: {\n      __typename: \"Item\",\n      id: 6,\n      text: \"Item #6 ignored\",\n    },\n  });\n\n  await expect(parentStream).not.toEmitAnything();\n  await expect(childStream).not.toEmitAnything();\n});\n\ntest(\"can subscribe to the same object multiple times\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  const stream1 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n      ],\n    })\n  );\n  // ensure we only watch the item once\n  expect(cache).toHaveNumWatches(1);\n\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: `Item #1 updated` },\n  });\n\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  const stream2 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n      ],\n    })\n  );\n  expect(cache).toHaveNumWatches(1);\n\n  await expect(stream2).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  const stream3 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 2 },\n        { __typename: \"Item\", id: 1 },\n      ],\n    })\n  );\n  expect(cache).toHaveNumWatches(2);\n\n  await expect(stream3).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: `Item #1 updated again` },\n  });\n\n  await expect(stream3).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream2).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n      { __typename: \"Item\", id: 1, text: \"Item #1 updated again\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await Promise.all([\n    expect(stream1).not.toEmitAnything(),\n    expect(stream2).not.toEmitAnything(),\n    expect(stream3).not.toEmitAnything(),\n  ]);\n\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true },\n    { id: \"Item:2\", optimistic: true },\n  ]);\n\n  stream3.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(1);\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true },\n  ]);\n\n  stream1.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(1);\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true },\n  ]);\n\n  stream2.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(0);\n});\n\ntest(\"differentiates watches between optimistic and variables\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text(casing: $casing)\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"ITEM #1\" },\n    variables: { casing: \"UPPER\" },\n  });\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"item #1\" },\n    variables: { casing: \"LOWER\" },\n  });\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"item #2\" },\n    variables: { casing: \"LOWER\" },\n  });\n\n  const stream1 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n      ],\n      variables: { casing: \"UPPER\" },\n    })\n  );\n  // ensure we only watch the item once\n  expect(cache).toHaveNumWatches(1);\n\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"ITEM #1\" },\n      { __typename: \"Item\", id: 1, text: \"ITEM #1\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"ITEM #1 UPDATED\" },\n    variables: { casing: \"UPPER\" },\n  });\n\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"ITEM #1 UPDATED\" },\n      { __typename: \"Item\", id: 1, text: \"ITEM #1 UPDATED\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  const stream2 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 1 },\n      ],\n      variables: { casing: \"LOWER\" },\n    })\n  );\n  expect(cache).toHaveNumWatches(2);\n\n  await expect(stream2).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"item #1\" },\n      { __typename: \"Item\", id: 1, text: \"item #1\" },\n      { __typename: \"Item\", id: 1, text: \"item #1\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n    variables: { casing: \"LOWER\" },\n  });\n\n  await expect(stream2).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream1).not.toEmitAnything();\n\n  const stream3 = new ObservableStream(\n    client.watchFragment({\n      fragment,\n      from: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 2 },\n        { __typename: \"Item\", id: 1 },\n      ],\n      variables: { casing: \"LOWER\" },\n      optimistic: false,\n    })\n  );\n  expect(cache).toHaveNumWatches(4);\n\n  await expect(stream3).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n      { __typename: \"Item\", id: 2, text: \"item #2\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n    variables: { casing: \"LOWER\" },\n  });\n\n  await expect(stream3).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n      { __typename: \"Item\", id: 2, text: \"item #2\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream2).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n      { __typename: \"Item\", id: 1, text: \"item #1 updated again\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream1).not.toEmitAnything();\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"FULL REPLACEMENT\" },\n    variables: { casing: \"UPPER\" },\n  });\n\n  await expect(stream1).toEmitTypedValue({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"FULL REPLACEMENT\" },\n      { __typename: \"Item\", id: 1, text: \"FULL REPLACEMENT\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(stream2).not.toEmitAnything();\n  await expect(stream3).not.toEmitAnything();\n\n  expect(cache).toHaveNumWatches(4);\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true, variables: { casing: \"UPPER\" } },\n    { id: \"Item:1\", optimistic: true, variables: { casing: \"LOWER\" } },\n    { id: \"Item:1\", optimistic: false, variables: { casing: \"LOWER\" } },\n    { id: \"Item:2\", optimistic: false, variables: { casing: \"LOWER\" } },\n  ]);\n\n  stream3.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(2);\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true, variables: { casing: \"UPPER\" } },\n    { id: \"Item:1\", optimistic: true, variables: { casing: \"LOWER\" } },\n  ]);\n\n  stream1.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(1);\n  expect(client).toHaveFragmentWatchesOn(fragment, [\n    { id: \"Item:1\", optimistic: true, variables: { casing: \"LOWER\" } },\n  ]);\n\n  stream2.unsubscribe();\n  await wait(2);\n\n  expect(cache).toHaveNumWatches(0);\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchFragment/general.test.ts",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport { ObservableStream, wait } from \"@apollo/client/testing/internal\";\n\ntest(\"can subscribe multiple times to watchFragment\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const ItemFragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment: ItemFragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment: ItemFragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  using stream1 = new ObservableStream(observable);\n  using stream2 = new ObservableStream(observable);\n\n  await expect(stream1).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream2).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment: ItemFragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n  });\n\n  await expect(stream1).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream2).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream1).not.toEmitAnything();\n  await expect(stream2).not.toEmitAnything();\n});\n\ntest(\"dedupes watches when subscribing multiple times\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const ItemFragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment: ItemFragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment: ItemFragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  expect(cache).toHaveNumWatches(0);\n\n  const sub1 = observable.subscribe(() => {});\n  const sub2 = observable.subscribe(() => {});\n  expect(cache).toHaveNumWatches(1);\n\n  const sub3 = observable.subscribe(() => {});\n  expect(cache).toHaveNumWatches(1);\n\n  [sub1, sub2, sub3].forEach((sub) => sub.unsubscribe());\n  await wait(0);\n  expect(cache).toHaveNumWatches(0);\n\n  const sub4 = observable.subscribe(() => {});\n  expect(cache).toHaveNumWatches(1);\n\n  sub4.unsubscribe();\n  await wait(0);\n  expect(cache).toHaveNumWatches(0);\n});\n\ntest(\"emits null with from: null\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const ItemFragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment: ItemFragment,\n    from: null,\n  });\n\n  using stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: null,\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"emits empty object when data is not in the cache\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const ItemFragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment: ItemFragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  using stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: {},\n    dataState: \"partial\",\n    complete: false,\n    missing: \"Dangling reference to missing Item:1 object\",\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchFragment/getCurrentResult.test.ts",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\ninterface Item {\n  __typename: \"Item\";\n  id: number;\n  text: string;\n}\n\ntest(\"returns initial result before subscribing\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"returns initial emitted value after subscribing\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const diffSpy = jest.spyOn(client.cache, \"diff\");\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  diffSpy.mockClear();\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n  expect(diffSpy).not.toHaveBeenCalled();\n});\n\ntest(\"returns most recently emitted value\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"returns updated value if changed before subscribing\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"returns referentially stable value\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  const firstResult = observable.getCurrentResult();\n  expect(firstResult).toStrictEqualTyped({\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  expect(observable.getCurrentResult()).toBe(firstResult);\n  expect(observable.getCurrentResult()).toBe(firstResult);\n  expect(observable.getCurrentResult()).toBe(firstResult);\n\n  const stream = new ObservableStream(observable);\n  const result = await stream.takeNext();\n\n  // Ensure subscribing to the observable and emitting the first value doesn't\n  // change the identity of the object\n  expect(result).toBe(firstResult);\n  expect(observable.getCurrentResult()).toBe(firstResult);\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 updated\" },\n  });\n\n  // ensure it changes identity when a new value is emitted\n  const result2 = await stream.takeNext();\n  const secondResult = observable.getCurrentResult();\n\n  expect(secondResult).not.toBe(firstResult);\n  expect(secondResult).toBe(result2);\n  expect(observable.getCurrentResult()).toBe(secondResult);\n  expect(observable.getCurrentResult()).toBe(secondResult);\n  expect(observable.getCurrentResult()).toBe(secondResult);\n});\n\ntest(\"returns partial result with no cache data\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: {},\n    dataState: \"partial\",\n    complete: false,\n    missing: \"Dangling reference to missing Item:1 object\",\n  });\n});\n\ntest(\"is lazy computed\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  jest.spyOn(cache, \"diff\");\n\n  const observable = client.watchFragment({\n    fragment,\n    from: { __typename: \"Item\", id: 1 },\n  });\n\n  expect(cache.diff).not.toHaveBeenCalled();\n  observable.getCurrentResult();\n  expect(cache.diff).toHaveBeenCalledTimes(1);\n});\n\ntest(\"handles arrays\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"handles arrays with an active subscription\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  observable.subscribe();\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"handles arrays with null\", async () => {\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const observable = client.watchFragment({\n    fragment,\n    from: [null, null, { __typename: \"Item\", id: 5 }],\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [null, null, null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n});\n\ntest(\"works with data masking\", async () => {\n  type ItemDetails = {\n    __typename: string;\n    text: string;\n  } & { \" $fragmentName\"?: \"ItemDetailsFragment\" };\n\n  type Item = {\n    __typename: string;\n    id: number;\n  } & {\n    \" $fragmentRefs\"?: { ItemDetailsFragment: ItemDetails };\n  };\n\n  const detailsFragment: TypedDocumentNode<ItemDetails> = gql`\n    fragment ItemDetailsFragment on Item {\n      text\n    }\n  `;\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      ...ItemDetailsFragment\n    }\n\n    ${detailsFragment}\n  `;\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      fragmentName: \"ItemFragment\",\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const parentObservable = client.watchFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n  const childObservable = client.watchFragment({\n    fragment: detailsFragment,\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  expect(parentObservable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  expect(childObservable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", text: \"Item #1\" },\n      { __typename: \"Item\", text: \"Item #2\" },\n      { __typename: \"Item\", text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n  });\n\n  expect(parentObservable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n  expect(childObservable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", text: \"Item #1\" },\n      { __typename: \"Item\", text: \"Item #2 updated\" },\n      { __typename: \"Item\", text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n});\n\ntest(\"works with data masking @unmask migrate mode\", async () => {\n  using consoleSpy = spyOnConsole(\"warn\");\n  type ItemDetails = {\n    __typename: string;\n    text: string;\n  } & { \" $fragmentName\"?: \"ItemDetailsFragment\" };\n\n  type Item = {\n    __typename: string;\n    id: number;\n    text: string;\n  } & {\n    \" $fragmentRefs\"?: { ItemDetailsFragment: ItemDetails };\n  };\n\n  const detailsFragment: TypedDocumentNode<ItemDetails> = gql`\n    fragment ItemDetailsFragment on Item {\n      text\n    }\n  `;\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      ...ItemDetailsFragment @unmask(mode: \"migrate\")\n    }\n\n    ${detailsFragment}\n  `;\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      fragmentName: \"ItemFragment\",\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  const observable = client.watchFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(3);\n  for (let i = 0; i < 3; i++) {\n    expect(console.warn).toHaveBeenNthCalledWith(\n      i + 1,\n      expect.stringContaining(\"Accessing unmasked field on %s at path '%s'.\"),\n      \"fragment 'ItemFragment'\",\n      `[${i}].text`\n    );\n  }\n  consoleSpy.warn.mockClear();\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n  });\n\n  expect(observable.getCurrentResult()).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(3);\n  for (let i = 0; i < 3; i++) {\n    expect(console.warn).toHaveBeenNthCalledWith(\n      i + 1,\n      expect.stringContaining(\"Accessing unmasked field on %s at path '%s'.\"),\n      \"fragment 'ItemFragment'\",\n      `[${i}].text`\n    );\n  }\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchFragment/types.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport type {\n  DataValue,\n  Reference,\n  StoreObject,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport type { MissingTree } from \"@apollo/client/cache\";\n\ndescribe.skip(\"type tests\", () => {\n  interface Item {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let fragment!: TypedDocumentNode<Item, Record<string, never>>;\n\n  test(\"from: null -> null\", () => {\n    const observable = client.watchFragment({ fragment, from: null });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<{\n      data: null;\n      dataState: \"complete\";\n      complete: true;\n      missing?: never;\n    }>();\n  });\n\n  test(\"from: StoreObject -> TData\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: string -> TData\", () => {\n    const observable = client.watchFragment({ fragment, from: \"Item:1\" });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Reference -> TData\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: { __ref: \"Item:1\" },\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: StoreObject | null -> TData | null\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 } as StoreObject | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: string | null -> TData | null\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: \"Item:1\" as string | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Reference | null -> TData | null\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: { __ref: \"Item:1\" } as Reference | null,\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Item | null>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: null;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Item;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: DataValue.Partial<Item>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Array<null> -> Array<null>\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: [null],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Array<null>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<{\n      data: Array<null>;\n      dataState: \"complete\";\n      complete: true;\n      missing?: never;\n    }>();\n  });\n\n  test(\"from: Array<FromValue> -> Array<TData>\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: [{ __typename: \"Item\", id: 1 }, \"Item:1\", { __ref: \"Item:1\" }],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Array<Item>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Array<Item>;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Array<DataValue.Partial<Item> | null>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n\n  test(\"from: Array<FromValue | null> -> Array<TData | null>\", () => {\n    const observable = client.watchFragment({\n      fragment,\n      from: [{ __typename: \"Item\", id: 1 }, null],\n    });\n    const result = observable.getCurrentResult();\n\n    expectTypeOf(observable).toEqualTypeOf<\n      ApolloClient.ObservableFragment<Array<Item | null>>\n    >();\n    expectTypeOf(result).toEqualTypeOf<\n      | {\n          data: Array<Item | null>;\n          dataState: \"complete\";\n          complete: true;\n          missing?: never;\n        }\n      | {\n          data: Array<DataValue.Partial<Item> | null>;\n          dataState: \"partial\";\n          complete: false;\n          missing?: MissingTree;\n        }\n    >();\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchQuery/defer20220824.test.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport type { ObservableQuery } from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport {\n  markAsStreaming,\n  mockDefer20220824,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\ntest(\"deduplicates queries as long as a query still has deferred chunks\", async () => {\n  const query = gql`\n    query LazyLoadLuke {\n      people(id: 1) {\n        id\n        name\n        friends {\n          id\n          ... @defer {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const outgoingRequestSpy = jest.fn(((operation, forward) =>\n    forward(operation)) satisfies ApolloLink.RequestHandler);\n  const defer = mockDefer20220824();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({}),\n    link: new ApolloLink(outgoingRequestSpy).concat(defer.httpLink),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query1 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  const query2 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const initialData = {\n    people: {\n      __typename: \"Person\",\n      id: 1,\n      name: \"Luke\",\n      friends: [\n        {\n          __typename: \"Person\",\n          id: 5,\n        } as { __typename: \"Person\"; id: number; name?: string },\n        {\n          __typename: \"Person\",\n          id: 8,\n        } as { __typename: \"Person\"; id: number; name?: string },\n      ],\n    },\n  };\n  const initialResult: ObservableQuery.Result<typeof initialData> = {\n    data: initialData,\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  };\n\n  defer.enqueueInitialChunk({\n    data: initialData,\n    hasNext: true,\n  });\n\n  await expect(query1).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n  await expect(query2).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(query1).toEmitTypedValue(initialResult);\n  await expect(query2).toEmitTypedValue(initialResult);\n\n  const query3 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  await expect(query3).toEmitTypedValue(initialResult);\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const firstChunk = {\n    incremental: [\n      {\n        data: {\n          name: \"Leia\",\n        },\n        path: [\"people\", \"friends\", 0],\n      },\n    ],\n    hasNext: true,\n  };\n  const resultAfterFirstChunk = structuredClone(\n    initialResult\n  ) as ObservableQuery.Result<any>;\n  resultAfterFirstChunk.data.people.friends[0].name = \"Leia\";\n\n  defer.enqueueSubsequentChunk(firstChunk);\n\n  await expect(query1).toEmitTypedValue(resultAfterFirstChunk);\n  await expect(query2).toEmitTypedValue(resultAfterFirstChunk);\n  await expect(query3).toEmitTypedValue(resultAfterFirstChunk);\n\n  const query4 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  await expect(query4).toEmitTypedValue(resultAfterFirstChunk);\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const secondChunk = {\n    incremental: [\n      {\n        data: {\n          name: \"Han Solo\",\n        },\n        path: [\"people\", \"friends\", 1],\n      },\n    ],\n    hasNext: false,\n  };\n  const resultAfterSecondChunk = {\n    ...structuredClone(resultAfterFirstChunk),\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    dataState: \"complete\",\n    partial: false,\n  } as ObservableQuery.Result<any>;\n  resultAfterSecondChunk.data.people.friends[1].name = \"Han Solo\";\n\n  defer.enqueueSubsequentChunk(secondChunk);\n\n  await expect(query1).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query2).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query3).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query4).toEmitTypedValue(resultAfterSecondChunk);\n\n  // TODO: Re-enable once below condition can be met\n  /* const query5 = */ new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  // TODO: Re-enable once notifyOnNetworkStatusChange controls whether we\n  // get the loading state. This test fails with the switch to RxJS for now\n  // since the initial value is emitted synchronously unlike zen-observable\n  // where the emitted result wasn't emitted until after this assertion.\n  // expect(query5).not.toEmitAnything();\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(2);\n});\n\nit.each([[\"cache-first\"], [\"no-cache\"]] as const)(\n  \"correctly merges deleted rows when receiving a deferred payload\",\n  async (fetchPolicy) => {\n    const query = gql`\n      query Characters {\n        characters {\n          id\n          uppercase\n          ... @defer {\n            lowercase\n          }\n        }\n      }\n    `;\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDefer20220824();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: httpLink,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    enqueueInitialChunk({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      },\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [{ data: { lowercase: \"a\" }, path: [\"characters\", 0] }],\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [\n        { data: { lowercase: \"b\" }, path: [\"characters\", 1] },\n        { data: { lowercase: \"c\" }, path: [\"characters\", 2] },\n      ],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\", lowercase: \"c\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\", lowercase: \"c\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    // on refetch, the list is shorter\n    enqueueInitialChunk({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n        ],\n      },\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters:\n          // no-cache fetch policy doesn't merge with existing cache data, so\n          // the lowercase field is not added to each item\n          fetchPolicy === \"no-cache\" ?\n            [\n              { __typename: \"Character\", id: 1, uppercase: \"A\" },\n              { __typename: \"Character\", id: 2, uppercase: \"B\" },\n            ]\n          : [\n              {\n                __typename: \"Character\",\n                id: 1,\n                uppercase: \"A\",\n                lowercase: \"a\",\n              },\n              {\n                __typename: \"Character\",\n                id: 2,\n                uppercase: \"B\",\n                lowercase: \"b\",\n              },\n            ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [\n        { data: { lowercase: \"a\" }, path: [\"characters\", 0] },\n        { data: { lowercase: \"b\" }, path: [\"characters\", 1] },\n      ],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  }\n);\n"
  },
  {
    "path": "src/core/__tests__/client.watchQuery/deferGraphQL17Alpha9.test.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport type { ObservableQuery } from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport {\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\ntest(\"deduplicates queries as long as a query still has deferred chunks\", async () => {\n  const query = gql`\n    query LazyLoadLuke {\n      people(id: 1) {\n        id\n        name\n        friends {\n          id\n          ... @defer {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const outgoingRequestSpy = jest.fn(((operation, forward) =>\n    forward(operation)) satisfies ApolloLink.RequestHandler);\n  const defer = mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({}),\n    link: new ApolloLink(outgoingRequestSpy).concat(defer.httpLink),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query1 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  const query2 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const initialData = {\n    people: {\n      __typename: \"Person\",\n      id: 1,\n      name: \"Luke\",\n      friends: [\n        {\n          __typename: \"Person\",\n          id: 5,\n        } as { __typename: \"Person\"; id: number; name?: string },\n        {\n          __typename: \"Person\",\n          id: 8,\n        } as { __typename: \"Person\"; id: number; name?: string },\n      ],\n    },\n  };\n  const initialResult: ObservableQuery.Result<typeof initialData> = {\n    data: initialData,\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  };\n\n  defer.enqueueInitialChunk({\n    data: initialData,\n    pending: [\n      { id: \"0\", path: [\"people\", \"friends\", 0] },\n      { id: \"1\", path: [\"people\", \"friends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  await expect(query1).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n  await expect(query2).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(query1).toEmitTypedValue(initialResult);\n  await expect(query2).toEmitTypedValue(initialResult);\n\n  const query3 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  await expect(query3).toEmitTypedValue(initialResult);\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const firstChunk: GraphQL17Alpha9Handler.SubsequentResult<\n    Record<string, unknown>\n  > = {\n    incremental: [\n      {\n        data: {\n          name: \"Leia\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: true,\n  };\n  const resultAfterFirstChunk = structuredClone(\n    initialResult\n  ) as ObservableQuery.Result<any>;\n  resultAfterFirstChunk.data.people.friends[0].name = \"Leia\";\n\n  defer.enqueueSubsequentChunk(firstChunk);\n\n  await expect(query1).toEmitTypedValue(resultAfterFirstChunk);\n  await expect(query2).toEmitTypedValue(resultAfterFirstChunk);\n  await expect(query3).toEmitTypedValue(resultAfterFirstChunk);\n\n  const query4 = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  await expect(query4).toEmitTypedValue(resultAfterFirstChunk);\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(1);\n\n  const secondChunk: GraphQL17Alpha9Handler.SubsequentResult<\n    Record<string, unknown>\n  > = {\n    incremental: [\n      {\n        data: {\n          name: \"Han Solo\",\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"1\" }],\n    hasNext: false,\n  };\n  const resultAfterSecondChunk = {\n    ...structuredClone(resultAfterFirstChunk),\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    dataState: \"complete\",\n    partial: false,\n  } as ObservableQuery.Result<any>;\n  resultAfterSecondChunk.data.people.friends[1].name = \"Han Solo\";\n\n  defer.enqueueSubsequentChunk(secondChunk);\n\n  await expect(query1).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query2).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query3).toEmitTypedValue(resultAfterSecondChunk);\n  await expect(query4).toEmitTypedValue(resultAfterSecondChunk);\n\n  // TODO: Re-enable once below condition can be met\n  /* const query5 = */ new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"network-only\" })\n  );\n  // TODO: Re-enable once notifyOnNetworkStatusChange controls whether we\n  // get the loading state. This test fails with the switch to RxJS for now\n  // since the initial value is emitted synchronously unlike zen-observable\n  // where the emitted result wasn't emitted until after this assertion.\n  // expect(query5).not.toEmitAnything();\n  expect(outgoingRequestSpy).toHaveBeenCalledTimes(2);\n});\n\nit.each([[\"cache-first\"], [\"no-cache\"]] as const)(\n  \"correctly merges deleted rows when receiving a deferred payload\",\n  async (fetchPolicy) => {\n    const query = gql`\n      query Characters {\n        characters {\n          id\n          uppercase\n          ... @defer {\n            lowercase\n          }\n        }\n      }\n    `;\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDeferStreamGraphQL17Alpha9();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: httpLink,\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    const observable = client.watchQuery({ query, fetchPolicy });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    enqueueInitialChunk({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      },\n      pending: [\n        { id: \"0\", path: [\"characters\", 0] },\n        { id: \"1\", path: [\"characters\", 1] },\n        { id: \"2\", path: [\"characters\", 2] },\n      ],\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [{ data: { lowercase: \"a\" }, id: \"0\" }],\n      completed: [{ id: \"0\" }],\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [\n        { data: { lowercase: \"b\" }, id: \"1\" },\n        { data: { lowercase: \"c\" }, id: \"2\" },\n      ],\n      completed: [{ id: \"1\" }, { id: \"2\" }],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\", lowercase: \"c\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    void observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n          { __typename: \"Character\", id: 3, uppercase: \"C\", lowercase: \"c\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    // on refetch, the list is shorter\n    enqueueInitialChunk({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\" },\n        ],\n      },\n      pending: [\n        { id: \"0\", path: [\"characters\", 0] },\n        { id: \"1\", path: [\"characters\", 1] },\n      ],\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: markAsStreaming({\n        characters:\n          // no-cache fetch policy doesn't merge with existing cache data, so\n          // the lowercase field is not available in the refetch\n          fetchPolicy === \"no-cache\" ?\n            [\n              { __typename: \"Character\", id: 1, uppercase: \"A\" },\n              { __typename: \"Character\", id: 2, uppercase: \"B\" },\n            ]\n          : [\n              {\n                __typename: \"Character\",\n                id: 1,\n                uppercase: \"A\",\n                lowercase: \"a\",\n              },\n              {\n                __typename: \"Character\",\n                id: 2,\n                uppercase: \"B\",\n                lowercase: \"b\",\n              },\n            ],\n      }),\n      dataState: \"streaming\",\n      loading: true,\n      networkStatus: NetworkStatus.streaming,\n      partial: true,\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [\n        { data: { lowercase: \"a\" }, id: \"0\" },\n        { data: { lowercase: \"b\" }, id: \"1\" },\n      ],\n      completed: [{ id: \"0\" }, { id: \"1\" }],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        characters: [\n          { __typename: \"Character\", id: 1, uppercase: \"A\", lowercase: \"a\" },\n          { __typename: \"Character\", id: 2, uppercase: \"B\", lowercase: \"b\" },\n        ],\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  }\n);\n"
  },
  {
    "path": "src/core/__tests__/client.watchQuery/streamDefer20220824.test.ts",
    "content": "import { from } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport {\n  executeSchemaGraphQL17Alpha2,\n  friendListSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  mockDefer20220824,\n  ObservableStream,\n  promiseWithResolvers,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { hasDirectives } from \"@apollo/client/utilities/internal\";\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\nfunction createLink(rootValue?: Record<string, unknown>) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha2(\n        friendListSchemaGraphQL17Alpha2,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\ntest(\"handles streamed scalar lists\", async () => {\n  const client = new ApolloClient({\n    link: createLink({ scalarList: [\"apple\", \"banana\", \"orange\"] }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query ScalarListQuery {\n      scalarList @stream(initialCount: 1)\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"apple\"],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      scalarList: [\"apple\", \"banana\", \"orange\"],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"handles streamed multi-dimensional lists\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      scalarListList: [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query ScalarListQuery {\n      scalarListList @stream(initialCount: 1)\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarListList: [[\"apple\", \"apple\", \"apple\"]],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      scalarListList: [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"merges cache updates that happen concurrently\", async () => {\n  const stream = mockDefer20220824();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  stream.enqueueInitialChunk({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  client.cache.writeFragment({\n    id: \"Friend:1\",\n    fragment: gql`\n      fragment FriendName on Friend {\n        name\n      }\n    `,\n    data: {\n      name: \"Jedi\",\n    },\n  });\n\n  stream.enqueueSubsequentChunk({\n    incremental: [\n      {\n        items: [{ __typename: \"Friend\", id: \"2\", name: \"Han\" }] as any,\n        path: [\"friendList\", 1],\n      },\n      {\n        items: [{ __typename: \"Friend\", id: \"3\", name: \"Leia\" }] as any,\n        path: [\"friendList\", 2],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Jedi\", // updated from cache\n        },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"handles errors from items before initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () =>\n        friends.map((friend, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n\n          return Promise.resolve(friend);\n        }),\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 2) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors from items after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () =>\n        friends.map((friend, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n\n          return Promise.resolve(friend);\n        }),\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles final chunk without incremental value\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    }),\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors thrown before initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 2) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors thrown after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\n// This test documents a sort of \"impossible\" situation with the older\n// incremental format when a list of non-null items throws due to a null value.\n// Here, the server emits an error for the item at index 1 because it is\n// non-null, but also emits the friend at index 2 to add to the array. This\n// leaves us in a bit of an impossible state as we can't really set\n// nonNullFriendList[1] to `null`, otherwise we violate the schema. Instead we\n// stop processing updates to the stream array while continuing to merge data,\n// errors, and extensions for other fields in future chunks.\n//\n// This can be addressed in a more robust way in the the future once Apollo\n// Client supports field-level errors rather just than top-level errors since\n// accessing index 1 would throw instead of returning a value. Until then, this\n// is the best we can do to ensure we don't introduce runtime errors that\n// TypeScript wouldn't be able to catch.\ntest(\"handles errors thrown due to null returned in non-null list items after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      nonNullFriendList: () => [friends[0], null, friends[1]],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      nonNullFriendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"ensures all chunks are streamed even when another non-null list returns an error\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: async function* () {\n        yield friends[0];\n        await wait(50);\n        yield friends[1];\n        await wait(50);\n        yield friends[2];\n      },\n      nonNullFriendList: () => [friends[0], null, friends[1]],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n      nonNullFriendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    }),\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"combines errors from other streamed fields with null items from non-null streamed fields\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: async function* () {\n        yield friends[0];\n        await wait(50);\n        throw new Error(\"Oops\");\n      },\n      nonNullFriendList: () => [friends[0], null, friends[1]],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n      nonNullFriendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n        {\n          message: \"Oops\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\nit(\"handles stream when in parent deferred fragment\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n\n  const client = new ApolloClient({\n    link: createLink({\n      nestedObject: {\n        scalarField: () => slowFieldPromise,\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      nestedObject {\n        ...DeferFragment @defer\n      }\n    }\n    fragment DeferFragment on NestedObject {\n      scalarField\n      nestedFriendList @stream(initialCount: 0) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  resolveSlowField(\"slow\");\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    }),\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles @defer inside @stream\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n  const {\n    promise: iterableCompletionPromise,\n    resolve: resolveIterableCompletion,\n  } = promiseWithResolvers();\n\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve({\n          id: friends[1].id,\n          name: () => slowFieldPromise,\n        });\n        await iterableCompletionPromise;\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream {\n        ...NameFragment @defer\n        id\n      }\n    }\n    fragment NameFragment on Friend {\n      name\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  resolveIterableCompletion(null);\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\" }],\n      }),\n      dataState: \"streaming\",\n    }),\n  });\n\n  resolveSlowField(\"Han\");\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\" },\n        ],\n      }),\n      dataState: \"streaming\",\n    }),\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"can use custom merge function to combine cached and streamed lists\", async () => {\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: (existing = [], incoming, { field }) => {\n              if (field && hasDirectives([\"stream\"], field)) {\n                const merged: any[] = [];\n\n                for (\n                  let i = 0;\n                  i < Math.max(existing.length, incoming.length);\n                  i++\n                ) {\n                  merged[i] =\n                    incoming[i] === undefined ? existing[i] : incoming[i];\n                }\n\n                return merged;\n              }\n\n              return incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => friends.map((friend) => Promise.resolve(friend)),\n    }),\n    cache,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-and-network\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n"
  },
  {
    "path": "src/core/__tests__/client.watchQuery/streamGraphQL17Alpha9.test.ts",
    "content": "import { from } from \"rxjs\";\n\nimport type { FieldMergeFunction } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport {\n  asyncIterableSubject,\n  executeSchemaGraphQL17Alpha9,\n  friendListSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n  ObservableStream,\n  promiseWithResolvers,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { hasDirectives } from \"@apollo/client/utilities/internal\";\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntype Friend = (typeof friends)[number];\n\nfunction createLink(rootValue?: Record<string, unknown>) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha9(\n        friendListSchemaGraphQL17Alpha9,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\ntest(\"handles streamed scalar lists\", async () => {\n  const client = new ApolloClient({\n    link: createLink({ scalarList: [\"apple\", \"banana\", \"orange\"] }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query ScalarListQuery {\n      scalarList @stream(initialCount: 1)\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"apple\"],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      scalarList: [\"apple\", \"banana\", \"orange\"],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"handles streamed multi-dimensional lists\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      scalarListList: [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query ScalarListQuery {\n      scalarListList @stream(initialCount: 1)\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarListList: [[\"apple\", \"apple\", \"apple\"]],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      scalarListList: [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"merges cache updates that happen concurrently\", async () => {\n  const stream = mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  stream.enqueueInitialChunk({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    pending: [{ id: \"0\", path: [\"friendList\"] }],\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  client.cache.writeFragment({\n    id: \"Friend:1\",\n    fragment: gql`\n      fragment FriendName on Friend {\n        name\n      }\n    `,\n    data: {\n      name: \"Jedi\",\n    },\n  });\n\n  stream.enqueueSubsequentChunk({\n    incremental: [\n      {\n        items: [\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ] as any,\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Jedi\", // updated from cache\n        },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"handles errors from items before initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () =>\n        friends.map((friend, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n\n          return Promise.resolve(friend);\n        }),\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 2) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors from items after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () =>\n        friends.map((friend, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n\n          return Promise.resolve(friend);\n        }),\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [{ message: \"bad\", path: [\"friendList\", 1] }],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles final chunk without incremental value\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    }),\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors thrown before initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 2) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: null,\n    },\n    error: new CombinedGraphQLErrors({\n      data: { friendList: null },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"friendList\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles errors thrown after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    error: new CombinedGraphQLErrors({\n      data: { friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }] },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"friendList\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\nit(\"handles errors thrown due to null returned in non-null list items after initialCount is reached\", async () => {\n  const client = new ApolloClient({\n    link: createLink({\n      nonNullFriendList: () => [friends[0], null, friends[1]],\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      nonNullFriendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n          path: [\"nonNullFriendList\", 1],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\nit(\"handles stream when in parent deferred fragment\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n\n  const client = new ApolloClient({\n    link: createLink({\n      nestedObject: {\n        scalarField: () => slowFieldPromise,\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      nestedObject {\n        ...DeferFragment @defer\n      }\n    }\n    fragment DeferFragment on NestedObject {\n      scalarField\n      nestedFriendList @stream(initialCount: 0) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  resolveSlowField(\"slow\");\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarField: \"slow\",\n        nestedFriendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    }),\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"handles @defer inside @stream\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n  const {\n    promise: iterableCompletionPromise,\n    resolve: resolveIterableCompletion,\n  } = promiseWithResolvers<void>();\n\n  const client = new ApolloClient({\n    link: createLink({\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve({\n          id: friends[1].id,\n          name: () => slowFieldPromise,\n        });\n        await iterableCompletionPromise;\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream {\n        ...NameFragment @defer\n        id\n      }\n    }\n    fragment NameFragment on Friend {\n      name\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  resolveIterableCompletion();\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n    }),\n  });\n\n  resolveSlowField(\"Han\");\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\" },\n        ],\n      }),\n      dataState: \"streaming\",\n    }),\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"can use custom merge function to combine cached and streamed lists\", async () => {\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: (existing = [], incoming, { field }) => {\n              if (field && hasDirectives([\"stream\"], field)) {\n                const merged: any[] = [];\n\n                for (\n                  let i = 0;\n                  i < Math.max(existing.length, incoming.length);\n                  i++\n                ) {\n                  merged[i] =\n                    incoming[i] === undefined ? existing[i] : incoming[i];\n                }\n\n                return merged;\n              }\n\n              return incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => friends.map((friend) => Promise.resolve(friend)),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-and-network\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\ntest(\"provides streamFieldInfo to merge functions\", async () => {\n  const merge = createMockStreamMergeFn();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => friends.map((friend) => Promise.resolve(friend)),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(merge).toHaveBeenCalledTimes(3);\n  expect(merge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [{ __ref: \"Friend:1\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    2,\n    [{ __ref: \"Friend:1\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    3,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"returns correct streamFieldInfo when final chunk is only hasNext: false\", async () => {\n  const merge = createMockStreamMergeFn();\n  const { stream: friendStream, subject } = asyncIterableSubject<Friend>();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: async () => friendStream,\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  subject.next(friends[0]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next(friends[1]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next(friends[2]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.complete();\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(merge).toHaveBeenCalledTimes(4);\n  expect(merge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [{ __ref: \"Friend:1\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    2,\n    [{ __ref: \"Friend:1\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    3,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    4,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"provides streamFieldInfo to merge functions in nested stream fields\", async () => {\n  const merge = createMockStreamMergeFn();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      NestedObject: {\n        fields: {\n          nestedFriendList: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      nestedObject: {\n        nestedFriendList: () =>\n          friends.map((friend) => Promise.resolve(friend)),\n      },\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      nestedObject {\n        nestedFriendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        nestedFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        nestedFriendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      nestedObject: {\n        __typename: \"NestedObject\",\n        nestedFriendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  expect(merge).toHaveBeenCalledTimes(3);\n  expect(merge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [{ __ref: \"Friend:1\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    2,\n    [{ __ref: \"Friend:1\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(merge).toHaveBeenNthCalledWith(\n    3,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"provides streamFieldInfo to merge functions in sibling stream fields\", async () => {\n  const friendListMerge = createMockStreamMergeFn();\n  const nonNullFriendListMerge = createMockStreamMergeFn();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: friendListMerge,\n          },\n          nonNullFriendList: {\n            merge: nonNullFriendListMerge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => friends.map((friend) => Promise.resolve(friend)),\n      nonNullFriendList: () => friends.map((friend) => Promise.resolve(friend)),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n      nonNullFriendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      nonNullFriendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n      nonNullFriendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n      nonNullFriendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n      nonNullFriendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(friendListMerge).toHaveBeenCalledTimes(3);\n  expect(friendListMerge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [{ __ref: \"Friend:1\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(friendListMerge).toHaveBeenNthCalledWith(\n    2,\n    [{ __ref: \"Friend:1\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(friendListMerge).toHaveBeenNthCalledWith(\n    3,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n\n  expect(nonNullFriendListMerge).toHaveBeenCalledTimes(3);\n  expect(nonNullFriendListMerge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [{ __ref: \"Friend:1\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(nonNullFriendListMerge).toHaveBeenNthCalledWith(\n    2,\n    [{ __ref: \"Friend:1\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(nonNullFriendListMerge).toHaveBeenNthCalledWith(\n    3,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }],\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"provides undefined streamFieldInfo to non-stream merge functions\", async () => {\n  const nestedObjectMerge = jest.fn((_, incoming) => incoming);\n  const friendListMerge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: friendListMerge,\n          },\n          nestedObject: {\n            merge: nestedObjectMerge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => friends,\n      nestedObject: () => ({}),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      nestedObject {\n        __typename\n      }\n      friendList {\n        id\n        name\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n      nestedObject: {\n        __typename: \"NestedObject\",\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(friendListMerge).toHaveBeenCalledTimes(1);\n  expect(friendListMerge).toHaveBeenCalledWith(\n    undefined,\n    [{ __ref: \"Friend:1\" }, { __ref: \"Friend:2\" }, { __ref: \"Friend:3\" }],\n    expect.not.objectContaining({\n      streamFieldInfo: expect.anything(),\n    })\n  );\n  expect(nestedObjectMerge).toHaveBeenCalledTimes(1);\n  expect(nestedObjectMerge).toHaveBeenCalledWith(\n    undefined,\n    { __typename: \"NestedObject\" },\n    expect.not.objectContaining({\n      streamFieldInfo: expect.anything(),\n    })\n  );\n});\n\ntest(\"sets correct streamFieldInfo when field name is same in different locations\", async () => {\n  const scalarListMerge = createMockStreamMergeFn();\n  const nestedScalarListMerge = createMockStreamMergeFn();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          scalarList: {\n            merge: scalarListMerge,\n          },\n        },\n      },\n      NestedObject: {\n        fields: {\n          scalarList: {\n            merge: nestedScalarListMerge,\n          },\n        },\n      },\n    },\n  });\n\n  const list = [\"one\", \"two\", \"three\"];\n\n  const client = new ApolloClient({\n    link: createLink({\n      scalarList: () => list.map((str) => Promise.resolve(str)),\n      nestedObject: () => ({\n        scalarList: list.map((str) => Promise.resolve(str)),\n      }),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      scalarList @stream(initialCount: 1)\n      nestedObject {\n        scalarList @stream(initialCount: 1)\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"one\"],\n      nestedObject: { __typename: \"NestedObject\", scalarList: [\"one\"] },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"one\", \"two\"],\n      nestedObject: { __typename: \"NestedObject\", scalarList: [\"one\", \"two\"] },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"one\", \"two\", \"three\"],\n      nestedObject: { __typename: \"NestedObject\", scalarList: [\"one\", \"two\"] },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      scalarList: [\"one\", \"two\", \"three\"],\n      nestedObject: {\n        __typename: \"NestedObject\",\n        scalarList: [\"one\", \"two\", \"three\"],\n      },\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(scalarListMerge).toHaveBeenCalledTimes(3);\n  expect(scalarListMerge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [\"one\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(scalarListMerge).toHaveBeenNthCalledWith(\n    2,\n    [\"one\"],\n    [\"one\", \"two\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(scalarListMerge).toHaveBeenNthCalledWith(\n    3,\n    [\"one\", \"two\"],\n    [\"one\", \"two\", \"three\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n\n  expect(nestedScalarListMerge).toHaveBeenCalledTimes(3);\n  expect(nestedScalarListMerge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [\"one\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  expect(nestedScalarListMerge).toHaveBeenNthCalledWith(\n    2,\n    [\"one\"],\n    [\"one\", \"two\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  expect(nestedScalarListMerge).toHaveBeenNthCalledWith(\n    3,\n    [\"one\", \"two\"],\n    [\"one\", \"two\", \"three\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"sets correct streamFieldInfo when stream field is inside another list\", async () => {\n  const merge = createMockStreamMergeFn();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Friend: {\n        fields: {\n          scalarList: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  const scalarList = [\"one\", \"two\", \"three\"];\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () =>\n        friends.slice(0, 2).map((friend, i) => ({\n          ...friend,\n          scalarList: scalarList.map((str, j) =>\n            wait((i + j) * 10).then(() => str)\n          ),\n        })),\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList {\n        id\n        name\n        scalarList @stream(initialCount: 1)\n      }\n    }\n  `;\n\n  const stream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\", scalarList: [\"one\"] },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\", scalarList: [\"one\"] },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Luke\",\n          scalarList: [\"one\", \"two\"],\n        },\n        {\n          __typename: \"Friend\",\n          id: \"2\",\n          name: \"Han\",\n          scalarList: [\"one\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Luke\",\n          scalarList: [\"one\", \"two\", \"three\"],\n        },\n        {\n          __typename: \"Friend\",\n          id: \"2\",\n          name: \"Han\",\n          scalarList: [\"one\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Luke\",\n          scalarList: [\"one\", \"two\", \"three\"],\n        },\n        {\n          __typename: \"Friend\",\n          id: \"2\",\n          name: \"Han\",\n          scalarList: [\"one\", \"two\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        {\n          __typename: \"Friend\",\n          id: \"1\",\n          name: \"Luke\",\n          scalarList: [\"one\", \"two\", \"three\"],\n        },\n        {\n          __typename: \"Friend\",\n          id: \"2\",\n          name: \"Han\",\n          scalarList: [\"one\", \"two\", \"three\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  expect(merge).toHaveBeenCalledTimes(6);\n  // friend:1 [\"one\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    1,\n    undefined,\n    [\"one\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  // friend:2 [\"one\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    2,\n    undefined,\n    [\"one\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: true, isLastChunk: false },\n    })\n  );\n  // friend:1 [\"one\", \"two\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    3,\n    [\"one\"],\n    [\"one\", \"two\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  // friend:1 [\"one\", \"two\", \"three\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    4,\n    [\"one\", \"two\"],\n    [\"one\", \"two\", \"three\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n  // friend:2 [\"one\", \"two\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    5,\n    [\"one\"],\n    [\"one\", \"two\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: false },\n    })\n  );\n  // friend:2 [\"one\", \"two\", \"three\"]\n  expect(merge).toHaveBeenNthCalledWith(\n    6,\n    [\"one\", \"two\"],\n    [\"one\", \"two\", \"three\"],\n    expect.objectContaining({\n      streamFieldInfo: { isFirstChunk: false, isLastChunk: true },\n    })\n  );\n});\n\ntest(\"truncates array with default merge function on refetch when last chunk is emitted when refetched array is shorter\", async () => {\n  let { stream: friendStream, subject } = asyncIterableSubject<Friend>();\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: async () => friendStream,\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observable = client.watchQuery({ query });\n  const stream = new ObservableStream(observable);\n\n  await expect(stream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  subject.next(friends[0]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next(friends[1]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next(friends[2]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.complete();\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n\n  ({ stream: friendStream, subject } = asyncIterableSubject<Friend>());\n\n  const refetchPromise = observable.refetch();\n\n  subject.next({ ...friends[0], name: `${friends[0].name} (refetch)` });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    partial: false,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next({ ...friends[1], name: `${friends[1].name} (refetch)` });\n  subject.complete();\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n      ],\n    },\n  });\n});\n\ntest(\"truncates array when fetched array is shorter than cached array with cache-and-network fetch policy\", async () => {\n  let { stream: friendStream, subject } = asyncIterableSubject<Friend>();\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: async () => friendStream,\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: friends.map((friend) => ({\n        __typename: \"Friend\",\n        id: String(friend.id),\n        name: `Cached ${friend.name}`,\n      })),\n    },\n  });\n\n  const stream = new ObservableStream(\n    client.watchQuery({ query, fetchPolicy: \"cache-and-network\" })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: false,\n  });\n\n  subject.next(friends[0]);\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  subject.next(friends[1]);\n  subject.complete();\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(stream).toEmitTypedValue({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n\n  await expect(stream).not.toEmitAnything();\n});\n\nfunction createMockStreamMergeFn() {\n  return jest.fn<\n    ReturnType<FieldMergeFunction<any[]>>,\n    Parameters<FieldMergeFunction<any[]>>\n  >((existing = [], incoming) => {\n    const length = Math.max(existing.length, incoming.length);\n    const result = [];\n\n    for (let i = 0; i < length; i++) {\n      result[i] = incoming[i] === undefined ? existing[i] : incoming[i];\n    }\n\n    return result;\n  });\n}\n"
  },
  {
    "path": "src/core/__tests__/client.writeFragment/general.test.ts",
    "content": "import { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\n\ntest(\"can use `from` with writeFragment\", async () => {\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    data: {\n      id: 1,\n      a: 1,\n      b: 2,\n      __typename: \"Foo\",\n    },\n    from: { __typename: \"Foo\", id: 1 },\n    fragment: gql`\n      fragment foo on Foo {\n        id\n        a\n        b\n      }\n    `,\n  });\n\n  expect(client.extract()).toEqual({\n    __META: {\n      extraRootIds: [\"Foo:1\"],\n    },\n    \"Foo:1\": {\n      __typename: \"Foo\",\n      id: 1,\n      a: 1,\n      b: 2,\n    },\n  });\n\n  client.writeFragment({\n    data: {\n      c: 3,\n      d: 4,\n      __typename: \"Foo\",\n    },\n    from: { __ref: \"Foo:1\" },\n    fragment: gql`\n      fragment foo on Foo {\n        c\n        d\n      }\n    `,\n  });\n\n  expect(client.extract()).toEqual({\n    __META: {\n      extraRootIds: [\"Foo:1\"],\n    },\n    \"Foo:1\": {\n      __typename: \"Foo\",\n      id: 1,\n      a: 1,\n      b: 2,\n      c: 3,\n      d: 4,\n    },\n  });\n\n  client.writeFragment({\n    data: {\n      e: 5,\n      f: 6,\n      __typename: \"Foo\",\n    },\n    from: \"Foo:1\",\n    fragment: gql`\n      fragment foo on Foo {\n        e\n        f\n      }\n    `,\n  });\n\n  expect(client.extract()).toEqual({\n    __META: {\n      extraRootIds: [\"Foo:1\"],\n    },\n    \"Foo:1\": {\n      __typename: \"Foo\",\n      id: 1,\n      a: 1,\n      b: 2,\n      c: 3,\n      d: 4,\n      e: 5,\n      f: 6,\n    },\n  });\n});\n"
  },
  {
    "path": "src/core/__tests__/client.writeQuery/extensions.test.ts",
    "content": "import { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\n\ntest(\"extensions are available in merge functions\", () => {\n  const merge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  const extensions = {\n    customField: \"customValue\",\n    metadata: { version: 1 },\n  };\n\n  client.writeQuery({\n    query: gql`\n      query {\n        book {\n          title\n        }\n      }\n    `,\n    data: {\n      book: {\n        __typename: \"Book\",\n        title: \"Test Book\",\n      },\n    },\n    extensions,\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    undefined,\n    { __typename: \"Book\", title: \"Test Book\" },\n    expect.objectContaining({ extensions })\n  );\n});\n\ntest(\"extensions are undefined when not provided\", () => {\n  const merge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            merge,\n          },\n        },\n      },\n    },\n  });\n\n  cache.writeQuery({\n    query: gql`\n      query {\n        book {\n          title\n        }\n      }\n    `,\n    data: {\n      book: {\n        __typename: \"Book\",\n        title: \"Test Book\",\n      },\n    },\n  });\n\n  expect(merge).toHaveBeenCalledTimes(1);\n  expect(merge).toHaveBeenCalledWith(\n    undefined,\n    { __typename: \"Book\", title: \"Test Book\" },\n    expect.objectContaining({ extensions: undefined })\n  );\n});\n\ntest(\"extensions are available in nested merges\", () => {\n  const extensions = {\n    depth: \"nested\",\n  };\n\n  const outerMerge = jest.fn((_, incoming) => incoming);\n  const innerMerge = jest.fn((_, incoming) => incoming);\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          book: {\n            merge: outerMerge,\n          },\n        },\n      },\n      Book: {\n        fields: {\n          chapters: {\n            merge: innerMerge,\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        book {\n          title\n          chapters {\n            title\n          }\n        }\n      }\n    `,\n    data: {\n      book: {\n        __typename: \"Book\",\n        title: \"Test Book\",\n        chapters: [\n          {\n            __typename: \"Chapter\",\n            title: \"Chapter 1\",\n          },\n        ],\n      },\n    },\n    extensions,\n  });\n\n  expect(outerMerge).toHaveBeenCalledTimes(1);\n  expect(outerMerge).toHaveBeenCalledWith(\n    undefined,\n    {\n      __typename: \"Book\",\n      title: \"Test Book\",\n      chapters: [{ __typename: \"Chapter\", title: \"Chapter 1\" }],\n    },\n    expect.objectContaining({ extensions })\n  );\n  expect(innerMerge).toHaveBeenCalledTimes(1);\n  expect(innerMerge).toHaveBeenCalledWith(\n    undefined,\n    [{ __typename: \"Chapter\", title: \"Chapter 1\" }],\n    expect.objectContaining({ extensions })\n  );\n});\n"
  },
  {
    "path": "src/core/__tests__/fetchPolicies.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { gql } from \"graphql-tag\";\nimport { map, Observable } from \"rxjs\";\n\nimport type { ObservableQuery } from \"@apollo/client\";\nimport { ApolloClient, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nimport type { WatchQueryFetchPolicy } from \"../watchQueryOptions.js\";\n\nconst query = gql`\n  query {\n    author {\n      __typename\n      id\n      firstName\n      lastName\n    }\n  }\n`;\n\nconst result = {\n  author: {\n    __typename: \"Author\",\n    id: 1,\n    firstName: \"John\",\n    lastName: \"Smith\",\n  },\n};\n\nconst mutation = gql`\n  mutation updateName($id: ID!, $firstName: String!) {\n    updateName(id: $id, firstName: $firstName) {\n      __typename\n      id\n      firstName\n    }\n  }\n`;\n\nconst variables = {\n  id: 1,\n  firstName: \"James\",\n};\n\nconst mutationResult = {\n  updateName: {\n    id: 1,\n    __typename: \"Author\",\n    firstName: \"James\",\n  },\n};\n\nconst merged = { author: { ...result.author, firstName: \"James\" } };\n\nconst createLink = () =>\n  new MockLink([\n    {\n      request: { query },\n      result: { data: result },\n    },\n    {\n      request: { query },\n      result: { data: result },\n    },\n  ]);\n\nconst createFailureLink = () =>\n  new MockLink([\n    {\n      request: { query },\n      error: new Error(\"query failed\"),\n    },\n    {\n      request: { query },\n      result: { data: result },\n    },\n  ]);\n\nconst createMutationLink = () =>\n  // fetch the data\n  new MockLink([\n    {\n      request: { query },\n      result: { data: result },\n    }, // update the data\n    {\n      request: { query: mutation, variables },\n      result: { data: mutationResult },\n    }, // get the new results\n    {\n      request: { query },\n      result: { data: merged },\n    },\n  ]);\n\ndescribe(\"network-only\", () => {\n  it(\"requests from the network even if already in cache\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query });\n    const actualResult = await client.query({\n      fetchPolicy: \"network-only\",\n      query,\n    });\n\n    expect(actualResult.data).toEqual(result);\n    expect(called).toBe(4);\n  });\n\n  it(\"saves data to the cache on success\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query, fetchPolicy: \"network-only\" });\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n    expect(called).toBe(2);\n  });\n\n  it(\"does not save data to the cache on failure\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createFailureLink()),\n      cache: new InMemoryCache(),\n    });\n\n    let didFail = false;\n    await client.query({ query, fetchPolicy: \"network-only\" }).catch((e) => {\n      expect(e.message).toMatch(\"query failed\");\n      didFail = true;\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n    // the first error doesn't call .map on the inspector\n    expect(called).toBe(3);\n    expect(didFail).toBe(true);\n  });\n\n  it(\"updates the cache on a mutation\", async () => {\n    const inspector = new ApolloLink((operation, forward) => {\n      return forward(operation).pipe(\n        map((result) => {\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createMutationLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query });\n    // XXX currently only no-cache is supported as a fetchPolicy\n    // this mainly serves to ensure the cache is updated correctly\n    await client.mutate({ mutation, variables });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(merged);\n  });\n});\n\ndescribe(\"no-cache\", () => {\n  it(\"requests from the network when not in cache\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createLink()),\n      cache: new InMemoryCache(),\n    });\n\n    const actualResult = await client.query({ fetchPolicy: \"no-cache\", query });\n\n    expect(actualResult.data).toEqual(result);\n    expect(called).toBe(2);\n  });\n\n  it(\"requests from the network even if already in cache\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query });\n    const actualResult = await client.query({ fetchPolicy: \"no-cache\", query });\n\n    expect(actualResult.data).toEqual(result);\n    expect(called).toBe(4);\n  });\n\n  it(\"does not save the data to the cache on success\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query, fetchPolicy: \"no-cache\" });\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n    // the second query couldn't read anything from the cache\n    expect(called).toBe(4);\n  });\n\n  it(\"does not save data to the cache on failure\", async () => {\n    let called = 0;\n    const inspector = new ApolloLink((operation, forward) => {\n      called++;\n      return forward(operation).pipe(\n        map((result) => {\n          called++;\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createFailureLink()),\n      cache: new InMemoryCache(),\n    });\n\n    let didFail = false;\n    await client.query({ query, fetchPolicy: \"no-cache\" }).catch((e) => {\n      expect(e.message).toMatch(\"query failed\");\n      didFail = true;\n    });\n\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n    // the first error doesn't call .map on the inspector\n    expect(called).toBe(3);\n    expect(didFail).toBe(true);\n  });\n\n  it(\"does not update the cache on a mutation\", async () => {\n    const inspector = new ApolloLink((operation, forward) => {\n      return forward(operation).pipe(\n        map((result) => {\n          return result;\n        })\n      );\n    });\n\n    const client = new ApolloClient({\n      link: inspector.concat(createMutationLink()),\n      cache: new InMemoryCache(),\n    });\n\n    await client.query({ query });\n    await client.mutate({ mutation, variables, fetchPolicy: \"no-cache\" });\n    const actualResult = await client.query({ query });\n\n    expect(actualResult.data).toEqual(result);\n  });\n\n  describe(\"when notifyOnNetworkStatusChange is set\", () => {\n    it(\"gives appropriate networkStatus for watched queries\", async () => {\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n        localState: new LocalState({\n          resolvers: {\n            Query: {\n              hero(_data, args) {\n                return {\n                  __typename: \"Hero\",\n                  ...args,\n                  name: \"Luke Skywalker\",\n                };\n              },\n            },\n          },\n        }),\n      });\n\n      const observable = client.watchQuery({\n        query: gql`\n          query FetchLuke($id: String) {\n            hero(id: $id) @client {\n              id\n              name\n            }\n          }\n        `,\n        fetchPolicy: \"no-cache\",\n        variables: { id: \"1\" },\n      });\n\n      const stream = new ObservableStream(observable);\n\n      function dataWithId(id: number | string) {\n        return {\n          hero: {\n            __typename: \"Hero\",\n            id: String(id),\n            name: \"Luke Skywalker\",\n          },\n        };\n      }\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataWithId(1),\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await observable.setVariables({ id: \"2\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        partial: true,\n      });\n\n      await expect(stream).toEmitTypedValue({\n        data: dataWithId(2),\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await observable.refetch();\n\n      await expect(stream).toEmitTypedValue({\n        data: dataWithId(2),\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: false,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await expect(stream).toEmitTypedValue({\n        data: dataWithId(2),\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await observable.refetch({ id: \"3\" });\n\n      await expect(stream).toEmitTypedValue({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        partial: true,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await expect(stream).toEmitTypedValue({\n        data: dataWithId(3),\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        partial: false,\n      });\n      expect(client.cache.extract(true)).toEqual({});\n\n      await expect(stream).not.toEmitAnything();\n    });\n  });\n});\n\ndescribe(\"cache-first\", () => {\n  it(\"does not trigger network request during optimistic update\", async () => {\n    const results: any[] = [];\n    const client = new ApolloClient({\n      link: new ApolloLink((operation, forward) => {\n        return forward(operation).pipe(\n          map((result) => {\n            results.push(result);\n            return result;\n          })\n        );\n      }).concat(createMutationLink()),\n      cache: new InMemoryCache(),\n    });\n\n    let inOptimisticTransaction = false;\n\n    const stream = new ObservableStream(\n      client.watchQuery({\n        query,\n        fetchPolicy: \"cache-and-network\",\n        returnPartialData: true,\n      })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n    expect(results).toHaveLength(0);\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        author: {\n          __typename: \"Author\",\n          id: 1,\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(results).toHaveLength(1);\n\n    inOptimisticTransaction = true;\n    client.cache.recordOptimisticTransaction((cache) => {\n      // Silence partial data write error\n      using _ = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          author: {\n            __typename: \"Bogus\",\n          },\n        },\n      });\n    }, \"bogus\");\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        author: {\n          __typename: \"Bogus\",\n        },\n      },\n      dataState: \"partial\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: true,\n    });\n    expect(results).toHaveLength(1);\n\n    setTimeout(() => {\n      inOptimisticTransaction = false;\n      client.cache.removeOptimistic(\"bogus\");\n    }, 50);\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        author: {\n          __typename: \"Author\",\n          id: 1,\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    // A network request should not be triggered until after the bogus\n    // optimistic transaction has been removed.\n    expect(inOptimisticTransaction).toBe(false);\n    expect(results).toHaveLength(1);\n\n    client.cache.writeQuery({\n      query,\n      data: {\n        author: {\n          __typename: \"Author\",\n          id: 2,\n          firstName: \"Chinua\",\n          lastName: \"Achebe\",\n        },\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        author: {\n          __typename: \"Author\",\n          id: 2,\n          firstName: \"Chinua\",\n          lastName: \"Achebe\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(inOptimisticTransaction).toBe(false);\n    expect(results).toHaveLength(1);\n\n    await expect(stream).not.toEmitAnything();\n  });\n});\n\ndescribe(\"cache-only\", () => {\n  it(\"allows explicit refetch to happen\", async () => {\n    let counter = 0;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink(\n        () =>\n          new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({\n                data: {\n                  count: ++counter,\n                },\n              });\n              observer.complete();\n            });\n          })\n      ),\n    });\n\n    const query = gql`\n      query {\n        count\n      }\n    `;\n\n    const observable = client.watchQuery({\n      query,\n      nextFetchPolicy: \"cache-only\",\n    });\n\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      data: undefined,\n      dataState: \"empty\",\n      partial: true,\n    });\n    await expect(stream).toEmitTypedValue({\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      data: {\n        count: 1,\n      },\n      dataState: \"complete\",\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-only\");\n\n    await expect(observable.refetch()).resolves.toStrictEqualTyped({\n      data: { count: 2 },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        count: 1,\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        count: 2,\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(observable.options.fetchPolicy).toBe(\"cache-only\");\n\n    await expect(stream).not.toEmitAnything();\n  });\n});\n\ndescribe(\"cache-and-network\", function () {\n  it(\"gives appropriate networkStatus for refetched queries\", async () => {\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n      localState: new LocalState({\n        resolvers: {\n          Query: {\n            hero(_data, args) {\n              return {\n                __typename: \"Hero\",\n                ...args,\n                name: \"Luke Skywalker\",\n              };\n            },\n          },\n        },\n      }),\n    });\n\n    const observable = client.watchQuery({\n      query: gql`\n        query FetchLuke($id: String) {\n          hero(id: $id) @client {\n            id\n            name\n          }\n        }\n      `,\n      fetchPolicy: \"cache-and-network\",\n      variables: { id: \"1\" },\n    });\n\n    const stream = new ObservableStream(observable);\n\n    function dataWithId(id: number | string) {\n      return {\n        hero: {\n          __typename: \"Hero\",\n          id: String(id),\n          name: \"Luke Skywalker\",\n        },\n      };\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: dataWithId(1),\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await observable.setVariables({ id: \"2\" });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: dataWithId(2),\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await observable.refetch();\n\n    await expect(stream).toEmitTypedValue({\n      data: dataWithId(2),\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: dataWithId(2),\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await observable.refetch({ id: \"3\" });\n\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: dataWithId(3),\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    await expect(stream).not.toEmitAnything();\n  });\n});\n\ndescribe(\"standby\", () => {\n  test(\"is not supported with client.query\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    expect(() =>\n      client.query({\n        query,\n        // @ts-expect-error\n        fetchPolicy: \"standby\",\n      })\n    ).toThrow();\n  });\n});\n\ndescribe(\"nextFetchPolicy\", () => {\n  type TData = {\n    echo: {\n      __typename: \"Echo\";\n      linkCounter: number;\n      opName: string;\n      opVars: Record<string, any>;\n    };\n  };\n\n  type TVariables = {\n    refetching?: boolean;\n  };\n\n  const EchoQuery: TypedDocumentNode<TData> = gql`\n    query EchoQuery {\n      echo {\n        linkCounter\n        opName\n        opVars\n      }\n    }\n  `;\n\n  function makeLink() {\n    let linkCounter = 0;\n    return new ApolloLink(\n      (request) =>\n        new Observable((observer) => {\n          setTimeout(() => {\n            observer.next({\n              data: {\n                echo: {\n                  __typename: \"Echo\",\n                  linkCounter: ++linkCounter,\n                  opName: request.operationName,\n                  opVars: request.variables,\n                },\n              },\n            });\n            observer.complete();\n          }, 10);\n        })\n    );\n  }\n\n  const checkNextFetchPolicy = (args: {\n    fetchPolicy: WatchQueryFetchPolicy;\n    nextFetchPolicy: ApolloClient.WatchQueryOptions<\n      TData,\n      {}\n    >[\"nextFetchPolicy\"];\n    useDefaultOptions: boolean;\n    checkResult: (info: {\n      stream: ObservableStream<ObservableQuery.Result<TData>>;\n      observable: ObservableQuery<TData, TVariables>;\n    }) => Promise<void>;\n  }) =>\n    it(`transitions ${args.fetchPolicy} to ${\n      typeof args.nextFetchPolicy === \"function\" ?\n        args.nextFetchPolicy.name\n      : args.nextFetchPolicy\n    } (${args.useDefaultOptions ? \"\" : \"not \"}using defaults)`, async () => {\n      const client = new ApolloClient({\n        link: makeLink(),\n        cache: new InMemoryCache(),\n        defaultOptions: {\n          watchQuery:\n            args.useDefaultOptions ?\n              {\n                nextFetchPolicy: args.nextFetchPolicy,\n              }\n            : {},\n        },\n      });\n\n      const watchQueryOptions: ApolloClient.WatchQueryOptions<\n        TData,\n        TVariables\n      > = {\n        query: EchoQuery,\n        fetchPolicy: args.fetchPolicy,\n      };\n\n      if (!args.useDefaultOptions) {\n        watchQueryOptions.nextFetchPolicy = args.nextFetchPolicy;\n      }\n\n      const observable = client.watchQuery(watchQueryOptions);\n\n      expect(observable.options.fetchPolicy).toBe(args.fetchPolicy);\n\n      await args.checkResult({\n        observable,\n        stream: new ObservableStream(observable),\n      });\n    });\n\n  type CheckOptions = Parameters<typeof checkNextFetchPolicy>[0];\n  type NextFetchPolicy = CheckOptions[\"nextFetchPolicy\"];\n  type CheckResultCallback = CheckOptions[\"checkResult\"];\n\n  // We'll use this same OnResultCallback for multiple tests, to make it easier\n  // to tell that the behavior of the tests is the same.\n  const onResultNetworkOnlyToCacheFirst: CheckResultCallback = async ({\n    observable,\n    stream,\n  }) => {\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.refetch({ refetching: true });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 2,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: true,\n            },\n          },\n        },\n      });\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 2,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: true,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.reobserve({\n        variables: {\n          refetching: false,\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 3,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: false,\n            },\n          },\n        },\n      });\n\n      // Changing variables resets the fetchPolicy to its initial value - but\n      // it also immediately applies `nextFetchPolicy` again.\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n    }\n\n    // Changing variables resets the fetchPolicy to its initial value of `network-only`.\n    // That means the loading state will reset to an initial state, and `network-only`\n    // is not allowed to read data from the cache, hence `data` is `undefined`.\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 3,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: false,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n\n    // But nextFetchPolicy is applied again after the first request.\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    await expect(stream).not.toEmitAnything();\n  };\n\n  checkNextFetchPolicy({\n    useDefaultOptions: false,\n    fetchPolicy: \"network-only\",\n    nextFetchPolicy: \"cache-first\",\n    checkResult: onResultNetworkOnlyToCacheFirst,\n  });\n\n  checkNextFetchPolicy({\n    useDefaultOptions: true,\n    fetchPolicy: \"network-only\",\n    nextFetchPolicy: \"cache-first\",\n    checkResult: onResultNetworkOnlyToCacheFirst,\n  });\n\n  const nextFetchPolicyNetworkOnlyToCacheFirst: NextFetchPolicy = function (\n    currentFetchPolicy,\n    context\n  ): WatchQueryFetchPolicy {\n    expect(currentFetchPolicy).toBe(context.options.fetchPolicy);\n    switch (context.reason) {\n      case \"variables-changed\":\n        expect(context.initialFetchPolicy).toBe(\n          context.options.initialFetchPolicy\n        );\n        return context.initialFetchPolicy;\n      default:\n      case \"after-fetch\":\n        return \"cache-first\";\n    }\n  };\n\n  checkNextFetchPolicy({\n    useDefaultOptions: false,\n    fetchPolicy: \"network-only\",\n    nextFetchPolicy: nextFetchPolicyNetworkOnlyToCacheFirst,\n    checkResult: onResultNetworkOnlyToCacheFirst,\n  });\n\n  checkNextFetchPolicy({\n    useDefaultOptions: true,\n    fetchPolicy: \"network-only\",\n    nextFetchPolicy: nextFetchPolicyNetworkOnlyToCacheFirst,\n    checkResult: onResultNetworkOnlyToCacheFirst,\n  });\n\n  const onResultCacheAndNetworkToCacheFirst: CheckResultCallback = async ({\n    observable,\n    stream,\n  }) => {\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.refetch({ refetching: true });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 2,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: true,\n            },\n          },\n        },\n      });\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 2,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: true,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    // Changing variables resets the fetchPolicy to its initial value.\n    // expect(observable.options.fetchPolicy).toBe(\"cache-and-network\");\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.reobserve({\n        variables: {\n          refetching: false,\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 3,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: false,\n            },\n          },\n        },\n      });\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 2,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: true,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      partial: false,\n    });\n    // But nextFetchPolicy is applied again after the first request.\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 3,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: false,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    await expect(stream).not.toEmitAnything();\n  };\n\n  checkNextFetchPolicy({\n    useDefaultOptions: false,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: \"cache-first\",\n    checkResult: onResultCacheAndNetworkToCacheFirst,\n  });\n\n  checkNextFetchPolicy({\n    useDefaultOptions: true,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: \"cache-first\",\n    checkResult: onResultCacheAndNetworkToCacheFirst,\n  });\n\n  const nextFetchPolicyCacheAndNetworkToCacheFirst: NextFetchPolicy = function (\n    currentFetchPolicy,\n    context\n  ): WatchQueryFetchPolicy {\n    expect(currentFetchPolicy).toBe(context.options.fetchPolicy);\n    switch (context.reason) {\n      case \"variables-changed\":\n        expect(context.initialFetchPolicy).toBe(\n          context.options.initialFetchPolicy\n        );\n        return context.initialFetchPolicy;\n      default:\n      case \"after-fetch\":\n        return \"cache-first\";\n    }\n  };\n\n  checkNextFetchPolicy({\n    useDefaultOptions: false,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: nextFetchPolicyCacheAndNetworkToCacheFirst,\n    checkResult: onResultCacheAndNetworkToCacheFirst,\n  });\n\n  checkNextFetchPolicy({\n    useDefaultOptions: true,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: nextFetchPolicyCacheAndNetworkToCacheFirst,\n    checkResult: onResultCacheAndNetworkToCacheFirst,\n  });\n\n  const nextFetchPolicyAlwaysCacheFirst: NextFetchPolicy = function (\n    currentFetchPolicy,\n    context\n  ): WatchQueryFetchPolicy {\n    expect(currentFetchPolicy).toBe(context.options.fetchPolicy);\n    // Return cache-first no matter what context.reason was.\n    return \"cache-first\";\n  };\n\n  const onResultCacheAndNetworkAlwaysCacheFirst: CheckResultCallback = async ({\n    observable,\n    stream,\n  }) => {\n    await expect(stream).toEmitTypedValue({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      partial: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.refetch({ refetching: true });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 2,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: true,\n            },\n          },\n        },\n      });\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 1,\n          opName: \"EchoQuery\",\n          opVars: {},\n        },\n      },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      partial: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 2,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: true,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    {\n      const result = await observable.reobserve({\n        variables: {\n          refetching: false,\n        },\n      });\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          echo: {\n            __typename: \"Echo\",\n            linkCounter: 2,\n            opName: \"EchoQuery\",\n            opVars: {\n              refetching: true,\n            },\n          },\n        },\n      });\n\n      // The nextFetchPolicy function we provided always returns cache-first,\n      // even when context.reason is variables-changed (which by default\n      // resets the fetchPolicy to context.initialFetchPolicy), so cache-first is\n      // still what we see here.\n      expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n    }\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        echo: {\n          __typename: \"Echo\",\n          linkCounter: 2,\n          opName: \"EchoQuery\",\n          opVars: {\n            refetching: true,\n          },\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      partial: false,\n    });\n    expect(observable.options.fetchPolicy).toBe(\"cache-first\");\n\n    await expect(stream).not.toEmitAnything();\n  };\n\n  checkNextFetchPolicy({\n    useDefaultOptions: false,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: nextFetchPolicyAlwaysCacheFirst,\n    checkResult: onResultCacheAndNetworkAlwaysCacheFirst,\n  });\n\n  checkNextFetchPolicy({\n    useDefaultOptions: true,\n    fetchPolicy: \"cache-and-network\",\n    nextFetchPolicy: nextFetchPolicyAlwaysCacheFirst,\n    checkResult: onResultCacheAndNetworkAlwaysCacheFirst,\n  });\n});\n"
  },
  {
    "path": "src/core/deprecated.ts",
    "content": "import type { ApolloCache } from \"@apollo/client/cache\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport type { DataState, OperationVariables } from \"./types.js\";\n\n/** @deprecated Use `ApolloClient.Options` instead */\nexport type ApolloClientOptions = ApolloClient.Options;\n\n/** @deprecated Use `ObservableQuery.Result` instead */\nexport type ApolloQueryResult<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n> = ObservableQuery.Result<TData, TStates>;\n\n/** @deprecated Use `ApolloClient.DefaultOptions` instead */\nexport type DefaultOptions = ApolloClient.DefaultOptions;\n\n/** @deprecated Use `ApolloClient.DevtoolsOptions` instead */\nexport type DevtoolsOptions = ApolloClient.DevtoolsOptions;\n\n/** @deprecated Use `ApolloClient.MutateOptions` instead */\nexport type MutationOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TCache extends ApolloCache = ApolloCache,\n> = ApolloClient.MutateOptions<TData, TVariables, TCache>;\n\n/** @deprecated Use `ApolloClient.MutateResult` instead */\nexport type MutateResult<TData = unknown> = ApolloClient.MutateResult<TData>;\n\n/** @deprecated Use `ApolloClient.QueryOptions` instead */\nexport type QueryOptions<\n  TVariables extends OperationVariables = OperationVariables,\n  // eslint-disable-next-line local-rules/tdata-tvariables-order\n  TData = unknown,\n> = ApolloClient.QueryOptions<TData, TVariables>;\n\n/** @deprecated Use `ApolloClient.RefetchQueriesOptions` instead */\nexport type RefetchQueriesOptions<\n  TCache extends ApolloCache,\n  TResult,\n> = ApolloClient.RefetchQueriesOptions<TCache, TResult>;\n\n/** @deprecated Use `ApolloClient.RefetchQueriesResult` instead */\nexport type RefetchQueriesResult<TResult> =\n  ApolloClient.RefetchQueriesResult<TResult>;\n\n/** @deprecated Use `ObservableQuery.SubscribeToMoreOptions` instead */\nexport type SubscribeToMoreOptions<\n  // eslint-disable-next-line local-rules/tdata-tvariables-order\n  TData = unknown,\n  TSubscriptionVariables extends OperationVariables = OperationVariables,\n  TSubscriptionData = TData,\n  TVariables extends OperationVariables = TSubscriptionVariables,\n> = ObservableQuery.SubscribeToMoreOptions<\n  TData,\n  TSubscriptionVariables,\n  TSubscriptionData,\n  TVariables\n>;\n\n/** @deprecated Use `ApolloClient.SubscribeOptions` instead */\nexport type SubscriptionOptions<\n  TVariables extends OperationVariables = OperationVariables,\n  // eslint-disable-next-line local-rules/tdata-tvariables-order\n  TData = unknown,\n> = ApolloClient.SubscribeOptions<TData, TVariables>;\n\n/** @deprecated Use `ApolloClient.WatchQueryOptions` instead */\nexport type WatchQueryOptions<\n  TVariables extends OperationVariables = OperationVariables,\n  // eslint-disable-next-line local-rules/tdata-tvariables-order\n  TData = unknown,\n> = ApolloClient.WatchQueryOptions<TData, TVariables>;\n"
  },
  {
    "path": "src/core/index.ts",
    "content": "/* Core */\n\nexport type {\n  ApolloClientOptions,\n  ApolloQueryResult,\n  DefaultOptions,\n  DevtoolsOptions,\n  MutateResult,\n  MutationOptions,\n  QueryOptions,\n  RefetchQueriesOptions,\n  RefetchQueriesResult,\n  SubscribeToMoreOptions,\n  SubscriptionOptions,\n  WatchQueryOptions,\n} from \"./deprecated.js\";\nexport { ApolloClient } from \"./ApolloClient.js\";\nexport { ObservableQuery } from \"./ObservableQuery.js\";\nexport type {\n  ErrorPolicy,\n  FetchPolicy,\n  MutationFetchPolicy,\n  RefetchWritePolicy,\n  SubscribeToMoreFunction,\n  SubscribeToMoreUpdateQueryFn,\n  UpdateQueryMapFn,\n  UpdateQueryOptions,\n  WatchQueryFetchPolicy,\n} from \"./watchQueryOptions.js\";\nexport { NetworkStatus } from \"./networkStatus.js\";\nexport type {\n  DataState,\n  DataValue,\n  DefaultContext,\n  ErrorLike,\n  GetDataState,\n  InternalRefetchQueriesInclude,\n  InternalRefetchQueriesMap,\n  InternalRefetchQueriesOptions,\n  InternalRefetchQueriesResult,\n  InternalRefetchQueryDescriptor,\n  MutationQueryReducer,\n  MutationQueryReducersMap,\n  MutationUpdaterFunction,\n  NormalizedExecutionResult,\n  OnQueryUpdated,\n  OperationVariables,\n  RefetchQueriesInclude,\n  RefetchQueriesPromiseResults,\n  RefetchQueryDescriptor,\n  SubscriptionObservable,\n  TypedDocumentNode,\n  TypeOverrides,\n} from \"./types.js\";\nexport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n  LinkError,\n  LocalStateError,\n  ServerError,\n  ServerParseError,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\n/* Cache */\n\nexport type {\n  ApolloReducerConfig,\n  Cache,\n  DiffQueryAgainstStoreOptions,\n  FieldFunctionOptions,\n  FieldMergeFunction,\n  FieldPolicy,\n  FieldReadFunction,\n  IdGetter,\n  IdGetterObj,\n  InMemoryCacheConfig,\n  MergeInfo,\n  MergeTree,\n  NormalizedCache,\n  NormalizedCacheObject,\n  OptimisticStoreItem,\n  PossibleTypesMap,\n  ReactiveVar,\n  ReadMergeModifyContext,\n  ReadQueryOptions,\n  StoreValue,\n  // All the exports (types) from ../cache, minus cacheSlot,\n  // which we want to keep semi-private.\n  Transaction,\n  TypePolicies,\n  TypePolicy,\n  WatchFragmentOptions,\n  WatchFragmentResult,\n} from \"@apollo/client/cache\";\n\nexport {\n  ApolloCache,\n  defaultDataIdFromObject,\n  InMemoryCache,\n  makeVar,\n  MissingFieldError,\n} from \"@apollo/client/cache\";\n\n/* Link */\n\nexport {\n  ApolloLink,\n  concat,\n  empty,\n  execute,\n  from,\n  split,\n} from \"@apollo/client/link\";\nexport type {\n  ApolloPayloadResult,\n  DocumentNode,\n  FetchResult,\n  GraphQLRequest,\n  Operation,\n  RequestHandler,\n} from \"@apollo/client/link\";\n\nexport {\n  checkFetcher,\n  createHttpLink,\n  createSignalIfSupported,\n  defaultPrinter,\n  fallbackHttpConfig,\n  HttpLink,\n  parseAndCheckHttpResponse,\n  rewriteURIForGET,\n  selectHttpOptionsAndBody,\n  // TODO remove: needed by @apollo/client/link/batch-http but not public\n  selectHttpOptionsAndBodyInternal,\n  selectURI,\n} from \"@apollo/client/link/http\";\n\n/* Masking */\nexport type {\n  FragmentType,\n  MaybeMasked,\n  Unmasked,\n} from \"@apollo/client/masking\";\n\n/* Utilities */\n\nexport type {\n  DocumentTransformCacheKey,\n  Reference,\n  StoreObject,\n} from \"@apollo/client/utilities\";\nexport {\n  DocumentTransform,\n  /** @deprecated Please import `isNetworkRequestSettled` from `@apollo/client/utilities`. */\n  isNetworkRequestSettled,\n  isReference,\n  Observable,\n} from \"@apollo/client/utilities\";\n\n/* Supporting */\n\n// The verbosity of invariant.{log,warn,error} can be controlled globally\n// by passing \"log\", \"warn\", \"error\", or \"silent\" to setVerbosity (\"log\" is the default).\n// Note that all invariant.* logging is hidden in production.\nexport { setVerbosity as setLogVerbosity } from \"@apollo/client/utilities/invariant\";\n\n// Note that importing `gql` by itself, then destructuring\n// additional properties separately before exporting, is intentional.\n// Due to the way the `graphql-tag` library is setup, certain bundlers\n// can't find the properties added to the exported `gql` function without\n// additional guidance (e.g. Rollup - see\n// https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module).\n// Instead of having people that are using bundlers with `@apollo/client` add\n// extra bundler config to help `graphql-tag` exports be found (which would be\n// awkward since they aren't importing `graphql-tag` themselves), this\n// workaround of pulling the extra properties off the `gql` function,\n// then re-exporting them separately, helps keeps bundlers happy without any\n// additional config changes.\nexport {\n  disableExperimentalFragmentVariables,\n  disableFragmentWarnings,\n  enableExperimentalFragmentVariables,\n  gql,\n  resetCaches,\n} from \"graphql-tag\";\nexport { build, version } from \"../version.js\";\n\n// internal types\nimport type { QueryManager } from \"./QueryManager.js\";\nimport type { NextFetchPolicyContext } from \"./watchQueryOptions.js\";\n/** @internal */\nexport declare namespace InternalTypes {\n  export type { NextFetchPolicyContext, QueryManager };\n}\n"
  },
  {
    "path": "src/core/networkStatus.ts",
    "content": "/**\n * The current status of a query’s execution in our system.\n */\nexport enum NetworkStatus {\n  /**\n   * The query has never been run before and the query is now currently running. A query will still\n   * have this network status even if a partial data result was returned from the cache, but a\n   * query was dispatched anyway.\n   */\n  loading = 1,\n\n  /**\n   * If `setVariables` was called and a query was fired because of that then the network status\n   * will be `setVariables` until the result of that query comes back.\n   */\n  setVariables = 2,\n\n  /**\n   * Indicates that `fetchMore` was called on this query and that the query created is currently in\n   * flight.\n   */\n  fetchMore = 3,\n\n  /**\n   * Similar to the `setVariables` network status. It means that `refetch` was called on a query\n   * and the refetch request is currently in flight.\n   */\n  refetch = 4,\n\n  /**\n   * Indicates that a polling query is currently in flight. So for example if you are polling a\n   * query every 10 seconds then the network status will switch to `poll` every 10 seconds whenever\n   * a poll request has been sent but not resolved.\n   */\n  poll = 6,\n\n  /**\n   * No request is in flight for this query, and no errors happened. Everything is OK.\n   */\n  ready = 7,\n\n  /**\n   * No request is in flight for this query, but one or more errors were detected.\n   */\n  error = 8,\n\n  /**\n   * Indicates that a `@defer` query has received at least the first chunk of\n   * the result but the full result has not yet been fully streamed to the\n   * client.\n   */\n  streaming = 9,\n}\n"
  },
  {
    "path": "src/core/types.ts",
    "content": "import type { DocumentNode, FormattedExecutionResult } from \"graphql\";\nimport type {\n  NextNotification,\n  Observable,\n  ObservableNotification,\n} from \"rxjs\";\n\nimport type { ApolloCache } from \"@apollo/client/cache\";\nimport type { Cache } from \"@apollo/client/cache\";\nimport type { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport type { DeepPartial, HKT } from \"@apollo/client/utilities\";\nimport type {\n  ApplyHKTImplementationWithDefault,\n  IsAny,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\n\nexport type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\n\nexport interface TypeOverrides {}\n\ndeclare namespace OverridableTypes {\n  export interface Defaults {\n    Complete: Complete;\n    Streaming: Streaming;\n    Partial: Partial;\n  }\n\n  interface Complete extends HKT {\n    arg1: unknown; // TData\n    return: this[\"arg1\"];\n  }\n\n  interface Streaming extends HKT {\n    arg1: unknown; // TData\n    return: this[\"arg1\"];\n  }\n\n  interface Partial extends HKT {\n    arg1: unknown; // TData\n    return: DeepPartial<this[\"arg1\"]>;\n  }\n}\n\nexport declare namespace DataValue {\n  /**\n   * Returns a representation of `TData` in it's \"complete\" state.\n   *\n   * @defaultValue `TData` if no overrides are provided.\n   *\n   * @example\n   * You can override this type globally - this example shows how to override it\n   * with `DeepPartial<TData>`:\n   *\n   * ```ts\n   * import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n   *\n   * type CompleteOverride<TData> =\n   *   TData extends { _complete?: infer _Complete } ? _Complete : TData;\n   *\n   * interface CompleteOverrideHKT extends HKT {\n   *   return: CompleteOverride<this[\"arg1\"]>;\n   * }\n   *\n   * declare module \"@apollo/client\" {\n   *   export interface TypeOverrides {\n   *     Complete: CompleteOverrideHKT;\n   *   }\n   * }\n   * ```\n   */\n  export type Complete<TData> = ApplyHKTImplementationWithDefault<\n    TypeOverrides,\n    \"Complete\",\n    OverridableTypes.Defaults,\n    TData\n  >;\n\n  /**\n   * Returns a representation of `TData` while it is streaming.\n   *\n   * @defaultValue `TData` if no overrides are provided.\n   *\n   * @example\n   * You can override this type globally - this example shows how to override it\n   * with `DeepPartial<TData>`:\n   *\n   * ```ts\n   * import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n   *\n   * type StreamingOverride<TData> = DeepPartial<TData>;\n   *\n   * interface StreamingOverrideHKT extends HKT {\n   *   return: StreamingOverride<this[\"arg1\"]>;\n   * }\n   *\n   * declare module \"@apollo/client\" {\n   *   export interface TypeOverrides {\n   *     Streaming: StreamingOverrideHKT;\n   *   }\n   * }\n   * ```\n   */\n  export type Streaming<TData> = ApplyHKTImplementationWithDefault<\n    TypeOverrides,\n    \"Streaming\",\n    OverridableTypes.Defaults,\n    TData\n  >;\n\n  /**\n   * Returns a representation of `TData` while it is partial.\n   *\n   * @defaultValue `DeepPartial<TData>` if no overrides are provided.\n   *\n   * @example\n   * You can override this type globally - this example shows how to override it\n   * with `DeepPartial<TData>`:\n   *\n   * ```ts\n   * import { HKT, DeepPartial } from \"@apollo/client/utilities\";\n   *\n   * type PartialOverride<TData> = DeepPartial<Complete<TData>>;\n   *\n   * interface PartialOverrideHKT extends HKT {\n   *   return: PartialOverride<this[\"arg1\"]>;\n   * }\n   *\n   * declare module \"@apollo/client\" {\n   *   export interface TypeOverrides {\n   *     Partial: PartialOverrideHKT;\n   *   }\n   * }\n   * ```\n   */\n  export type Partial<TData> = ApplyHKTImplementationWithDefault<\n    TypeOverrides,\n    \"Partial\",\n    OverridableTypes.Defaults,\n    TData\n  >;\n}\n\nexport interface DefaultContext extends Record<string, any> {\n  /**\n   * Indicates whether `queryDeduplication` was enabled for the request.\n   */\n  queryDeduplication?: boolean;\n  clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n}\n\n/**\n * Represents an `Error` type, but used throughout Apollo Client to represent\n * errors that may otherwise fail `instanceof` checks if they are cross-realm\n * Error instances (see the [`Error.isError` proposal](https://github.com/tc39/proposal-is-error) for more details).\n *\n * Apollo Client uses several types of errors throughout the client which can be\n * narrowed using `instanceof`:\n *\n * - `CombinedGraphQLErrors` - `errors` returned from a GraphQL result\n * - `CombinedProtocolErrors` - Transport-level errors from multipart subscriptions.\n * - `ServerParseError` - A JSON-parse error when parsing the server response.\n * - `ServerError` - A non-200 server response.\n *\n * @example\n *\n * ```ts\n * import { CombinedGraphQLErrors } from \"@apollo/client\";\n *\n * try {\n *   await client.query({ query });\n * } catch (error) {\n *   // Use `instanceof` to check for more specific types of errors.\n *   if (error instanceof CombinedGraphQLErrors) {\n *     error.errors.map((graphQLError) => console.log(graphQLError.message));\n *   } else {\n *     console.error(errors);\n *   }\n * }\n * ```\n */\nexport interface ErrorLike {\n  message: string;\n  name: string;\n  stack?: string;\n}\n\nexport type OnQueryUpdated<TResult> = (\n  observableQuery: ObservableQuery<any>,\n  diff: Cache.DiffResult<any>,\n  lastDiff: Cache.DiffResult<any> | undefined\n) => boolean | TResult;\n\nexport type RefetchQueryDescriptor = string | DocumentNode;\nexport type InternalRefetchQueryDescriptor =\n  | RefetchQueryDescriptor\n  | ApolloClient.QueryOptions;\n\ntype RefetchQueriesIncludeShorthand = \"all\" | \"active\";\n\nexport type RefetchQueriesInclude =\n  | RefetchQueryDescriptor[]\n  | RefetchQueriesIncludeShorthand;\n\nexport type InternalRefetchQueriesInclude =\n  | InternalRefetchQueryDescriptor[]\n  | RefetchQueriesIncludeShorthand;\n\n// The client.refetchQueries method returns a thenable (PromiseLike) object\n// whose result is an array of Promise.resolve'd TResult values, where TResult\n// is whatever type the (optional) onQueryUpdated function returns. When no\n// onQueryUpdated function is given, TResult defaults to ApolloQueryResult<any>\n// (thanks to default type parameters for client.refetchQueries).\nexport type RefetchQueriesPromiseResults<TResult> =\n  // If onQueryUpdated returns any, all bets are off, so the results array must\n  // be a generic any[] array, which is much less confusing than the union type\n  // we get if we don't check for any. I hoped `any extends TResult` would do\n  // the trick here, instead of IsStrictlyAny, but you can see for yourself what\n  // fails in the refetchQueries tests if you try making that simplification.\n  IsAny<TResult> extends true ? any[]\n  : // If the onQueryUpdated function passed to client.refetchQueries returns true\n  // or false, that means either to refetch the query (true) or to skip the\n  // query (false). Since refetching produces an ApolloQueryResult<any>, and\n  // skipping produces nothing, the fully-resolved array of all results produced\n  // will be an ApolloQueryResult<any>[], when TResult extends boolean.\n  TResult extends boolean ? ApolloClient.QueryResult<any>[]\n  : // If onQueryUpdated returns a PromiseLike<U>, that thenable will be passed as\n  // an array element to Promise.all, so we infer/unwrap the array type U here.\n  TResult extends PromiseLike<infer U> ? U[]\n  : // All other onQueryUpdated results end up in the final Promise.all array as\n    // themselves, with their original TResult type. Note that TResult will\n    // default to ApolloQueryResult<any> if no onQueryUpdated function is passed\n    // to client.refetchQueries.\n    TResult[];\n\n// Used by QueryManager[\"refetchQueries\"]\nexport interface InternalRefetchQueriesOptions<\n  TCache extends ApolloCache,\n  TResult,\n> extends Omit<ApolloClient.RefetchQueriesOptions<TCache, TResult>, \"include\"> {\n  // Just like the refetchQueries option for a mutation, an array of strings,\n  // DocumentNode objects, and/or QueryOptions objects, or one of the shorthand\n  // strings \"all\" or \"active\", to select every (active) query.\n  include?: InternalRefetchQueriesInclude;\n  // This part of the API is a (useful) implementation detail, but need not be\n  // exposed in the public client.refetchQueries API (above).\n  removeOptimistic?: string;\n}\n\nexport type InternalRefetchQueriesResult<TResult> =\n  // If onQueryUpdated returns a boolean, that's equivalent to refetching the\n  // query when the boolean is true and skipping the query when false, so the\n  // internal type of refetched results is Promise<ApolloQueryResult<any>>.\n  TResult extends boolean ? Promise<ApolloClient.QueryResult<any>>\n  : // Otherwise, onQueryUpdated returns whatever it returns. If onQueryUpdated is\n    // not provided, TResult defaults to Promise<ApolloQueryResult<any>> (see the\n    // generic type parameters of client.refetchQueries).\n    TResult;\n\nexport type InternalRefetchQueriesMap<TResult> = Map<\n  ObservableQuery<any>,\n  InternalRefetchQueriesResult<TResult>\n>;\n\nexport type OperationVariables = Record<string, any>;\n\nexport type DataState<TData> =\n  | {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n      data: DataValue.Complete<TData>;\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n      dataState: \"complete\";\n    }\n  | {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n      data: DataValue.Streaming<TData>;\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n      dataState: \"streaming\";\n    }\n  | {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n      data: DataValue.Partial<TData>;\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n      dataState: \"partial\";\n    }\n  | {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n      data: undefined;\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n      dataState: \"empty\";\n    };\n\nexport type GetDataState<\n  TData,\n  TState extends DataState<TData>[\"dataState\"],\n> = Extract<DataState<TData>, { dataState: TState }>;\n\n/**\n * Represents a result that might be complete or still streaming and\n * has been normalized into a plain GraphQL result. When the result is\n * still `streaming`, some fields might not yet be available.\n */\nexport type NormalizedExecutionResult<\n  TData = Record<string, unknown>,\n  TExtensions = Record<string, unknown>,\n> = Omit<FormattedExecutionResult<TData, TExtensions>, \"data\"> &\n  GetDataState<TData, \"streaming\" | \"complete\">;\n\n// This is part of the public API, people write these functions in `updateQueries`.\nexport type MutationQueryReducer<T> = (\n  previousResult: Record<string, any>,\n  options: {\n    mutationResult: NormalizedExecutionResult<Unmasked<T>>;\n    queryName: string | undefined;\n    queryVariables: Record<string, any>;\n  }\n) => Record<string, any>;\n\nexport type MutationQueryReducersMap<T = { [key: string]: any }> = {\n  [queryName: string]: MutationQueryReducer<T>;\n};\n\nexport type MutationUpdaterFunction<\n  TData,\n  TVariables extends OperationVariables,\n  TCache extends ApolloCache,\n> = (\n  cache: TCache,\n  result: FormattedExecutionResult<Unmasked<TData>>,\n  options: {\n    context?: DefaultContext;\n    variables?: TVariables;\n  }\n) => void;\n\nexport declare namespace QueryNotification {\n  type NewNetworkStatus = NextNotification<{\n    resetError?: boolean;\n  }> & {\n    source: \"newNetworkStatus\";\n  };\n\n  type SetResult<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n    source: \"setResult\";\n  };\n\n  type FromNetwork<TData> = ObservableNotification<\n    ObservableQuery.Result<TData>\n  > & {\n    source: \"network\";\n  };\n\n  type FromCache<TData> = NextNotification<ObservableQuery.Result<TData>> & {\n    source: \"cache\";\n  };\n\n  type Value<TData> =\n    | FromCache<TData>\n    | FromNetwork<TData>\n    | NewNetworkStatus\n    | SetResult<TData>;\n}\n\n/** Observable created by initiating a subscription operation. */\nexport interface SubscriptionObservable<T> extends Observable<T> {\n  /**\n   * Used to restart the connection to the link chain. Calling this on a\n   * deduplicated subscription will restart the connection for all observables\n   * that share the request.\n   *\n   * @example\n   *\n   * ```ts\n   * const observable = client.subscribe({ query: subscription });\n   * observable.subscribe((value) => {\n   *   // ...\n   * });\n   *\n   * observable.restart();\n   * ```\n   */\n  restart: () => void;\n}\n"
  },
  {
    "path": "src/core/watchQueryOptions.ts",
    "content": "import type { Unmasked } from \"@apollo/client/masking\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\n\nimport type { ApolloClient } from \"./ApolloClient.js\";\nimport type { ObservableQuery } from \"./ObservableQuery.js\";\nimport type { OperationVariables } from \"./types.js\";\n\n/**\n * fetchPolicy determines where the client may return a result from. The options are:\n *\n * - cache-first (default): return result from cache. Only fetch from network if cached result is not available.\n * - cache-and-network: return result from cache first (if it exists), then return network result once it's available.\n * - cache-only: return result from cache if available, fail otherwise.\n * - no-cache: return result from network, fail if network call doesn't succeed, don't save to cache\n * - network-only: return result from network, fail if network call doesn't succeed, save to cache\n * - standby: only for queries that aren't actively watched, but should be available for refetch and updateQueries.\n */\nexport type FetchPolicy =\n  | \"cache-first\"\n  | \"network-only\"\n  | \"cache-only\"\n  | \"no-cache\";\n\nexport type WatchQueryFetchPolicy =\n  | FetchPolicy\n  | \"cache-and-network\"\n  | \"standby\";\n\nexport type MutationFetchPolicy = Extract<\n  FetchPolicy,\n  | \"network-only\" // default behavior (mutation results written to cache)\n  | \"no-cache\" // alternate behavior (results not written to cache)\n>;\n\nexport type RefetchWritePolicy = \"merge\" | \"overwrite\";\n\n/**\n * errorPolicy determines the level of events for errors in the execution result. The options are:\n *\n * - none (default): any errors from the request are treated like runtime errors and the observable is stopped\n * - ignore: errors from the request do not stop the observable, but also don't call `next`\n * - all: errors are treated like data and will notify observables\n */\nexport type ErrorPolicy = \"none\" | \"ignore\" | \"all\";\n\nexport interface NextFetchPolicyContext<\n  TData,\n  TVariables extends OperationVariables,\n> {\n  reason: \"after-fetch\" | \"variables-changed\";\n  observable: ObservableQuery<TData, TVariables>;\n  options: ApolloClient.WatchQueryOptions<TData, TVariables>;\n  initialFetchPolicy: WatchQueryFetchPolicy;\n}\n\nexport type UpdateQueryOptions<TData, TVariables extends OperationVariables> = {\n  variables?: TVariables;\n} & (\n  | {\n      /**\n       * Indicate if the previous query result has been found fully in the cache.\n       */\n      complete: true;\n      previousData: Unmasked<TData>;\n    }\n  | {\n      /**\n       * Indicate if the previous query result has not been found fully in the cache.\n       * Might have partial or missing data.\n       */\n      complete: false;\n      previousData: DeepPartial<Unmasked<TData>> | undefined;\n    }\n);\n\nexport interface UpdateQueryMapFn<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> {\n  (\n    /**\n     * @deprecated This value is not type-safe and may contain partial data. This\n     * argument will be removed in Apollo Client v5. Use `options.previousData`\n     * instead for a more type-safe value.\n     */\n    unsafePreviousData: DeepPartial<Unmasked<TData>>,\n    options: UpdateQueryOptions<TData, TVariables>\n  ): Unmasked<TData> | void;\n}\n\nexport type SubscribeToMoreUpdateQueryFn<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TSubscriptionData = TData,\n> = {\n  (\n    /**\n     * @deprecated This value is not type-safe and may contain partial data. This\n     * argument will be removed in Apollo Client v5. Use `options.previousData`\n     * instead for a more type-safe value.\n     */\n    unsafePreviousData: DeepPartial<Unmasked<TData>>,\n    options: UpdateQueryOptions<TData, TVariables> & {\n      subscriptionData: { data: Unmasked<TSubscriptionData> };\n    }\n  ): Unmasked<TData> | void;\n};\n\nexport interface SubscribeToMoreFunction<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n> {\n  <\n    TSubscriptionData = TData,\n    TSubscriptionVariables extends OperationVariables = TVariables,\n  >(\n    options: ObservableQuery.SubscribeToMoreOptions<\n      TData,\n      TSubscriptionVariables,\n      TSubscriptionData,\n      TVariables\n    >\n  ): () => void;\n}\n"
  },
  {
    "path": "src/dev/index.ts",
    "content": "export { loadDevMessages } from \"./loadDevMessages.js\";\nexport { loadErrorMessageHandler } from \"./loadErrorMessageHandler.js\";\nexport { loadErrorMessages } from \"./loadErrorMessages.js\";\nexport { setErrorMessageHandler } from \"./setErrorMessageHandler.js\";\nexport type { ErrorMessageHandler } from \"./setErrorMessageHandler.js\";\n"
  },
  {
    "path": "src/dev/loadDevMessages.ts",
    "content": "import { devDebug, devError, devLog, devWarn } from \"../invariantErrorCodes.js\";\n\nimport { loadErrorMessageHandler } from \"./loadErrorMessageHandler.js\";\n\nexport function loadDevMessages() {\n  loadErrorMessageHandler(devDebug, devError, devLog, devWarn);\n}\n"
  },
  {
    "path": "src/dev/loadErrorMessageHandler.ts",
    "content": "import { global } from \"@apollo/client/utilities/internal/globals\";\n\nimport type { ErrorCodes } from \"../invariantErrorCodes.js\";\n\nimport type { ErrorMessageHandler } from \"./setErrorMessageHandler.js\";\nimport { setErrorMessageHandler } from \"./setErrorMessageHandler.js\";\nimport { ApolloErrorMessageHandler } from \"./symbol.js\";\n\n/**\n * Injects Apollo Client's default error message handler into the application and\n * also loads the error codes that are passed in as arguments.\n */\nexport function loadErrorMessageHandler(...errorCodes: ErrorCodes[]) {\n  setErrorMessageHandler(handler as typeof handler & ErrorCodes);\n\n  for (const codes of errorCodes) {\n    Object.assign(handler, codes);\n  }\n\n  return handler;\n}\n\nconst handler = ((message: string | number, args: unknown[]) => {\n  if (typeof message === \"number\") {\n    const definition = global[ApolloErrorMessageHandler]![message];\n    if (!message || !definition?.message) return;\n    message = definition.message;\n  }\n  return args.reduce<string>(\n    (msg, arg) => msg.replace(/%[sdfo]/, String(arg)),\n    String(message)\n  );\n}) as ErrorMessageHandler & ErrorCodes;\n"
  },
  {
    "path": "src/dev/loadErrorMessages.ts",
    "content": "import { errorCodes } from \"../invariantErrorCodes.js\";\n\nimport { loadErrorMessageHandler } from \"./loadErrorMessageHandler.js\";\n\nexport function loadErrorMessages() {\n  loadErrorMessageHandler(errorCodes);\n}\n"
  },
  {
    "path": "src/dev/setErrorMessageHandler.ts",
    "content": "import { global } from \"@apollo/client/utilities/internal/globals\";\n\nimport type { ErrorCodes } from \"../invariantErrorCodes.js\";\n\nimport { ApolloErrorMessageHandler } from \"./symbol.js\";\n\n/**\n * The error message handler is a function that is called when a message is\n * logged or an error is thrown to determine the contents of the error message\n * to be logged or thrown.\n */\nexport type ErrorMessageHandler = {\n  /**\n   * @param message - Usually the error message number (as defined in\n   * `@apollo/client/invariantErrorCodes.js`).\n   * In some edge cases, this can already be a string, that can be passed through\n   * as an error message.\n   *\n   * @param args - The placeholders that can be passed into the error message (pre-stringified).\n   * These relate with the `%s` and `%d` [substitution strings](https://developer.mozilla.org/en-US/docs/Web/API/console#using_string_substitutions)\n   * in the error message defined in `@apollo/client/invariantErrorCodes.js`.\n   *\n   * ⚠️ Note that arguments will only be passed in for error messages.\n   * For normal log messages, you will get an empty array here and they will directly\n   * be passed to `console.log` instead, to have the string substitution done by the\n   * engine, as that allows for nicer (and in the case of a browser, interactive)\n   * output.\n   *\n   * @returns The error message to be logged or thrown. If it returns `undefined`,\n   * the mechanism will fall back to the default:\n   * A link to https://go.apollo.dev/c/err with Apollo Client version,\n   * the error message number, and the error message arguments encoded into\n   * the URL hash.\n   */ (message: string | number, args: string[]): string | undefined;\n};\n\n/**\n * Overrides the global \"Error Message Handler\" with a custom implementation.\n */\nexport function setErrorMessageHandler(handler: ErrorMessageHandler) {\n  global[ApolloErrorMessageHandler] = handler as typeof handler & ErrorCodes;\n}\n"
  },
  {
    "path": "src/dev/symbol.ts",
    "content": "import type { ErrorCodes } from \"../invariantErrorCodes.js\";\nimport { version } from \"../version.js\";\n\n// This is duplicated between `@apollo/client/dev` and `@apollo/client/utilities/invariant` to prevent circular references.\nexport const ApolloErrorMessageHandler = Symbol.for(\n  \"ApolloErrorMessageHandler_\" + version\n);\ndeclare global {\n  interface Window {\n    [ApolloErrorMessageHandler]?: {\n      (message: string | number, args: string[]): string | undefined;\n    } & ErrorCodes;\n  }\n}\n"
  },
  {
    "path": "src/errors/CombinedGraphQLErrors.ts",
    "content": "import type { FormattedExecutionResult, GraphQLFormattedError } from \"graphql\";\n\nimport type { ApolloLink } from \"@apollo/client/link\";\n\nimport { brand, isBranded } from \"./utils.js\";\n\nexport declare namespace CombinedGraphQLErrors {\n  export interface MessageFormatterOptions {\n    /**\n     * The raw result returned from the server.\n     */\n    result: ApolloLink.Result<unknown>;\n\n    /**\n     * The default message formatter. Call this to get a string with the default\n     * formatted message.\n     *\n     * @remarks\n     * To format part of the message using the default message formatter, call\n     * the `defaultFormatMessage` function provided to the `options` argument of\n     * your message formatter.\n     *\n     * @example\n     *\n     * The following example prepends a string to the message and uses the\n     * default message formatter to format the error messages.\n     *\n     * ```ts\n     * CombinedGraphQLErrors.formatMessage = (errors, { defaultFormatMessage }) => {\n     *   return `[GraphQL errors]: ${defaultFormatMessage(errors)}`;\n     * };\n     * ```\n     */\n    defaultFormatMessage: (\n      errors: ReadonlyArray<GraphQLFormattedError>\n    ) => string;\n  }\n\n  /**\n   * By default, `CombinedGraphQLErrors` formats the `message` property by\n   * joining each error's `message` field with a newline. To customize the\n   * format of the `message`, such as changing the delimiter or adding a message\n   * prefix, override the static `formatMessage` method.\n   *\n   * @example\n   *\n   * The following example demonstrates how to format the error message by\n   * joining each error with a comma.\n   *\n   * ```ts\n   * import { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n   *\n   * CombinedGraphQLErrors.formatMessage = (errors) => {\n   *   return errors.map((error) => error.message).join(\", \");\n   * };\n   * ```\n   *\n   * @remarks\n   *\n   * See the [`formatMessage`](https://www.apollographql.com/docs/react/api/errors/CombinedGraphQLErrors#formatmessage) docs for details about the parameters provided to the `formatMessage` function.\n   *\n   * > [!NOTE]\n   * > The message formatter needs to be configured before any operation is executed by Apollo Client, otherwise the default message formatter is used. We recommend configuring the message formatter before initializing your `ApolloClient` instance.\n   *\n   * @param errors - The array of GraphQL errors returned from the server in the\n   * `errors` field of the response.\n   * @param options - Additional context that could be useful when formatting\n   * the message.\n   */\n  export type MessageFormatter = (\n    errors: ReadonlyArray<GraphQLFormattedError>,\n    options: MessageFormatterOptions\n  ) => string;\n\n  namespace DocumentationTypes {\n    /**\n     * A function that formats the error message used for the error's `message`\n     * property. Override this method to provide your own formatting.\n     *\n     * @remarks\n     *\n     * The `formatMessage` function is called by the `CombinedGraphQLErrors`\n     * constructor to provide a formatted message as the `message` property of the\n     * `CombinedGraphQLErrors` object. Follow the [\"Providing a custom message\n     * formatter\"](https://www.apollographql.com/docs/react/api/errors/CombinedGraphQLErrors#providing-a-custom-message-formatter) guide to learn how to modify the message format.\n     *\n     * @param errors - The array of GraphQL errors returned from the server in\n     * the `errors` field of the response.\n     * @param options - Additional context that could be useful when formatting\n     * the message.\n     */\n    function formatMessage(\n      errors: ReadonlyArray<GraphQLFormattedError>,\n      options: MessageFormatterOptions\n    ): string;\n\n    interface InstanceProperties {\n      /**\n       * The raw list of GraphQL errors returned by the `errors` field in the GraphQL response.\n       */\n      readonly errors: ReadonlyArray<GraphQLFormattedError>;\n\n      /**\n       * Partial data returned in the `data` field of the GraphQL response.\n       */\n      readonly data: Record<string, unknown> | null | undefined;\n\n      /**\n       * Extensions returned by the `extensions` field in the GraphQL response.\n       */\n      readonly extensions: Record<string, unknown> | undefined;\n    }\n\n    /**\n     * A method that determines whether an error is a `{{errorClass}}`\n     * object. This method enables TypeScript to narrow the error type.\n     *\n     * @example\n     *\n     * ```ts\n     * if ({{errorClass}}.is(error)) {\n     *   // TypeScript now knows `error` is a `{{errorClass}}` object\n     *   console.log(error.errors);\n     * }\n     * ```\n     */\n    function is(error: unknown): boolean;\n  }\n}\n\nfunction defaultFormatMessage(errors: ReadonlyArray<GraphQLFormattedError>) {\n  return (\n    errors\n      // Handle non-spec-compliant servers: See #1185\n      .filter((e) => e)\n      .map((e) => e.message || \"Error message not found.\")\n      .join(\"\\n\")\n  );\n}\n\n/**\n * Represents the combined list of GraphQL errors returned from the server in a\n * GraphQL response. This error type is used when your GraphQL operation returns\n * errors in the `errors` field of the response.\n *\n * @remarks\n *\n * When your GraphQL operation encounters errors on the server side (such as\n * resolver errors, validation errors, or syntax errors), the server returns\n * these errors in the `errors` array of the GraphQL response. Apollo Client\n * wraps these errors in a `CombinedGraphQLErrors` object, which provides access\n * to the individual errors while maintaining additional context about the\n * response.\n *\n * @example\n *\n * ```ts\n * import { CombinedGraphQLErrors } from \"@apollo/client/errors\";\n *\n * // Check if an error is a CombinedGraphQLErrors object\n * if (CombinedGraphQLErrors.is(error)) {\n *   // Access individual GraphQL errors\n *   error.errors.forEach((graphQLError) => {\n *     console.log(graphQLError.message);\n *     console.log(graphQLError.path);\n *     console.log(graphQLError.locations);\n *   });\n *\n *   // Access the original GraphQL result\n *   console.log(error.result);\n * }\n * ```\n */\nexport class CombinedGraphQLErrors extends Error {\n  /**\n   * {@inheritDoc @apollo/client!CombinedGraphQLErrors.DocumentationTypes.is:function(1) {\"errorClass\":\"CombinedGraphQLErrors\"}}\n   */\n  static is(error: unknown): error is CombinedGraphQLErrors {\n    return isBranded(error, \"CombinedGraphQLErrors\");\n  }\n\n  /** {@inheritDoc @apollo/client!CombinedGraphQLErrors.DocumentationTypes.formatMessage:function(1)} */\n  static formatMessage: CombinedGraphQLErrors.MessageFormatter =\n    defaultFormatMessage;\n\n  /** {@inheritDoc @apollo/client!CombinedGraphQLErrors.DocumentationTypes.InstanceProperties#errors:member} */\n  readonly errors: ReadonlyArray<GraphQLFormattedError>;\n\n  /** {@inheritDoc @apollo/client!CombinedGraphQLErrors.DocumentationTypes.InstanceProperties#data:member} */\n  readonly data: Record<string, unknown> | null | undefined;\n\n  /** {@inheritDoc @apollo/client!CombinedGraphQLErrors.DocumentationTypes.InstanceProperties#extensions:member} */\n  readonly extensions: Record<string, unknown> | undefined;\n\n  constructor(result: FormattedExecutionResult<any>);\n  constructor(\n    result: ApolloLink.Result<any>,\n    errors: ReadonlyArray<GraphQLFormattedError>\n  );\n\n  constructor(\n    result: ApolloLink.Result<any> | FormattedExecutionResult<any>,\n    errors = (result as FormattedExecutionResult<any>).errors || []\n  ) {\n    super(\n      CombinedGraphQLErrors.formatMessage(errors, {\n        result,\n        defaultFormatMessage,\n      })\n    );\n    this.errors = errors;\n    this.data = (result as Partial<FormattedExecutionResult>).data;\n    this.extensions = (result as Partial<FormattedExecutionResult>).extensions;\n    this.name = \"CombinedGraphQLErrors\";\n\n    brand(this);\n    Object.setPrototypeOf(this, CombinedGraphQLErrors.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/CombinedProtocolErrors.ts",
    "content": "import type { GraphQLFormattedError } from \"graphql\";\n\nimport { brand, isBranded } from \"./utils.js\";\n\nexport declare namespace CombinedProtocolErrors {\n  export interface MessageFormatterOptions {\n    /**\n     * The default message formatter. Call this to get a string with the default\n     * formatted message.\n     *\n     * @remarks\n     * To format part of the message using the default message formatter, call\n     * the `defaultFormatMessage` function provided to the `options` argument of\n     * your message formatter.\n     *\n     * @example\n     *\n     * The following example prepends a string to the message and uses the\n     * default message formatter to format the error messages.\n     *\n     * ```ts\n     * CombinedProtocolErrors.formatMessage = (errors, { defaultFormatMessage }) => {\n     *   return `[Protocol errors]: ${defaultFormatMessage(errors)}`;\n     * };\n     * ```\n     */\n    defaultFormatMessage: (\n      errors: ReadonlyArray<GraphQLFormattedError>\n    ) => string;\n  }\n\n  /**\n   * By default, `CombinedProtocolErrors` formats the `message` property by\n   * joining each error's `message` field with a newline. To customize the\n   * format of the `message`, such as changing the delimiter or adding a message\n   * prefix, override the static `formatMessage` method.\n   *\n   * @remarks\n   *\n   * See the [`formatMessage`](https://www.apollographql.com/docs/react/api/errors/CombinedProtocolErrors) section for details about the parameters provided to the `formatMessage` function.\n   *\n   * > [!NOTE]\n   * > The message formatter needs to be configured before any operation is executed by Apollo Client, otherwise the default message formatter is used. We recommend configuring the message formatter before initializing your `ApolloClient` instance.\n   *\n   * @example\n   *\n   * The following example demonstrates how to format the error message by\n   * joining each error with a comma.\n   *\n   * ```ts\n   * import { CombinedProtocolErrors } from \"@apollo/client/errors\";\n   *\n   * CombinedProtocolErrors.formatMessage = (errors) => {\n   *   return errors.map((error) => error.message).join(\", \");\n   * };\n   * ```\n   *\n   * @param errors - The array of GraphQL errors returned from the server in the\n   * `errors` field of the response.\n   * @param options - Additional context that could be useful when formatting\n   * the message.\n   */\n  export type MessageFormatter = (\n    errors: ReadonlyArray<GraphQLFormattedError>,\n    options: MessageFormatterOptions\n  ) => string;\n\n  namespace DocumentationTypes {\n    /**\n     * A function that formats the error message used for the error's `message`\n     * property. Override this method to provide your own formatting.\n     *\n     * @remarks\n     *\n     * The `formatMessage` function is called by the `CombinedProtocolErrors`\n     * constructor to provide a formatted message as the `message` property of the\n     * `CombinedProtocolErrors` object. Follow the [\"Providing a custom message\n     * formatter\"](https://www.apollographql.com/docs/react/api/errors/CombinedProtocolErrors#providing-a-custom-message-formatter) guide to learn how to modify the message format.\n     *\n     * @param errors - The array of GraphQL errors returned from the server in the\n     * `errors` field of the response.\n     * @param options - Additional context that could be useful when formatting\n     * the message.\n     */\n    function formatMessage(\n      errors: ReadonlyArray<GraphQLFormattedError>,\n      options: MessageFormatterOptions\n    ): string;\n\n    interface InstanceProperties {\n      /**\n       * The raw list of errors returned by the top-level `errors` field in the\n       * multipart HTTP subscription response.\n       */\n      readonly errors: ReadonlyArray<GraphQLFormattedError>;\n    }\n  }\n}\n\nfunction defaultFormatMessage(errors: ReadonlyArray<GraphQLFormattedError>) {\n  return errors.map((e) => e.message || \"Error message not found.\").join(\"\\n\");\n}\n\n/**\n * Fatal transport-level errors returned when executing a subscription using the\n * multipart HTTP subscription protocol. See the documentation on the\n * [multipart HTTP protocol for GraphQL Subscriptions](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/multipart-protocol) for more information on these errors.\n *\n * @remarks\n *\n * These errors indicate issues with the subscription transport itself, rather\n * than GraphQL-level errors. They typically occur when there are problems\n * communicating with subgraphs from the Apollo Router.\n *\n * @example\n *\n * ```ts\n * import { CombinedProtocolErrors } from \"@apollo/client/errors\";\n *\n * // Check if an error is a CombinedProtocolErrors instance\n * if (CombinedProtocolErrors.is(error)) {\n *   // Access individual protocol errors\n *   error.errors.forEach((protocolError) => {\n *     console.log(protocolError.message);\n *     console.log(protocolError.extensions);\n *   });\n * }\n * ```\n */\nexport class CombinedProtocolErrors extends Error {\n  /**\n   * A method that determines whether an error is a `CombinedProtocolErrors`\n   * object. This method enables TypeScript to narrow the error type.\n   *\n   * @example\n   *\n   * ```ts\n   * if (CombinedProtocolErrors.is(error)) {\n   *   // TypeScript now knows `error` is a CombinedProtocolErrors object\n   *   console.log(error.errors);\n   * }\n   * ```\n   */\n  static is(error: unknown): error is CombinedProtocolErrors {\n    return isBranded(error, \"CombinedProtocolErrors\");\n  }\n\n  /** {@inheritDoc @apollo/client!CombinedProtocolErrors.DocumentationTypes.formatMessage:function(1)} */\n  static formatMessage: CombinedProtocolErrors.MessageFormatter =\n    defaultFormatMessage;\n\n  /** {@inheritDoc @apollo/client!CombinedProtocolErrors.DocumentationTypes.InstanceProperties#errors:member} */\n  readonly errors: ReadonlyArray<GraphQLFormattedError>;\n\n  constructor(\n    protocolErrors:\n      | Array<GraphQLFormattedError>\n      | ReadonlyArray<GraphQLFormattedError>\n  ) {\n    super(\n      CombinedProtocolErrors.formatMessage(protocolErrors, {\n        defaultFormatMessage,\n      })\n    );\n    this.name = \"CombinedProtocolErrors\";\n    this.errors = protocolErrors;\n\n    brand(this);\n    Object.setPrototypeOf(this, CombinedProtocolErrors.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/LinkError.ts",
    "content": "import type { ErrorLike } from \"@apollo/client\";\n\nconst registry = new WeakSet<ErrorLike>();\n\n/** @internal Please do not use directly. */\nexport function registerLinkError(error: ErrorLike) {\n  registry.add(error);\n}\n\n/**\n * A facade error type that keeps a registry of errors emitted from the link\n * chain. `LinkError` is not an error class itself but rather a utility to\n * detect whether an error originated from the link chain.\n *\n * @remarks\n *\n * Use `LinkError` to distinguish between errors from the link chain and custom\n * errors. This is helpful for retrying an operation at the call site only when\n * the error originates from the link chain.\n *\n * @example\n *\n * The following example creates a custom wrapped query function that detects\n * whether the query includes an operation name and throws if not.\n *\n * ```ts\n * import { LinkError } from \"@apollo/client/errors\";\n *\n * async function runQuery<TData>(query: TypedDocumentNode<TData>) {\n *   if (!hasOperationName(query)) {\n *     throw new Error(\"Queries should have operation names.\");\n *   }\n *\n *   return client.watchQuery({ query });\n * }\n *\n * try {\n *   const result = await runQuery(query);\n * } catch (error) {\n *   // Only log the error if the error wasn't our own custom thrown error\n *   if (LinkError.is(error)) {\n *     console.log(\"Got network error:\", error.message);\n *   }\n * }\n * ```\n */\nexport const LinkError = {\n  /**\n   * A method that determines whether an error originated from the link chain.\n   * `is` does not provide any type narrowing.\n   *\n   * @example\n   *\n   * ```ts\n   * if (LinkError.is(error)) {\n   *   // The error originated from the link chain\n   *   console.log(\"Got network error:\", error.message);\n   * }\n   * ```\n   */\n  is: (error: unknown) => registry.has(error as ErrorLike),\n};\n"
  },
  {
    "path": "src/errors/LocalStateError.ts",
    "content": "import { brand, isBranded } from \"./utils.js\";\n\nexport declare namespace LocalStateError {\n  export interface Options {\n    path?: Array<string | number>;\n    sourceError?: unknown;\n  }\n\n  namespace DocumentationTypes {\n    interface InstanceProperties {\n      /** The path to the field that caused the error. */\n      readonly path?: Array<string | number>;\n    }\n  }\n}\n\n/**\n * Represents a fatal error when executing `@client` fields from `LocalState`,\n * typically to indicate a problem with the `LocalState` configuration or\n * incorrect usage of a resolver function. This error does not represent user\n * errors thrown in a local resolver when resolving `@client` fields.\n *\n * @example\n *\n * ```ts\n * import { LocalStateError } from \"@apollo/client/errors\";\n *\n * // Check if an error is a LocalStateError instance\n * if (LocalStateError.is(error)) {\n *   console.log(\"Original error:\", error.cause);\n *\n *   // Determine which field caused the error\n *   if (error.path) {\n *     console.log(\"Error occurred at field path:\", error.path.join(\".\"));\n *   }\n * }\n * ```\n */\nexport class LocalStateError extends Error {\n  /**\n   * A method that determines whether an error is a `LocalStateError`\n   * object. This method enables TypeScript to narrow the error type.\n   *\n   * @example\n   *\n   * ```ts\n   * if (LocalStateError.is(error)) {\n   *   // TypeScript now knows `error` is a LocalStateError object\n   *   console.log(error.path);\n   * }\n   * ```\n   */\n  static is(error: unknown): error is LocalStateError {\n    return isBranded(error, \"LocalStateError\");\n  }\n\n  /** {@inheritDoc @apollo/client!LocalStateError.DocumentationTypes.InstanceProperties#path:member} */\n  readonly path?: Array<string | number>;\n\n  constructor(message: string, options: LocalStateError.Options = {}) {\n    super(message, { cause: options.sourceError });\n    this.name = \"LocalStateError\";\n    this.path = options.path;\n\n    brand(this);\n    Object.setPrototypeOf(this, LocalStateError.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/ServerError.ts",
    "content": "import { brand, isBranded } from \"./utils.js\";\n\nexport declare namespace ServerError {\n  export interface Options {\n    response: Response;\n    bodyText: string;\n  }\n\n  namespace DocumentationTypes {\n    interface InstanceProperties {\n      /**\n       * The raw [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object provided by the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n       */\n      readonly response: Response;\n      /**\n       * The status code returned by the server in the response. This is provided as\n       * a shortcut for `response.status`.\n       */\n      readonly statusCode: number;\n\n      /**\n       * The raw response body text.\n       */\n      readonly bodyText: string;\n    }\n  }\n}\n\n/**\n * Represents an error when a non-200 HTTP status code is returned from the\n * server according to the [GraphQL Over HTTP specification](https://graphql.github.io/graphql-over-http/draft/). This error\n * contains the full server response, including status code and body text.\n *\n * @remarks\n *\n * This error occurs when your GraphQL server responds with an HTTP status code\n * other than 200 (such as 4xx or 5xx status codes) with any media type other\n * than [`application/graphql-response+json`](https://graphql.github.io/graphql-over-http/draft/#sec-application-graphql-response-json).\n *\n * Servers that return non-200 status codes with other media types are not\n * guaranteed to contain a well-formed GraphQL response and may indicate issues\n * at the HTTP level, such as authentication failures, server unavailability,\n * or other HTTP-level problems.\n *\n * @example\n *\n * ```ts\n * import { ServerError } from \"@apollo/client/errors\";\n *\n * // Check if an error is a ServerError instance\n * if (ServerError.is(error)) {\n *   console.log(`Server returned status: ${error.statusCode}`);\n *   console.log(`Response body: ${error.bodyText}`);\n *\n *   // Handle specific status codes\n *   if (error.statusCode === 401) {\n *     // Handle unauthorized access\n *   }\n * }\n * ```\n */\nexport class ServerError extends Error {\n  /**\n   * A method that determines whether an error is a `ServerError` object. This\n   * method enables TypeScript to narrow the error type.\n   *\n   * @example\n   *\n   * ```ts\n   * if (ServerError.is(error)) {\n   *   // TypeScript now knows `error` is a ServerError object\n   *   console.log(error.errors);\n   * }\n   * ```\n   */\n  static is(error: unknown): error is ServerError {\n    return isBranded(error, \"ServerError\");\n  }\n\n  /** {@inheritDoc @apollo/client!ServerError.DocumentationTypes.InstanceProperties#response:member} */\n  readonly response: Response;\n\n  /** {@inheritDoc @apollo/client!ServerError.DocumentationTypes.InstanceProperties#statusCode:member} */\n  readonly statusCode: number;\n\n  /** {@inheritDoc @apollo/client!ServerError.DocumentationTypes.InstanceProperties#bodyText:member} */\n  readonly bodyText: string;\n\n  constructor(message: string, options: ServerError.Options) {\n    super(message);\n    this.name = \"ServerError\";\n    this.response = options.response;\n    this.statusCode = options.response.status;\n    this.bodyText = options.bodyText;\n\n    brand(this);\n    Object.setPrototypeOf(this, ServerError.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/ServerParseError.ts",
    "content": "import { brand, isBranded } from \"./utils.js\";\n\nexport declare namespace ServerParseError {\n  export interface Options {\n    response: Response;\n    bodyText: string;\n  }\n\n  namespace DocumentationTypes {\n    interface InstanceProperties {\n      /**\n       * The raw [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object provided by the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).\n       */\n      readonly response: Response;\n      /**\n       * The status code returned by the server in the response. This is provided\n       * as a shortcut for `response.status`.\n       */\n      readonly statusCode: number;\n      /**\n       * The raw response body text.\n       */\n      readonly bodyText: string;\n    }\n  }\n}\n\n/**\n * Represents a failure to parse the response as JSON from the server. This\n * error helps debug issues where the server returns malformed JSON or non-JSON\n * content.\n *\n * @remarks\n *\n * This error occurs when Apollo Client receives a response from the server but\n * cannot parse it as valid JSON. This typically happens when the server returns\n * HTML error pages, plain text responses, or malformed JSON instead of the\n * expected GraphQL JSON response format.\n *\n * @example\n *\n * ```ts\n * import { ServerParseError } from \"@apollo/client/errors\";\n *\n * // Check if an error is a ServerParseError instance\n * if (ServerParseError.is(error)) {\n *   console.log(`Failed to parse response from ${error.response.url}`);\n *   console.log(`Raw response: ${error.bodyText}`);\n *   console.log(`Status code: ${error.statusCode}`);\n *\n *   // Access the original parse error\n *   console.log(`Parse error: ${error.cause}`);\n * }\n * ```\n */\nexport class ServerParseError extends Error {\n  /**\n   * A method that determines whether an error is a `ServerParseError`\n   * object. This method enables TypeScript to narrow the error type.\n   *\n   * @example\n   *\n   * ```ts\n   * if (ServerParseError.is(error)) {\n   *   // TypeScript now knows `error` is a ServerParseError object\n   *   console.log(error.statusCode);\n   * }\n   * ```\n   */\n  static is(error: unknown): error is ServerParseError {\n    return isBranded(error, \"ServerParseError\");\n  }\n  /** {@inheritDoc @apollo/client!ServerParseError.DocumentationTypes.InstanceProperties#response:member} */\n  readonly response: Response;\n\n  /** {@inheritDoc @apollo/client!ServerParseError.DocumentationTypes.InstanceProperties#statusCode:member} */\n  readonly statusCode: number;\n\n  /** {@inheritDoc @apollo/client!ServerParseError.DocumentationTypes.InstanceProperties#bodyText:member} */\n  readonly bodyText: string;\n\n  constructor(originalParseError: unknown, options: ServerParseError.Options) {\n    super(\n      originalParseError instanceof Error ?\n        originalParseError.message\n      : \"Could not parse server response\",\n      { cause: originalParseError }\n    );\n    this.name = \"ServerParseError\";\n    this.response = options.response;\n    this.statusCode = options.response.status;\n    this.bodyText = options.bodyText;\n\n    brand(this);\n    Object.setPrototypeOf(this, ServerParseError.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/UnconventionalError.ts",
    "content": "import { brand, isBranded } from \"./utils.js\";\n\n/**\n * A wrapper error type that represents a non-standard error thrown from a\n * A wrapper error type that represents a non-error value thrown from the\n * link chain, such as a symbol, primitive or plain object. Read the `cause` property to\n * determine the source of the error.\n *\n * @remarks\n *\n * This error is used to standardize error handling when non-Error values are\n * thrown in the Apollo Client link chain or other parts of the system.\n * JavaScript allows throwing any value (not just Error instances), and this\n * wrapper ensures that all thrown values can be handled consistently as\n * Error-like objects while preserving the original thrown value.\n *\n * > [!NOTE]\n * > Plain strings thrown as errors are wrapped in regular [`Error`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) objects instead of `UnconventionalError` objects since strings can be safely used as the error's `message`.\n *\n * @example\n *\n * ```ts\n * import { UnconventionalError } from \"@apollo/client/errors\";\n *\n * // Check if an error is an UnconventionalError instance\n * if (UnconventionalError.is(error)) {\n *   console.log(\"Non-standard error thrown:\", error.cause);\n *\n *   // Check the type of the original thrown value\n *   if (typeof error.cause === \"symbol\") {\n *     console.log(\"A symbol was thrown:\", error.cause.toString());\n *   } else if (typeof error.cause === \"object\") {\n *     console.log(\"An object was thrown:\", error.cause);\n *   } else {\n *     console.log(\"Unexpected value thrown:\", error.cause);\n *   }\n * }\n * ```\n */\nexport class UnconventionalError extends Error {\n  /**\n   * A method that determines whether an error is an `UnconventionalError`\n   * object. This method enables TypeScript to narrow the error type.\n   *\n   * @example\n   *\n   * ```ts\n   * if (UnconventionalError.is(error)) {\n   *   // TypeScript now knows `error` is a UnconventionalError object\n   *   console.log(\"What caused this?\", error.cause);\n   * }\n   * ```\n   */\n  static is(error: unknown): error is UnconventionalError {\n    return isBranded(error, \"UnconventionalError\");\n  }\n\n  constructor(errorType: unknown) {\n    super(\"An error of unexpected shape occurred.\", { cause: errorType });\n    this.name = \"UnconventionalError\";\n\n    brand(this);\n    Object.setPrototypeOf(this, UnconventionalError.prototype);\n  }\n}\n"
  },
  {
    "path": "src/errors/__tests__/CombinedGraphQLErrors.test.ts",
    "content": "import { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport type { ApolloLink } from \"@apollo/client/link\";\n\nconst defaultFormatMessage = CombinedGraphQLErrors.formatMessage;\n\nafterEach(() => {\n  CombinedGraphQLErrors.formatMessage = defaultFormatMessage;\n});\n\ntest(\"uses default message format\", () => {\n  const error = new CombinedGraphQLErrors({\n    errors: [{ message: \"Email already taken\" }],\n  });\n\n  expect(error.message).toMatchInlineSnapshot(`\"Email already taken\"`);\n\n  const multipleErrors = new CombinedGraphQLErrors({\n    errors: [\n      { message: \"Username already in use\" },\n      { message: \"Password doesn't match\" },\n    ],\n  });\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Username already in use\nPassword doesn't match\"\n`);\n});\n\ntest(\"adds default message for empty error messages\", () => {\n  const error = new CombinedGraphQLErrors({\n    errors: [{ message: \"\" }],\n  });\n\n  expect(error.message).toMatchInlineSnapshot(`\"Error message not found.\"`);\n\n  const multipleErrors = new CombinedGraphQLErrors({\n    errors: [{ message: \"Username already in use\" }, { message: \"\" }],\n  });\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Username already in use\nError message not found.\"\n`);\n});\n\ntest(\"allows message formatter to be overwritten\", () => {\n  const errors = [{ message: \"Email already taken\" }];\n  const result: ApolloLink.Result = { data: { registerUser: null }, errors };\n\n  {\n    const formatMessage = jest.fn(() => \"Errors happened\");\n    CombinedGraphQLErrors.formatMessage = formatMessage;\n\n    const error = new CombinedGraphQLErrors(result);\n\n    expect(error.message).toBe(\"Errors happened\");\n    expect(formatMessage).toHaveBeenCalledWith(errors, {\n      defaultFormatMessage: expect.any(Function),\n      result,\n    });\n  }\n\n  {\n    const formatMessage = jest.fn(() => \"Oops. Something went wrong\");\n    CombinedGraphQLErrors.formatMessage = formatMessage;\n\n    const error = new CombinedGraphQLErrors(result);\n\n    expect(error.message).toBe(\"Oops. Something went wrong\");\n    expect(formatMessage).toHaveBeenCalledWith(errors, {\n      defaultFormatMessage: expect.any(Function),\n      result,\n    });\n  }\n});\n\ntest(\"can use default formatter from options\", () => {\n  CombinedGraphQLErrors.formatMessage = (errors, { defaultFormatMessage }) =>\n    `Overwritten error message:\\n ${defaultFormatMessage(errors)}`;\n\n  const error = new CombinedGraphQLErrors({\n    errors: [{ message: \"Email already taken\" }],\n  });\n\n  expect(error.message).toMatchInlineSnapshot(`\n\"Overwritten error message:\n Email already taken\"\n`);\n\n  const multipleErrors = new CombinedGraphQLErrors({\n    errors: [\n      { message: \"Username already in use\" },\n      { message: \"Password doesn't match\" },\n    ],\n  });\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Overwritten error message:\n Username already in use\nPassword doesn't match\"\n`);\n});\n"
  },
  {
    "path": "src/errors/__tests__/CombinedProtocolErrors.test.ts",
    "content": "import { CombinedProtocolErrors } from \"@apollo/client/errors\";\n\nconst defaultFormatMessage = CombinedProtocolErrors.formatMessage;\n\nafterEach(() => {\n  CombinedProtocolErrors.formatMessage = defaultFormatMessage;\n});\n\ntest(\"uses default message format\", () => {\n  const error = new CombinedProtocolErrors([{ message: \"Could not connect\" }]);\n\n  expect(error.message).toMatchInlineSnapshot(`\"Could not connect\"`);\n\n  const multipleErrors = new CombinedProtocolErrors([\n    { message: \"Username already in use\" },\n    { message: \"Password doesn't match\" },\n  ]);\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Username already in use\nPassword doesn't match\"\n`);\n});\n\ntest(\"adds default message for empty error messages\", () => {\n  const error = new CombinedProtocolErrors([{ message: \"\" }]);\n\n  expect(error.message).toMatchInlineSnapshot(`\"Error message not found.\"`);\n\n  const multipleErrors = new CombinedProtocolErrors([\n    { message: \"Username already in use\" },\n    { message: \"\" },\n  ]);\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Username already in use\nError message not found.\"\n`);\n});\n\ntest(\"allows message formatter to be overwritten\", () => {\n  const errors = [{ message: \"Email already taken\" }];\n\n  {\n    const formatMessage = jest.fn(() => \"Errors happened\");\n    CombinedProtocolErrors.formatMessage = formatMessage;\n\n    const error = new CombinedProtocolErrors(errors);\n\n    expect(error.message).toBe(\"Errors happened\");\n    expect(formatMessage).toHaveBeenCalledWith(errors, {\n      defaultFormatMessage: expect.any(Function),\n    });\n  }\n\n  {\n    const formatMessage = jest.fn(() => \"Oops. Something went wrong\");\n    CombinedProtocolErrors.formatMessage = formatMessage;\n\n    const error = new CombinedProtocolErrors(errors);\n\n    expect(error.message).toBe(\"Oops. Something went wrong\");\n    expect(formatMessage).toHaveBeenCalledWith(errors, {\n      defaultFormatMessage: expect.any(Function),\n    });\n  }\n});\n\ntest(\"can use default formatter from options\", () => {\n  CombinedProtocolErrors.formatMessage = (errors, { defaultFormatMessage }) =>\n    `Overwritten error message:\\n ${defaultFormatMessage(errors)}`;\n\n  const error = new CombinedProtocolErrors([\n    { message: \"Email already taken\" },\n  ]);\n\n  expect(error.message).toMatchInlineSnapshot(`\n\"Overwritten error message:\n Email already taken\"\n`);\n\n  const multipleErrors = new CombinedProtocolErrors([\n    { message: \"Username already in use\" },\n    { message: \"Password doesn't match\" },\n  ]);\n\n  expect(multipleErrors.message).toMatchInlineSnapshot(`\n\"Overwritten error message:\n Username already in use\nPassword doesn't match\"\n`);\n});\n"
  },
  {
    "path": "src/errors/__tests__/LinkError.test.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n  LinkError,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  mockMultipartSubscriptionStream,\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query {\n    foo\n  }\n`;\n\nconst mutation = gql`\n  mutation {\n    foo\n  }\n`;\n\nconst subscription = gql`\n  subscription {\n    foo\n  }\n`;\n\nfunction createErrorLink(error: unknown) {\n  return new ApolloLink(() => {\n    return new Observable((observer) => {\n      observer.error(error);\n    });\n  });\n}\n\ntest(\"error is not registered until emitted from the link chain\", async () => {\n  const error = new Error(\"Oops\");\n  const client = new ApolloClient({\n    link: createErrorLink(error),\n    cache: new InMemoryCache(),\n  });\n\n  // Error has not yet been emitted from the link chain\n  expect(LinkError.is(error)).toBe(false);\n\n  const actual = await client.query({ query }).catch((error) => error);\n  expect(actual).toBe(error);\n\n  // We've run the operation and the error has been emitted from the link chain,\n  expect(LinkError.is(actual)).toBe(true);\n});\n\ntest(\"handles errors emitted as strings\", async () => {\n  const client = new ApolloClient({\n    link: createErrorLink(\"Oops\"),\n    cache: new InMemoryCache(),\n  });\n\n  const error = await client.query({ query }).catch((error) => error);\n  expect(error).toEqual(new Error(\"Oops\"));\n\n  expect(LinkError.is(error)).toBe(true);\n});\n\ntest(\"handles errors emitted from unconventional types\", async () => {\n  const symbol = Symbol();\n  const client = new ApolloClient({\n    link: createErrorLink(symbol),\n    cache: new InMemoryCache(),\n  });\n\n  const error = await client.query({ query }).catch((error) => error);\n  expect(error).toEqual(new UnconventionalError(symbol));\n\n  expect(LinkError.is(error)).toBe(true);\n});\n\ndescribe(\"client.query\", () => {\n  test(\"errors emitted from the link chain are network errors\", async () => {\n    const error = new Error(\"Oops\");\n    const client = new ApolloClient({\n      link: createErrorLink(error),\n      cache: new InMemoryCache(),\n    });\n\n    const actual = await client.query({ query }).catch((error) => error);\n    expect(actual).toBe(error);\n\n    expect(LinkError.is(actual)).toBe(true);\n  });\n\n  test(\"does not register GraphQL errors as network errors\", async () => {\n    const client = new ApolloClient({\n      link: new MockLink([\n        { request: { query }, result: { errors: [{ message: \"Oops\" }] } },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const error = await client.query({ query }).catch((error) => error);\n    expect(error).toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n\n    expect(LinkError.is(error)).toBe(false);\n  });\n});\n\ndescribe(\"client.watchQuery\", () => {\n  test(\"errors emitted from the link chain are network errors\", async () => {\n    const error = new Error(\"Oops\");\n    const client = new ApolloClient({\n      link: createErrorLink(error),\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, notifyOnNetworkStatusChange: false })\n    );\n\n    const result = await stream.takeNext();\n\n    expect(result.error).toBe(error);\n    expect(LinkError.is(result.error)).toBe(true);\n  });\n\n  test(\"does not register GraphQL errors as network errors\", async () => {\n    const client = new ApolloClient({\n      link: new MockLink([\n        { request: { query }, result: { errors: [{ message: \"Oops\" }] } },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.watchQuery({ query, notifyOnNetworkStatusChange: false })\n    );\n\n    const result = await stream.takeNext();\n\n    expect(result.error).toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n    expect(LinkError.is(result.error)).toBe(false);\n  });\n});\n\ndescribe(\"client.mutate\", () => {\n  test(\"errors emitted from the link chain are network errors\", async () => {\n    const error = new Error(\"Oops\");\n    const client = new ApolloClient({\n      link: createErrorLink(error),\n      cache: new InMemoryCache(),\n    });\n\n    const actual = await client.mutate({ mutation }).catch((error) => error);\n    expect(actual).toBe(error);\n\n    expect(LinkError.is(actual)).toBe(true);\n  });\n\n  test(\"does not register GraphQL errors as network errors\", async () => {\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { errors: [{ message: \"Oops\" }] },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const error = await client.mutate({ mutation }).catch((error) => error);\n    expect(error).toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n\n    expect(LinkError.is(error)).toBe(false);\n  });\n\n  test(\"does not report as a network error if error is thrown when updating the cache\", async () => {\n    const error = new Error(\"Error updating cache\");\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: mutation },\n          result: { data: { foo: \"bar\" } },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const actual = await client\n      .mutate({\n        mutation,\n        update: () => {\n          throw error;\n        },\n      })\n      .catch((error) => error);\n    expect(actual).toBe(error);\n\n    expect(LinkError.is(actual)).toBe(false);\n  });\n});\n\ndescribe(\"client.subscribe\", () => {\n  test(\"errors emitted from the link chain are network errors\", async () => {\n    const error = new Error(\"Oops\");\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n    link.simulateResult({ error });\n\n    const result = await stream.takeNext();\n    expect(result.error).toBe(error);\n\n    expect(LinkError.is(result.error)).toBe(true);\n  });\n\n  test(\"does not register GraphQL errors as network errors\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n    link.simulateResult({ result: { errors: [{ message: \"Oops\" }] } });\n\n    const result = await stream.takeNext();\n    expect(result.error).toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n\n    expect(LinkError.is(result.error)).toBe(false);\n  });\n\n  test(\"does not register protocol errors as network errors\", async () => {\n    // silence warning for cache write\n    using _ = spyOnConsole(\"error\");\n    const { httpLink, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const client = new ApolloClient({\n      link: httpLink,\n      cache: new InMemoryCache(),\n    });\n\n    const stream = new ObservableStream(\n      client.subscribe({ query: subscription })\n    );\n\n    enqueueProtocolErrors([{ message: \"Oops\" }]);\n\n    const result = await stream.takeNext();\n    expect(result.error).toEqual(\n      new CombinedProtocolErrors([{ message: \"Oops\" }])\n    );\n\n    expect(LinkError.is(result.error)).toBe(false);\n  });\n});\n"
  },
  {
    "path": "src/errors/__tests__/is.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n  LocalStateError,\n  ServerError,\n  ServerParseError,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\n\nconst graphQLErrors = new CombinedGraphQLErrors({ errors: [] });\nconst localStateError = new LocalStateError(\"Oops\");\nconst protocolErrors = new CombinedProtocolErrors([]);\nconst serverError = new ServerError(\"Oops\", {\n  response: new Response(\"\", { status: 400 }),\n  bodyText: \"\",\n});\nconst serverParseError = new ServerParseError(new Error(\"Oops\"), {\n  response: new Response(\"\", { status: 400 }),\n  bodyText: \"\",\n});\n\nconst unconventionalError = new UnconventionalError(Symbol());\n\ntest(\"CombinedGraphQLErrors.is\", () => {\n  expect(CombinedGraphQLErrors.is(graphQLErrors)).toBe(true);\n\n  expect(CombinedGraphQLErrors.is(localStateError)).toBe(false);\n  expect(CombinedGraphQLErrors.is(protocolErrors)).toBe(false);\n  expect(CombinedGraphQLErrors.is(serverError)).toBe(false);\n  expect(CombinedGraphQLErrors.is(serverParseError)).toBe(false);\n  expect(CombinedGraphQLErrors.is(unconventionalError)).toBe(false);\n  expect(CombinedGraphQLErrors.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(CombinedGraphQLErrors.is(undefined)).toBe(false);\n  expect(CombinedGraphQLErrors.is(null)).toBe(false);\n  expect(CombinedGraphQLErrors.is({})).toBe(false);\n  expect(CombinedGraphQLErrors.is(Symbol())).toBe(false);\n  expect(CombinedGraphQLErrors.is(10)).toBe(false);\n  expect(CombinedGraphQLErrors.is(\"true\")).toBe(false);\n  expect(CombinedGraphQLErrors.is(true)).toBe(false);\n});\n\ntest(\"CombinedProtocolErrors.is\", () => {\n  expect(CombinedProtocolErrors.is(protocolErrors)).toBe(true);\n\n  expect(CombinedProtocolErrors.is(graphQLErrors)).toBe(false);\n  expect(CombinedProtocolErrors.is(localStateError)).toBe(false);\n  expect(CombinedProtocolErrors.is(serverError)).toBe(false);\n  expect(CombinedProtocolErrors.is(serverParseError)).toBe(false);\n  expect(CombinedProtocolErrors.is(unconventionalError)).toBe(false);\n  expect(CombinedProtocolErrors.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(CombinedProtocolErrors.is(undefined)).toBe(false);\n  expect(CombinedProtocolErrors.is(null)).toBe(false);\n  expect(CombinedProtocolErrors.is({})).toBe(false);\n  expect(CombinedProtocolErrors.is(Symbol())).toBe(false);\n  expect(CombinedProtocolErrors.is(10)).toBe(false);\n  expect(CombinedProtocolErrors.is(\"true\")).toBe(false);\n  expect(CombinedProtocolErrors.is(true)).toBe(false);\n});\n\ntest(\"LocalStateError.is\", () => {\n  expect(LocalStateError.is(localStateError)).toBe(true);\n\n  expect(LocalStateError.is(graphQLErrors)).toBe(false);\n  expect(LocalStateError.is(protocolErrors)).toBe(false);\n  expect(LocalStateError.is(serverError)).toBe(false);\n  expect(LocalStateError.is(serverParseError)).toBe(false);\n  expect(LocalStateError.is(unconventionalError)).toBe(false);\n  expect(LocalStateError.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(LocalStateError.is(undefined)).toBe(false);\n  expect(LocalStateError.is(null)).toBe(false);\n  expect(LocalStateError.is({})).toBe(false);\n  expect(LocalStateError.is(Symbol())).toBe(false);\n  expect(LocalStateError.is(10)).toBe(false);\n  expect(LocalStateError.is(\"true\")).toBe(false);\n  expect(LocalStateError.is(true)).toBe(false);\n});\n\ntest(\"ServerError.is\", () => {\n  expect(ServerError.is(serverError)).toBe(true);\n\n  expect(ServerError.is(graphQLErrors)).toBe(false);\n  expect(ServerError.is(localStateError)).toBe(false);\n  expect(ServerError.is(protocolErrors)).toBe(false);\n  expect(ServerError.is(serverParseError)).toBe(false);\n  expect(ServerError.is(unconventionalError)).toBe(false);\n  expect(ServerError.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(ServerError.is(undefined)).toBe(false);\n  expect(ServerError.is(null)).toBe(false);\n  expect(ServerError.is({})).toBe(false);\n  expect(ServerError.is(Symbol())).toBe(false);\n  expect(ServerError.is(10)).toBe(false);\n  expect(ServerError.is(\"true\")).toBe(false);\n  expect(ServerError.is(true)).toBe(false);\n});\n\ntest(\"ServerParseError.is\", () => {\n  expect(ServerParseError.is(serverParseError)).toBe(true);\n\n  expect(ServerParseError.is(graphQLErrors)).toBe(false);\n  expect(ServerParseError.is(localStateError)).toBe(false);\n  expect(ServerParseError.is(protocolErrors)).toBe(false);\n  expect(ServerParseError.is(serverError)).toBe(false);\n  expect(ServerParseError.is(unconventionalError)).toBe(false);\n  expect(ServerParseError.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(ServerParseError.is(undefined)).toBe(false);\n  expect(ServerParseError.is(null)).toBe(false);\n  expect(ServerParseError.is({})).toBe(false);\n  expect(ServerParseError.is(Symbol())).toBe(false);\n  expect(ServerParseError.is(10)).toBe(false);\n  expect(ServerParseError.is(\"true\")).toBe(false);\n  expect(ServerParseError.is(true)).toBe(false);\n});\n\ntest(\"UnconventionalError.is\", () => {\n  expect(UnconventionalError.is(unconventionalError)).toBe(true);\n\n  expect(UnconventionalError.is(graphQLErrors)).toBe(false);\n  expect(UnconventionalError.is(localStateError)).toBe(false);\n  expect(UnconventionalError.is(protocolErrors)).toBe(false);\n  expect(UnconventionalError.is(serverError)).toBe(false);\n  expect(UnconventionalError.is(serverParseError)).toBe(false);\n  expect(UnconventionalError.is(new Error(\"Oops\"))).toBe(false);\n\n  expect(UnconventionalError.is(undefined)).toBe(false);\n  expect(UnconventionalError.is(null)).toBe(false);\n  expect(UnconventionalError.is({})).toBe(false);\n  expect(UnconventionalError.is(Symbol())).toBe(false);\n  expect(UnconventionalError.is(10)).toBe(false);\n  expect(UnconventionalError.is(\"true\")).toBe(false);\n  expect(UnconventionalError.is(true)).toBe(false);\n});\n\ndeclare const error: unknown;\n\ndescribe.skip(\"type tests\", () => {\n  test(\"type narrows CombinedGraphQLErrors\", () => {\n    if (CombinedGraphQLErrors.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<CombinedGraphQLErrors>();\n    }\n  });\n\n  test(\"type narrows CombinedProtocolErrors\", () => {\n    if (CombinedProtocolErrors.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<CombinedProtocolErrors>();\n    }\n  });\n\n  test(\"type narrows LocalStateError\", () => {\n    if (LocalStateError.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<LocalStateError>();\n    }\n  });\n\n  test(\"type narrows ServerError\", () => {\n    if (ServerError.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<ServerError>();\n    }\n  });\n\n  test(\"type narrows ServerParseError\", () => {\n    if (ServerParseError.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<ServerParseError>();\n    }\n  });\n\n  test(\"type narrows UnconventionalError\", () => {\n    if (UnconventionalError.is(error)) {\n      expectTypeOf(error).toEqualTypeOf<UnconventionalError>();\n    }\n  });\n});\n"
  },
  {
    "path": "src/errors/index.ts",
    "content": "import { CombinedProtocolErrors } from \"./CombinedProtocolErrors.js\";\nimport { isErrorLike } from \"./isErrorLike.js\";\nimport { UnconventionalError } from \"./UnconventionalError.js\";\n\n// This Symbol allows us to pass transport-specific errors from the link chain\n// into QueryManager/client internals without risking a naming collision within\n// extensions (which implementers can use as they see fit).\nexport const PROTOCOL_ERRORS_SYMBOL: unique symbol = Symbol();\n\ntype WithSymbolExtensions<T> = T & {\n  extensions: Record<string | symbol, any>;\n};\n\nexport function graphQLResultHasProtocolErrors<T extends {}>(\n  result: T\n): result is T & {\n  extensions: Record<string | symbol, any>;\n} {\n  if (\"extensions\" in result) {\n    return CombinedProtocolErrors.is(\n      (result as WithSymbolExtensions<T>).extensions[PROTOCOL_ERRORS_SYMBOL]\n    );\n  }\n  return false;\n}\n\nexport function toErrorLike(error: unknown) {\n  if (isErrorLike(error)) {\n    return error;\n  }\n\n  if (typeof error === \"string\") {\n    return new Error(error, { cause: error });\n  }\n\n  return new UnconventionalError(error);\n}\n\nexport { CombinedGraphQLErrors } from \"./CombinedGraphQLErrors.js\";\nexport { CombinedProtocolErrors } from \"./CombinedProtocolErrors.js\";\nexport { isErrorLike } from \"./isErrorLike.js\";\nexport { LinkError, registerLinkError } from \"./LinkError.js\";\nexport { LocalStateError } from \"./LocalStateError.js\";\nexport { ServerError } from \"./ServerError.js\";\nexport { ServerParseError } from \"./ServerParseError.js\";\nexport { UnconventionalError } from \"./UnconventionalError.js\";\n"
  },
  {
    "path": "src/errors/isErrorLike.ts",
    "content": "import type { ErrorLike } from \"@apollo/client\";\n\nexport function isErrorLike(error: unknown): error is ErrorLike {\n  return (\n    error !== null &&\n    typeof error === \"object\" &&\n    typeof (error as ErrorLike).message === \"string\" &&\n    typeof (error as ErrorLike).name === \"string\" &&\n    (typeof (error as ErrorLike).stack === \"string\" ||\n      typeof (error as ErrorLike).stack === \"undefined\")\n  );\n}\n"
  },
  {
    "path": "src/errors/utils.ts",
    "content": "export function isBranded(error: unknown, name: string) {\n  return (\n    typeof error === \"object\" &&\n    error !== null &&\n    (error as any)[Symbol.for(\"apollo.error\")] === name\n  );\n}\n\nexport function brand(error: Error) {\n  Object.defineProperty(error, Symbol.for(\"apollo.error\"), {\n    value: error.name,\n    enumerable: false,\n    writable: false,\n    configurable: false,\n  });\n}\n"
  },
  {
    "path": "src/incremental/handlers/__tests__/defer20220824/defer.test.ts",
    "content": "import assert from \"node:assert\";\n\nimport {\n  GraphQLID,\n  GraphQLList,\n  GraphQLNonNull,\n  GraphQLObjectType,\n  GraphQLSchema,\n  GraphQLString,\n} from \"graphql-17-alpha2\";\nimport { from } from \"rxjs\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport {\n  executeSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  mockDefer20220824,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nimport {\n  hasIncrementalChunks,\n  // eslint-disable-next-line local-rules/no-relative-imports\n} from \"../../defer20220824.js\";\n\n// This is the test setup of the `graphql-js` v17.0.0-alpha.2 release:\n// https://github.com/graphql/graphql-js/blob/364cd71d1a26eb6f62661efd7fa399e91332d30d/src/execution/__tests__/defer-test.ts\n\nconst friendType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n  },\n  name: \"Friend\",\n});\n\nconst friends = [\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n  { name: \"C-3PO\", id: 4 },\n];\n\nconst heroType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n    slowField: {\n      type: GraphQLString,\n      resolve: async () => {\n        await resolveOnNextTick();\n        return \"slow\";\n      },\n    },\n    errorField: {\n      type: GraphQLString,\n      resolve: () => {\n        throw new Error(\"bad\");\n      },\n    },\n    nonNullErrorField: {\n      type: new GraphQLNonNull(GraphQLString),\n      resolve: () => null,\n    },\n    promiseNonNullErrorField: {\n      type: new GraphQLNonNull(GraphQLString),\n      resolve: () => Promise.resolve(null),\n    },\n    friends: {\n      type: new GraphQLList(friendType),\n      resolve: () => friends,\n    },\n  },\n  name: \"Hero\",\n});\n\nconst hero = { name: \"Luke\", id: 1 };\n\nconst query = new GraphQLObjectType({\n  fields: {\n    hero: {\n      type: heroType,\n      resolve: () => hero,\n    },\n  },\n  name: \"Query\",\n});\n\nconst schema = new GraphQLSchema({ query });\n\nfunction resolveOnNextTick(): Promise<void> {\n  return Promise.resolve(undefined);\n}\n\nfunction run(query: DocumentNode) {\n  return executeSchemaGraphQL17Alpha2(schema, query);\n}\n\nconst schemaLink = new ApolloLink((operation) => {\n  return from(run(operation.query));\n});\n\ndescribe(\"graphql-js test cases\", () => {\n  // These test cases mirror defer tests of the `graphql-js` v17.0.0-alpha.2 release:\n  // https://github.com/graphql/graphql-js/blob/364cd71d1a26eb6f62661efd7fa399e91332d30d/src/execution/__tests__/defer-test.ts\n\n  it(\"Can defer fragments containing scalar types\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        id\n        name\n      }\n    `;\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Can disable defer using if argument\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer(if: false)\n        }\n      }\n      fragment NameFragment on Hero {\n        name\n      }\n    `;\n    const handler = new Defer20220824Handler();\n    const incoming = run(query);\n\n    const { value: chunk } = (await incoming.next())!;\n    assert(chunk);\n    expect(handler.isIncrementalResult(chunk)).toBe(false);\n    expect(hasIncrementalChunks(chunk)).toBe(false);\n  });\n  it.skip(\"Does not disable defer with null if argument\", async () => {\n    // test is not interesting from a client perspective\n  });\n  it(\"Can defer fragments on the top level Query field\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ...QueryFragment @defer(label: \"DeferQuery\")\n      }\n      fragment QueryFragment on Query {\n        hero {\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Can defer fragments with errors on the top level Query field\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ...QueryFragment @defer(label: \"DeferQuery\")\n      }\n      fragment QueryFragment on Query {\n        hero {\n          errorField\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            errorField: null,\n          },\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"hero\", \"errorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Can defer a fragment within an already deferred fragment\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...TopFragment @defer(label: \"DeferTop\")\n        }\n      }\n      fragment TopFragment on Hero {\n        name\n        ...NestedFragment @defer(label: \"DeferNested\")\n      }\n      fragment NestedFragment on Hero {\n        friends {\n          name\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            friends: [{ name: \"Han\" }, { name: \"Leia\" }, { name: \"C-3PO\" }],\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Can defer a fragment that is also not deferred, deferred fragment is first\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...TopFragment @defer(label: \"DeferTop\")\n          ...TopFragment\n        }\n      }\n      fragment TopFragment on Hero {\n        name\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: { id: \"1\", name: \"Luke\" },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it.skip(\"Can defer a fragment that is also not deferred, non-deferred fragment is first\", async () => {\n    // from client perspective, a repeat of the last one\n  });\n\n  it.skip(\"Can defer an inline fragment\", async () => {\n    // from client perspective, a repeat of a previous test\n  });\n  it(\"Handles errors thrown in deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        errorField\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: { hero: { id: \"1\" } },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            errorField: null,\n          },\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"hero\", \"errorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Handles non-nullable errors thrown in deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        nonNullErrorField\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: { hero: { id: \"1\" } },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            // in a perfect world, this would bubble up `null` to `hero` or the top level,\n            // but we don't have the necessary schema information here to do that\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Hero.nonNullErrorField.\",\n            path: [\"hero\", \"nonNullErrorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it(\"Handles non-nullable errors thrown outside deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          nonNullErrorField\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        id\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const incoming = run(query);\n\n    const { value: chunk } = (await incoming.next())!;\n    assert(chunk);\n    expect(handler.isIncrementalResult(chunk)).toBe(false);\n    expect(hasIncrementalChunks(chunk)).toBe(false);\n  });\n  it.skip(\"Handles async non-nullable errors thrown in deferred fragments\", async () => {\n    // from client perspective, a repeat of a previous one\n  });\n  it(\"Returns payloads in correct order\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        slowField\n        friends {\n          ...NestedFragment @defer\n        }\n      }\n      fragment NestedFragment on Friend {\n        name\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(false);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: { hero: { id: \"1\" } },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            friends: [{}, {}, {}],\n            slowField: \"slow\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n    {\n      const { value: chunk, done } = (await incoming.next())!;\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(hasIncrementalChunks(chunk)).toBe(true);\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            friends: [\n              {\n                name: \"Han\",\n              },\n              {\n                name: \"Leia\",\n              },\n              {\n                name: \"C-3PO\",\n              },\n            ],\n            slowField: \"slow\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n  it.skip(\"Returns payloads from synchronous data in correct order\", async () => {\n    // from client perspective, a repeat of the previous one\n  });\n\n  it.skip(\"original execute function throws error if anything is deferred and everything else is sync\", () => {\n    // not relevant for the client\n  });\n\n  it.skip(\"original execute function resolves to error if anything is deferred and something else is async\", async () => {\n    // not relevant for the client\n  });\n});\n\ntest(\"Defer20220824Handler can be used with `ApolloClient`\", async () => {\n  const client = new ApolloClient({\n    link: schemaLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"merges cache updates that happen concurrently\", async () => {\n  const stream = mockDefer20220824();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        job\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  stream.enqueueInitialChunk({\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Farmer\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Farmer\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  client.cache.writeFragment({\n    id: \"Hero:1\",\n    fragment: gql`\n      fragment HeroJob on Hero {\n        job\n      }\n    `,\n    data: {\n      job: \"Jedi\",\n    },\n  });\n\n  stream.enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          name: \"Luke\",\n        },\n        path: [\"hero\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Jedi\", // updated from cache\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"returns error on initial result\", async () => {\n  const client = new ApolloClient({\n    link: schemaLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n        errorField\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        errorField: null,\n      },\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n          errorField: null,\n        },\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"hero\", \"errorField\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        errorField: null,\n        name: \"Luke\",\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n          errorField: null,\n          name: \"Luke\",\n        },\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"hero\", \"errorField\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"stream that returns an error but continues to stream\", async () => {\n  const client = new ApolloClient({\n    link: schemaLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          errorField\n        }\n        ... @defer {\n          slowField\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        errorField: null,\n      },\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n          errorField: null,\n        },\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"hero\", \"errorField\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        errorField: null,\n        slowField: \"slow\",\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n          errorField: null,\n          slowField: \"slow\",\n        },\n      },\n      errors: [\n        {\n          message: \"bad\",\n          path: [\"hero\", \"errorField\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n});\n\ntest(\"handles final chunk of { hasNext: false } correctly in usage with Apollo Client\", async () => {\n  const stream = mockDefer20220824();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query ProductsQuery {\n      allProducts {\n        id\n        nonNullErrorField\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n  stream.enqueueInitialChunk({\n    data: {\n      allProducts: [null, null, null],\n    },\n    errors: [\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n    ],\n    hasNext: true,\n  });\n\n  stream.enqueueSubsequentChunk({\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      allProducts: [null, null, null],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        allProducts: [null, null, null],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    }),\n  });\n  await expect(observableStream).not.toEmitAnything();\n});\n\n// Servers that return a `data` property in subsequent payloads are technically\n// invalid, but we still want to handle cases where the server misbehaves.\n//\n// See the following issue for more information:\n// https://github.com/apollographql/apollo-client/issues/12976\ntest(\"ignores `data` property added to subsequent chunks by misbehaving servers\", async () => {\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  enqueueInitialChunk({\n    data: { hero: { __typename: \"Hero\", id: \"1\" } },\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  enqueueSubsequentChunk({\n    // @ts-expect-error simulate misbehaving server\n    data: null,\n    incremental: [{ data: { name: \"Luke\" }, path: [\"hero\"] }],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n"
  },
  {
    "path": "src/incremental/handlers/__tests__/defer20220824/stream.test.ts",
    "content": "import assert from \"node:assert\";\n\nimport { from } from \"rxjs\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport {\n  executeSchemaGraphQL17Alpha2,\n  friendListSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  ObservableStream,\n  promiseWithResolvers,\n} from \"@apollo/client/testing/internal\";\n\n// This is the test setup of the `graphql-js` v17.0.0-alpha.2 release:\n// https://github.com/graphql/graphql-js/blob/042002c3d332d36c67861f5b37d39b74d54d97d4/src/execution/__tests__/stream-test.ts\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\nfunction run(document: DocumentNode, rootValue: unknown = {}) {\n  return executeSchemaGraphQL17Alpha2(\n    friendListSchemaGraphQL17Alpha2,\n    document,\n    rootValue\n  );\n}\n\nfunction createSchemaLink(rootValue?: Record<string, unknown>) {\n  return new ApolloLink((operation) => {\n    return from(run(operation.query, rootValue));\n  });\n}\n\ndescribe(\"Execute: stream directive\", () => {\n  it(\"Can stream a list field\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream(initialCount: 1)\n      }\n    `;\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\"],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can use default value of initialCount\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream\n      }\n    `;\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\"],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Negative values of initialCount throw field errors\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it.skip(\"Returns label from stream directive\", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it.skip(\"Can disable @stream using if argument\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Does not disable stream with null if argument\", async () => {\n    const query = gql`\n      query ($shouldStream: Boolean) {\n        scalarList @stream(initialCount: 2, if: $shouldStream)\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\"],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream multi-dimensional lists\", async () => {\n    const query = gql`\n      query {\n        scalarListList @stream(initialCount: 1)\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarListList: () => [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarListList: [[\"apple\", \"apple\", \"apple\"]],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarListList: [\n            [\"apple\", \"apple\", \"apple\"],\n            [\"banana\", \"banana\", \"banana\"],\n            [\"coconut\", \"coconut\", \"coconut\"],\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns a list of promises\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () => friends.map((f) => Promise.resolve(f)),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            {\n              name: \"Luke\",\n              id: \"1\",\n            },\n            {\n              name: \"Han\",\n              id: \"2\",\n            },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream in correct order with lists of promises\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () => friends.map((f) => Promise.resolve(f)),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles rejections in a field that returns a list of promises before initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n          return Promise.resolve(f);\n        }),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }, null],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            null,\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles rejections in a field that returns a list of promises after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n          return Promise.resolve(f);\n        }),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            null,\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns an async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns an async iterable, using a non-zero initialCount\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Negative values of initialCount throw field errors on a field that returns an async iterable\", async () => {\n    // from a client persective, a regular graphql query\n  });\n\n  it.skip(\"Can handle concurrent calls to .next() without waiting\", async () => {\n    // from a client persective, a repeat of a previous test\n  });\n\n  it.skip(\"Handles error thrown in async iterable before initialCount is reached\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Handles error thrown in async iterable after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }, null],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles null returned in non-null list items after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        nonNullFriendList @stream(initialCount: 1) {\n          name\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nonNullFriendList: () => [friends[0], null],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ name: \"Luke\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ name: \"Luke\" }],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n            path: [\"nonNullFriendList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles null returned in non-null async iterable list items after initialCount is reached\", async () => {\n    // from a client perspective, a repeat of the previous test\n  });\n\n  it(\"Handles errors thrown by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream(initialCount: 1)\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [friends[0].name, {}],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"Luke\"],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"Luke\", null],\n        },\n        errors: [\n          {\n            message: \"String cannot represent value: {}\",\n            path: [\"scalarList\", 1],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles async errors thrown by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        nonNullFriendList @stream(initialCount: 1) {\n          nonNullName\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nonNullFriendList: () => [\n        Promise.resolve({ nonNullName: friends[0].name }),\n        Promise.resolve({\n          nonNullName: () => Promise.reject(new Error(\"Oops\")),\n        }),\n        Promise.resolve({ nonNullName: friends[1].name }),\n      ],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ nonNullName: \"Luke\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ nonNullName: \"Luke\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"nonNullFriendList\", 1, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles async errors thrown by completeValue after initialCount is reached from async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          nonNullName\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve({ nonNullName: friends[0].name });\n        yield await Promise.resolve({\n          nonNullName: () => Promise.reject(new Error(\"Oops\")),\n        });\n        yield await Promise.resolve({ nonNullName: friends[1].name });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null, { nonNullName: \"Han\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null, { nonNullName: \"Han\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Filters payloads that are nulled\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Does not filter payloads when null error is in a different path\", async () => {\n    const query = gql`\n      query {\n        otherNestedObject: nestedObject {\n          ... @defer {\n            scalarField\n          }\n        }\n        nestedObject {\n          nestedFriendList @stream(initialCount: 0) {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        scalarField: () => Promise.reject(new Error(\"Oops\")),\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          otherNestedObject: {},\n          nestedObject: { nestedFriendList: [] },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          otherNestedObject: {\n            scalarField: null,\n          },\n          nestedObject: { nestedFriendList: [{ name: \"Luke\" }] },\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"otherNestedObject\", \"scalarField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Filters stream payloads that are nulled in a deferred payload\", async () => {\n    const query = gql`\n      query {\n        nestedObject {\n          ... @defer {\n            deeperNestedObject {\n              nonNullScalarField\n              deeperNestedFriendList @stream(initialCount: 0) {\n                name\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        deeperNestedObject: {\n          nonNullScalarField: () => Promise.resolve(null),\n          async *deeperNestedFriendList() {\n            yield await Promise.resolve(friends[0]);\n          },\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            deeperNestedObject: null,\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field DeeperNestedObject.nonNullScalarField.\",\n            path: [\"nestedObject\", \"deeperNestedObject\", \"nonNullScalarField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Filters defer payloads that are nulled in a stream response\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          nonNullName\n          ... @defer {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve({\n          name: friends[0].name,\n          nonNullName: () => Promise.resolve(null),\n        });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [null],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Friend.nonNullName.\",\n            path: [\"friendList\", 0, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [null],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Friend.nonNullName.\",\n            path: [\"friendList\", 0, \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Returns iterator and ignores errors when stream payloads are filtered\", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it(\"Handles promises returned by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve({\n          id: friends[2].id,\n          name: () => Promise.resolve(friends[2].name),\n        });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n            { id: \"3\", name: \"Leia\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n            { id: \"3\", name: \"Leia\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Returns payloads in correct order when parent deferred fragment resolves slower than stream\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n    const query = gql`\n      query {\n        nestedObject {\n          ...DeferFragment @defer\n        }\n      }\n      fragment DeferFragment on NestedObject {\n        scalarField\n        nestedFriendList @stream(initialCount: 0) {\n          name\n        }\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        scalarField: () => slowFieldPromise,\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"slow\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can @defer fields that are resolved after async iterable is complete\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n    const {\n      promise: iterableCompletionPromise,\n      resolve: resolveIterableCompletion,\n    } = promiseWithResolvers();\n\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1, label: \"stream-label\") {\n          ...NameFragment @defer(label: \"DeferName\") @defer(label: \"DeferName\")\n          id\n        }\n      }\n      fragment NameFragment on Friend {\n        name\n      }\n    `;\n\n    const handler = new Defer20220824Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve({\n          id: friends[1].id,\n          name: () => slowFieldPromise,\n        });\n        await iterableCompletionPromise;\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveIterableCompletion(null);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }, { id: \"2\" }],\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"Han\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Can @defer fields that are resolved before async iterable is complete\", async () => {\n    // from a client perspective, a repeat of the previous test\n  });\n\n  it.skip(\"Returns underlying async iterables when returned generator is returned\", async () => {\n    // not interesting from a client perspective\n  });\n\n  it.skip(\"Can return async iterable when underlying iterable does not have a return method\", async () => {\n    // not interesting from a client perspective\n  });\n\n  it.skip(\"Returns underlying async iterables when returned generator is thrown\", async () => {\n    // not interesting from a client perspective\n  });\n});\n\n// quick smoke test. More exhaustive `@stream` tests can be found in\n// src/core/__tests__/client.watchQuery/streamDefer20220824.test.ts\ntest(\"Defer20220824Handler can be used with `ApolloClient`\", async () => {\n  const client = new ApolloClient({\n    link: createSchemaLink({ friendList: friends }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"properly merges streamed data into cache data\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke Cached\", id: \"1\" },\n            { name: \"Han Cached\", id: \"2\" },\n            { name: \"Leia Cached\", id: \"3\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into partial cache data\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        { friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }] },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into list with fewer items\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle({ friendList: [{ id: \"1\", name: \"Luke Cached\" }] }, chunk)\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into list with more items\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke Cached\", id: \"1\" },\n            { name: \"Han Cached\", id: \"2\" },\n            { name: \"Leia Cached\", id: \"3\" },\n            { name: \"Chewbacca Cached\", id: \"4\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges cache data when list is included in deferred chunk\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n\n  const query = gql`\n    query {\n      nestedObject {\n        ...DeferFragment @defer\n      }\n    }\n    fragment DeferFragment on NestedObject {\n      scalarField\n      nestedFriendList @stream(initialCount: 0) {\n        name\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    nestedObject: {\n      scalarField: () => slowFieldPromise,\n      async *nestedFriendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n      },\n    },\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"cached\",\n            nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"cached\",\n          nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  resolveSlowField(\"slow\");\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"cached\",\n            nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\n// This behavior isn't exhibited in the graphql.js test suite, but we want to\n// test for it in case other server implementations send multiple items in a\n// stream payload.\ntest(\"handles streams with more than one item in a chunk\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new Defer20220824Handler();\n  const request = handler.startRequest({ query });\n\n  {\n    const chunk: Defer20220824Handler.InitialResult = {\n      data: { friendList: [{ name: \"Luke\", id: \"1\" }] },\n      hasNext: true,\n    };\n\n    expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n      data: {\n        friendList: [{ name: \"Luke\", id: \"1\" }],\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const chunk: Defer20220824Handler.SubsequentResult<\n      Array<Record<string, any>>\n    > = {\n      incremental: [\n        {\n          items: [\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n          path: [\"friendList\", 1],\n        },\n      ],\n      hasNext: false,\n    };\n\n    assert(handler.isIncrementalResult(chunk));\n    expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n"
  },
  {
    "path": "src/incremental/handlers/__tests__/graphql17Alpha9/defer.test.ts",
    "content": "import assert from \"node:assert\";\n\nimport {\n  GraphQLID,\n  GraphQLList,\n  GraphQLNonNull,\n  GraphQLObjectType,\n  GraphQLSchema,\n  GraphQLString,\n} from \"graphql-17-alpha9\";\nimport { from } from \"rxjs\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport {\n  executeSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n  ObservableStream,\n  promiseWithResolvers,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\n// This is the test setup of the `graphql-js` v17.0.0-alpha.9 release:\n// https://github.com/graphql/graphql-js/blob/3283f8adf52e77a47f148ff2f30185c8d11ff0f0/src/execution/__tests__/defer-test.ts\n\nconst friendType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n    nonNullName: { type: new GraphQLNonNull(GraphQLString) },\n  },\n  name: \"Friend\",\n});\n\nconst friends = [\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n  { name: \"C-3PO\", id: 4 },\n];\n\nconst deeperObject = new GraphQLObjectType({\n  fields: {\n    foo: { type: GraphQLString },\n    bar: { type: GraphQLString },\n    baz: { type: GraphQLString },\n    bak: { type: GraphQLString },\n  },\n  name: \"DeeperObject\",\n});\n\nconst nestedObject = new GraphQLObjectType({\n  fields: {\n    deeperObject: { type: deeperObject },\n    name: { type: GraphQLString },\n  },\n  name: \"NestedObject\",\n});\n\nconst anotherNestedObject = new GraphQLObjectType({\n  fields: {\n    deeperObject: { type: deeperObject },\n  },\n  name: \"AnotherNestedObject\",\n});\n\nconst hero = {\n  name: \"Luke\",\n  id: 1,\n  friends,\n  nestedObject,\n  anotherNestedObject,\n};\n\nconst c = new GraphQLObjectType({\n  fields: {\n    d: { type: GraphQLString },\n    nonNullErrorField: { type: new GraphQLNonNull(GraphQLString) },\n  },\n  name: \"c\",\n});\n\nconst e = new GraphQLObjectType({\n  fields: {\n    f: { type: GraphQLString },\n  },\n  name: \"e\",\n});\n\nconst b = new GraphQLObjectType({\n  fields: {\n    c: { type: c },\n    e: { type: e },\n  },\n  name: \"b\",\n});\n\nconst a = new GraphQLObjectType({\n  fields: {\n    b: { type: b },\n    someField: { type: GraphQLString },\n  },\n  name: \"a\",\n});\n\nconst g = new GraphQLObjectType({\n  fields: {\n    h: { type: GraphQLString },\n  },\n  name: \"g\",\n});\n\nconst heroType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n    nonNullName: { type: new GraphQLNonNull(GraphQLString) },\n    friends: {\n      type: new GraphQLList(friendType),\n    },\n    nestedObject: { type: nestedObject },\n    anotherNestedObject: { type: anotherNestedObject },\n  },\n  name: \"Hero\",\n});\n\nconst query = new GraphQLObjectType({\n  fields: {\n    hero: {\n      type: heroType,\n    },\n    a: { type: a },\n    g: { type: g },\n  },\n  name: \"Query\",\n});\n\nconst schema = new GraphQLSchema({ query });\n\nfunction resolveOnNextTick(): Promise<void> {\n  return Promise.resolve(undefined);\n}\n\nfunction run(\n  document: DocumentNode,\n  rootValue: unknown = { hero },\n  enableEarlyExecution?: boolean\n) {\n  return executeSchemaGraphQL17Alpha9(\n    schema,\n    document,\n    rootValue,\n    enableEarlyExecution\n  );\n}\n\nfunction createSchemaLink(rootValue?: Record<string, unknown>) {\n  return new ApolloLink((operation) => {\n    return from(run(operation.query, rootValue));\n  });\n}\n\ndescribe(\"graphql-js test cases\", () => {\n  // These test cases mirror defer tests of the `graphql-js` v17.0.0-alpha.9 release:\n  // https://github.com/graphql/graphql-js/blob/3283f8adf52e77a47f148ff2f30185c8d11ff0f0/src/execution/__tests__/defer-test.ts\n\n  it(\"Can defer fragments containing scalar types\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        name\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can disable defer using if argument\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer(if: false)\n        }\n      }\n      fragment NameFragment on Hero {\n        name\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const incoming = run(query);\n\n    const { value: chunk } = await incoming.next();\n\n    assert(chunk);\n    expect(handler.isIncrementalResult(chunk)).toBe(false);\n  });\n\n  it.skip(\"Does not disable defer with null if argument\", async () => {\n    // test is not interesting from a client perspective\n  });\n\n  it.skip(\"Does not execute deferred fragments early when not specified\", async () => {\n    // test is not interesting from a client perspective\n  });\n\n  it.skip(\"Does execute deferred fragments early when specified\", async () => {\n    // test is not interesting from a client perspective\n  });\n\n  it(\"Can defer fragments on the top level Query field\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ...QueryFragment @defer(label: \"DeferQuery\")\n      }\n      fragment QueryFragment on Query {\n        hero {\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can defer fragments with errors on the top level Query field\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ...QueryFragment @defer(label: \"DeferQuery\")\n      }\n      fragment QueryFragment on Query {\n        hero {\n          name\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        ...hero,\n        name: () => {\n          throw new Error(\"bad\");\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            name: null,\n          },\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"hero\", \"name\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can defer a fragment within an already deferred fragment\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          ...TopFragment @defer(label: \"DeferTop\")\n        }\n      }\n      fragment TopFragment on Hero {\n        id\n        ...NestedFragment @defer(label: \"DeferNested\")\n      }\n      fragment NestedFragment on Hero {\n        friends {\n          name\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            friends: [{ name: \"Han\" }, { name: \"Leia\" }, { name: \"C-3PO\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Can defer a fragment that is also not deferred, deferred fragment is first\", async () => {\n    // from the client perspective, a regular graphql query\n  });\n\n  it.skip(\"Can defer a fragment that is also not deferred, non-deferred fragment is first\", async () => {\n    // from the client perspective, a regular graphql query\n  });\n\n  it(\"Can defer an inline fragment\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ... on Hero @defer(label: \"InlineDeferred\") {\n            name\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Does not emit empty defer fragments\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it(\"Emits children of empty defer fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          ... @defer {\n            ... @defer {\n              name\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can separately emit defer fragments with different labels with varying fields\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          ... @defer(label: \"DeferID\") {\n            id\n          }\n          ... @defer(label: \"DeferName\") {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Separately emits defer fragments with different labels with varying subfields\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ... @defer(label: \"DeferID\") {\n          hero {\n            id\n          }\n        }\n        ... @defer(label: \"DeferName\") {\n          hero {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Separately emits defer fragments with different labels with varying subfields that return promises\", async () => {\n    // from the client perspective, a repeat of the last one\n  });\n\n  it(\"Separately emits defer fragments with varying subfields of same priorities but different level of defers\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          ... @defer(label: \"DeferID\") {\n            id\n          }\n        }\n        ... @defer(label: \"DeferName\") {\n          hero {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Separately emits nested defer fragments with varying subfields of same priorities but different level of defers\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ... @defer(label: \"DeferName\") {\n          hero {\n            name\n            ... @defer(label: \"DeferID\") {\n              id\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Initiates deferred grouped field sets only if they have been released as pending\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            ... @defer {\n              b {\n                c {\n                  d\n                }\n              }\n            }\n          }\n        }\n        ... @defer {\n          a {\n            someField\n            ... @defer {\n              b {\n                e {\n                  f\n                }\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        someField: slowFieldPromise,\n        b: {\n          c: () => {\n            return { d: \"d\" };\n          },\n          e: () => {\n            return { f: \"f\" };\n          },\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"someField\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n              e: { f: \"f\" },\n            },\n            someField: \"someField\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Initiates unique deferred grouped field sets after those that are common to sibling defers\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            ... @defer {\n              b {\n                c {\n                  d\n                }\n              }\n            }\n          }\n        }\n        ... @defer {\n          a {\n            ... @defer {\n              b {\n                c {\n                  d\n                }\n                e {\n                  f\n                }\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const { promise: cPromise, resolve: resolveC } =\n      promiseWithResolvers<void>();\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        b: {\n          c: async () => {\n            await cPromise;\n            return { d: \"d\" };\n          },\n          e: () => {\n            return { f: \"f\" };\n          },\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveC();\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n              e: { f: \"f\" },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can deduplicate multiple defers on the same object\", async () => {\n    const query = gql`\n      query {\n        hero {\n          friends {\n            ... @defer {\n              ...FriendFrag\n              ... @defer {\n                ...FriendFrag\n                ... @defer {\n                  ...FriendFrag\n                  ... @defer {\n                    ...FriendFrag\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n\n      fragment FriendFrag on Friend {\n        id\n        name\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            friends: [{}, {}, {}],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            friends: [\n              { id: \"2\", name: \"Han\" },\n              { id: \"3\", name: \"Leia\" },\n              { id: \"4\", name: \"C-3PO\" },\n            ],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Deduplicates fields present in the initial payload\", async () => {\n    const query = gql`\n      query {\n        hero {\n          nestedObject {\n            deeperObject {\n              foo\n            }\n          }\n          anotherNestedObject {\n            deeperObject {\n              foo\n            }\n          }\n          ... @defer {\n            nestedObject {\n              deeperObject {\n                bar\n              }\n            }\n            anotherNestedObject {\n              deeperObject {\n                foo\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        nestedObject: { deeperObject: { foo: \"foo\", bar: \"bar\" } },\n        anotherNestedObject: { deeperObject: { foo: \"foo\" } },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n              },\n            },\n            anotherNestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n                bar: \"bar\",\n              },\n            },\n            anotherNestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Deduplicates fields present in a parent defer payload\", async () => {\n    const query = gql`\n      query {\n        hero {\n          ... @defer {\n            nestedObject {\n              deeperObject {\n                foo\n                ... @defer {\n                  foo\n                  bar\n                }\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: { nestedObject: { deeperObject: { foo: \"foo\", bar: \"bar\" } } },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n                bar: \"bar\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Deduplicates fields with deferred fragments at multiple levels\", async () => {\n    const query = gql`\n      query {\n        hero {\n          nestedObject {\n            deeperObject {\n              foo\n            }\n          }\n          ... @defer {\n            nestedObject {\n              deeperObject {\n                foo\n                bar\n              }\n              ... @defer {\n                deeperObject {\n                  foo\n                  bar\n                  baz\n                  ... @defer {\n                    foo\n                    bar\n                    baz\n                    bak\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        nestedObject: {\n          deeperObject: { foo: \"foo\", bar: \"bar\", baz: \"baz\", bak: \"bak\" },\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n                bar: \"bar\",\n                baz: \"baz\",\n                bak: \"bak\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Deduplicates multiple fields from deferred fragments from different branches occurring at the same level\", async () => {\n    const query = gql`\n      query {\n        hero {\n          nestedObject {\n            deeperObject {\n              ... @defer {\n                foo\n              }\n            }\n          }\n          ... @defer {\n            nestedObject {\n              deeperObject {\n                ... @defer {\n                  foo\n                  bar\n                }\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: { nestedObject: { deeperObject: { foo: \"foo\", bar: \"bar\" } } },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {},\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            nestedObject: {\n              deeperObject: {\n                foo: \"foo\",\n                bar: \"bar\",\n              },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Deduplicate fields with deferred fragments in different branches at multiple non-overlapping levels\", async () => {\n    const query = gql`\n      query {\n        a {\n          b {\n            c {\n              d\n            }\n            ... @defer {\n              e {\n                f\n              }\n            }\n          }\n        }\n        ... @defer {\n          a {\n            b {\n              e {\n                f\n              }\n            }\n          }\n          g {\n            h\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        b: {\n          c: { d: \"d\" },\n          e: { f: \"f\" },\n        },\n      },\n      g: { h: \"h\" },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n              e: { f: \"f\" },\n            },\n          },\n          g: {\n            h: \"h\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Correctly bundles varying subfields into incremental data records unique by defer combination, ignoring fields in a fragment masked by a parent defer\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        ... @defer {\n          hero {\n            id\n          }\n        }\n        ... @defer {\n          hero {\n            name\n            shouldBeWithNameDespiteAdditionalDefer: name\n            ... @defer {\n              shouldBeWithNameDespiteAdditionalDefer: name\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"Luke\",\n            shouldBeWithNameDespiteAdditionalDefer: \"Luke\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Nulls cross defer boundaries, null first\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            someField\n            b {\n              c {\n                nonNullErrorField\n              }\n            }\n          }\n        }\n        a {\n          ... @defer {\n            b {\n              c {\n                d\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: { b: { c: { d: \"d\" } }, someField: \"someField\" },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"c\", \"nonNullErrorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Nulls cross defer boundaries, value first\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            b {\n              c {\n                d\n              }\n            }\n          }\n        }\n        a {\n          ... @defer {\n            someField\n            b {\n              c {\n                nonNullErrorField\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        b: { c: { d: \"d\" }, nonNullErrorFIeld: null },\n        someField: \"someField\",\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"c\", \"nonNullErrorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles multiple erroring deferred grouped field sets\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            b {\n              c {\n                someError: nonNullErrorField\n              }\n            }\n          }\n        }\n        ... @defer {\n          a {\n            b {\n              c {\n                anotherError: nonNullErrorField\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        b: { c: { nonNullErrorField: null } },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"c\", \"someError\"],\n          },\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"c\", \"anotherError\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles multiple erroring deferred grouped field sets for the same fragment\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            b {\n              someC: c {\n                d: d\n              }\n              anotherC: c {\n                d: d\n              }\n            }\n          }\n        }\n        ... @defer {\n          a {\n            b {\n              someC: c {\n                someError: nonNullErrorField\n              }\n              anotherC: c {\n                anotherError: nonNullErrorField\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      a: {\n        b: { c: { d: \"d\", nonNullErrorField: null } },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              someC: { d: \"d\" },\n              anotherC: { d: \"d\" },\n            },\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"someC\", \"someError\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"filters a payload with a null that cannot be merged\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          a {\n            someField\n            b {\n              c {\n                nonNullErrorField\n              }\n            }\n          }\n        }\n        a {\n          ... @defer {\n            b {\n              c {\n                d\n              }\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(\n      query,\n      {\n        a: {\n          b: {\n            c: {\n              d: \"d\",\n              nonNullErrorField: async () => {\n                await resolveOnNextTick();\n                return null;\n              },\n            },\n          },\n          someField: \"someField\",\n        },\n      },\n      true\n    );\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          a: {\n            b: {\n              c: { d: \"d\" },\n            },\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field c.nonNullErrorField.\",\n            path: [\"a\", \"b\", \"c\", \"nonNullErrorField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Cancels deferred fields when initial result exhibits null bubbling\", async () => {\n    // from the client perspective, a regular graphql query\n  });\n\n  it(\"Cancels deferred fields when deferred result exhibits null bubbling\", async () => {\n    const query = gql`\n      query {\n        ... @defer {\n          hero {\n            nonNullName\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(\n      query,\n      {\n        hero: {\n          ...hero,\n          nonNullName: () => null,\n        },\n      },\n      true\n    );\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {},\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: null,\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Hero.nonNullName.\",\n            path: [\"hero\", \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Deduplicates list fields\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it.skip(\"Deduplicates async iterable list fields\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it.skip(\"Deduplicates empty async iterable list fields\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it(\"Does not deduplicate list fields with non-overlapping fields\", async () => {\n    const query = gql`\n      query {\n        hero {\n          friends {\n            name\n          }\n          ... @defer {\n            friends {\n              id\n            }\n          }\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            friends: [{ name: \"Han\" }, { name: \"Leia\" }, { name: \"C-3PO\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            friends: [\n              { id: \"2\", name: \"Han\" },\n              { id: \"3\", name: \"Leia\" },\n              { id: \"4\", name: \"C-3PO\" },\n            ],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Deduplicates list fields that return empty lists\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it.skip(\"Deduplicates null object fields\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it.skip(\"Deduplicates promise object fields\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it(\"Handles errors thrown in deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        name\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        ...hero,\n        name: () => {\n          throw new Error(\"bad\");\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: null,\n          },\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"hero\", \"name\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles non-nullable errors thrown in deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        nonNullName\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        ...hero,\n        nonNullName: () => null,\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Hero.nonNullName.\",\n            path: [\"hero\", \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles non-nullable errors thrown outside deferred fragments\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it(\"Handles async non-nullable errors thrown in deferred fragments\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        nonNullName\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        ...hero,\n        nonNullName: () => Promise.resolve(null),\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Hero.nonNullName.\",\n            path: [\"hero\", \"nonNullName\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Returns payloads in correct order\", async () => {\n    const query = gql`\n      query HeroNameQuery {\n        hero {\n          id\n          ...NameFragment @defer\n        }\n      }\n      fragment NameFragment on Hero {\n        name\n        friends {\n          ...NestedFragment @defer\n        }\n      }\n      fragment NestedFragment on Friend {\n        name\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      hero: {\n        ...hero,\n        name: async () => {\n          await resolveOnNextTick();\n          return \"slow\";\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          hero: {\n            id: \"1\",\n            name: \"slow\",\n            friends: [{ name: \"Han\" }, { name: \"Leia\" }, { name: \"C-3PO\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Returns payloads from synchronous data in correct order\", async () => {\n    // from the client perspective, a repeat of the last one\n  });\n\n  it.skip(\"Filters deferred payloads when a list item returned by an async iterable is nulled\", async () => {\n    // from the client perspective, a regular query\n  });\n\n  it.skip(\"original execute function throws error if anything is deferred and everything else is sync\", () => {\n    // not relevant for the client\n  });\n\n  it.skip(\"original execute function resolves to error if anything is deferred and something else is async\", async () => {\n    // not relevant for the client\n  });\n});\n\ntest(\"GraphQL17Alpha9Handler can be used with `ApolloClient`\", async () => {\n  const client = new ApolloClient({\n    link: createSchemaLink(),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"merges cache updates that happen concurrently\", async () => {\n  const stream = mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        job\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  stream.enqueueInitialChunk({\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Farmer\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"hero\"] }],\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Farmer\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  client.cache.writeFragment({\n    id: \"Hero:1\",\n    fragment: gql`\n      fragment HeroJob on Hero {\n        job\n      }\n    `,\n    data: {\n      job: \"Jedi\",\n    },\n  });\n\n  stream.enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          name: \"Luke\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        job: \"Jedi\", // updated from cache\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"returns error on initial result\", async () => {\n  const client = new ApolloClient({\n    link: createSchemaLink({\n      hero: {\n        ...hero,\n        nonNullName: null,\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n        nonNullName\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: null,\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: null,\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Hero.nonNullName.\",\n          path: [\"hero\", \"nonNullName\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n\n  await expect(observableStream).not.toEmitAnything();\n});\n\ntest(\"stream that returns an error but continues to stream\", async () => {\n  const client = new ApolloClient({\n    link: createSchemaLink({\n      hero: {\n        ...hero,\n        nonNullName: null,\n        name: async () => {\n          await wait(100);\n          return \"slow\";\n        },\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          nonNullName\n        }\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n        },\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Hero.nonNullName.\",\n          path: [\"hero\", \"nonNullName\"],\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        name: \"slow\",\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          __typename: \"Hero\",\n          id: \"1\",\n          name: \"slow\",\n        },\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Hero.nonNullName.\",\n          path: [\"hero\", \"nonNullName\"],\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.error,\n    partial: false,\n  });\n});\n\ntest(\"handles final chunk of { hasNext: false } correctly in usage with Apollo Client\", async () => {\n  const stream = mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query ProductsQuery {\n      allProducts {\n        id\n        nonNullErrorField\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(\n    client.watchQuery({ query, errorPolicy: \"all\" })\n  );\n  stream.enqueueInitialChunk({\n    data: {\n      allProducts: [null, null, null],\n    },\n    pending: [],\n    errors: [\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n      {\n        message:\n          \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n      },\n    ],\n    hasNext: true,\n  });\n\n  stream.enqueueSubsequentChunk({\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      allProducts: [null, null, null],\n    }),\n    error: new CombinedGraphQLErrors({\n      data: {\n        allProducts: [null, null, null],\n      },\n      errors: [\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n        {\n          message:\n            \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitSimilarValue({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      partial: false,\n    }),\n  });\n  await expect(observableStream).not.toEmitAnything();\n});\n\n// Servers that return a `data` property in subsequent payloads are technically\n// invalid, but we still want to handle cases where the server misbehaves.\n//\n// See the following issue for more information:\n// https://github.com/apollographql/apollo-client/issues/12976\ntest(\"ignores `data` property added to subsequent chunks by misbehaving servers\", async () => {\n  const stream = mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    link: stream.httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query HeroNameQuery {\n      hero {\n        id\n        ... @defer {\n          name\n        }\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  stream.enqueueInitialChunk({\n    data: { hero: { __typename: \"Hero\", id: \"1\" } },\n    pending: [{ id: \"0\", path: [\"hero\"] }],\n    hasNext: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: undefined,\n    dataState: \"empty\",\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n      },\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  stream.enqueueSubsequentChunk({\n    // @ts-expect-error simulate misbehaving server\n    data: null,\n    incremental: [{ data: { name: \"Luke\" }, id: \"0\" }],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: false,\n    data: {\n      hero: {\n        __typename: \"Hero\",\n        id: \"1\",\n        name: \"Luke\",\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n"
  },
  {
    "path": "src/incremental/handlers/__tests__/graphql17Alpha9/stream.test.ts",
    "content": "import assert from \"node:assert\";\n\nimport { Trie } from \"@wry/trie\";\nimport { from } from \"rxjs\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport {\n  executeSchemaGraphQL17Alpha9,\n  friendListSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  ObservableStream,\n  promiseWithResolvers,\n} from \"@apollo/client/testing/internal\";\nimport { streamInfoSymbol } from \"@apollo/client/utilities/internal\";\n\n// This is the test setup of the `graphql-js` v17.0.0-alpha.9 release:\n// https://github.com/graphql/graphql-js/blob/3283f8adf52e77a47f148ff2f30185c8d11ff0f0/src/execution/__tests__/stream-test.ts\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\nfunction resolveOnNextTick(): Promise<void> {\n  return Promise.resolve(undefined);\n}\n\nfunction run(\n  document: DocumentNode,\n  rootValue: unknown = {},\n  enableEarlyExecution = false\n) {\n  return executeSchemaGraphQL17Alpha9(\n    friendListSchemaGraphQL17Alpha9,\n    document,\n    rootValue,\n    enableEarlyExecution\n  );\n}\n\nfunction createSchemaLink(rootValue?: Record<string, unknown>) {\n  return new ApolloLink((operation) => {\n    return from(run(operation.query, rootValue));\n  });\n}\n\nconst extensionsWithStreamDetails = {\n  [streamInfoSymbol]: new WeakRef(expect.any(Trie)),\n};\n\ndescribe(\"graphql-js test cases\", () => {\n  // These test cases mirror stream tests of the `graphql-js` v17.0.0-alpha.9 release:\n  // https://github.com/graphql/graphql-js/blob/3283f8adf52e77a47f148ff2f30185c8d11ff0f0/src/execution/__tests__/stream-test.ts\n\n  it(\"Can stream a list field\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream(initialCount: 1)\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can use default value of initialCount\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Negative values of initialCount throw field errors\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it.skip(\"Returns label from stream directive\", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it.skip(\"Can disable @stream using if argument\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Does not disable stream with null if argument\", async () => {\n    const query = gql`\n      query ($shouldStream: Boolean) {\n        scalarList @stream(initialCount: 2, if: $shouldStream)\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [\"apple\", \"banana\", \"coconut\"],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"apple\", \"banana\", \"coconut\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream multi-dimensional lists\", async () => {\n    const query = gql`\n      query {\n        scalarListList @stream(initialCount: 1)\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarListList: () => [\n        [\"apple\", \"apple\", \"apple\"],\n        [\"banana\", \"banana\", \"banana\"],\n        [\"coconut\", \"coconut\", \"coconut\"],\n      ],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarListList: [[\"apple\", \"apple\", \"apple\"]],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarListList: [\n            [\"apple\", \"apple\", \"apple\"],\n            [\"banana\", \"banana\", \"banana\"],\n            [\"coconut\", \"coconut\", \"coconut\"],\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns a list of promises\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () => friends.map((f) => Promise.resolve(f)),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            {\n              name: \"Luke\",\n              id: \"1\",\n            },\n            {\n              name: \"Han\",\n              id: \"2\",\n            },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            {\n              name: \"Luke\",\n              id: \"1\",\n            },\n            {\n              name: \"Han\",\n              id: \"2\",\n            },\n            {\n              name: \"Leia\",\n              id: \"3\",\n            },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream in correct order with lists of promises\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () => friends.map((f) => Promise.resolve(f)),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Does not execute early if not specified\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          id\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f, i) => ({\n          id: async () => {\n            const slowness = 3 - i;\n            for (let j = 0; j < slowness; j++) {\n              await resolveOnNextTick();\n            }\n            return f.id;\n          },\n        })),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Executes early if specified\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          id\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(\n      query,\n      {\n        friendList: () =>\n          friends.map((f, i) => ({\n            id: async () => {\n              const slowness = 3 - i;\n              for (let j = 0; j < slowness; j++) {\n                await resolveOnNextTick();\n              }\n              return f.id;\n            },\n          })),\n      },\n      true\n    );\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns a list with nested promises\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f) => ({\n          name: Promise.resolve(f.name),\n          id: Promise.resolve(f.id),\n        })),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            {\n              name: \"Luke\",\n              id: \"1\",\n            },\n            {\n              name: \"Han\",\n              id: \"2\",\n            },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            {\n              name: \"Luke\",\n              id: \"1\",\n            },\n            {\n              name: \"Han\",\n              id: \"2\",\n            },\n            {\n              name: \"Leia\",\n              id: \"3\",\n            },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles rejections in a field that returns a list of promises before initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n          return Promise.resolve(f);\n        }),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }, null],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            null,\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles rejections in a field that returns a list of promises after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () =>\n        friends.map((f, i) => {\n          if (i === 1) {\n            return Promise.reject(new Error(\"bad\"));\n          }\n          return Promise.resolve(f);\n        }),\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }, null],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            null,\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns an async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can stream a field that returns an async iterable, using a non-zero initialCount\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Negative values of initialCount throw field errors on a field that returns an async iterable\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Does not execute early if not specified, when streaming from an async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          id\n        }\n      }\n    `;\n\n    const slowFriend = async (n: number) => ({\n      id: async () => {\n        const slowness = (3 - n) * 10;\n        for (let j = 0; j < slowness; j++) {\n          await resolveOnNextTick();\n        }\n        return friends[n].id;\n      },\n    });\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(slowFriend(0));\n        yield await Promise.resolve(slowFriend(1));\n        yield await Promise.resolve(slowFriend(2));\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Executes early if specified when streaming from an async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          id\n        }\n      }\n    `;\n    const order: Array<number> = [];\n    const slowFriend = (n: number) => ({\n      id: async () => {\n        const slowness = (3 - n) * 10;\n        for (let j = 0; j < slowness; j++) {\n          await resolveOnNextTick();\n        }\n        order.push(n);\n        return friends[n].id;\n      },\n    });\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(\n      query,\n      {\n        async *friendList() {\n          yield await Promise.resolve(slowFriend(0));\n          yield await Promise.resolve(slowFriend(1));\n          yield await Promise.resolve(slowFriend(2));\n        },\n      },\n      true\n    );\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can handle concurrent calls to .next() without waiting\", async () => {\n    const query = gql(`\n      query {\n        friendList @stream(initialCount: 2) {\n          name\n          id\n        }\n      }\n    `);\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve(friends[2]);\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n            { name: \"Leia\", id: \"3\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles error thrown in async iterable before initialCount is reached\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Handles error thrown in async iterable after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          name\n          id\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        throw new Error(\"bad\");\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ name: \"Luke\", id: \"1\" }],\n        },\n        errors: [\n          {\n            message: \"bad\",\n            path: [\"friendList\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles null returned in non-null list items after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        nonNullFriendList @stream(initialCount: 1) {\n          name\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nonNullFriendList: () => [friends[0], null, friends[1]],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ name: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ name: \"Luke\" }],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Query.nonNullFriendList.\",\n            path: [\"nonNullFriendList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles null returned in non-null async iterable list items after initialCount is reached\", async () => {\n    // from a client perspective, a repeat of the last test\n  });\n\n  it(\"Handles errors thrown by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        scalarList @stream(initialCount: 1)\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      scalarList: () => [friends[0].name, {}],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"Luke\"],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          scalarList: [\"Luke\", null],\n        },\n        errors: [\n          {\n            message: \"String cannot represent value: {}\",\n            path: [\"scalarList\", 1],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles async errors thrown by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          nonNullName\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      friendList: () => [\n        Promise.resolve({ nonNullName: friends[0].name }),\n        Promise.resolve({\n          nonNullName: () => Promise.reject(new Error(\"Oops\")),\n        }),\n        Promise.resolve({ nonNullName: friends[1].name }),\n      ],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null, { nonNullName: \"Han\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles nested async errors thrown by completeValue after initialCount is reached\", async () => {\n    // from a client perspective, a repeat of the last test\n  });\n\n  it(\"Handles async errors thrown by completeValue after initialCount is reached for a non-nullable list\", async () => {\n    const query = gql`\n      query {\n        nonNullFriendList @stream(initialCount: 1) {\n          nonNullName\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nonNullFriendList: () => [\n        Promise.resolve({ nonNullName: friends[0].name }),\n        Promise.resolve({\n          nonNullName: () => Promise.reject(new Error(\"Oops\")),\n        }),\n        Promise.resolve({ nonNullName: friends[1].name }),\n      ],\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ nonNullName: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nonNullFriendList: [{ nonNullName: \"Luke\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"nonNullFriendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles nested async errors thrown by completeValue after initialCount is reached for a non-nullable list\", async () => {\n    // from a client perspective, a repeat of the last test\n  });\n\n  it(\"Handles async errors thrown by completeValue after initialCount is reached from async iterable\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          nonNullName\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve({ nonNullName: friends[0].name });\n        yield await Promise.resolve({\n          nonNullName: () => Promise.reject(new Error(\"Oops\")),\n        });\n        yield await Promise.resolve({ nonNullName: friends[1].name });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null, { nonNullName: \"Han\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ nonNullName: \"Luke\" }, null, { nonNullName: \"Han\" }],\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"friendList\", 1, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Handles async errors thrown by completeValue after initialCount is reached from async generator for a non-nullable list\", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it.skip(\"Handles async errors thrown by completeValue after initialCount is reached from async iterable for a non-nullable list when the async iterable does not provide a return method) \", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it.skip(\"Handles async errors thrown by completeValue after initialCount is reached from async iterable for a non-nullable list when the async iterable provides concurrent next/return methods and has a slow return \", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it.skip(\"Filters payloads that are nulled\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it.skip(\"Filters payloads that are nulled by a later synchronous error\", async () => {\n    // from a client perspective, a regular graphql query\n  });\n\n  it(\"Does not filter payloads when null error is in a different path\", async () => {\n    const query = gql`\n      query {\n        otherNestedObject: nestedObject {\n          ... @defer {\n            scalarField\n          }\n        }\n        nestedObject {\n          nestedFriendList @stream(initialCount: 0) {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        scalarField: () => Promise.reject(new Error(\"Oops\")),\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          otherNestedObject: {},\n          nestedObject: { nestedFriendList: [] },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          otherNestedObject: { scalarField: null },\n          nestedObject: { nestedFriendList: [{ name: \"Luke\" }] },\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"otherNestedObject\", \"scalarField\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          otherNestedObject: { scalarField: null },\n          nestedObject: { nestedFriendList: [{ name: \"Luke\" }] },\n        },\n        errors: [\n          {\n            message: \"Oops\",\n            path: [\"otherNestedObject\", \"scalarField\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Filters stream payloads that are nulled in a deferred payload\", async () => {\n    const query = gql`\n      query {\n        nestedObject {\n          ... @defer {\n            deeperNestedObject {\n              nonNullScalarField\n              deeperNestedFriendList @stream(initialCount: 0) {\n                name\n              }\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        deeperNestedObject: {\n          nonNullScalarField: () => Promise.resolve(null),\n          async *deeperNestedFriendList() {\n            yield await Promise.resolve(friends[0]); /* c8 ignore start */\n          } /* c8 ignore stop */,\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            deeperNestedObject: null,\n          },\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field DeeperNestedObject.nonNullScalarField.\",\n            path: [\"nestedObject\", \"deeperNestedObject\", \"nonNullScalarField\"],\n          },\n        ],\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Filters defer payloads that are nulled in a stream response\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 0) {\n          nonNullName\n          ... @defer {\n            name\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve({\n          name: friends[0].name,\n          nonNullName: () => Promise.resolve(null),\n        });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [null],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Friend.nonNullName.\",\n            path: [\"friendList\", 0, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [null],\n        },\n        errors: [\n          {\n            message:\n              \"Cannot return null for non-nullable field Friend.nonNullName.\",\n            path: [\"friendList\", 0, \"nonNullName\"],\n          },\n        ],\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Returns iterator and ignores errors when stream payloads are filtered\", async () => {\n    // from a client perspective, a repeat of a previous test\n  });\n\n  it(\"Handles promises returned by completeValue after initialCount is reached\", async () => {\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n        yield await Promise.resolve({\n          id: friends[2].id,\n          name: () => Promise.resolve(friends[2].name),\n        });\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n            { id: \"3\", name: \"Leia\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n            { id: \"3\", name: \"Leia\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Handles overlapping deferred and non-deferred streams\", async () => {\n    const query = gql`\n      query {\n        nestedObject {\n          nestedFriendList @stream(initialCount: 0) {\n            id\n          }\n        }\n        nestedObject {\n          ... @defer {\n            nestedFriendList @stream(initialCount: 0) {\n              id\n              name\n            }\n          }\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            nestedFriendList: [],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            nestedFriendList: [{ id: \"1\", name: \"Luke\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            nestedFriendList: [\n              { id: \"1\", name: \"Luke\" },\n              { id: \"2\", name: \"Han\" },\n            ],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            nestedFriendList: [\n              { id: \"1\", name: \"Luke\" },\n              { id: \"2\", name: \"Han\" },\n            ],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Returns payloads in correct order when parent deferred fragment resolves slower than stream\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n\n    const query = gql`\n      query {\n        nestedObject {\n          ...DeferFragment @defer\n        }\n      }\n      fragment DeferFragment on NestedObject {\n        scalarField\n        nestedFriendList @stream(initialCount: 0) {\n          name\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        scalarField: () => slowFieldPromise,\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"slow\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  // this test does not exist in the original test suite but added to ensure\n  // deferred non-empty lists are properly merged\n  it(\"Returns payloads in correct order when parent deferred fragment resolves slower than stream with > 0 initialCount\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n\n    const query = gql`\n      query {\n        nestedObject {\n          ...DeferFragment @defer\n        }\n      }\n      fragment DeferFragment on NestedObject {\n        scalarField\n        nestedFriendList @stream(initialCount: 1) {\n          name\n        }\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      nestedObject: {\n        scalarField: () => slowFieldPromise,\n        async *nestedFriendList() {\n          yield await Promise.resolve(friends[0]);\n          yield await Promise.resolve(friends[1]);\n        },\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {},\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"slow\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }],\n          },\n        },\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can @defer fields that are resolved after async iterable is complete\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n    const {\n      promise: iterableCompletionPromise,\n      resolve: resolveIterableCompletion,\n    } = promiseWithResolvers();\n\n    const query = gql`\n      query {\n        friendList @stream(label: \"stream-label\") {\n          ...NameFragment @defer(label: \"DeferName\") @defer(label: \"DeferName\")\n          id\n        }\n      }\n      fragment NameFragment on Friend {\n        name\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve({\n          id: friends[1].id,\n          name: () => slowFieldPromise,\n        });\n        await iterableCompletionPromise;\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveIterableCompletion(null);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"Han\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }, { id: \"2\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }, { id: \"2\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it(\"Can @defer fields that are resolved before async iterable is complete\", async () => {\n    const { promise: slowFieldPromise, resolve: resolveSlowField } =\n      promiseWithResolvers();\n    const {\n      promise: iterableCompletionPromise,\n      resolve: resolveIterableCompletion,\n    } = promiseWithResolvers();\n\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1, label: \"stream-label\") {\n          ...NameFragment @defer(label: \"DeferName\") @defer(label: \"DeferName\")\n          id\n        }\n      }\n      fragment NameFragment on Friend {\n        name\n      }\n    `;\n\n    const handler = new GraphQL17Alpha9Handler();\n    const request = handler.startRequest({ query });\n\n    const incoming = run(query, {\n      async *friendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve({\n          id: friends[1].id,\n          name: () => slowFieldPromise,\n        });\n        await iterableCompletionPromise;\n      },\n    });\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveSlowField(\"Han\");\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [{ id: \"1\", name: \"Luke\" }, { id: \"2\" }],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(true);\n    }\n\n    resolveIterableCompletion(null);\n\n    {\n      const { value: chunk, done } = await incoming.next();\n\n      assert(!done);\n      assert(handler.isIncrementalResult(chunk));\n      expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { id: \"1\", name: \"Luke\" },\n            { id: \"2\", name: \"Han\" },\n          ],\n        },\n        extensions: extensionsWithStreamDetails,\n      });\n      expect(request.hasNext).toBe(false);\n    }\n  });\n\n  it.skip(\"Returns underlying async iterables when returned generator is returned\", async () => {\n    // not interesting from a client perspective\n  });\n\n  it.skip(\"Can return async iterable when underlying iterable does not have a return method\", async () => {\n    // not interesting from a client perspective\n  });\n\n  it.skip(\"Returns underlying async iterables when returned generator is thrown\", async () => {\n    // not interesting from a client perspective\n  });\n});\n\n// quick smoke test. More exhaustive `@stream` tests can be found in\n// src/core/__tests__/client.watchQuery/streamGraphQL17Alpha9.test.ts\ntest(\"GraphQL17Alpha9Handler can be used with `ApolloClient`\", async () => {\n  const client = new ApolloClient({\n    link: createSchemaLink({ friendList: friends }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const query = gql`\n    query FriendListQuery {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const observableStream = new ObservableStream(client.watchQuery({ query }));\n\n  await expect(observableStream).toEmitTypedValue({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    loading: true,\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    networkStatus: NetworkStatus.streaming,\n    partial: true,\n  });\n\n  await expect(observableStream).toEmitTypedValue({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    partial: false,\n  });\n});\n\ntest(\"properly merges streamed data into cache data\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new GraphQL17Alpha9Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke Cached\", id: \"1\" },\n            { name: \"Han Cached\", id: \"2\" },\n            { name: \"Leia Cached\", id: \"3\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into partial cache data\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new GraphQL17Alpha9Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [{ id: \"1\" }, { id: \"2\" }, { id: \"3\" }],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into list with fewer items\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new GraphQL17Alpha9Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [{ id: \"1\", name: \"Luke Cached\" }],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges streamed data into list with more items\", async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 2) {\n        name\n        id\n      }\n    }\n  `;\n\n  const handler = new GraphQL17Alpha9Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    friendList: () => friends.map((f) => Promise.resolve(f)),\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke Cached\", id: \"1\" },\n            { name: \"Han Cached\", id: \"2\" },\n            { name: \"Leia Cached\", id: \"3\" },\n            { name: \"Chewbacca Cached\", id: \"4\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          friendList: [\n            { name: \"Luke\", id: \"1\" },\n            { name: \"Han\", id: \"2\" },\n          ],\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { name: \"Luke\", id: \"1\" },\n          { name: \"Han\", id: \"2\" },\n          { name: \"Leia\", id: \"3\" },\n        ],\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n\ntest(\"properly merges cache data when list is included in deferred chunk\", async () => {\n  const { promise: slowFieldPromise, resolve: resolveSlowField } =\n    promiseWithResolvers();\n\n  const query = gql`\n    query {\n      nestedObject {\n        ...DeferFragment @defer\n      }\n    }\n    fragment DeferFragment on NestedObject {\n      scalarField\n      nestedFriendList @stream(initialCount: 0) {\n        name\n      }\n    }\n  `;\n\n  const handler = new GraphQL17Alpha9Handler();\n  const request = handler.startRequest({ query });\n\n  const incoming = run(query, {\n    nestedObject: {\n      scalarField: () => slowFieldPromise,\n      async *nestedFriendList() {\n        yield await Promise.resolve(friends[0]);\n        yield await Promise.resolve(friends[1]);\n      },\n    },\n  });\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"cached\",\n            nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"cached\",\n          nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  resolveSlowField(\"slow\");\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"cached\",\n            nestedFriendList: [{ name: \"Luke Cached\" }, { name: \"Han Cached\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [],\n        },\n      },\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(request.handle(undefined, chunk)).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }],\n        },\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n        },\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(true);\n  }\n\n  {\n    const { value: chunk, done } = await incoming.next();\n\n    assert(!done);\n    assert(handler.isIncrementalResult(chunk));\n    expect(\n      request.handle(\n        {\n          nestedObject: {\n            scalarField: \"slow\",\n            nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n          },\n        },\n        chunk\n      )\n    ).toStrictEqualTyped({\n      data: {\n        nestedObject: {\n          scalarField: \"slow\",\n          nestedFriendList: [{ name: \"Luke\" }, { name: \"Han\" }],\n        },\n      },\n      extensions: extensionsWithStreamDetails,\n    });\n    expect(request.hasNext).toBe(false);\n  }\n});\n"
  },
  {
    "path": "src/incremental/handlers/defer20220824.ts",
    "content": "import type {\n  DocumentNode,\n  FormattedExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql\";\n\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport type { DeepPartial, HKT } from \"@apollo/client/utilities\";\nimport {\n  DeepMerger,\n  hasDirectives,\n  isNonEmptyArray,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { Incremental } from \"../types.js\";\n\nexport declare namespace Defer20220824Handler {\n  interface Defer20220824Result extends HKT {\n    arg1: unknown; // TData\n    arg2: unknown; // TExtensions\n    return: Defer20220824Handler.Chunk<Record<string, unknown>>;\n  }\n  export interface TypeOverrides {\n    AdditionalApolloLinkResultTypes: Defer20220824Result;\n  }\n\n  export type InitialResult<TData = Record<string, unknown>> = {\n    data?: TData | null | undefined;\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    extensions?: Record<string, unknown>;\n    hasNext: boolean;\n    incremental?: ReadonlyArray<IncrementalResult<TData>>;\n  };\n\n  export type SubsequentResult<TData = Record<string, unknown>> = {\n    extensions?: Record<string, unknown>;\n    hasNext: boolean;\n    incremental?: Array<IncrementalResult<TData>>;\n  };\n\n  export type IncrementalDeferResult<TData = Record<string, unknown>> = {\n    data?: TData | null;\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    extensions?: Record<string, unknown>;\n    path?: Incremental.Path;\n    label?: string;\n  };\n\n  export type IncrementalStreamResult<TData = Array<unknown>> = {\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    items?: TData;\n    path?: Incremental.Path;\n    label?: string;\n    extensions?: Record<string, unknown>;\n  };\n\n  export type IncrementalResult<TData = Record<string, unknown>> =\n    | IncrementalDeferResult<TData>\n    | IncrementalStreamResult<TData>;\n\n  export type Chunk<TData extends Record<string, unknown>> =\n    | InitialResult<TData>\n    | SubsequentResult<TData>;\n}\n\nclass DeferRequest<TData extends Record<string, unknown>>\n  implements\n    Incremental.IncrementalRequest<Defer20220824Handler.Chunk<TData>, TData>\n{\n  public hasNext = true;\n\n  private errors: Array<GraphQLFormattedError> = [];\n  private extensions: Record<string, any> = {};\n  private data: any = {};\n  // This tracks paths for `@stream` arrays that returns items: null due to\n  // errors thrown for non-null array items. We stop processing future updates\n  // to these stream arrays to prevent creating sparse arrays or inserting\n  // `null` for an expected non-null value which could cause runtime crashes.\n  private ignoredImpossibleStreamPaths = new Set<string>();\n\n  private merge(\n    normalized: FormattedExecutionResult<TData>,\n    atPath?: DeepMerger.MergeOptions[\"atPath\"]\n  ) {\n    if (normalized.data !== undefined) {\n      this.data = new DeepMerger({ arrayMerge: \"truncate\" }).merge(\n        this.data,\n        normalized.data,\n        { atPath }\n      );\n    }\n    if (normalized.errors) {\n      this.errors.push(...normalized.errors);\n    }\n    Object.assign(this.extensions, normalized.extensions);\n  }\n\n  handle(\n    // we'll get `undefined` here in case of a `no-cache` fetch policy,\n    // so we'll continue with the last value this request had accumulated\n    cacheData: TData | DeepPartial<TData> | null | undefined = this.data,\n    chunk: Defer20220824Handler.Chunk<TData>\n  ): FormattedExecutionResult<TData> {\n    this.hasNext = chunk.hasNext;\n    this.data = cacheData;\n\n    if (hasIncrementalChunks(chunk)) {\n      for (const incremental of chunk.incremental) {\n        const { path, errors, extensions } = incremental;\n\n        if (\"items\" in incremental) {\n          // Remove the array index from the end of the array since each future\n          // chunk sends a different array index. This normalizes the path to\n          // ensure we ignore updates to this field if `items` is `null`.\n          const stringPath = path?.slice(0, -1).join(\".\") ?? \"\";\n\n          if (incremental.items === null) {\n            this.ignoredImpossibleStreamPaths.add(stringPath);\n          }\n\n          if (this.ignoredImpossibleStreamPaths.has(stringPath)) {\n            this.merge({ errors, extensions });\n            continue;\n          }\n        }\n\n        let data: any =\n          \"items\" in incremental ? incremental.items\n            // Ensure `data: null` isn't merged for `@defer` responses by\n            // falling back to `undefined`\n          : \"data\" in incremental ? incremental.data ?? undefined\n          : undefined;\n\n        if (path && typeof path.at(-1) === \"number\" && Array.isArray(data)) {\n          const startingIdx = path.at(-1) as number;\n          data.forEach((item, idx) => {\n            this.merge({ data: item }, [\n              ...path!.slice(0, -1),\n              startingIdx + idx,\n            ]);\n          });\n        } else {\n          this.merge({ data }, path);\n        }\n\n        this.merge({ errors, extensions });\n      }\n    } else {\n      this.merge(chunk);\n    }\n\n    const result: FormattedExecutionResult<TData> = { data: this.data };\n\n    if (isNonEmptyArray(this.errors)) {\n      result.errors = this.errors;\n    }\n\n    if (Object.keys(this.extensions).length > 0) {\n      result.extensions = this.extensions;\n    }\n\n    return result;\n  }\n}\n\n/**\n * This handler implements the `@defer` directive as specified in this historical commit:\n * https://github.com/graphql/graphql-spec/tree/48cf7263a71a683fab03d45d309fd42d8d9a6659/spec\n */\nexport class Defer20220824Handler\n  implements Incremental.Handler<Defer20220824Handler.Chunk<any>>\n{\n  isIncrementalResult(\n    result: Record<string, any>\n  ): result is\n    | Defer20220824Handler.SubsequentResult\n    | Defer20220824Handler.InitialResult {\n    return \"hasNext\" in result;\n  }\n\n  extractErrors(result: ApolloLink.Result<any>) {\n    const acc: GraphQLFormattedError[] = [];\n    const push = ({\n      errors,\n    }: {\n      errors?: ReadonlyArray<GraphQLFormattedError>;\n    }) => {\n      if (errors) {\n        acc.push(...errors);\n      }\n    };\n    if (this.isIncrementalResult(result)) {\n      if (\"errors\" in result) {\n        push(result);\n      }\n      if (hasIncrementalChunks(result)) {\n        result.incremental.forEach(push);\n      }\n    }\n    if (acc.length) {\n      return acc;\n    }\n  }\n\n  prepareRequest(request: ApolloLink.Request): ApolloLink.Request {\n    if (hasDirectives([\"defer\", \"stream\"], request.query)) {\n      const context = request.context ?? {};\n      const http = (context.http ??= {});\n      http.accept = [\n        \"multipart/mixed;deferSpec=20220824\",\n        ...(http.accept || []),\n      ];\n    }\n\n    return request;\n  }\n  startRequest<TData extends Record<string, unknown>>(_: {\n    query: DocumentNode;\n  }) {\n    return new DeferRequest<TData>();\n  }\n}\n\n// only exported for use in tests\nexport function hasIncrementalChunks(\n  result: Record<string, any>\n): result is Required<Defer20220824Handler.SubsequentResult> {\n  return isNonEmptyArray(result.incremental);\n}\n"
  },
  {
    "path": "src/incremental/handlers/graphql17Alpha9.ts",
    "content": "import { Trie } from \"@wry/trie\";\nimport type {\n  DocumentNode,\n  FormattedExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql\";\n\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport type { DeepPartial, HKT } from \"@apollo/client/utilities\";\nimport type {\n  ExtensionsWithStreamInfo,\n  StreamInfoTrie,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  DeepMerger,\n  streamInfoSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  hasDirectives,\n  isNonEmptyArray,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { Incremental } from \"../types.js\";\n\nexport declare namespace GraphQL17Alpha9Handler {\n  interface GraphQL17Alpha9Result extends HKT {\n    arg1: unknown; // TData\n    arg2: unknown; // TExtensions\n    return: GraphQL17Alpha9Handler.Chunk<Record<string, unknown>>;\n  }\n\n  export interface TypeOverrides {\n    AdditionalApolloLinkResultTypes: GraphQL17Alpha9Result;\n  }\n\n  export type InitialResult<TData = Record<string, unknown>> = {\n    data: TData;\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    pending: ReadonlyArray<PendingResult>;\n    hasNext: boolean;\n    extensions?: Record<string, unknown>;\n  };\n\n  export type SubsequentResult<TData = unknown> = {\n    hasNext: boolean;\n    pending?: ReadonlyArray<PendingResult>;\n    incremental?: ReadonlyArray<IncrementalResult<TData>>;\n    completed?: ReadonlyArray<CompletedResult>;\n    extensions?: Record<string, unknown>;\n  };\n\n  export interface PendingResult {\n    id: string;\n    path: Incremental.Path;\n    label?: string;\n  }\n\n  export interface CompletedResult {\n    id: string;\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n  }\n\n  export interface IncrementalDeferResult<TData = Record<string, unknown>> {\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    data: TData;\n    id: string;\n    subPath?: Incremental.Path;\n    extensions?: Record<string, unknown>;\n  }\n\n  export interface IncrementalStreamResult<TData = ReadonlyArray<unknown>> {\n    errors?: ReadonlyArray<GraphQLFormattedError>;\n    items: TData;\n    id: string;\n    subPath?: Incremental.Path;\n    extensions?: Record<string, unknown>;\n  }\n\n  export type IncrementalResult<TData = unknown> =\n    | IncrementalDeferResult<TData>\n    | IncrementalStreamResult<TData>;\n\n  export type Chunk<TData> = InitialResult<TData> | SubsequentResult<TData>;\n}\n\nclass IncrementalRequest<TData>\n  implements\n    Incremental.IncrementalRequest<GraphQL17Alpha9Handler.Chunk<TData>, TData>\n{\n  hasNext = true;\n\n  private data: any = {};\n  private errors: GraphQLFormattedError[] = [];\n  private extensions: Record<string, any> = {};\n  private pending = new Map<string, GraphQL17Alpha9Handler.PendingResult>();\n  private streamInfo: StreamInfoTrie = new Trie(false, () => ({\n    current: { isFirstChunk: true, isLastChunk: false },\n  }));\n  // `streamPositions` maps `pending.id` to the index that should be set by the\n  // next `incremental` stream chunk to ensure the streamed array item is placed\n  // at the correct point in the data array. `this.data` contains cached\n  // references with the full array so we can't rely on the array length in\n  // `this.data` to determine where to place item. This also ensures that items\n  // updated by the cache between a streamed chunk aren't overwritten by merges\n  // of future stream items from already merged stream items.\n  private streamPositions: Record<string, number> = {};\n\n  handle(\n    cacheData: TData | DeepPartial<TData> | null | undefined = this.data,\n    chunk: GraphQL17Alpha9Handler.Chunk<TData>\n  ): FormattedExecutionResult<TData> {\n    this.hasNext = chunk.hasNext;\n    this.data = cacheData;\n\n    if (chunk.pending) {\n      for (const pending of chunk.pending) {\n        this.pending.set(pending.id, pending);\n\n        if (\"data\" in chunk) {\n          const dataAtPath = pending.path.reduce(\n            (data, key) => (data as any)[key],\n            chunk.data\n          );\n\n          if (Array.isArray(dataAtPath)) {\n            this.streamPositions[pending.id] = dataAtPath.length;\n            this.streamInfo.lookupArray(pending.path as any[]).current = {\n              isFirstChunk: true,\n              isLastChunk: false,\n            };\n          }\n        }\n      }\n    }\n\n    if (hasIncrementalChunks(chunk)) {\n      for (const incremental of chunk.incremental) {\n        const pending = this.pending.get(incremental.id);\n\n        invariant(\n          pending,\n          \"Could not find pending chunk for incremental value. Please file an issue for the Apollo Client team to investigate.\"\n        );\n\n        const path = pending.path.concat(incremental.subPath ?? []);\n\n        let data: any;\n        if (\"items\" in incremental) {\n          const items = incremental.items as any[];\n          const parent: any[] = [];\n\n          // This creates a sparse array with values set at the indices streamed\n          // from the server. DeepMerger uses Object.keys and will correctly\n          // place the values in this array in the correct place\n          for (let i = 0; i < items.length; i++) {\n            parent[i + this.streamPositions[pending.id]] = items[i];\n          }\n\n          this.streamPositions[pending.id] += items.length;\n          this.streamInfo.lookupArray(path).current = {\n            isFirstChunk: false,\n            isLastChunk: false,\n          };\n          data = parent;\n        } else {\n          data = incremental.data;\n\n          // Check if any pending streams added arrays from deferred data so\n          // that we can update streamPositions with the initial length of the\n          // array to ensure future streamed items are inserted at the right\n          // starting index.\n          this.pending.forEach((pendingItem) => {\n            if (!(pendingItem.id in this.streamPositions)) {\n              // Check if this incremental data contains array data for the pending path\n              // The pending path is absolute, but incremental data is relative to the defer\n              // E.g., pending.path = [\"nestedObject\"], pendingItem.path = [\"nestedObject\", \"nestedFriendList\"]\n              // incremental.data = { scalarField: \"...\", nestedFriendList: [...] }\n              // So we need the path from pending.path onwards\n              const relativePath = pendingItem.path.slice(pending.path.length);\n              const dataAtPath = relativePath.reduce(\n                (data, key) => (data as any)?.[key],\n                incremental.data\n              );\n\n              if (Array.isArray(dataAtPath)) {\n                this.streamPositions[pendingItem.id] = dataAtPath.length;\n              }\n            }\n          });\n        }\n\n        this.merge(\n          {\n            data,\n            extensions: incremental.extensions,\n            errors: incremental.errors,\n          },\n          path\n        );\n      }\n    } else {\n      this.merge(chunk);\n    }\n\n    if (\"completed\" in chunk && chunk.completed) {\n      for (const completed of chunk.completed) {\n        const { path } = this.pending.get(completed.id)!;\n        const streamPosition = this.streamPositions[completed.id];\n\n        // Truncate any stream arrays in case the chunk only contains `hasNext`\n        // and `completed`.\n        if (streamPosition !== undefined) {\n          const dataAtPath = path.reduce(\n            (data, key) => (data as any)?.[key],\n            this.data\n          );\n\n          this.merge({ data: dataAtPath.slice(0, streamPosition) }, path);\n        }\n\n        // peek instead of lookup to avoid creating an entry for non-array values\n        const details = this.streamInfo.peekArray(path as any[]);\n        if (details) {\n          details.current = {\n            isFirstChunk: false,\n            isLastChunk: true,\n          };\n        }\n        this.pending.delete(completed.id);\n\n        if (completed.errors) {\n          this.errors.push(...completed.errors);\n        }\n      }\n    }\n\n    const result: FormattedExecutionResult<TData> = { data: this.data };\n\n    if (isNonEmptyArray(this.errors)) {\n      result.errors = this.errors;\n    }\n\n    if (Object.keys(this.extensions).length > 0) {\n      result.extensions = this.extensions;\n    }\n\n    if (this.streamInfo[\"strong\"]) {\n      result.extensions = {\n        ...result.extensions,\n        // Create a new object so we can check for === in QueryInfo to trigger a\n        // final cache write when emitting a `hasNext: false` by itself.\n        // We create a `WeakRef`, not a plain object to avoid retaining memory\n        // in case the `result` or `extensions` stays around longer than the handler\n        // itself.\n        [streamInfoSymbol]: new WeakRef(this.streamInfo),\n      } satisfies ExtensionsWithStreamInfo;\n    }\n\n    return result;\n  }\n\n  private merge(\n    normalized: FormattedExecutionResult<TData>,\n    atPath?: DeepMerger.MergeOptions[\"atPath\"]\n  ) {\n    if (normalized.data !== undefined) {\n      this.data = new DeepMerger({ arrayMerge: \"truncate\" }).merge(\n        this.data,\n        normalized.data,\n        { atPath }\n      );\n    }\n\n    if (normalized.errors) {\n      this.errors.push(...normalized.errors);\n    }\n\n    Object.assign(this.extensions, normalized.extensions);\n  }\n}\n\n/**\n * Provides handling for the incremental delivery specification implemented by\n * graphql.js version `17.0.0-alpha.9`.\n */\nexport class GraphQL17Alpha9Handler\n  implements Incremental.Handler<GraphQL17Alpha9Handler.Chunk<any>>\n{\n  /** @internal */\n  isIncrementalResult(\n    result: ApolloLink.Result<any>\n  ): result is\n    | GraphQL17Alpha9Handler.InitialResult\n    | GraphQL17Alpha9Handler.SubsequentResult {\n    return \"hasNext\" in result;\n  }\n\n  /** @internal */\n  prepareRequest(request: ApolloLink.Request): ApolloLink.Request {\n    if (hasDirectives([\"defer\", \"stream\"], request.query)) {\n      const context = request.context ?? {};\n      const http = (context.http ??= {});\n      // https://specs.apollo.dev/incremental/v0.2/\n      http.accept = [\n        \"multipart/mixed;incrementalSpec=v0.2\",\n        ...(http.accept || []),\n      ];\n\n      request.context = context;\n    }\n\n    return request;\n  }\n\n  /** @internal */\n  extractErrors(result: ApolloLink.Result<any>) {\n    const acc: GraphQLFormattedError[] = [];\n    const push = ({\n      errors,\n    }: {\n      errors?: ReadonlyArray<GraphQLFormattedError>;\n    }) => {\n      if (errors) {\n        acc.push(...errors);\n      }\n    };\n\n    if (this.isIncrementalResult(result)) {\n      if (\"errors\" in result) {\n        push(result);\n      }\n      if (hasIncrementalChunks(result)) {\n        result.incremental.forEach(push);\n      }\n      if (hasCompletedChunks(result)) {\n        result.completed.forEach(push);\n      }\n    } else if (\"errors\" in result) {\n      push(result);\n    }\n\n    if (acc.length) {\n      return acc;\n    }\n  }\n\n  /** @internal */\n  startRequest<TData>(_: { query: DocumentNode }) {\n    return new IncrementalRequest<TData>();\n  }\n}\n\nfunction hasIncrementalChunks(\n  result: Record<string, any>\n): result is Required<GraphQL17Alpha9Handler.SubsequentResult> {\n  return isNonEmptyArray(result.incremental);\n}\n\nfunction hasCompletedChunks(\n  result: Record<string, any>\n): result is Required<GraphQL17Alpha9Handler.SubsequentResult> {\n  return isNonEmptyArray(result.completed);\n}\n"
  },
  {
    "path": "src/incremental/handlers/notImplemented.ts",
    "content": "import type { ApolloLink } from \"@apollo/client/link\";\nimport type { HKT } from \"@apollo/client/utilities\";\nimport { hasDirectives } from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { Incremental } from \"../types.js\";\n\nexport declare namespace NotImplementedHandler {\n  interface NotImplementedResult extends HKT {\n    arg1: unknown; // TData\n    arg2: unknown; // TExtensions\n    return: never;\n  }\n  export interface TypeOverrides {\n    AdditionalApolloLinkResultTypes: NotImplementedResult;\n  }\n}\n\nexport class NotImplementedHandler implements Incremental.Handler<never> {\n  isIncrementalResult(_: any): _ is never {\n    return false;\n  }\n  prepareRequest(request: ApolloLink.Request) {\n    invariant(\n      !hasDirectives([\"defer\", \"stream\"], request.query),\n      \"`@defer` and `@stream` are not supported without specifying an incremental handler. Please pass a handler as the `incrementalHandler` option to the `ApolloClient` constructor.\"\n    );\n\n    return request;\n  }\n  extractErrors() {}\n  // This code path can never be reached, so we won't implement it.\n  startRequest = undefined as any;\n}\n"
  },
  {
    "path": "src/incremental/index.ts",
    "content": "export type { Incremental } from \"./types.js\";\nexport { NotImplementedHandler } from \"./handlers/notImplemented.js\";\nexport {\n  Defer20220824Handler,\n  Defer20220824Handler as GraphQL17Alpha2Handler,\n} from \"./handlers/defer20220824.js\";\nexport { GraphQL17Alpha9Handler } from \"./handlers/graphql17Alpha9.js\";\n"
  },
  {
    "path": "src/incremental/types.ts",
    "content": "import type {\n  DocumentNode,\n  FormattedExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql\";\n\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\n\nexport declare namespace Incremental {\n  export type Path = ReadonlyArray<string | number>;\n\n  /** @internal */\n  export interface Handler<\n    Chunk extends Record<string, unknown> = Record<string, unknown>,\n  > {\n    isIncrementalResult: (result: ApolloLink.Result<any>) => result is Chunk;\n    prepareRequest: (request: ApolloLink.Request) => ApolloLink.Request;\n    extractErrors: (\n      result: ApolloLink.Result<any>\n    ) => readonly GraphQLFormattedError[] | undefined | void;\n    startRequest: <TData extends Record<string, unknown>>(request: {\n      query: DocumentNode;\n    }) => IncrementalRequest<Chunk, TData>;\n  }\n\n  export interface IncrementalRequest<\n    Chunk extends Record<string, unknown>,\n    TData,\n  > {\n    hasNext: boolean;\n    handle: (\n      cacheData: TData | DeepPartial<TData> | undefined | null,\n      chunk: Chunk\n    ) => FormattedExecutionResult<TData>;\n  }\n\n  /** @internal */\n  export interface StreamFieldInfo {\n    isFirstChunk: boolean;\n    isLastChunk: boolean;\n  }\n}\n"
  },
  {
    "path": "src/invariantErrorCodes.ts",
    "content": "export interface ErrorCodes {\n  [key: number]: { file: string; condition?: string; message?: string };\n}\n\nexport const errorCodes: ErrorCodes = {};\nexport const devDebug: ErrorCodes = {};\nexport const devLog: ErrorCodes = {};\nexport const devWarn: ErrorCodes = {};\nexport const devError: ErrorCodes = {};\n"
  },
  {
    "path": "src/link/batch/__tests__/batchLink.ts",
    "content": "import type { FormattedExecutionResult } from \"graphql\";\nimport { print } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { EMPTY, map, Observable, of } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { BatchLink } from \"@apollo/client/link/batch\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\nimport type { BatchableRequest } from \"../batching.js\";\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { OperationBatcher } from \"../batching.js\";\n\ninterface MockedResponse {\n  request: ApolloLink.Request;\n  result?: ApolloLink.Result;\n  error?: Error;\n  delay?: number;\n  maxUsageCount?: number;\n}\n\nconst EMPTY_FORWARD: ApolloLink.ForwardFunction = () => EMPTY;\n\nfunction createOperation(\n  starting: any,\n  operation: ApolloLink.Request\n): ApolloLink.Operation {\n  let context = { ...starting };\n  const setContext = (next: any) => {\n    if (typeof next === \"function\") {\n      context = { ...context, ...next(context) };\n    } else {\n      context = { ...context, ...next };\n    }\n  };\n  const getContext = () => ({ ...context });\n\n  Object.defineProperty(operation, \"setContext\", {\n    enumerable: false,\n    value: setContext,\n  });\n\n  Object.defineProperty(operation, \"getContext\", {\n    enumerable: false,\n    value: getContext,\n  });\n\n  return operation as ApolloLink.Operation;\n}\n\nfunction requestToKey(request: ApolloLink.Request): string {\n  const queryString =\n    typeof request.query === \"string\" ? request.query : print(request.query);\n\n  return JSON.stringify({\n    variables: request.variables || {},\n    query: queryString,\n  });\n}\n\nfunction createMockBatchHandler(...mockedResponses: MockedResponse[]) {\n  const mockedResponsesByKey: { [key: string]: MockedResponse[] } = {};\n\n  const mockBatchHandler: BatchLink.BatchHandler = (\n    operations: ApolloLink.Operation[]\n  ) => {\n    return new Observable((observer) => {\n      const results = operations.map((operation) => {\n        const key = requestToKey(operation);\n        const responses = mockedResponsesByKey[key];\n        if (!responses || responses.length === 0) {\n          throw new Error(\n            `No more mocked responses for the query: ${print(\n              operation.query\n            )}, variables: ${JSON.stringify(operation.variables)}`\n          );\n        }\n\n        let response: MockedResponse;\n\n        if (responses[0].maxUsageCount && responses[0].maxUsageCount > 1) {\n          responses[0].maxUsageCount--;\n          response = responses[0];\n        } else {\n          response = responses.shift()!;\n        }\n\n        const { result, error } = response;\n\n        if (!result && !error) {\n          throw new Error(\n            `Mocked response should contain either result or error: ${key}`\n          );\n        }\n\n        if (error) {\n          observer.error(error);\n        }\n\n        return result;\n      }) as any;\n\n      observer.next(results);\n    });\n  };\n\n  (mockBatchHandler as any).addMockedResponse = (\n    mockedResponse: MockedResponse\n  ) => {\n    const key = requestToKey(mockedResponse.request);\n    let _mockedResponses = mockedResponsesByKey[key];\n    if (!_mockedResponses) {\n      _mockedResponses = [];\n      mockedResponsesByKey[key] = _mockedResponses;\n    }\n    _mockedResponses.push(mockedResponse);\n  };\n\n  mockedResponses.map((mockBatchHandler as any).addMockedResponse);\n\n  return mockBatchHandler;\n}\n\nbeforeEach(() => jest.useFakeTimers());\nafterEach(() => jest.useRealTimers());\n\ndescribe(\"OperationBatcher\", () => {\n  it(\"should construct\", () => {\n    expect(() => {\n      const querySched = new OperationBatcher({\n        batchInterval: 10,\n        batchHandler: () => EMPTY,\n      });\n      querySched.consumeQueue(\"\");\n    }).not.toThrow();\n  });\n\n  it(\"should not do anything when faced with an empty queue\", () => {\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () => EMPTY,\n      batchKey: () => \"yo\",\n    });\n\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n    expect(batcher[\"batchesByKey\"].get(\"yo\")).toBeUndefined();\n    batcher.consumeQueue();\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n    expect(batcher[\"batchesByKey\"].get(\"yo\")).toBeUndefined();\n  });\n\n  it(\"should be able to add to the queue\", () => {\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () => EMPTY,\n    });\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const request: BatchableRequest = {\n      operation: createOperation({}, { query }),\n      forward: EMPTY_FORWARD,\n    };\n\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n    batcher.enqueueRequest(request).subscribe({});\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(1);\n    batcher.enqueueRequest(request).subscribe({});\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(2);\n  });\n\n  describe(\"request queue\", () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const data = {\n      author: {\n        firstName: \"John\",\n        lastName: \"Smith\",\n      },\n    };\n    const batchHandler = createMockBatchHandler({\n      request: { query },\n      result: { data },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n    });\n    const operation = createOperation(\n      {},\n      {\n        query,\n      }\n    );\n\n    it(\"should be able to consume from a queue containing a single query\", async () => {\n      const myBatcher = new OperationBatcher({\n        batchInterval: 10,\n        batchHandler,\n      });\n\n      const observable = myBatcher.enqueueRequest({\n        operation,\n        forward: EMPTY_FORWARD,\n      });\n      const stream = new ObservableStream(observable);\n\n      const observables: (Observable<ApolloLink.Result> | undefined)[] =\n        myBatcher.consumeQueue()!;\n\n      expect(observables.length).toBe(1);\n      expect(myBatcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n\n      await expect(stream).toEmitTypedValue({ data });\n    });\n\n    it(\"should be able to consume from a queue containing multiple queries\", async () => {\n      const request2 = createOperation(\n        {},\n        {\n          query,\n        }\n      );\n\n      const BH = createMockBatchHandler(\n        {\n          request: { query },\n          result: { data },\n        },\n        {\n          request: { query },\n          result: { data },\n        }\n      );\n\n      const myBatcher = new OperationBatcher({\n        batchInterval: 10,\n        batchMax: 10,\n        batchHandler: BH,\n      });\n      const observable1 = myBatcher.enqueueRequest({\n        operation,\n        forward: EMPTY_FORWARD,\n      });\n      const observable2 = myBatcher.enqueueRequest({\n        operation: request2,\n        forward: EMPTY_FORWARD,\n      });\n\n      const stream1 = new ObservableStream(observable1);\n      const stream2 = new ObservableStream(observable2);\n\n      expect(myBatcher[\"batchesByKey\"].get(\"\")!.size).toBe(2);\n      const observables: (Observable<ApolloLink.Result> | undefined)[] =\n        myBatcher.consumeQueue()!;\n      expect(myBatcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n      expect(observables.length).toBe(2);\n\n      await expect(stream1).toEmitTypedValue({ data });\n      await expect(stream2).toEmitTypedValue({ data });\n    });\n\n    it(\"should be able to consume from a queue containing multiple queries with different batch keys\", async () => {\n      // NOTE: this test was added to ensure that queries don't \"hang\" when consumed by BatchLink.\n      // \"Hanging\" in this case results in this test never resolving.  So\n      // if this test times out it's probably a real issue and not a flake\n      const request2 = createOperation(\n        {},\n        {\n          query,\n        }\n      );\n\n      const BH = createMockBatchHandler(\n        {\n          request: { query },\n          result: { data },\n        },\n        {\n          request: { query },\n          result: { data },\n        }\n      );\n\n      let key = true;\n      const batchKey = () => {\n        key = !key;\n        return \"\" + !key;\n      };\n\n      const myBatcher = new OperationBatcher({\n        batchInterval: 10,\n        batchMax: 10,\n        batchHandler: BH,\n        batchKey,\n      });\n\n      const observable1 = myBatcher.enqueueRequest({\n        operation,\n        forward: EMPTY_FORWARD,\n      });\n      const observable2 = myBatcher.enqueueRequest({\n        operation: request2,\n        forward: EMPTY_FORWARD,\n      });\n\n      const stream1 = new ObservableStream(observable1);\n      const stream2 = new ObservableStream(observable2);\n\n      jest.runAllTimers();\n\n      await expect(stream1).toEmitTypedValue({ data });\n      await expect(stream2).toEmitTypedValue({ data });\n    });\n\n    it(\"should return a promise when we enqueue a request and resolve it with a result\", async () => {\n      const BH = createMockBatchHandler({\n        request: { query },\n        result: { data },\n      });\n      const myBatcher = new OperationBatcher({\n        batchInterval: 10,\n        batchHandler: BH,\n      });\n      const observable = myBatcher.enqueueRequest({\n        operation,\n        forward: EMPTY_FORWARD,\n      });\n      const stream = new ObservableStream(observable);\n\n      myBatcher.consumeQueue();\n\n      await expect(stream).toEmitTypedValue({ data });\n    });\n\n    it(\"should be able to debounce requests\", () => {\n      const batchInterval = 10;\n      const myBatcher = new OperationBatcher({\n        batchDebounce: true,\n        batchInterval,\n        batchHandler,\n      });\n\n      // 1. Queue up 3 requests\n      myBatcher\n        .enqueueRequest({ operation, forward: EMPTY_FORWARD })\n        .subscribe({});\n      myBatcher\n        .enqueueRequest({ operation, forward: EMPTY_FORWARD })\n        .subscribe({});\n      myBatcher\n        .enqueueRequest({ operation, forward: EMPTY_FORWARD })\n        .subscribe({});\n      expect(myBatcher[\"batchesByKey\"].get(\"\")!.size).toEqual(3);\n\n      // 2. Run the timer halfway.\n      jest.advanceTimersByTime(batchInterval / 2);\n      expect(myBatcher[\"batchesByKey\"].get(\"\")!.size).toEqual(3);\n\n      // 3. Queue a 4th request, causing the timer to reset.\n      myBatcher\n        .enqueueRequest({ operation, forward: EMPTY_FORWARD })\n        .subscribe({});\n      expect(myBatcher[\"batchesByKey\"].get(\"\")!.size).toEqual(4);\n\n      // 4. Run the timer to batchInterval + 1, at this point, if debounce were\n      // not set, the original 3 requests would have fired, but we expect\n      // instead that the queries will instead fire at\n      // (batchInterval + batchInterval / 2).\n      jest.advanceTimersByTime(batchInterval / 2 + 1);\n      expect(myBatcher[\"batchesByKey\"].get(\"\")!.size).toEqual(4);\n\n      // 5. Finally, run the timer to (batchInterval + batchInterval / 2) +1,\n      // and expect the queue to be empty.\n      jest.advanceTimersByTime(batchInterval / 2);\n      expect(myBatcher[\"batchesByKey\"].size).toEqual(0);\n    });\n  });\n\n  it(\"should work when single query\", async () => {\n    const data = {\n      lastName: \"Ever\",\n      firstName: \"Greatest\",\n    };\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable((observer) => {\n          observer.next([{ data }]);\n          setTimeout(observer.complete.bind(observer));\n        }),\n    });\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const operation = createOperation({}, { query });\n\n    batcher.enqueueRequest({ operation, forward: EMPTY_FORWARD }).subscribe({});\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(1);\n\n    const promise = wait(20);\n    jest.runAllTimers();\n    await promise;\n\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n  });\n\n  it(\"should cancel single query in queue when unsubscribing\", async () => {\n    const data = {\n      lastName: \"Ever\",\n      firstName: \"Greatest\",\n    };\n\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable((observer) => {\n          observer.next([{ data }]);\n          setTimeout(observer.complete.bind(observer));\n        }),\n    });\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    batcher\n      .enqueueRequest({\n        operation: createOperation({}, { query }),\n        forward: EMPTY_FORWARD,\n      })\n      .subscribe(() => {\n        throw new Error(\"next should never be called\");\n      })\n      .unsubscribe();\n\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n  });\n\n  it(\"should cancel single query in queue with multiple subscriptions\", () => {\n    const data = {\n      lastName: \"Ever\",\n      firstName: \"Greatest\",\n    };\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable((observer) => {\n          observer.next([{ data }]);\n          setTimeout(observer.complete.bind(observer));\n        }),\n    });\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const operation = createOperation({}, { query });\n\n    const observable = batcher.enqueueRequest({\n      operation,\n      forward: EMPTY_FORWARD,\n    });\n\n    const checkQueuedRequests = (expectedSubscriberCount: number) => {\n      const batch = batcher[\"batchesByKey\"].get(\"\");\n      expect(batch).not.toBeUndefined();\n      expect(batch!.size).toBe(1);\n      batch!.forEach((request) => {\n        expect(request.subscribers.size).toBe(expectedSubscriberCount);\n      });\n    };\n\n    const sub1 = observable.subscribe(() => {\n      throw new Error(\"next should never be called\");\n    });\n    checkQueuedRequests(1);\n\n    const sub2 = observable.subscribe(() => {\n      throw new Error(\"next should never be called\");\n    });\n    checkQueuedRequests(2);\n\n    sub1.unsubscribe();\n    checkQueuedRequests(1);\n\n    sub2.unsubscribe();\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n  });\n\n  it(\"should cancel single query in flight when unsubscribing\", (done) => {\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable(() => {\n          // Instead of typically starting an XHR, we trigger the unsubscription from outside\n          setTimeout(() => subscription?.unsubscribe(), 5);\n\n          return () => {\n            expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n            done();\n          };\n        }),\n    });\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const subscription = batcher\n      .enqueueRequest({\n        operation: createOperation({}, { query }),\n        forward: EMPTY_FORWARD,\n      })\n      .subscribe(() => {\n        throw new Error(\"next should never be called\");\n      });\n\n    jest.runAllTimers();\n  });\n\n  it(\"should correctly batch multiple queries\", async () => {\n    const data = {\n      lastName: \"Ever\",\n      firstName: \"Greatest\",\n    };\n    const data2 = {\n      lastName: \"Hauser\",\n      firstName: \"Evans\",\n    };\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable((observer) => {\n          observer.next([{ data }, { data: data2 }, { data }]);\n          setTimeout(observer.complete.bind(observer));\n        }),\n    });\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const operation = createOperation({}, { query });\n    const operation2 = createOperation({}, { query });\n    const operation3 = createOperation({}, { query });\n\n    batcher.enqueueRequest({ operation, forward: EMPTY_FORWARD }).subscribe({});\n    batcher\n      .enqueueRequest({ operation: operation2, forward: EMPTY_FORWARD })\n      .subscribe({});\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(2);\n\n    setTimeout(() => {\n      // The batch shouldn't be fired yet, so we can add one more request.\n      batcher\n        .enqueueRequest({ operation: operation3, forward: EMPTY_FORWARD })\n        .subscribe({});\n      expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(3);\n    }, 5);\n\n    const promise = wait(20);\n    jest.runAllTimers();\n    await promise;\n\n    // The batch should've been fired by now.\n    expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n  });\n\n  it(\"should cancel multiple queries in queue when unsubscribing and let pass still subscribed one\", (done) => {\n    const data2 = {\n      lastName: \"Hauser\",\n      firstName: \"Evans\",\n    };\n\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: () =>\n        new Observable((observer) => {\n          observer.next([{ data: data2 }]);\n          setTimeout(observer.complete.bind(observer));\n        }),\n    });\n\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const operation = createOperation({}, { query });\n    const operation2 = createOperation({}, { query });\n    const operation3 = createOperation({}, { query });\n\n    const sub1 = batcher\n      .enqueueRequest({ operation, forward: EMPTY_FORWARD })\n      .subscribe(() => {\n        throw new Error(\"next should never be called\");\n      });\n    batcher\n      .enqueueRequest({ operation: operation2, forward: EMPTY_FORWARD })\n      .subscribe((result) => {\n        expect((result as FormattedExecutionResult).data).toBe(data2);\n\n        // The batch should've been fired by now.\n        expect(batcher[\"batchesByKey\"].get(\"\")).toBeUndefined();\n\n        done();\n      });\n\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(2);\n\n    sub1.unsubscribe();\n    expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(1);\n\n    setTimeout(() => {\n      // The batch shouldn't be fired yet, so we can add one more request.\n      const sub3 = batcher\n        .enqueueRequest({ operation: operation3, forward: EMPTY_FORWARD })\n        .subscribe(() => {\n          throw new Error(\"next should never be called\");\n        });\n      expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(2);\n\n      sub3.unsubscribe();\n      expect(batcher[\"batchesByKey\"].get(\"\")!.size).toBe(1);\n    }, 5);\n\n    jest.runAllTimers();\n  });\n\n  it(\"should reject the promise if there is a network error\", async () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const operation = createOperation({}, { query });\n    const error = new Error(\"Network error\");\n    const BH = createMockBatchHandler({\n      request: { query },\n      error,\n    });\n    const batcher = new OperationBatcher({\n      batchInterval: 10,\n      batchHandler: BH,\n    });\n\n    const observable = batcher.enqueueRequest({\n      operation,\n      forward: EMPTY_FORWARD,\n    });\n    const stream = new ObservableStream(observable);\n    batcher.consumeQueue();\n\n    await expect(stream).toEmitError(error);\n  });\n});\n\ndescribe(\"BatchLink\", () => {\n  const query = gql`\n    {\n      id\n    }\n  `;\n\n  it(\"does not need any constructor arguments\", () => {\n    expect(() => new BatchLink({ batchHandler: () => EMPTY })).not.toThrow();\n  });\n\n  it(\"passes forward on\", async () => {\n    expect.assertions(3);\n    const link = ApolloLink.from([\n      new BatchLink({\n        batchInterval: 0,\n        batchMax: 1,\n        batchHandler: (operation, forward) => {\n          expect(forward!.length).toBe(1);\n          expect(operation.length).toBe(1);\n\n          return forward![0]!(operation[0]).pipe(map((result) => [result]));\n        },\n      }),\n      new ApolloLink((operation) => {\n        expect(operation.query).toEqual(query);\n        return EMPTY;\n      }),\n    ]);\n\n    execute(\n      link,\n      createOperation(\n        {},\n        {\n          query,\n        }\n      )\n    ).subscribe(() => {});\n  });\n\n  it(\"correctly uses batch size\", async () => {\n    const sizes = [1, 2, 3];\n    const terminating = new ApolloLink((operation) => {\n      expect(operation.query).toEqual(query);\n      return of(operation.variables.count);\n    });\n\n    let runBatchSize = async (size: number) => {\n      const batchHandler = jest.fn((operation, forward) => {\n        expect(operation.length).toBe(size);\n        expect(forward.length).toBe(size);\n        const observables = forward.map((f: any, i: any) => f(operation[i]));\n        return new Observable((observer) => {\n          const data: any[] = [];\n          observables.forEach((obs: any) =>\n            obs.subscribe((d: any) => {\n              data.push(d);\n              if (data.length === observables.length) {\n                observer.next(data);\n                observer.complete();\n              }\n            })\n          );\n        });\n      }) as any;\n\n      const link = ApolloLink.from([\n        new BatchLink({\n          batchInterval: 1000,\n          batchMax: size,\n          batchHandler,\n        }),\n        terminating,\n      ]);\n\n      return Promise.all(\n        Array.from(new Array(size)).map((_, i) => {\n          return new Promise<void>((resolve) => {\n            execute(link, {\n              query,\n              variables: { count: i },\n            }).subscribe({\n              next: (data) => {\n                expect(data).toBe(i);\n              },\n              complete: () => {\n                expect(batchHandler.mock.calls.length).toBe(1);\n                resolve();\n              },\n            });\n          });\n        })\n      );\n    };\n\n    for (const size of sizes) {\n      await runBatchSize(size);\n    }\n  });\n\n  it(\"correctly follows batch interval\", (done) => {\n    const intervals = [10, 20, 30];\n\n    const runBatchInterval = () => {\n      const mock = jest.fn();\n\n      const batchInterval = intervals.pop();\n      if (!batchInterval) return done();\n\n      const batchHandler = jest.fn(((operation, forward) => {\n        expect(operation.length).toBe(1);\n        expect(forward!.length).toBe(1);\n\n        return forward![0]!(operation[0]).pipe(map((d: any) => [d]));\n      }) as BatchLink.BatchHandler);\n\n      const link = ApolloLink.from([\n        new BatchLink({\n          batchInterval,\n          batchMax: 0,\n          batchHandler,\n        }),\n        new ApolloLink(() => of(42) as any),\n      ]);\n\n      execute(\n        link,\n        createOperation(\n          {},\n          {\n            query,\n          }\n        )\n      ).subscribe({\n        next: (data) => {\n          expect(data).toBe(42);\n        },\n        complete: () => {\n          mock(batchHandler.mock.calls.length);\n        },\n      });\n\n      const delayedBatchInterval = async () => {\n        await wait(batchInterval);\n\n        const checkCalls = mock.mock.calls.slice(0, -1);\n        expect(checkCalls.length).toBe(2);\n        checkCalls.forEach((args) => expect(args[0]).toBe(0));\n        expect(mock).toHaveBeenLastCalledWith(1);\n        expect(batchHandler.mock.calls.length).toBe(1);\n\n        runBatchInterval();\n      };\n\n      void delayedBatchInterval();\n\n      mock(batchHandler.mock.calls.length);\n      mock(batchHandler.mock.calls.length);\n\n      jest.runOnlyPendingTimers();\n    };\n    runBatchInterval();\n  });\n\n  it(\"throws an error when more requests than results\", () => {\n    expect.assertions(4);\n    const result = [{ data: {} }];\n    const batchHandler = jest.fn((op) => of(result));\n\n    const link = ApolloLink.from([\n      new BatchLink({\n        batchInterval: 10,\n        batchMax: 2,\n        batchHandler,\n      }),\n    ]);\n\n    [1, 2].forEach((x) => {\n      execute(link, {\n        query,\n      }).subscribe({\n        next: (data) => {\n          throw new Error(\"next should not be called\");\n        },\n        error: (error: any) => {\n          expect(error).toBeDefined();\n          expect(error.result).toEqual(result);\n        },\n        complete: () => {\n          throw new Error(\"complete should not be called\");\n        },\n      });\n    });\n  });\n\n  describe(\"batchKey\", () => {\n    it(\"should allow different batches to be created separately\", (done) => {\n      const data = { data: {} };\n      const result = [data, data];\n\n      const batchHandler = jest.fn((op) => {\n        expect(op.length).toBe(2);\n        return of(result);\n      });\n      let key = true;\n      const batchKey = () => {\n        key = !key;\n        return \"\" + !key;\n      };\n\n      const link = ApolloLink.from([\n        new BatchLink({\n          batchInterval: 1,\n          //if batchKey does not work, then the batch size would be 3\n          batchMax: 2,\n          batchHandler,\n          batchKey,\n        }),\n      ]);\n\n      let count = 0;\n      [1, 2, 3, 4].forEach(() => {\n        execute(link, {\n          query,\n        }).subscribe({\n          next: (d) => {\n            expect(d).toEqual(data);\n          },\n          error: (e) => {\n            throw e;\n          },\n          complete: () => {\n            count++;\n            if (count === 4) {\n              expect(batchHandler.mock.calls.length).toBe(2);\n              done();\n            }\n          },\n        });\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/batch/batchLink.ts",
    "content": "import type { Observable } from \"rxjs\";\nimport { EMPTY } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\n\nimport { OperationBatcher } from \"./batching.js\";\n\nexport declare namespace BatchLink {\n  export namespace Shared {\n    /** These options are shared between `BatchLink` and `BatchHttpLink` */\n    interface Options {\n      /**\n       * The interval at which to batch, in milliseconds.\n       *\n       * @defaultValue 10\n       */\n      batchInterval?: number;\n\n      /**\n       * \"batchInterval\" is a throttling behavior by default, if you instead wish\n       * to debounce outbound requests, set \"batchDebounce\" to true. More useful\n       * for mutations than queries.\n       */\n      batchDebounce?: boolean;\n\n      /**\n       * The maximum number of operations to include in a single batch.\n       *\n       * @defaultValue \\{\\{defaultValue\\}\\}\n       */\n      batchMax?: number;\n\n      /**\n       * Creates the key for a batch\n       */\n      batchKey?: (operation: ApolloLink.Operation) => string;\n    }\n  }\n\n  /**\n   * Function type for handling a batch of GraphQL operations.\n   *\n   * @remarks\n   *\n   * The batch handler is responsible for processing multiple operations together\n   * and returning their results. Each operation has a corresponding forward function\n   * that can be used to continue processing down the link chain.\n   *\n   * Results must be returned in the same order as the input operations to ensure\n   * proper correlation with the original requests.\n   *\n   * @param operations - Array of GraphQL operations to process\n   * @param forward - Array of forward functions, one per operation\n   * @returns Observable that emits an array of results in the same order as operations\n   */\n  export type BatchHandler = (\n    operations: ApolloLink.Operation[],\n    forward: ApolloLink.ForwardFunction[]\n  ) => Observable<ApolloLink.Result[]>;\n\n  /**\n   * Configuration options for creating a `BatchLink` instance.\n   *\n   * @remarks\n   *\n   * `BatchLink` options control how operations are grouped into batches\n   * and when those batches are processed. The `batchHandler` function\n   * is responsible for actually processing the batched operations.\n   *\n   * Most batching behavior is configured through timing options:\n   *\n   * - `batchInterval`: How long to wait before processing a batch\n   * - `batchDebounce`: Whether to reset the timer on new operations\n   * - `batchMax`: Maximum operations per batch (0 = unlimited)\n   *\n   * Custom grouping logic can be implemented via `batchKey` function.\n   */\n  export interface Options extends Shared.Options {\n    /**\n     * The handler that executes a batch of operations.\n     *\n     * @remarks\n     *\n     * This function receives an array of operations and their corresponding\n     * forward functions, and should return an Observable that emits the results\n     * for all operations in the batch.\n     */\n    batchHandler?: BatchLink.BatchHandler;\n\n    /** {@inheritDoc @apollo/client/link/batch!BatchLink.Shared.Options#batchMax:member {\"defaultValue\": 0}} */\n    batchMax?: number;\n  }\n}\n\n/**\n * `BatchLink` is a non-terminating link that provides the core batching\n * functionality for grouping multiple GraphQL operations into batches based\n * on configurable timing and key-based grouping strategies. It serves as a base\n * link to `BatchHttpLink`.\n *\n * @remarks\n *\n * > [!NOTE]\n * > You will not generally use `BatchLink` on your own unless you need to\n * > provide batching capabilities to third-party terminating links. Prefer\n * > using `BatchHttpLink` to batch GraphQL operations over HTTP.\n *\n * @example\n *\n * ```ts\n * import { BatchLink } from \"@apollo/client/link/batch\";\n *\n * const link = new BatchLink({\n *   batchInterval: 20,\n *   batchMax: 5,\n *   batchHandler: (operations, forwards) => {\n *     // Custom logic to process batch of operations\n *     return handleBatch(operations, forwards);\n *   },\n * });\n * ```\n */\nexport class BatchLink extends ApolloLink {\n  private batcher: OperationBatcher;\n\n  constructor(options?: BatchLink.Options) {\n    super();\n\n    const {\n      batchDebounce,\n      batchInterval = 10,\n      batchMax = 0,\n      batchHandler = () => EMPTY,\n      batchKey = () => \"\",\n    } = options || {};\n\n    this.batcher = new OperationBatcher({\n      batchDebounce,\n      batchInterval,\n      batchMax,\n      batchHandler,\n      batchKey,\n    });\n  }\n\n  public request(\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ): Observable<ApolloLink.Result> {\n    return this.batcher.enqueueRequest({ operation, forward });\n  }\n}\n"
  },
  {
    "path": "src/link/batch/batching.ts",
    "content": "import type { Subscription } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nimport type { ApolloLink } from \"@apollo/client/link\";\n\nimport type { BatchLink } from \"./batchLink.js\";\n\nexport interface BatchableRequest {\n  operation: ApolloLink.Operation;\n  forward: ApolloLink.ForwardFunction;\n}\n\ntype QueuedRequest = BatchableRequest & {\n  observable?: Observable<ApolloLink.Result>;\n  next: Array<(result: ApolloLink.Result) => void>;\n  error: Array<(error: Error) => void>;\n  complete: Array<() => void>;\n  subscribers: Set<object>;\n};\n\n// Batches are primarily a Set<QueuedRequest>, but may have other optional\n// properties, such as batch.subscription.\ntype RequestBatch = Set<QueuedRequest> & {\n  subscription?: Subscription;\n};\n\n// QueryBatcher doesn't fire requests immediately. Requests that were enqueued within\n// a certain amount of time (configurable through `batchInterval`) will be batched together\n// into one query.\nexport class OperationBatcher {\n  // Queue on which the QueryBatcher will operate on a per-tick basis.\n  private batchesByKey = new Map<string, RequestBatch>();\n\n  private scheduledBatchTimerByKey = new Map<\n    string,\n    ReturnType<typeof setTimeout>\n  >();\n  private batchDebounce?: boolean;\n  private batchInterval?: number;\n  private batchMax: number;\n\n  //This function is called to the queries in the queue to the server.\n  private batchHandler: BatchLink.BatchHandler;\n  private batchKey: (operation: ApolloLink.Operation) => string;\n\n  constructor({\n    batchDebounce,\n    batchInterval,\n    batchMax,\n    batchHandler,\n    batchKey,\n  }: {\n    batchDebounce?: boolean;\n    batchInterval?: number;\n    batchMax?: number;\n    batchHandler: BatchLink.BatchHandler;\n    batchKey?: (operation: ApolloLink.Operation) => string;\n  }) {\n    this.batchDebounce = batchDebounce;\n    this.batchInterval = batchInterval;\n    this.batchMax = batchMax || 0;\n    this.batchHandler = batchHandler;\n    this.batchKey = batchKey || (() => \"\");\n  }\n\n  public enqueueRequest(\n    request: BatchableRequest\n  ): Observable<ApolloLink.Result> {\n    const requestCopy: QueuedRequest = {\n      ...request,\n      next: [],\n      error: [],\n      complete: [],\n      subscribers: new Set(),\n    };\n\n    const key = this.batchKey(request.operation);\n\n    if (!requestCopy.observable) {\n      requestCopy.observable = new Observable<ApolloLink.Result>((observer) => {\n        let batch = this.batchesByKey.get(key)!;\n        if (!batch) this.batchesByKey.set(key, (batch = new Set()));\n\n        // These booleans seem to me (@benjamn) like they might always be the\n        // same (and thus we could do with only one of them), but I'm not 100%\n        // sure about that.\n        const isFirstEnqueuedRequest = batch.size === 0;\n        const isFirstSubscriber = requestCopy.subscribers.size === 0;\n        requestCopy.subscribers.add(observer);\n        if (isFirstSubscriber) {\n          batch.add(requestCopy);\n        }\n\n        // called for each subscriber, so need to save all listeners (next, error, complete)\n        if (observer.next) {\n          requestCopy.next.push(observer.next.bind(observer));\n        }\n\n        if (observer.error) {\n          requestCopy.error.push(observer.error.bind(observer));\n        }\n\n        if (observer.complete) {\n          requestCopy.complete.push(observer.complete.bind(observer));\n        }\n\n        // The first enqueued request triggers the queue consumption after `batchInterval` milliseconds.\n        if (isFirstEnqueuedRequest || this.batchDebounce) {\n          this.scheduleQueueConsumption(key);\n        }\n\n        // When amount of requests reaches `batchMax`, trigger the queue consumption without waiting on the `batchInterval`.\n        if (batch.size === this.batchMax) {\n          this.consumeQueue(key);\n        }\n\n        return () => {\n          // If this is last subscriber for this request, remove request from queue\n          if (\n            requestCopy.subscribers.delete(observer) &&\n            requestCopy.subscribers.size < 1\n          ) {\n            // If this is last request from queue, remove queue entirely\n            if (batch.delete(requestCopy) && batch.size < 1) {\n              this.consumeQueue(key);\n              // If queue was in flight, cancel it\n              batch.subscription?.unsubscribe();\n            }\n          }\n        };\n      });\n    }\n\n    return requestCopy.observable;\n  }\n\n  // Consumes the queue.\n  // Returns a list of promises (one for each query).\n  public consumeQueue(\n    key: string = \"\"\n  ): (Observable<ApolloLink.Result> | undefined)[] | undefined {\n    const batch = this.batchesByKey.get(key);\n    // Delete this batch and process it below.\n    this.batchesByKey.delete(key);\n    if (!batch || !batch.size) {\n      // No requests to be processed.\n      return;\n    }\n\n    const operations: QueuedRequest[\"operation\"][] = [];\n    const forwards: QueuedRequest[\"forward\"][] = [];\n    const observables: QueuedRequest[\"observable\"][] = [];\n    const nexts: QueuedRequest[\"next\"][] = [];\n    const errors: QueuedRequest[\"error\"][] = [];\n    const completes: QueuedRequest[\"complete\"][] = [];\n\n    // Even though batch is a Set, it preserves the order of first insertion\n    // when iterating (per ECMAScript specification), so these requests will be\n    // handled in the order they were enqueued (minus any deleted ones).\n    batch.forEach((request) => {\n      operations.push(request.operation);\n      forwards.push(request.forward);\n      observables.push(request.observable);\n      nexts.push(request.next);\n      errors.push(request.error);\n      completes.push(request.complete);\n    });\n\n    const batchedObservable = this.batchHandler(operations, forwards);\n\n    const onError = (error: Error) => {\n      //each callback list in batch\n      errors.forEach((rejecters) => {\n        if (rejecters) {\n          //each subscriber to request\n          rejecters.forEach((e) => e(error));\n        }\n      });\n    };\n\n    batch.subscription = batchedObservable.subscribe({\n      next: (results) => {\n        if (!Array.isArray(results)) {\n          results = [results];\n        }\n\n        if (nexts.length !== results.length) {\n          const error = new Error(\n            `server returned results with length ${results.length}, expected length of ${nexts.length}`\n          );\n          (error as any).result = results;\n\n          return onError(error);\n        }\n\n        results.forEach((result, index) => {\n          if (nexts[index]) {\n            nexts[index].forEach((next) => next(result));\n          }\n        });\n      },\n      error: onError,\n      complete: () => {\n        completes.forEach((complete) => {\n          if (complete) {\n            //each subscriber to request\n            complete.forEach((c) => c());\n          }\n        });\n      },\n    });\n\n    return observables;\n  }\n\n  private scheduleQueueConsumption(key: string): void {\n    clearTimeout(this.scheduledBatchTimerByKey.get(key));\n    this.scheduledBatchTimerByKey.set(\n      key,\n      setTimeout(() => {\n        this.consumeQueue(key);\n        this.scheduledBatchTimerByKey.delete(key);\n      }, this.batchInterval)\n    );\n  }\n}\n"
  },
  {
    "path": "src/link/batch/index.ts",
    "content": "export { BatchLink } from \"./batchLink.js\";\n"
  },
  {
    "path": "src/link/batch-http/BaseBatchHttpLink.ts",
    "content": "import { Observable, throwError } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { BatchLink } from \"@apollo/client/link/batch\";\nimport type { BaseHttpLink } from \"@apollo/client/link/http\";\nimport {\n  checkFetcher,\n  defaultPrinter,\n  fallbackHttpConfig,\n  parseAndCheckHttpResponse,\n  selectHttpOptionsAndBodyInternal,\n  selectURI,\n} from \"@apollo/client/link/http\";\nimport { filterOperationVariables } from \"@apollo/client/link/utils\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { compact } from \"@apollo/client/utilities/internal\";\nimport { maybe } from \"@apollo/client/utilities/internal/globals\";\n\nexport declare namespace BaseBatchHttpLink {\n  /**\n   * Options passed to `BaseBatchHttpLink` through [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context). Previous\n   * non-terminating links in the link chain also can set these values to\n   * customize the behavior of `BatchHttpLink` for each operation.\n   *\n   * > [!NOTE]\n   * > Some of these values can also be provided to the `BaseBatchHttpLink` constructor.\n   * > If a value is provided to both, the value in `context` takes precedence.\n   */\n  export interface ContextOptions extends BaseHttpLink.ContextOptions {}\n  /**\n   * Configuration options for creating a `BaseBatchHttpLink` instance.\n   *\n   * > [!NOTE]\n   * > Some of these options are also available to override in [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context).\n   * > Context options override the options passed to the constructor. Treat\n   * > these options as default values that are used when the request context\n   * > does not override the value.\n   */\n  interface Options\n    extends BatchLink.Shared.Options,\n      BaseHttpLink.Shared.Options {\n    /** {@inheritDoc @apollo/client/link/batch!BatchLink.Shared.Options#batchMax:member {\"defaultValue\": 10}} */\n    batchMax?: number;\n  }\n}\n\nconst backupFetch = maybe(() => fetch);\n\n/**\n * `BaseBatchHttpLink` is a terminating link that batches array of individual\n * GraphQL operations into a single HTTP request that's sent to a single GraphQL\n * endpoint. It serves as a base link to `BatchHttpLink`.\n *\n * @remarks\n *\n * > [!NOTE]\n * > Prefer using `BatchHttpLink` over `BaseBatchHttpLink`. Use\n * > `BaseBatchHttpLink` when you need to disable client awareness features and\n * > would like to tree-shake the implementation of `ClientAwarenessLink` out\n * > of your app bundle.\n *\n * @example\n *\n * ```ts\n * import { BaseBatchHttpLink } from \"@apollo/client/link/batch-http\";\n *\n * const link = new BaseBatchHttpLink({\n *   uri: \"http://localhost:4000/graphql\",\n *   batchMax: 5, // No more than 5 operations per batch\n *   batchInterval: 20, // Wait no more than 20ms after first batched operation\n * });\n * ```\n */\nexport class BaseBatchHttpLink extends ApolloLink {\n  private batchDebounce?: boolean;\n  private batchInterval: number;\n  private batchMax: number;\n  private batcher: ApolloLink;\n\n  constructor(options: BaseBatchHttpLink.Options = {}) {\n    super();\n\n    let {\n      uri = \"/graphql\",\n      // use default global fetch if nothing is passed in\n      fetch: preferredFetch,\n      print = defaultPrinter,\n      includeExtensions,\n      preserveHeaderCase,\n      batchInterval,\n      batchDebounce,\n      batchMax,\n      batchKey,\n      includeUnusedVariables = false,\n      ...requestOptions\n    } = options;\n\n    if (__DEV__) {\n      // Make sure at least one of preferredFetch, window.fetch, or backupFetch\n      // is defined, so requests won't fail at runtime.\n      checkFetcher(preferredFetch || backupFetch);\n    }\n\n    const linkConfig = {\n      http: compact({ includeExtensions, preserveHeaderCase }),\n      options: requestOptions.fetchOptions,\n      credentials: requestOptions.credentials,\n      headers: requestOptions.headers,\n    };\n\n    this.batchDebounce = batchDebounce;\n    this.batchInterval = batchInterval || 10;\n    this.batchMax = batchMax || 10;\n\n    const batchHandler: BatchLink.BatchHandler = (operations) => {\n      const chosenURI = selectURI(operations[0], uri);\n\n      const context = operations[0].getContext();\n\n      const contextConfig = {\n        http: context.http,\n        options: context.fetchOptions,\n        credentials: context.credentials,\n        headers: context.headers,\n      };\n\n      //uses fallback, link, and then context to build options\n      const optsAndBody = operations.map((operation) => {\n        const result = selectHttpOptionsAndBodyInternal(\n          operation,\n          print,\n          fallbackHttpConfig,\n          linkConfig,\n          contextConfig\n        );\n\n        if (result.body.variables && !includeUnusedVariables) {\n          result.body.variables = filterOperationVariables(\n            result.body.variables,\n            operation.query\n          );\n        }\n\n        return result;\n      });\n\n      const loadedBody = optsAndBody.map(({ body }) => body);\n      const options = optsAndBody[0].options;\n\n      // There's no spec for using GET with batches.\n      if (options.method === \"GET\") {\n        return throwError(\n          () =>\n            new Error(\"apollo-link-batch-http does not support GET requests\")\n        );\n      }\n\n      try {\n        (options as any).body = JSON.stringify(loadedBody);\n      } catch (parseError) {\n        return throwError(() => parseError);\n      }\n\n      let controller: AbortController | undefined;\n      if (!options.signal && typeof AbortController !== \"undefined\") {\n        controller = new AbortController();\n        options.signal = controller.signal;\n      }\n\n      return new Observable((observer) => {\n        // Prefer BatchHttpLink.Options.fetch (preferredFetch) if provided, and\n        // otherwise fall back to the *current* global window.fetch function\n        // (see issue #7832), or (if all else fails) the backupFetch function we\n        // saved when this module was first evaluated. This last option protects\n        // against the removal of window.fetch, which is unlikely but not\n        // impossible.\n        const currentFetch =\n          preferredFetch || maybe(() => fetch) || backupFetch;\n\n        currentFetch!(chosenURI, options)\n          .then((response) => {\n            // Make the raw response available in the context.\n            operations.forEach((operation) =>\n              operation.setContext({ response })\n            );\n            return response;\n          })\n          .then(parseAndCheckHttpResponse(operations))\n          .then((result) => {\n            controller = undefined;\n            // we have data and can send it to back up the link chain\n            observer.next(result);\n            observer.complete();\n            return result;\n          })\n          .catch((err) => {\n            controller = undefined;\n            observer.error(err);\n          });\n\n        return () => {\n          // XXX support canceling this request\n          // https://developers.google.com/web/updates/2017/09/abortable-fetch\n          if (controller) controller.abort();\n        };\n      });\n    };\n\n    batchKey =\n      batchKey ||\n      ((operation: ApolloLink.Operation) => {\n        const context = operation.getContext();\n\n        const contextConfig = {\n          http: context.http,\n          options: context.fetchOptions,\n          credentials: context.credentials,\n          headers: context.headers,\n        };\n\n        //may throw error if config not serializable\n        return selectURI(operation, uri) + JSON.stringify(contextConfig);\n      });\n\n    this.batcher = new BatchLink({\n      batchDebounce: this.batchDebounce,\n      batchInterval: this.batchInterval,\n      batchMax: this.batchMax,\n      batchKey,\n      batchHandler,\n    });\n  }\n\n  public request(\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ): Observable<ApolloLink.Result> {\n    return this.batcher.request(operation, forward);\n  }\n}\n"
  },
  {
    "path": "src/link/batch-http/__tests__/batchHttpLink.ts",
    "content": "import fetchMock from \"fetch-mock\";\nimport type { ASTNode } from \"graphql\";\nimport { print, stripIgnoredCharacters } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Subscription } from \"rxjs\";\nimport { map, Observable, Subject } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  InMemoryCache,\n  ServerError,\n  ServerParseError,\n  version,\n} from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport {\n  BaseBatchHttpLink,\n  BatchHttpLink,\n} from \"@apollo/client/link/batch-http\";\nimport { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\nconst sampleQuery = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\nconst sampleMutation = gql`\n  mutation SampleMutation {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"BatchHttpLink\", () => {\n  beforeAll(() => {\n    jest.resetModules();\n  });\n\n  const headers = { cookie: \"monster\" };\n  const data = { data: { hello: \"world\" } };\n  const data2 = { data: { hello: \"everyone\" } };\n  const roflData = { data: { haha: \"hehe\" } };\n  const lawlData = { data: { tehe: \"haaa\" } };\n  const makePromise = (res: any) =>\n    new Promise((resolve, reject) =>\n      setTimeout(() =>\n        resolve({\n          headers,\n          body: res,\n        })\n      )\n    );\n\n  beforeEach(() => {\n    fetchMock.restore();\n    fetchMock.post(\"begin:/rofl\", makePromise([roflData, roflData]));\n    fetchMock.post(\"begin:/lawl\", makePromise([lawlData, lawlData]));\n  });\n\n  it(\"does not need any constructor arguments\", () => {\n    expect(() => new BatchHttpLink()).not.toThrow();\n  });\n\n  it(\"handles batched requests\", async () => {\n    fetchMock.post(\"/batch\", makePromise([data, data2]));\n\n    const clientAwareness = {\n      name: \"Some Client Name\",\n      version: \"1.0.1\",\n    };\n\n    const link = new BatchHttpLink({\n      uri: \"/batch\",\n      batchInterval: 0,\n      batchMax: 2,\n    });\n\n    const stream1 = new ObservableStream(\n      execute(link, {\n        query: sampleQuery,\n        context: { credentials: \"two\", clientAwareness },\n      })\n    );\n    const stream2 = new ObservableStream(\n      execute(link, {\n        query: sampleQuery,\n        context: { credentials: \"two\", clientAwareness },\n      })\n    );\n\n    await expect(stream1).toEmitTypedValue(data);\n    await expect(stream1).toComplete();\n\n    await expect(stream2).toEmitTypedValue(data2);\n    await expect(stream2).toComplete();\n\n    expect(fetchMock.calls(\"/batch\").length).toBe(1);\n\n    const options: any = fetchMock.lastOptions(\"/batch\");\n    expect(options.credentials).toEqual(\"two\");\n\n    const { headers } = options;\n    expect(headers[\"apollographql-client-name\"]).toEqual(clientAwareness.name);\n    expect(headers[\"apollographql-client-version\"]).toEqual(\n      clientAwareness.version\n    );\n  });\n\n  it(\"errors on an incorrect number of results for a batch\", async () => {\n    fetchMock.post(\"/batch\", makePromise([data, data2]));\n\n    const link = new BatchHttpLink({\n      uri: \"/batch\",\n      batchInterval: 0,\n      batchMax: 3,\n    });\n\n    const stream1 = new ObservableStream(execute(link, { query: sampleQuery }));\n    const stream2 = new ObservableStream(execute(link, { query: sampleQuery }));\n    const stream3 = new ObservableStream(execute(link, { query: sampleQuery }));\n\n    await expect(stream1).toEmitError(\n      new Error(\"server returned results with length 2, expected length of 3\")\n    );\n    await expect(stream2).toEmitError(\n      new Error(\"server returned results with length 2, expected length of 3\")\n    );\n    await expect(stream3).toEmitError(\n      new Error(\"server returned results with length 2, expected length of 3\")\n    );\n  });\n\n  describe(\"batchKey\", () => {\n    const query = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    it(\"should batch queries with different options separately\", (done) => {\n      let key = true;\n      const batchKey = () => {\n        key = !key;\n        return \"\" + !key;\n      };\n\n      const link = ApolloLink.from([\n        new BatchHttpLink({\n          uri: (operation) => {\n            return operation.variables.endpoint;\n          },\n          batchInterval: 1,\n          //if batchKey does not work, then the batch size would be 3\n          batchMax: 2,\n          batchKey,\n        }),\n      ]);\n\n      let count = 0;\n      const next = (expected: any) => (received: any) => {\n        expect(received).toEqual(expected);\n      };\n      const complete = () => {\n        count++;\n        if (count === 4) {\n          const lawlCalls = fetchMock.calls(\"begin:/lawl\");\n          expect(lawlCalls.length).toBe(1);\n          const roflCalls = fetchMock.calls(\"begin:/rofl\");\n          expect(roflCalls.length).toBe(1);\n          done();\n        }\n      };\n\n      [1, 2].forEach((x) => {\n        execute(link, { query, variables: { endpoint: \"/rofl\" } }).subscribe({\n          next: next(roflData),\n          error: (error) => {\n            throw error;\n          },\n          complete,\n        });\n\n        execute(link, { query, variables: { endpoint: \"/lawl\" } }).subscribe({\n          next: next(lawlData),\n          error: (error) => {\n            throw error;\n          },\n          complete,\n        });\n      });\n    });\n  });\n});\n\nconst convertBatchedBody = (body: any) => {\n  const parsed = JSON.parse(body);\n  expect(Array.isArray(parsed));\n  expect(parsed.length).toBe(1);\n  return parsed.pop();\n};\n\nconst subscriptions = new Set<Subscription>();\n\ndescribe(\"SharedHttpTest\", () => {\n  const data = { data: { hello: \"world\" } };\n  const data2 = { data: { hello: \"everyone\" } };\n  const mockError = { throws: new TypeError(\"mock me\") };\n\n  const makePromise = (res: any) =>\n    new Promise((resolve, reject) => setTimeout(() => resolve(res)));\n\n  let subscriber: any;\n\n  beforeEach(() => {\n    fetchMock.restore();\n    fetchMock.post(\"begin:/data2\", makePromise(data2));\n    fetchMock.post(\"begin:/data\", makePromise(data));\n    fetchMock.post(\"begin:/error\", mockError);\n    fetchMock.post(\"begin:/apollo\", makePromise(data));\n\n    fetchMock.get(\"begin:/data\", makePromise(data));\n    fetchMock.get(\"begin:/data2\", makePromise(data2));\n\n    const next = jest.fn();\n    const error = jest.fn();\n    const complete = jest.fn();\n\n    subscriber = {\n      next,\n      error,\n      complete,\n    };\n    subscriptions.clear();\n  });\n\n  afterEach(() => {\n    fetchMock.restore();\n    if (subscriptions.size) {\n      // Tests within this describe block can add subscriptions to this Set\n      // that they want to be canceled/unsubscribed after the test finishes.\n      subscriptions.forEach((sub) => sub.unsubscribe());\n    }\n  });\n\n  it(\"does not need any constructor arguments\", () => {\n    expect(() => new BatchHttpLink()).not.toThrow();\n  });\n\n  it(\"calls next and then complete\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n    const observable = execute(link, { query: sampleQuery });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n  });\n\n  it(\"calls error when fetch fails\", async () => {\n    const link = new BatchHttpLink({ uri: \"/error\" });\n    const observable = execute(link, { query: sampleQuery });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitError(mockError.throws);\n  });\n\n  it(\"calls error when fetch fails\", async () => {\n    const link = new BatchHttpLink({ uri: \"/error\" });\n    const observable = execute(link, { query: sampleMutation });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitError(mockError.throws);\n  });\n\n  it(\"strips unused variables, respecting nested fragments\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    const query = gql`\n      query PEOPLE($declaredAndUsed: String, $declaredButUnused: Int) {\n        people(surprise: $undeclared, noSurprise: $declaredAndUsed) {\n          ... on Doctor {\n            specialty(var: $usedByInlineFragment)\n          }\n          ...LawyerFragment\n        }\n      }\n      fragment LawyerFragment on Lawyer {\n        caseCount(var: $usedByNamedFragment)\n      }\n    `;\n\n    const variables = {\n      unused: \"strip\",\n      declaredButUnused: \"strip\",\n      declaredAndUsed: \"keep\",\n      undeclared: \"keep\",\n      usedByInlineFragment: \"keep\",\n      usedByNamedFragment: \"keep\",\n    };\n\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const [uri, options] = fetchMock.lastCall()!;\n    const { method, body } = options!;\n    expect(JSON.parse(body as string)).toEqual([\n      {\n        operationName: \"PEOPLE\",\n        query: print(query),\n        variables: {\n          declaredAndUsed: \"keep\",\n          undeclared: \"keep\",\n          usedByInlineFragment: \"keep\",\n          usedByNamedFragment: \"keep\",\n        },\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n        },\n      },\n    ]);\n    expect(method).toBe(\"POST\");\n    expect(uri).toBe(\"/data\");\n  });\n\n  it(\"unsubscribes without calling subscriber\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n    const observable = execute(link, { query: sampleQuery });\n    const stream = new ObservableStream(observable);\n    stream.unsubscribe();\n\n    await expect(stream).not.toEmitAnything();\n  });\n\n  const verifyRequest = async (\n    link: ApolloLink,\n    includeExtensions: boolean,\n    includeUnusedVariables: boolean\n  ) => {\n    const context = { info: \"stub\" };\n    const variables = { params: \"stub\" };\n\n    const observable = execute(link, {\n      query: sampleMutation,\n      context,\n      variables,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    let body = convertBatchedBody(fetchMock.lastCall()![1]!.body);\n    expect(body.query).toBe(print(sampleMutation));\n    expect(body.variables).toEqual(includeUnusedVariables ? variables : {});\n    expect(body.context).not.toBeDefined();\n    if (includeExtensions) {\n      expect(body.extensions).toBeDefined();\n    } else {\n      expect(body.extensions).not.toBeDefined();\n    }\n  };\n\n  it(\"passes all arguments to multiple fetch body including extensions\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    await verifyRequest(link, true, false);\n    await verifyRequest(link, true, false);\n  });\n\n  it(\"passes all arguments to multiple fetch body excluding extensions\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\", includeExtensions: false });\n\n    await verifyRequest(link, false, false);\n    await verifyRequest(link, false, false);\n  });\n\n  it(\"calls multiple subscribers\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n    const context = { info: \"stub\" };\n    const variables = { params: \"stub\" };\n\n    const observable = execute(link, {\n      query: sampleMutation,\n      context,\n      variables,\n    });\n\n    const observer1 = new Subject();\n    const stream1 = new ObservableStream(observer1);\n\n    const observer2 = new Subject();\n    const stream2 = new ObservableStream(observer2);\n\n    observable.subscribe(observer1);\n    observable.subscribe(observer2);\n\n    await expect(stream1).toEmitTypedValue(data);\n    await expect(stream2).toEmitTypedValue(data);\n\n    await expect(stream1).toComplete();\n    await expect(stream2).toComplete();\n\n    expect(fetchMock.calls().length).toBe(1);\n  });\n\n  it(\"calls remaining subscribers after unsubscribe\", async () => {\n    const link = new BatchHttpLink({ uri: \"/data\" });\n    const context = { info: \"stub\" };\n    const variables = { params: \"stub\" };\n\n    const observable = execute(link, {\n      query: sampleMutation,\n      context,\n      variables,\n    });\n\n    const observer = new Subject();\n    const stream = new ObservableStream(observer);\n\n    observable.subscribe(observer);\n\n    await wait(10);\n\n    const subscription = observable.subscribe(subscriber);\n    subscription.unsubscribe();\n\n    await wait(50);\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n  });\n\n  it(\"allows for dynamic endpoint setting\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    const stream = new ObservableStream(\n      execute(link, {\n        query: sampleQuery,\n        variables,\n        context: { uri: \"/data2\" },\n      })\n    );\n\n    await expect(stream).toEmitTypedValue(data2);\n  });\n\n  it(\"adds headers to the request from the context\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        headers: { authorization: \"1234\" },\n      });\n      return forward(operation).pipe(\n        map((result) => {\n          const { headers } = operation.getContext();\n          expect(headers).toBeDefined();\n          return result;\n        })\n      );\n    });\n    const link = middleware.concat(new BatchHttpLink({ uri: \"/data\" }));\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: Record<string, string> = fetchMock.lastCall()![1]!\n      .headers as Record<string, string>;\n    expect(headers.authorization).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"adds headers to the request from the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({\n      uri: \"/data\",\n      headers: { authorization: \"1234\" },\n    });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: Record<string, string> = fetchMock.lastCall()![1]!\n      .headers as Record<string, string>;\n    expect(headers.authorization).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"uses the latest window.fetch function if options.fetch not configured\", async () => {\n    const httpLink = new BatchHttpLink({ uri: \"data\" });\n\n    const fetch = window.fetch;\n    expect(typeof fetch).toBe(\"function\");\n\n    const fetchSpy = jest.spyOn(window, \"fetch\");\n    fetchSpy.mockImplementation(() =>\n      Promise.resolve(\n        Response.json(\n          { data: { hello: \"from spy\" } },\n          { headers: { \"content-type\": \"application/json\" } }\n        )\n      )\n    );\n\n    const spyFn = window.fetch;\n    expect(spyFn).not.toBe(fetch);\n\n    using stream = new ObservableStream(\n      execute(httpLink, { query: sampleQuery })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: { hello: \"from spy\" },\n    });\n    await expect(stream).toComplete();\n\n    expect(fetchSpy).toHaveBeenCalledTimes(1);\n    fetchSpy.mockRestore();\n\n    using stream2 = new ObservableStream(\n      execute(httpLink, { query: sampleQuery })\n    );\n\n    await expect(stream2).toEmitTypedValue({ data: { hello: \"world\" } });\n    await expect(stream2).toComplete();\n  });\n\n  it(\"prioritizes context headers over setup headers\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        headers: { authorization: \"1234\" },\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(\n      new BatchHttpLink({\n        uri: \"/data\",\n        headers: { authorization: \"no user\" },\n      })\n    );\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: Record<string, string> = fetchMock.lastCall()![1]!\n      .headers as Record<string, string>;\n    expect(headers.authorization).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"adds headers to the request from the context on an operation\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    const context = {\n      headers: { authorization: \"1234\" },\n    };\n    const stream = new ObservableStream(\n      execute(link, {\n        query: sampleQuery,\n        variables,\n        context,\n      })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: Record<string, string> = fetchMock.lastCall()![1]!\n      .headers as Record<string, string>;\n    expect(headers.authorization).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"adds headers w/ preserved case to the request from the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({\n      uri: \"/data\",\n      headers: {\n        authorization: \"1234\",\n        AUTHORIZATION: \"1234\",\n        \"CONTENT-TYPE\": \"application/json\",\n      },\n      preserveHeaderCase: true,\n    });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: any = fetchMock.lastCall()![1]!.headers;\n    expect(headers.AUTHORIZATION).toBe(\"1234\");\n    expect(headers[\"CONTENT-TYPE\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"prioritizes context headers w/ preserved case over setup headers\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        headers: { AUTHORIZATION: \"1234\" },\n        http: { preserveHeaderCase: true },\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(\n      new BatchHttpLink({\n        uri: \"/data\",\n        headers: { authorization: \"no user\" },\n        preserveHeaderCase: false,\n      })\n    );\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: any = fetchMock.lastCall()![1]!.headers;\n    expect(headers.AUTHORIZATION).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"adds headers w/ preserved case to the request from the context on an operation\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    const context = {\n      headers: { AUTHORIZATION: \"1234\" },\n      http: { preserveHeaderCase: true },\n    };\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables, context })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const headers: any = fetchMock.lastCall()![1]!.headers;\n    expect(headers.AUTHORIZATION).toBe(\"1234\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n    expect(headers.accept).toBe(\n      \"application/graphql-response+json,application/json;q=0.9\"\n    );\n  });\n\n  it(\"adds creds to the request from the context\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        credentials: \"same-team-yo\",\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(new BatchHttpLink({ uri: \"/data\" }));\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const creds = fetchMock.lastCall()![1]!.credentials;\n    expect(creds).toBe(\"same-team-yo\");\n  });\n\n  it(\"adds creds to the request from the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({\n      uri: \"/data\",\n      credentials: \"include\",\n    });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const creds = fetchMock.lastCall()![1]!.credentials;\n    expect(creds).toBe(\"include\");\n  });\n\n  it(\"prioritizes creds from the context over the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        credentials: \"omit\",\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(\n      new BatchHttpLink({ uri: \"/data\", credentials: \"include\" })\n    );\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const creds = fetchMock.lastCall()![1]!.credentials;\n    expect(creds).toBe(\"omit\");\n  });\n\n  it(\"adds uri to the request from the context\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        uri: \"/data\",\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(new BatchHttpLink());\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const uri = fetchMock.lastUrl();\n    expect(uri).toBe(\"/data\");\n  });\n\n  it(\"adds uri to the request from the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({ uri: \"/data\" });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const uri = fetchMock.lastUrl();\n    expect(uri).toBe(\"/data\");\n  });\n\n  it(\"prioritizes context uri over setup uri\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        uri: \"/apollo\",\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(\n      new BatchHttpLink({ uri: \"/data\", credentials: \"include\" })\n    );\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const uri = fetchMock.lastUrl();\n    expect(uri).toBe(\"/apollo\");\n  });\n\n  it(\"allows uri to be a function\", async () => {\n    const variables = { params: \"stub\" };\n    const customFetch = (_uri: any, options: any) => {\n      const { operationName } = convertBatchedBody(options.body);\n      expect(operationName).toBe(\"SampleQuery\");\n      return fetch(\"/dataFunc\", options);\n    };\n\n    const link = new BatchHttpLink({ fetch: customFetch });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    expect(fetchMock.lastUrl()).toBe(\"/dataFunc\");\n  });\n\n  it(\"adds fetchOptions to the request from the setup\", async () => {\n    const variables = { params: \"stub\" };\n    const link = new BatchHttpLink({\n      uri: \"/data\",\n      fetchOptions: { mode: \"no-cors\" },\n    });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const { mode, headers } = fetchMock.lastCall()![1]! as any;\n    expect(mode).toBe(\"no-cors\");\n    expect(headers[\"content-type\"]).toBe(\"application/json\");\n  });\n\n  it(\"adds fetchOptions to the request from the context\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        fetchOptions: {\n          someOption: \"foo\",\n        },\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(new BatchHttpLink({ uri: \"/data\" }));\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const { someOption } = fetchMock.lastCall()![1]! as any;\n    expect(someOption).toBe(\"foo\");\n  });\n\n  it(\"uses the print option function when defined\", async () => {\n    const customPrinter = jest.fn(\n      (ast: ASTNode, originalPrint: typeof print) => {\n        return stripIgnoredCharacters(originalPrint(ast));\n      }\n    );\n\n    const httpLink = new BatchHttpLink({ uri: \"data\", print: customPrinter });\n\n    const stream = new ObservableStream(\n      execute(httpLink, { query: sampleQuery })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    expect(customPrinter).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"prioritizes context over setup\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        fetchOptions: {\n          mode: \"cors\",\n        },\n      });\n      return forward(operation);\n    });\n    const link = middleware.concat(\n      new BatchHttpLink({ uri: \"/data\", fetchOptions: { mode: \"no-cors\" } })\n    );\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    const { mode } = fetchMock.lastCall()![1]! as any;\n    expect(mode).toBe(\"cors\");\n  });\n\n  it(\"allows for not sending the query with the request\", async () => {\n    const variables = { params: \"stub\" };\n    const middleware = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        http: {\n          includeQuery: false,\n          includeExtensions: true,\n        },\n      });\n      operation.extensions.persistedQuery = { hash: \"1234\" };\n      return forward(operation);\n    });\n    const link = middleware.concat(new BatchHttpLink({ uri: \"/data\" }));\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery, variables })\n    );\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    let body = convertBatchedBody(fetchMock.lastCall()![1]!.body);\n\n    expect(body.query).not.toBeDefined();\n    expect(body.extensions).toEqual({\n      persistedQuery: { hash: \"1234\" },\n      clientLibrary: {\n        name: \"@apollo/client\",\n        version,\n      },\n    });\n  });\n\n  it(\"sets the raw response on context\", async () => {\n    const middleware = new ApolloLink((operation, forward) => {\n      return new Observable((ob) => {\n        const op = forward(operation);\n        const sub = op.subscribe({\n          next: ob.next.bind(ob),\n          error: ob.error.bind(ob),\n          complete: () => {\n            expect(operation.getContext().response.headers).toBeDefined();\n            ob.complete();\n          },\n        });\n\n        return () => {\n          sub.unsubscribe();\n        };\n      });\n    });\n\n    const link = middleware.concat(new BatchHttpLink({ uri: \"/data\", fetch }));\n\n    const stream = new ObservableStream(execute(link, { query: sampleQuery }));\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n  });\n\n  describe(\"AbortController\", () => {\n    const originalAbortController = globalThis.AbortController;\n    afterEach(() => {\n      globalThis.AbortController = originalAbortController;\n    });\n\n    function trackGlobalAbortControllers() {\n      const instances: AbortController[] = [];\n      class AbortControllerMock {\n        constructor() {\n          const instance = new originalAbortController();\n          instances.push(instance);\n          return instance;\n        }\n      }\n\n      globalThis.AbortController = AbortControllerMock as any;\n      return instances;\n    }\n\n    it(\"aborts the request when unsubscribing before the request has completed\", async () => {\n      const fetch = jest.fn(async () => {\n        return Response.json(\n          { data: { stub: { id: \"foo\" } } },\n          { status: 200 }\n        );\n      });\n      const abortControllers = trackGlobalAbortControllers();\n\n      const link = new BatchHttpLink({\n        uri: \"data\",\n        fetch,\n        batchMax: 1,\n      });\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery })\n      );\n      stream.unsubscribe();\n\n      await expect(stream).not.toEmitAnything();\n\n      expect(abortControllers.length).toBe(1);\n      expect(abortControllers[0].signal.aborted).toBe(true);\n    });\n\n    it(\"a passed-in signal will be forwarded to the `fetch` call and not be overwritten by an internally-created one\", () => {\n      const fetch = jest.fn(async () => {\n        return Response.json(\n          { data: { stub: { id: \"foo\" } } },\n          { status: 200 }\n        );\n      });\n      const externalAbortController = new AbortController();\n\n      const link = new BatchHttpLink({\n        uri: \"data\",\n        fetch,\n        fetchOptions: { signal: externalAbortController.signal },\n        batchMax: 1,\n      });\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery })\n      );\n      stream.unsubscribe();\n\n      expect(fetch).toHaveBeenCalledTimes(1);\n      expect(fetch).toHaveBeenCalledWith(\n        \"data\",\n        expect.objectContaining({ signal: externalAbortController.signal })\n      );\n    });\n\n    it(\"aborting the internal signal emits abort error\", async () => {\n      try {\n        fetchMock.restore();\n        fetchMock.postOnce(\n          \"data\",\n          async () => '{ \"data\": { \"stub\": { \"id\": \"foo\" } } }'\n        );\n        const abortControllers = trackGlobalAbortControllers();\n\n        const link = new BatchHttpLink({ uri: \"/data\", batchMax: 1 });\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery })\n        );\n        abortControllers[0].abort();\n\n        await expect(stream).toEmitError(\n          new DOMException(\"The operation was aborted.\", \"AbortError\")\n        );\n      } finally {\n        fetchMock.restore();\n      }\n    });\n\n    it(\"resolving fetch does not cause the AbortController to be aborted\", async () => {\n      const abortControllers = trackGlobalAbortControllers();\n\n      const link = new BatchHttpLink({\n        uri: \"data\",\n        fetch: async () => {\n          return Response.json({ data: { hello: \"world\" } }, { status: 200 });\n        },\n        batchMax: 1,\n      });\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery })\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { hello: \"world\" } });\n      await expect(stream).toComplete();\n\n      expect(abortControllers.length).toBe(1);\n      expect(abortControllers[0].signal.aborted).toBe(false);\n    });\n\n    it(\"an unsuccessful fetch does not cause the AbortController to be aborted\", async () => {\n      const abortControllers = trackGlobalAbortControllers();\n\n      const link = new BatchHttpLink({\n        uri: \"data\",\n        fetch: async () => {\n          throw new Error(\"Could not connect to network\");\n        },\n        batchMax: 1,\n      });\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery })\n      );\n\n      await expect(stream).toEmitError();\n\n      expect(abortControllers.length).toBe(1);\n      expect(abortControllers[0].signal.aborted).toBe(false);\n    });\n  });\n});\n\ndescribe(\"GraphQL over HTTP\", () => {\n  test(\"emits result when content-type is not set with well formed GraphQL response\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json({ data: { foo: true } }, { status: 200 });\n    response.headers.delete(\"content-type\");\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { foo: true } });\n    await expect(stream).toComplete();\n  });\n\n  test(\"emits ServerError when content-type is not set with malformed GraphQL response\", async () => {\n    const query = gql`\n      query Foo {\n        foo\n      }\n    `;\n\n    const response = Response.json({ foo: true }, { status: 200 });\n    response.headers.delete(\"content-type\");\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(\n      new ServerError(\"Server response was malformed for query 'Foo'.\", {\n        response,\n        bodyText: JSON.stringify({ foo: true }),\n      })\n    );\n  });\n\n  test(\"emits ServerParseError when content-type is not set with unparsable JSON body\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = new Response(\"This is a response\", { status: 200 });\n    response.headers.delete(\"content-type\");\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(\n      new ServerParseError(\n        new Error(\n          `Unexpected token 'T', \"This is a response\" is not valid JSON`\n        ),\n        {\n          response,\n          bodyText: \"This is a response\",\n        }\n      )\n    );\n  });\n\n  test(\"emits ServerError when content-type is not set with well formed GraphQL response and non-200 status code\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: null, errors: [{ message: \"Something went wrong\" }] },\n      { status: 400 }\n    );\n    response.headers.delete(\"content-type\");\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(\n      new ServerError(\"Response not successful: Received status code 400\", {\n        response,\n        bodyText: JSON.stringify({\n          data: null,\n          errors: [{ message: \"Something went wrong\" }],\n        }),\n      })\n    );\n  });\n\n  test(\"emits ServerError when responding with application/json and non-200 status code with malformed GraphQL response\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { error: \"Could not process request\" },\n      {\n        status: 400,\n        headers: { \"content-type\": \"application/json\" },\n      }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(\n      new ServerError(\"Response not successful: Received status code 400\", {\n        response,\n        bodyText: JSON.stringify({\n          error: \"Could not process request\",\n        }),\n      })\n    );\n  });\n\n  test(\"emits ServerError when responding with application/json and non-200 status code with well-formed GraphQL response\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: null, errors: [{ message: \"Could not process request\" }] },\n      { status: 400, headers: { \"content-type\": \"application/json\" } }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(\n      new ServerError(\"Response not successful: Received status code 400\", {\n        response,\n        bodyText: JSON.stringify({\n          data: null,\n          errors: [{ message: \"Could not process request\" }],\n        }),\n      })\n    );\n  });\n\n  test(\"emits result when responding with a non-json mime type and 200 response with well formed GraphQL response\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: null, errors: [{ message: \"Could not process request\" }] },\n      {\n        status: 200,\n        headers: { \"content-type\": \"text/plain\" },\n      }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: null,\n      errors: [{ message: \"Could not process request\" }],\n    });\n    await expect(stream).toComplete();\n  });\n\n  test(\"handles 200 response with application/graphql-response+json\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: { foo: \"bar\" } },\n      {\n        status: 200,\n        headers: { \"content-type\": \"application/graphql-response+json\" },\n      }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { foo: \"bar\" } });\n    await expect(stream).toComplete();\n  });\n\n  test(\"parses non-200 response with application/graphql-response+json\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: null, errors: [{ message: \"Could not process request\" }] },\n      {\n        status: 400,\n        headers: { \"content-type\": \"application/graphql-response+json\" },\n      }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: null,\n      errors: [{ message: \"Could not process request\" }],\n    });\n    await expect(stream).toComplete();\n  });\n\n  test(\"parses 200 response with application/graphql-response+json and errors\", async () => {\n    const query = gql`\n      query {\n        foo\n      }\n    `;\n\n    const response = Response.json(\n      { data: null, errors: [{ message: \"Could not process request\" }] },\n      {\n        status: 200,\n        headers: { \"content-type\": \"application/graphql-response+json\" },\n      }\n    );\n\n    const link = new BatchHttpLink({\n      uri: \"/graphql\",\n      fetch: async () => response,\n    });\n\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: null,\n      errors: [{ message: \"Could not process request\" }],\n    });\n    await expect(stream).toComplete();\n  });\n});\n\ndescribe(\"client awareness\", () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const response = {\n    data: { hello: \"world\" },\n  };\n  const uri = \"https://example.com/graphql\";\n\n  afterEach(() => fetchMock.reset());\n\n  test(\"is part of `BatchHttpLink`\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    void client.query({ query, context: { queryDeduplication: false } });\n    await wait(10);\n\n    const headers = fetchMock.lastCall()![1]?.headers;\n    expect(headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  test(\"is not part of `BaseBatchHttpLink`\", async () => {\n    fetchMock.postOnce(uri, response);\n    const client = new ApolloClient({\n      link: new BaseBatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    await wait(10);\n\n    const headers = fetchMock.lastCall()![1]?.headers;\n    expect(headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n    });\n  });\n\n  test(\"`BatchHttpLink` options have priority over `ApolloClient` options\", async () => {\n    fetchMock.postOnce(uri, response);\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n\n        clientAwareness: {\n          name: \"overridden-client\",\n          version: \"2.0.0\",\n        },\n      }),\n      cache: new InMemoryCache(),\n\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    await wait(10);\n\n    const headers = fetchMock.lastCall()![1]?.headers;\n    expect(headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n      \"apollographql-client-name\": \"overridden-client\",\n      \"apollographql-client-version\": \"2.0.0\",\n    });\n  });\n\n  test(\"will batch requests with equal options\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query, context: { queryDeduplication: false } });\n    void client.query({ query, context: { queryDeduplication: false } });\n    await wait(10);\n\n    const headers = fetchMock.lastCall()![1]?.headers;\n    expect(headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  test(\"will not batch requests with different options\", async () => {\n    fetchMock.post(uri, [response], { repeat: 2 });\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query, context: { queryDeduplication: false } });\n    void client.query({\n      query,\n      context: {\n        queryDeduplication: false,\n        clientAwareness: {\n          name: \"overridden-client\",\n          version: \"2.0.0\",\n        },\n      },\n    });\n    await wait(10);\n\n    expect(fetchMock.calls()[0][1]?.headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n    expect(fetchMock.calls()[1][1]?.headers).toStrictEqual({\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n      \"apollographql-client-name\": \"overridden-client\",\n      \"apollographql-client-version\": \"2.0.0\",\n    });\n  });\n});\n\ndescribe(\"enhanced client awareness\", () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const response = {\n    data: { hello: \"world\" },\n  };\n  const uri = \"https://example.com/graphql\";\n\n  afterEach(() => fetchMock.reset());\n\n  test(\"is part of `BatchHttpLink`\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    void client.query({ query, context: { queryDeduplication: false } });\n    await wait(10);\n\n    const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n    expect(body[0].extensions).toStrictEqual({\n      clientLibrary: {\n        name: \"@apollo/client\",\n        version,\n      },\n    });\n    expect(body[1].extensions).toStrictEqual({\n      clientLibrary: {\n        name: \"@apollo/client\",\n        version,\n      },\n    });\n  });\n\n  test(\"is not part of `BaseBatchHttpLink`\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: new BaseBatchHttpLink({\n        uri,\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    void client.query({ query, context: { queryDeduplication: false } });\n    await wait(10);\n\n    const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n    expect(body[0].extensions).not.toBeDefined();\n    expect(body[1].extensions).not.toBeDefined();\n  });\n\n  test(\"can be disabled by disabling `includeExtensions`\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: new BatchHttpLink({\n        uri,\n        includeExtensions: false,\n      }),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    void client.query({ query, context: { queryDeduplication: false } });\n    await wait(10);\n\n    const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n    expect(body[0].extensions).not.toBeDefined();\n    expect(body[1].extensions).not.toBeDefined();\n  });\n\n  test(\"can send mixed requests with ECA enabled and disabled\", async () => {\n    fetchMock.postOnce(uri, [response, response]);\n    const client = new ApolloClient({\n      link: ApolloLink.split(\n        (operation) => operation.variables.a === 1,\n        new ClientAwarenessLink({\n          enhancedClientAwareness: { transport: \"extensions\" },\n        }),\n        new ClientAwarenessLink({\n          enhancedClientAwareness: { transport: false },\n        })\n      ).concat(new BaseBatchHttpLink({ uri })),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query, variables: { a: 1 } });\n    void client.query({\n      query,\n      variables: { a: 2 },\n    });\n    await wait(10);\n\n    const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n    expect(body[0].extensions).toStrictEqual({\n      clientLibrary: {\n        name: \"@apollo/client\",\n        version,\n      },\n    });\n    expect(body[1].extensions).not.toBeDefined();\n  });\n});\n"
  },
  {
    "path": "src/link/batch-http/batchHttpLink.ts",
    "content": "import { ApolloLink } from \"@apollo/client/link\";\nimport { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\n\nimport { BaseBatchHttpLink } from \"./BaseBatchHttpLink.js\";\n\nexport declare namespace BatchHttpLink {\n  /**\n   * Options provided to the `BatchHttpLink` constructor.\n   */\n  export interface Options\n    extends BaseBatchHttpLink.Options,\n      ClientAwarenessLink.Options {}\n\n  /**\n   * Options passed to `BatchHttpLink` through [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context). Previous\n   * non-terminating links in the link chain also can set these values to\n   * customize the behavior of `BatchHttpLink` for each operation.\n   *\n   * > [!NOTE]\n   * > Some of these values can also be provided to the `BatchHttpLink` constructor.\n   * > If a value is provided to both, the value in `context` takes precedence.\n   */\n  export interface ContextOptions\n    extends BaseBatchHttpLink.ContextOptions,\n      ClientAwarenessLink.ContextOptions {}\n}\n\n/**\n * `BatchHttpLink` is a terminating link that batches array of individual\n * GraphQL operations into a single HTTP request that's sent to a single GraphQL\n * endpoint. It combines the functionality of `BaseBatchHttpLink` and\n * `ClientAwarenessLink` into a single link.\n *\n * @remarks\n *\n * If you use `BatchHttpLink` instead of `HttpLink` as your terminating link,\n * Apollo Client automatically batches executed GraphQL operations and transmits\n * them to your server according to the batching options you provide.\n *\n * @example\n *\n * ```ts\n * import { BatchHttpLink } from \"@apollo/client/link/batch-http\";\n *\n * const link = new BatchHttpLink({\n *   uri: \"http://localhost:4000/graphql\",\n *   batchMax: 5, // No more than 5 operations per batch\n *   batchInterval: 20, // Wait no more than 20ms after first batched operation\n * });\n * ```\n */\nexport class BatchHttpLink extends ApolloLink {\n  constructor(options: BatchHttpLink.Options = {}) {\n    const { left, right, request } = ApolloLink.from([\n      new ClientAwarenessLink(options),\n      new BaseBatchHttpLink(options),\n    ]);\n    super(request);\n    Object.assign(this, { left, right });\n  }\n}\n"
  },
  {
    "path": "src/link/batch-http/index.ts",
    "content": "export { BaseBatchHttpLink } from \"./BaseBatchHttpLink.js\";\nexport { BatchHttpLink } from \"./batchHttpLink.js\";\n"
  },
  {
    "path": "src/link/client-awareness/ClientAwarenessLink.ts",
    "content": "import { ApolloLink } from \"@apollo/client/link\";\nimport { compact } from \"@apollo/client/utilities/internal\";\n\nexport declare namespace ClientAwarenessLink {\n  /**\n   * Options passed to `ClientAwarenessLink` through [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context). Previous\n   * non-terminating links in the link chain also can set these values to\n   * customize the behavior of `ClientAwarenessLink` for each operation.\n   *\n   * > [!NOTE]\n   * > Some of these values can also be provided to the `ClientAwarenessLink`\n   * > constructor. If a value is provided to both, the value in `context` takes\n   * > precedence.\n   */\n  export interface ContextOptions {\n    /** {@inheritDoc @apollo/client/link/client-awareness!ClientAwarenessLink.Options#clientAwareness:member} */\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n  }\n\n  export interface ClientAwarenessOptions {\n    /**\n     * A custom name (e.g., `iOS`) that identifies this particular client among your set of clients. Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n     *\n     * This option can either be set as part of the Apollo Client constructor call or when manually constructing a `HttpLink`, `BatchHttpLink` or `ClientAwarenessLink`.\n     */\n    name?: string;\n    /**\n     * A custom version that identifies the current version of this particular client (e.g., `1.2`). Apollo Server and Apollo Studio use this property as part of the [client awareness](https://www.apollographql.com/docs/apollo-server/monitoring/metrics#identifying-distinct-clients) feature.\n     *\n     * This is **not** the version of Apollo Client that you are using, but rather any version string that helps you differentiate between versions of your client.\n     *\n     * This option can either be set as part of the Apollo Client constructor call or when manually constructing a `HttpLink`, `BatchHttpLink` or `ClientAwarenessLink`.\n     */\n    version?: string;\n    /**\n     * Determines how `name` and `version` are sent in outgoing requests.\n     *\n     * If `name` and `version` are not provided, this option will be ignored.\n     * (These options can either be set as part of the Apollo Client constructor call or when manually constructing a `HttpLink`, `BatchHttpLink` or `ClientAwarenessLink`.)\n     *\n     * - If set to `\"headers\"`, `name` and `version` will be sent in the request headers as `apollographql-client-name` and `apollographql-client-version`, respectively.\n     * - If set to `false`, `name` and `version` will not be included in outgoing requests.\n     *\n     * @defaultValue \"headers\"\n     */\n    transport?: \"headers\" | false;\n  }\n  export interface EnhancedClientAwarenessOptions {\n    /**\n     * Determines how the the version information of Apollo Client is sent in outgoing requests.\n     *\n     * - If set to `\"extensions\"`, library `name` and `version` will be sent in an object in the request extensions as `clientLibrary`.\n     * - If set to `false`, library name and version will not be included in outgoing requests.\n     *\n     * @defaultValue \"extensions\"\n     */\n    transport?: \"headers\" | \"extensions\" | false;\n  }\n\n  export interface Options {\n    /**\n     * Configures the \"client awareness\" feature.\n     * This feature allows you to identify distinct applications in Apollo Studio\n     * and Apollo Server logs (and other monitoring or analytics tools) by adding\n     * information about the your application to outgoing requests.\n     */\n    clientAwareness?: ClientAwarenessLink.ClientAwarenessOptions;\n    /**\n     * Configures the \"enhanced client awareness\" feature.\n     * This feature allows you to identify the version of the Apollo Client library\n     * used in your application in Apollo Studio (and other monitoring or analytics tools)\n     * by adding information about the Apollo Client library to outgoing requests.\n     */\n    enhancedClientAwareness?: ClientAwarenessLink.EnhancedClientAwarenessOptions;\n  }\n}\n\n/**\n * `ClientAwarenessLink` provides support for providing client awareness\n * features.\n *\n * @remarks\n *\n * Client awareness adds identifying information about the client to HTTP\n * requests for use with metrics reporting tools, such as [Apollo GraphOS](https://apollographql.com/docs/graphos/platform).\n * It is included in the functionality of [`HttpLink`](https://apollographql.com/docs/react/api/link/apollo-link-http) by default.\n *\n * Client awareness distinguishes between user-provided client awareness\n * (provided by the `clientAwareness` option) and enhanced client awareness\n * (provided by the `enhancedClientAwareness` option). User-provided client\n * awareness enables you to set a customized client name and version for\n * identification in metrics reporting tools. Enhanced client awareness enables\n * the identification of the Apollo Client package name and version.\n *\n * @example\n *\n * ```ts\n * import { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\n *\n * const link = new ClientAwarenessLink({\n *   clientAwareness: {\n *     name: \"My Client\",\n *     version: \"1\",\n *   },\n *   enhancedClientAwareness: {\n *     transport: \"extensions\",\n *   },\n * });\n * ```\n */\nexport class ClientAwarenessLink extends ApolloLink {\n  constructor(options: ClientAwarenessLink.Options = {}) {\n    super((operation, forward) => {\n      const client = operation.client;\n\n      const clientOptions = client[\"queryManager\"].clientOptions;\n      const context = operation.getContext();\n      {\n        const {\n          name,\n          version,\n          transport = \"headers\",\n        } = compact(\n          {},\n          clientOptions.clientAwareness,\n          options.clientAwareness,\n          context.clientAwareness\n        );\n\n        if (transport === \"headers\") {\n          operation.setContext(({ headers }) => {\n            return {\n              headers: compact(\n                // setting these first so that they can be overridden by user-provided headers\n                {\n                  \"apollographql-client-name\": name,\n                  \"apollographql-client-version\": version,\n                },\n                headers\n              ),\n            };\n          });\n        }\n      }\n      {\n        const { transport = \"extensions\" } = compact(\n          {},\n          clientOptions.enhancedClientAwareness,\n          options.enhancedClientAwareness\n        );\n        if (transport === \"extensions\") {\n          operation.extensions = compact(\n            // setting these first so that it can be overridden by user-provided extensions\n            {\n              clientLibrary: {\n                name: \"@apollo/client\",\n                version: client.version,\n              },\n            },\n            operation.extensions\n          );\n        }\n\n        if (transport === \"headers\") {\n          operation.setContext(({ headers }) => {\n            return {\n              headers: compact(\n                // setting these first so that they can be overridden by user-provided headers\n                {\n                  \"apollographql-library-name\": \"@apollo/client\",\n                  \"apollographql-library-version\": client.version,\n                },\n                headers\n              ),\n            };\n          });\n        }\n      }\n\n      return forward(operation);\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/client-awareness/__tests__/ClientAwarenessLink.test.ts",
    "content": "import { ApolloClient, gql, InMemoryCache, version } from \"@apollo/client\";\nimport { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\n\nconst query = gql`\n  query {\n    hello\n  }\n`;\n\ndescribe(\"feature: client awareness\", () => {\n  test(\"does not add headers without options\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    // note that the headers are not set to default values, but `headers` itself is still defined\n    // as an empty object - this is okay\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({});\n  });\n\n  test(\"can be enabled from `ApolloClient` options\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  test(\"can be enabled from context\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({\n      query,\n      context: {\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      },\n    });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  test(\"can be enabled from `ClientAwarenessLink` constructor\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink({\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      }).concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({\n      \"apollographql-client-name\": \"test-client\",\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  test(\"can be disabled from `ClientAwarenessLink` constructor, even with options present\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink({\n        clientAwareness: { transport: false },\n      }).concat(terminatingLink),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        name: \"test-client\",\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual(undefined);\n  });\n\n  test(\"can set `name` without setting `version`\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        name: \"test-client\",\n      },\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({\n      \"apollographql-client-name\": \"test-client\",\n    });\n  });\n\n  test(\"can set `version` without setting `name`\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n      clientAwareness: {\n        version: \"1.0.0\",\n      },\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    expect(headers).toStrictEqual({\n      \"apollographql-client-version\": \"1.0.0\",\n    });\n  });\n\n  describe(\"option priorities\", () => {\n    test(\"context overrides `ApolloClient` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink().concat(terminatingLink),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({\n        query,\n        context: {\n          clientAwareness: {\n            name: \"overridden-client\",\n            version: \"2.0.0\",\n          },\n        },\n      });\n\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"overridden-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n\n    test(\"context overrides `ClientAwarenessLink` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink({\n          clientAwareness: {\n            name: \"test-client\",\n            version: \"1.0.0\",\n          },\n        }).concat(terminatingLink),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({\n        query,\n        context: {\n          clientAwareness: {\n            name: \"overridden-client\",\n            version: \"2.0.0\",\n          },\n        },\n      });\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"overridden-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n\n    test(\"`ClientAwarenessLink` options override `ApolloClient` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink({\n          clientAwareness: {\n            name: \"overridden-client\",\n            version: \"2.0.0\",\n          },\n        }).concat(terminatingLink),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({ query });\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"overridden-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n\n    test(\"merge-overrides `ClientAwarenessLink` and `ApolloClient` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink({\n          clientAwareness: {\n            version: \"2.0.0\",\n          },\n        }).concat(terminatingLink),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({ query });\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"test-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n\n    test(\"merge-overrides `context` and `ApolloClient` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink().concat(terminatingLink),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({\n        query,\n        context: {\n          clientAwareness: {\n            version: \"2.0.0\",\n          },\n        },\n      });\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"test-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n\n    test(\"merge-overrides `ClientAwarenessLink` and `context` options\", () => {\n      const terminatingLink = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link: new ClientAwarenessLink({\n          clientAwareness: {\n            name: \"test-client\",\n            version: \"1.0.0\",\n          },\n        }).concat(terminatingLink),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({\n        query,\n        context: {\n          clientAwareness: {\n            version: \"2.0.0\",\n          },\n        },\n      });\n      const headers = terminatingLink.operation?.getContext().headers;\n      expect(headers).toStrictEqual({\n        \"apollographql-client-name\": \"test-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n  });\n});\n\ndescribe(\"feature: enhanced client awareness\", () => {\n  test(\"is enabled by default\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    expect(terminatingLink.operation?.extensions).toStrictEqual({\n      clientLibrary: {\n        name: \"@apollo/client\",\n        version,\n      },\n    });\n  });\n\n  test(\"can use `headers` as transport\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink({\n        enhancedClientAwareness: { transport: \"headers\" },\n      }).concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    const headers = terminatingLink.operation?.getContext().headers;\n    const extensions = terminatingLink.operation?.extensions;\n    expect(headers).toStrictEqual({\n      \"apollographql-library-name\": \"@apollo/client\",\n      \"apollographql-library-version\": version,\n    });\n    expect(extensions).not.toHaveProperty(\"clientLibrary\");\n  });\n\n  test(\"can be disabled from `ApolloClient` options\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink().concat(terminatingLink),\n      cache: new InMemoryCache(),\n      enhancedClientAwareness: { transport: false },\n    });\n\n    void client.query({ query });\n    expect(terminatingLink.operation?.extensions).toStrictEqual({});\n  });\n\n  test(\"can be disabled from `ClientAwarenessLink` constructor\", () => {\n    const terminatingLink = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link: new ClientAwarenessLink({\n        enhancedClientAwareness: { transport: false },\n      }).concat(terminatingLink),\n      cache: new InMemoryCache(),\n    });\n\n    void client.query({ query });\n    expect(terminatingLink.operation?.extensions).toStrictEqual({});\n  });\n});\n"
  },
  {
    "path": "src/link/client-awareness/index.ts",
    "content": "export { ClientAwarenessLink } from \"./ClientAwarenessLink.js\";\n"
  },
  {
    "path": "src/link/context/__tests__/index.ts",
    "content": "import assert from \"node:assert\";\n\nimport { gql } from \"graphql-tag\";\nimport { Observable, of } from \"rxjs\";\n\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { setContext, SetContextLink } from \"@apollo/client/link/context\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query Test {\n    foo {\n      bar\n    }\n  }\n`;\nconst data = {\n  foo: { bar: true },\n};\n\nit(\"can be used to set the context with a simple function\", async () => {\n  const withContext = new SetContextLink(() => ({ dynamicallySet: true }));\n\n  const mockLink = new ApolloLink((operation) => {\n    expect(operation.getContext().dynamicallySet).toBe(true);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\ntest(\"`setContext` can be used to create a `SetContextLink`\", async () => {\n  const withContext = setContext(() => ({ dynamicallySet: true }));\n  expect(withContext).toBeInstanceOf(SetContextLink);\n\n  const mockLink = new ApolloLink((operation) => {\n    expect(operation.getContext().dynamicallySet).toBe(true);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\nit(\"can be used to set the context with a function returning a promise\", async () => {\n  const withContext = new SetContextLink(() =>\n    Promise.resolve({ dynamicallySet: true })\n  );\n\n  const mockLink = new ApolloLink((operation) => {\n    expect(operation.getContext().dynamicallySet).toBe(true);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\nit(\"can be used to set the context with a function returning a promise that is delayed\", async () => {\n  const withContext = new SetContextLink(() =>\n    wait(25).then(() => ({ dynamicallySet: true }))\n  );\n\n  const mockLink = new ApolloLink((operation) => {\n    expect(operation.getContext().dynamicallySet).toBe(true);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\nit(\"handles errors in the lookup correctly\", async () => {\n  const withContext = new SetContextLink(() =>\n    wait(5).then(() => {\n      throw new Error(\"dang\");\n    })\n  );\n\n  const mockLink = new ApolloLink((operation) => {\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitError(\"dang\");\n});\n\nit(\"handles errors in the lookup correctly with a normal function\", async () => {\n  const withContext = new SetContextLink(() => {\n    throw new Error(\"dang\");\n  });\n\n  const mockLink = new ApolloLink((operation) => {\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitError(\"dang\");\n});\n\nit(\"has access to the request information\", async () => {\n  const withContext = new SetContextLink(\n    (_, { operationName, query, variables }) =>\n      wait(1).then(() =>\n        Promise.resolve({\n          variables: variables ? true : false,\n          operation: query ? true : false,\n          operationName: operationName!.toUpperCase(),\n        })\n      )\n  );\n\n  const mockLink = new ApolloLink((op) => {\n    const { variables, operation, operationName } = op.getContext();\n    expect(variables).toBe(true);\n    expect(operation).toBe(true);\n    expect(operationName).toBe(\"TEST\");\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 1 } })\n  );\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\nit(\"has access to the context at execution time\", async () => {\n  const withContext = new SetContextLink(({ count }) =>\n    wait(1).then(() => ({ count: count + 1 }))\n  );\n\n  const mockLink = new ApolloLink((operation) => {\n    const { count } = operation.getContext();\n    expect(count).toEqual(2);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(\n    execute(link, { query, context: { count: 1 } })\n  );\n\n  await expect(stream).toEmitTypedValue({ data });\n});\n\nit(\"unsubscribes correctly\", async () => {\n  const withContext = new SetContextLink(({ count }) =>\n    wait(1).then(() => ({ count: count + 1 }))\n  );\n\n  const mockLink = new ApolloLink((operation) => {\n    const { count } = operation.getContext();\n    expect(count).toEqual(2);\n    return of({ data });\n  });\n\n  const link = withContext.concat(mockLink);\n\n  const stream = new ObservableStream(\n    execute(link, {\n      query,\n      context: { count: 1 },\n    })\n  );\n\n  await expect(stream).toEmitTypedValue({ data });\n  stream.unsubscribe();\n});\n\nit(\"unsubscribes without throwing before data\", async () => {\n  let called!: boolean;\n  const withContext = new SetContextLink(({ count }) => {\n    called = true;\n    return wait(1).then(() => ({ count: count + 1 }));\n  });\n\n  const mockLink = new ApolloLink((operation) => {\n    const { count } = operation.getContext();\n    expect(count).toEqual(2);\n    return new Observable((obs) => {\n      setTimeout(() => {\n        obs.next({ data });\n        obs.complete();\n      }, 25);\n    });\n  });\n\n  const link = withContext.concat(mockLink);\n\n  let handle = execute(link, {\n    query,\n    context: { count: 1 },\n  }).subscribe((result) => {\n    throw new Error(\"should have unsubscribed\");\n  });\n\n  await wait(10);\n\n  handle.unsubscribe();\n  expect(called).toBe(true);\n});\n\nit(\"does not start the next link subscription if the upstream subscription is already closed\", async () => {\n  let promiseResolved = false;\n  const withContext = new SetContextLink(() =>\n    wait(5).then(() => {\n      promiseResolved = true;\n      return { dynamicallySet: true };\n    })\n  );\n\n  let mockLinkCalled = false;\n  const mockLink = new ApolloLink(() => {\n    mockLinkCalled = true;\n    throw new Error(\"link should not be called\");\n  });\n\n  const link = withContext.concat(mockLink);\n\n  let subscriptionReturnedData = false;\n  let handle = execute(link, { query }).subscribe((result) => {\n    subscriptionReturnedData = true;\n    throw new Error(\"subscription should not return data\");\n  });\n\n  handle.unsubscribe();\n\n  await wait(10);\n\n  expect(promiseResolved).toBe(true);\n  expect(mockLinkCalled).toBe(false);\n  expect(subscriptionReturnedData).toBe(false);\n});\n\ntest(\"can access the client from operation argument\", async () => {\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const withContext = new SetContextLink((_, operation) => {\n    return { client: operation.client };\n  });\n\n  const mockLink = new ApolloLink((operation) => {\n    return of({ data: operation.getContext() });\n  });\n\n  const link = withContext.concat(mockLink);\n  const stream = new ObservableStream(execute(link, { query }, { client }));\n\n  const result = await stream.takeNext();\n\n  assert(\"data\" in result);\n  expect(result.data!.client).toBe(client);\n});\n"
  },
  {
    "path": "src/link/context/index.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\n\nexport declare namespace SetContextLink {\n  namespace SetContextLinkDocumentationTypes {\n    /**\n     * A function that returns an updated context object for an Apollo Link\n     * operation.\n     *\n     * The context setter function is called for each operation and allows you to\n     * modify the operation's context before it's passed to the next link in the\n     * chain. The returned context object is shallowly merged with the previous\n     * context object.\n     *\n     * @param prevContext - The previous context of the operation (e.g. the value\n     * of `operation.getContext()`)\n     * @param operation - The GraphQL operation being executed, without the\n     * `getContext` and `setContext` methods\n     * @returns A partial context object or a promise that resolves to a partial context object\n     */\n    export function ContextSetter(\n      prevContext: Readonly<ApolloLink.OperationContext>,\n      operation: SetContextLink.SetContextOperation\n    ):\n      | Promise<Partial<ApolloLink.OperationContext>>\n      | Partial<ApolloLink.OperationContext>;\n  }\n\n  /** {@inheritDoc @apollo/client/link/context!SetContextLink.SetContextLinkDocumentationTypes.ContextSetter:function(1)} */\n  export type ContextSetter = (\n    prevContext: Readonly<ApolloLink.OperationContext>,\n    operation: SetContextLink.SetContextOperation\n  ) =>\n    | Promise<Partial<ApolloLink.OperationContext>>\n    | Partial<ApolloLink.OperationContext>;\n\n  /**\n   * @deprecated\n   * Use `ContextSetter` instead. This type is used by the deprecated\n   * `setContext` function.\n   */\n  export type LegacyContextSetter = (\n    operation: SetContextLink.SetContextOperation,\n    prevContext: Readonly<ApolloLink.OperationContext>\n  ) =>\n    | Promise<Partial<ApolloLink.OperationContext>>\n    | Partial<ApolloLink.OperationContext>;\n\n  /**\n   * An `ApolloLink.Operation` object without the `getContext` and `setContext`\n   * methods. This prevents context setters from directly manipulating the\n   * context during the setter function execution.\n   */\n  export type SetContextOperation = Omit<\n    ApolloLink.Operation,\n    \"getContext\" | \"setContext\"\n  >;\n}\n\n/**\n * @deprecated\n * Use `SetContextLink` from `@apollo/client/link/context` instead. Note you\n * will need to flip the arguments when using `SetContextLink` as `prevContext`\n * is the first argument.\n *\n * ```ts\n * new SetContextLink((prevContext, operation) => {\n *   // ...\n * });\n * ```\n */\nexport function setContext(setter: SetContextLink.LegacyContextSetter) {\n  return new SetContextLink((prevContext, operation) =>\n    setter(operation, prevContext)\n  );\n}\n/**\n * `SetContextLink` is a non-terminating link that allows you to modify the\n * context of GraphQL operations before they're passed to the next link in the\n * chain. This is commonly used for authentication, adding headers, and other\n * request-time configuration.\n *\n * @example\n *\n * ```ts\n * import { SetContextLink } from \"@apollo/client/link/context\";\n *\n * const link = new SetContextLink((prevContext, operation) => {\n *   return {\n *     credentials: \"include\",\n *     // ...\n *   };\n * });\n * ```\n */\nexport class SetContextLink extends ApolloLink {\n  constructor(setter: SetContextLink.ContextSetter) {\n    super((operation, forward) => {\n      const { ...request } = operation as SetContextLink.SetContextOperation;\n\n      Object.defineProperty(request, \"client\", {\n        enumerable: false,\n        value: operation.client,\n      });\n\n      return new Observable((observer) => {\n        let closed = false;\n        Promise.resolve(request)\n          .then((req) => setter(operation.getContext(), req))\n          .then(operation.setContext)\n          .then(() => {\n            if (!closed) {\n              forward(operation).subscribe(observer);\n            }\n          })\n          .catch(observer.error.bind(observer));\n\n        return () => {\n          closed = true;\n        };\n      });\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/core/ApolloLink.ts",
    "content": "import type {\n  DocumentNode,\n  FormattedExecutionResult,\n  OperationTypeNode,\n} from \"graphql\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY } from \"rxjs\";\n\nimport type {\n  ApolloClient,\n  DefaultContext,\n  OperationVariables,\n} from \"@apollo/client\";\nimport type { TypeOverrides } from \"@apollo/client\";\nimport type { NotImplementedHandler } from \"@apollo/client/incremental\";\nimport { createOperation } from \"@apollo/client/link/utils\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { ApplyHKTImplementationWithDefault } from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nexport declare namespace ApolloLink {\n  /**\n   * Context provided for link execution, such as the client executing the\n   * request. It is separate from the request operation context.\n   */\n  export interface ExecuteContext {\n    /**\n     * The Apollo Client instance that executed the GraphQL request.\n     */\n    client: ApolloClient;\n  }\n\n  /** {@inheritDoc @apollo/client/link!ApolloLink.DocumentationTypes.ForwardFunction:function(1)} */\n  export type ForwardFunction = (\n    operation: ApolloLink.Operation\n  ) => Observable<ApolloLink.Result>;\n\n  /**\n   * The input object provided to `ApolloLink.execute` to send a GraphQL request through\n   * the link chain.\n   */\n  export interface Request {\n    /**\n     * The parsed GraphQL document that will be sent with the GraphQL request to\n     * the server.\n     */\n    query: DocumentNode;\n\n    /**\n     * The variables provided for the query.\n     */\n    variables?: OperationVariables;\n\n    /**\n     * Context provided to the link chain. Context is not sent to the server and\n     * is used to communicate additional metadata from a request to individual\n     * links in the link chain.\n     */\n    context?: DefaultContext;\n\n    /**\n     * A map of extensions that will be sent with the GraphQL request to the\n     * server.\n     */\n    extensions?: Record<string, any>;\n  }\n\n  /** {@inheritDoc @apollo/client/link!ApolloLink.DocumentationTypes.RequestHandler:function(1)} */\n  export type RequestHandler = (\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ) => Observable<ApolloLink.Result>;\n\n  export type AdditionalResultTypes<\n    TData = Record<string, any>,\n    TExtensions = Record<string, any>,\n  > = ApplyHKTImplementationWithDefault<\n    TypeOverrides,\n    \"AdditionalApolloLinkResultTypes\",\n    NotImplementedHandler.TypeOverrides,\n    TData,\n    TExtensions\n  >;\n\n  export type Result<\n    TData = Record<string, any>,\n    TExtensions = Record<string, any>,\n  > =\n    | FormattedExecutionResult<TData, TExtensions>\n    | AdditionalResultTypes<TData, TExtensions>;\n\n  /**\n   * The currently executed operation object provided to an `ApolloLink.RequestHandler`\n   * for each link in the link chain.\n   */\n  export interface Operation {\n    /**\n     * A `DocumentNode` that describes the operation taking place.\n     */\n    query: DocumentNode;\n\n    /**\n     * A map of GraphQL variables being sent with the operation.\n     */\n    variables: OperationVariables;\n\n    /**\n     * The string name of the GraphQL operation. If it is anonymous,\n     * `operationName` will be `undefined`.\n     */\n    operationName: string | undefined;\n\n    /**\n     * The type of the GraphQL operation, such as query or mutation.\n     */\n    operationType: OperationTypeNode;\n\n    /**\n     * A map that stores extensions data to be sent to the server.\n     */\n    extensions: Record<string, any>;\n\n    /**\n     * A function that takes either a new context object, or a function which\n     * takes in the previous context and returns a new one. See [managing\n     * context](https://apollographql.com/docs/react/api/link/introduction#managing-context).\n     */\n    setContext: {\n      (context: Partial<ApolloLink.OperationContext>): void;\n      (\n        updateContext: (\n          previousContext: Readonly<ApolloLink.OperationContext>\n        ) => Partial<ApolloLink.OperationContext>\n      ): void;\n    };\n\n    /**\n     * A function that gets the current context of the request. This can be used\n     * by links to determine which actions to perform. See [managing context](https://apollographql.com/docs/react/api/link/introduction#managing-context)\n     */\n    getContext: () => Readonly<ApolloLink.OperationContext>;\n\n    /**\n     * The Apollo Client instance executing the request.\n     */\n    readonly client: ApolloClient;\n  }\n\n  /**\n   * The `context` object that can be read and modified by links using the\n   * `operation.getContext()` and `operation.setContext()` methods.\n   */\n  export interface OperationContext extends DefaultContext {}\n\n  export namespace DocumentationTypes {\n    /**\n     * A request handler is responsible for performing some logic and executing the\n     * request, either by [forwarding](https://apollographql.com/docs/react/api/link/introduction#the-request-handler) the operation to the next link in the\n     * chain, or sending the operation to the destination that executes it, such as\n     * a GraphQL server.\n     *\n     * @param operation - The `Operation` object that provides information about the\n     * currently executed GraphQL request.\n     *\n     * @param forward - A function that is called to execute the next link in the\n     * chain.\n     */\n    export function RequestHandler(\n      operation: ApolloLink.Operation,\n      forward: ApolloLink.ForwardFunction\n    ): Observable<ApolloLink.Result>;\n\n    /**\n     * A function that when called will execute the next link in the link chain.\n     *\n     * @example\n     *\n     * ```ts\n     * const link = new ApolloLink((operation, forward) => {\n     *   // process the request\n     *\n     *   // Call `forward` to execute the next link in the chain\n     *   return forward(operation);\n     * });\n     * ```\n     *\n     * @param operation - The current `ApolloLink.Operation` object for the\n     * request.\n     */\n    export function ForwardFunction(\n      operation: ApolloLink.Operation\n    ): Observable<ApolloLink.Result>;\n  }\n}\n\n/**\n * The base class for all links in Apollo Client. A link represents either a\n * self-contained modification to a GraphQL operation or a side effect (such as\n * logging).\n *\n * @remarks\n *\n * Links enable you to customize Apollo Client's request flow by composing\n * together different pieces of functionality into a chain of links. Each\n * link represents a specific capability, such as adding authentication headers,\n * retrying failed requests, batching operations, or sending requests to a\n * GraphQL server.\n *\n * Every link must define a request handler via its constructor or by extending\n * this class and implementing the `request` method.\n *\n * @example\n *\n * ```ts\n * import { ApolloLink } from \"@apollo/client\";\n *\n * const link = new ApolloLink((operation, forward) => {\n *   console.log(\"Operation:\", operation.operationName);\n *   return forward(operation);\n * });\n * ```\n */\nexport class ApolloLink {\n  /**\n   * Creates a link that completes immediately and does not emit a result.\n   *\n   * @example\n   *\n   * ```ts\n   * const link = ApolloLink.empty();\n   * ```\n   */\n  public static empty(): ApolloLink {\n    return new ApolloLink(() => EMPTY);\n  }\n\n  /**\n   * Composes multiple links into a single composed link that executes each\n   * provided link in serial order.\n   *\n   * @example\n   *\n   * ```ts\n   * import { from, HttpLink, ApolloLink } from \"@apollo/client\";\n   * import { RetryLink } from \"@apollo/client/link/retry\";\n   * import MyAuthLink from \"../auth\";\n   *\n   * const link = ApolloLink.from([\n   *   new RetryLink(),\n   *   new MyAuthLink(),\n   *   new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n   * ]);\n   * ```\n   *\n   * @param links - An array of `ApolloLink` instances or request handlers that\n   * are executed in serial order.\n   */\n  public static from(links: ApolloLink[]): ApolloLink {\n    if (links.length === 0) return ApolloLink.empty();\n\n    const [first, ...rest] = links;\n    return first.concat(...rest);\n  }\n\n  /**\n   * Creates a link that conditionally routes a request to different links.\n   *\n   * @example\n   *\n   * ```ts\n   * import { ApolloLink, HttpLink } from \"@apollo/client\";\n   *\n   * const link = ApolloLink.split(\n   *   (operation) => operation.getContext().version === 1,\n   *   new HttpLink({ uri: \"http://localhost:4000/v1/graphql\" }),\n   *   new HttpLink({ uri: \"http://localhost:4000/v2/graphql\" })\n   * );\n   * ```\n   *\n   * @param test - A predicate function that receives the current `operation`\n   * and returns a boolean indicating which link to execute. Returning `true`\n   * executes the `left` link. Returning `false` executes the `right` link.\n   *\n   * @param left - The link that executes when the `test` function returns\n   * `true`.\n   *\n   * @param right - The link that executes when the `test` function returns\n   * `false`. If the `right` link is not provided, the request is forwarded to\n   * the next link in the chain.\n   */\n  public static split(\n    test: (op: ApolloLink.Operation) => boolean,\n    left: ApolloLink,\n    right: ApolloLink = new ApolloLink((op, forward) => forward(op))\n  ): ApolloLink {\n    const link = new ApolloLink((operation, forward) => {\n      const result = test(operation);\n\n      if (__DEV__) {\n        if (typeof result !== \"boolean\") {\n          invariant.warn(\n            \"[ApolloLink.split]: The test function returned a non-boolean value which could result in subtle bugs (e.g. such as using an `async` function which always returns a truthy value). Got `%o`.\",\n            result\n          );\n        }\n      }\n\n      return result ?\n          left.request(operation, forward)\n        : right.request(operation, forward);\n    });\n    return Object.assign(link, { left, right });\n  }\n\n  /**\n   * Executes a GraphQL request against a link. The `execute` function begins\n   * the request by calling the request handler of the link.\n   *\n   * @example\n   *\n   * ```ts\n   * const observable = ApolloLink.execute(link, { query, variables }, { client });\n   *\n   * observable.subscribe({\n   *   next(value) {\n   *     console.log(\"Received\", value);\n   *   },\n   *   error(error) {\n   *     console.error(\"Oops got error\", error);\n   *   },\n   *   complete() {\n   *     console.log(\"Request complete\");\n   *   },\n   * });\n   * ```\n   *\n   * @param link - The `ApolloLink` instance to execute the request.\n   *\n   * @param request - The GraphQL request details, such as the `query` and\n   * `variables`.\n   *\n   * @param context - The execution context for the request, such as the\n   * `client` making the request.\n   */\n  public static execute(\n    link: ApolloLink,\n    request: ApolloLink.Request,\n    context: ApolloLink.ExecuteContext\n  ): Observable<ApolloLink.Result> {\n    return link.request(createOperation(request, context), () => {\n      if (__DEV__) {\n        invariant.warn(\n          \"The terminating link provided to `ApolloLink.execute` called `forward` instead of handling the request. \" +\n            \"This results in an observable that immediately completes and does not emit a value. \" +\n            \"Please provide a terminating link that properly handles the request.\\n\\n\" +\n            \"If you are using a split link, ensure each branch contains a terminating link that handles the request.\"\n        );\n      }\n      return EMPTY;\n    });\n  }\n\n  /**\n   * Combines multiple links into a single composed link.\n   *\n   * @example\n   *\n   * ```ts\n   * const link = ApolloLink.concat(firstLink, secondLink, thirdLink);\n   * ```\n   *\n   * @param links - The links to concatenate into a single link. Each link will\n   * execute in serial order.\n   *\n   * @deprecated Use `ApolloLink.from` instead. `ApolloLink.concat` will be\n   * removed in a future major version.\n   */\n  public static concat(...links: ApolloLink[]) {\n    return ApolloLink.from(links);\n  }\n\n  constructor(request?: ApolloLink.RequestHandler) {\n    if (request) this.request = request;\n  }\n\n  /**\n   * Concatenates a link that conditionally routes a request to different links.\n   *\n   * @example\n   *\n   * ```ts\n   * import { ApolloLink, HttpLink } from \"@apollo/client\";\n   *\n   * const previousLink = new ApolloLink((operation, forward) => {\n   *   // Handle the request\n   *\n   *   return forward(operation);\n   * });\n   *\n   * const link = previousLink.split(\n   *   (operation) => operation.getContext().version === 1,\n   *   new HttpLink({ uri: \"http://localhost:4000/v1/graphql\" }),\n   *   new HttpLink({ uri: \"http://localhost:4000/v2/graphql\" })\n   * );\n   * ```\n   *\n   * @param test - A predicate function that receives the current `operation`\n   * and returns a boolean indicating which link to execute. Returning `true`\n   * executes the `left` link. Returning `false` executes the `right` link.\n   *\n   * @param left - The link that executes when the `test` function returns\n   * `true`.\n   *\n   * @param right - The link that executes when the `test` function returns\n   * `false`. If the `right` link is not provided, the request is forwarded to\n   * the next link in the chain.\n   */\n  public split(\n    test: (op: ApolloLink.Operation) => boolean,\n    left: ApolloLink,\n    right?: ApolloLink\n  ): ApolloLink {\n    return this.concat(ApolloLink.split(test, left, right));\n  }\n\n  /**\n   * Combines the link with other links into a single composed link.\n   *\n   * @example\n   *\n   * ```ts\n   * import { ApolloLink, HttpLink } from \"@apollo/client\";\n   *\n   * const previousLink = new ApolloLink((operation, forward) => {\n   *   // Handle the request\n   *\n   *   return forward(operation);\n   * });\n   *\n   * const link = previousLink.concat(\n   *   link1,\n   *   link2,\n   *   new HttpLink({ uri: \"http://localhost:4000/graphql\" })\n   * );\n   * ```\n   */\n  public concat(...links: ApolloLink[]): ApolloLink {\n    if (links.length === 0) {\n      return this;\n    }\n\n    return links.reduce(this.combine.bind(this), this);\n  }\n\n  private combine(left: ApolloLink, right: ApolloLink) {\n    const link = new ApolloLink((operation, forward) => {\n      return left.request(operation, (op) => right.request(op, forward));\n    });\n\n    return Object.assign(link, { left, right });\n  }\n\n  /**\n   * Runs the request handler for the provided operation.\n   *\n   * > [!NOTE]\n   * > This is called by the `ApolloLink.execute` function for you and should\n   * > not be called directly. Prefer using `ApolloLink.execute` to make the\n   * > request instead.\n   */\n  public request(\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ): Observable<ApolloLink.Result> {\n    throw newInvariantError(\"request is not implemented\");\n  }\n\n  /**\n   * @internal\n   * Used to iterate through all links that are concatenations or `split` links.\n   */\n  readonly left?: ApolloLink;\n  /**\n   * @internal\n   * Used to iterate through all links that are concatenations or `split` links.\n   */\n  readonly right?: ApolloLink;\n\n  /**\n   * @internal\n   * Can be provided by a link that has an internal cache to report it's memory details.\n   */\n  declare getMemoryInternals?: () => unknown;\n}\n"
  },
  {
    "path": "src/link/core/__tests__/ApolloLink.ts",
    "content": "import type { FormattedExecutionResult } from \"graphql\";\nimport { OperationTypeNode, print } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { EMPTY, map, Observable, of } from \"rxjs\";\n\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink, execute } from \"@apollo/client/link\";\nimport {\n  ObservableStream,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nclass SetContextLink extends ApolloLink {\n  constructor(\n    private setContext: (\n      context: Record<string, any>\n    ) => Record<string, any> = (c) => c\n  ) {\n    super();\n  }\n\n  public request(\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ): Observable<ApolloLink.Result> {\n    operation.setContext(this.setContext(operation.getContext()));\n    return forward(operation);\n  }\n}\n\nconst sampleQuery = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\nconst setContext = () => ({ add: 1 });\n\nconst defaultExecuteContext = {\n  client: new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  }),\n};\n\ndescribe(\"ApolloLink\", () => {\n  test(\"warns if the link provided to execute calls forward\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    const link = new ApolloLink((operation, forward) => {\n      return forward(operation);\n    });\n\n    const stream = new ObservableStream(\n      execute(link, { query: sampleQuery }, defaultExecuteContext)\n    );\n\n    await expect(stream).toComplete();\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      expect.stringContaining(\n        \"The terminating link provided to `ApolloLink.execute`\"\n      )\n    );\n  });\n\n  describe(\"context\", () => {\n    it(\"merges context\", async () => {\n      const returnOne = new SetContextLink(setContext);\n      const mock = new ApolloLink((op, forward) => {\n        op.setContext({ add: 3 });\n        op.setContext({ subtract: 1 });\n\n        return forward(op);\n      });\n      const link = returnOne.concat(mock).concat(\n        new ApolloLink((op) => {\n          expect(op.getContext()).toEqual({\n            add: 3,\n            subtract: 1,\n          });\n          return of({ data: { count: op.getContext().add } });\n        })\n      );\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery }, defaultExecuteContext)\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 3 } });\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"concat\", () => {\n    it(\"concats a Link\", async () => {\n      const returnOne = new SetContextLink(setContext);\n      const mock = new ApolloLink((op) =>\n        of({ data: { count: op.getContext().add } })\n      );\n      const link = returnOne.concat(mock);\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery }, defaultExecuteContext)\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n      await expect(stream).toComplete();\n    });\n\n    it(\"should pass error to observable's error\", async () => {\n      const error = new Error(\"thrown\");\n      const returnOne = new SetContextLink(setContext);\n      const mock = new ApolloLink(\n        (op) =>\n          new Observable((observer) => {\n            observer.next({ data: { count: op.getContext().add } });\n            observer.error(error);\n          })\n      );\n      const link = returnOne.concat(mock);\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery }, defaultExecuteContext)\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n      await expect(stream).toEmitError(error);\n    });\n\n    it(\"concats multiple links when chaining concat calls\", async () => {\n      const returnOne = new SetContextLink(setContext);\n      const mock1 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 2,\n        });\n        return forward(operation);\n      });\n      const mock2 = new ApolloLink((op) =>\n        of({ data: { count: op.getContext().add } })\n      );\n\n      const link = returnOne.concat(mock1).concat(mock2);\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery }, defaultExecuteContext)\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 3 } });\n      await expect(stream).toComplete();\n    });\n\n    it(\"returns a link that can be concat'd multiple times\", async () => {\n      const returnOne = new SetContextLink(setContext);\n      const mock1 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 2,\n        });\n        return forward(operation);\n      });\n      const mock2 = new ApolloLink((op) =>\n        of({ data: { count: op.getContext().add + 2 } })\n      );\n      const mock3 = new ApolloLink((op) =>\n        of({ data: { count: op.getContext().add + 3 } })\n      );\n      const link = returnOne.concat(mock1);\n\n      {\n        const stream = new ObservableStream(\n          execute(\n            link.concat(mock2),\n            { query: sampleQuery },\n            defaultExecuteContext\n          )\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 5 } });\n        await expect(stream).toComplete();\n      }\n\n      {\n        const stream = new ObservableStream(\n          execute(\n            link.concat(mock3),\n            { query: sampleQuery },\n            defaultExecuteContext\n          )\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 6 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"can provide multiple links to concat\", async () => {\n      const add1 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 1,\n        });\n        return forward(operation);\n      });\n      const add2 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 2,\n        });\n        return forward(operation);\n      });\n      const add3 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 3,\n        });\n        return forward(operation);\n      });\n\n      const calculate = new ApolloLink((operation) =>\n        of({ data: { count: operation.getContext().add } })\n      );\n\n      const link = add1.concat(add2, add3, calculate);\n\n      const stream = new ObservableStream(\n        execute(\n          link,\n          { query: sampleQuery, context: { add: 0 } },\n          defaultExecuteContext\n        )\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 6 } });\n      await expect(stream).toComplete();\n    });\n\n    it(\"can provide multiple links to static concat\", async () => {\n      const add1 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 1,\n        });\n        return forward(operation);\n      });\n      const add2 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 2,\n        });\n        return forward(operation);\n      });\n      const add3 = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          add: operation.getContext().add + 3,\n        });\n        return forward(operation);\n      });\n\n      const calculate = new ApolloLink((operation) =>\n        of({ data: { count: operation.getContext().add } })\n      );\n\n      const link = ApolloLink.concat(add1, add2, add3, calculate);\n\n      const stream = new ObservableStream(\n        execute(\n          link,\n          { query: sampleQuery, context: { add: 0 } },\n          defaultExecuteContext\n        )\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { count: 6 } });\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"empty\", () => {\n    it(\"should returns an immediately completed Observable\", async () => {\n      const stream = new ObservableStream(\n        execute(\n          ApolloLink.empty(),\n          { query: sampleQuery },\n          defaultExecuteContext\n        )\n      );\n\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"execute\", () => {\n    it(\"transforms an operation with context into something serlizable\", async () => {\n      const query = gql`\n        {\n          id\n        }\n      `;\n      const link = new ApolloLink((operation) => {\n        const str = JSON.stringify({\n          ...operation,\n          query: print(operation.query),\n        });\n\n        expect(str).toBe(\n          JSON.stringify({\n            query: print(operation.query),\n            variables: { id: 1 },\n            extensions: { cache: true },\n            operationType: OperationTypeNode.QUERY,\n          })\n        );\n        return EMPTY;\n      });\n      const stream = new ObservableStream(\n        execute(\n          link,\n          {\n            query,\n            variables: { id: 1 },\n            extensions: { cache: true },\n          },\n          defaultExecuteContext\n        )\n      );\n\n      await expect(stream).toComplete();\n    });\n\n    describe(\"execute\", () => {\n      let _warn: (message?: any, ...originalParams: any[]) => void;\n\n      beforeEach(() => {\n        _warn = console.warn;\n        console.warn = jest.fn((warning) => {\n          expect(warning).toBe(\n            `query should either be a string or GraphQL AST`\n          );\n        });\n      });\n\n      afterEach(() => {\n        console.warn = _warn;\n      });\n\n      it(\"should return an empty observable when a link is empty\", async () => {\n        const stream = new ObservableStream(\n          execute(\n            ApolloLink.empty(),\n            { query: sampleQuery },\n            defaultExecuteContext\n          )\n        );\n\n        await expect(stream).toComplete();\n      });\n\n      it(\"should set a default context, variable, and query on a copy of operation\", async () => {\n        const operation = {\n          query: gql`\n            {\n              id\n            }\n          `,\n        };\n        const link = new ApolloLink((op: ApolloLink.Operation) => {\n          expect((operation as any)[\"operationName\"]).toBeUndefined();\n          expect((operation as any)[\"variables\"]).toBeUndefined();\n          expect((operation as any)[\"context\"]).toBeUndefined();\n          expect((operation as any)[\"extensions\"]).toBeUndefined();\n          expect(op.variables).toBeDefined();\n          expect((op as any)[\"context\"]).toBeUndefined();\n          expect(op[\"extensions\"]).toBeDefined();\n          return EMPTY;\n        });\n\n        const stream = new ObservableStream(\n          execute(link, operation, defaultExecuteContext)\n        );\n\n        await expect(stream).toComplete();\n      });\n    });\n  });\n\n  describe(\"from\", () => {\n    const uniqueOperation: ApolloLink.Request = {\n      query: sampleQuery,\n      context: { name: \"uniqueName\" },\n      extensions: {},\n    };\n\n    it(\"should create an observable that completes when passed an empty array\", async () => {\n      const observable = ApolloLink.execute(\n        ApolloLink.from([]),\n        { query: sampleQuery },\n        defaultExecuteContext\n      );\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toComplete();\n    });\n\n    it(\"can create chain of one\", () => {\n      expect(() => ApolloLink.from([new ApolloLink()])).not.toThrow();\n    });\n\n    it(\"can create chain of two\", () => {\n      expect(() =>\n        ApolloLink.from([\n          new ApolloLink((operation, forward) => forward(operation)),\n          new ApolloLink(),\n        ])\n      ).not.toThrow();\n    });\n\n    it(\"should receive result of one link\", async () => {\n      const data: ApolloLink.Result = {\n        data: {\n          hello: \"world\",\n        },\n      };\n      const chain = ApolloLink.from([new ApolloLink(() => of(data))]);\n      // Smoke tests execute as a static method\n      const observable = ApolloLink.execute(\n        chain,\n        uniqueOperation,\n        defaultExecuteContext\n      );\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n    });\n\n    it(\"should accept AST query and pass AST to link\", () => {\n      const astOperation = {\n        ...uniqueOperation,\n        query: sampleQuery,\n      };\n\n      const stub = jest.fn();\n\n      const chain = ApolloLink.from([new ApolloLink(stub)]);\n      ApolloLink.execute(chain, astOperation, defaultExecuteContext);\n\n      expect(stub).toHaveBeenCalledWith(\n        {\n          query: sampleQuery,\n          operationName: \"SampleQuery\",\n          operationType: OperationTypeNode.QUERY,\n          variables: {},\n          extensions: {},\n        },\n        expect.any(Function)\n      );\n    });\n\n    it(\"should pass operation from one link to next with modifications\", async () => {\n      const chain = ApolloLink.from([\n        new ApolloLink((op, forward) =>\n          forward({\n            ...op,\n            query: sampleQuery,\n          })\n        ),\n        new ApolloLink((op) => {\n          expect(op).toStrictEqualTyped({\n            extensions: {},\n            operationName: \"SampleQuery\",\n            operationType: OperationTypeNode.QUERY,\n            query: sampleQuery,\n            variables: {},\n          });\n\n          return new Observable((observer) => {\n            observer.complete();\n          });\n        }),\n      ]);\n      const observable = ApolloLink.execute(\n        chain,\n        uniqueOperation,\n        defaultExecuteContext\n      );\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toComplete();\n    });\n\n    it(\"should pass result of one link to another with forward\", async () => {\n      const data: ApolloLink.Result = {\n        data: {\n          hello: \"world\",\n        },\n      };\n\n      const chain = ApolloLink.from([\n        new ApolloLink((op, forward) => {\n          return forward(op);\n        }),\n        new ApolloLink(() => of(data)),\n      ]);\n      const observable = ApolloLink.execute(\n        chain,\n        uniqueOperation,\n        defaultExecuteContext\n      );\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n    });\n\n    it(\"should receive final result of two link chain\", async () => {\n      const data: ApolloLink.Result = {\n        data: {\n          hello: \"world\",\n        },\n      };\n\n      const chain = ApolloLink.from([\n        new ApolloLink((op, forward) => {\n          const observable = forward(\n            op\n          ) as Observable<FormattedExecutionResult>;\n\n          return new Observable((observer) => {\n            observable.subscribe({\n              next: (actualData) => {\n                expect(data).toEqual(actualData);\n                observer.next({\n                  data: {\n                    ...actualData.data,\n                    modification: \"unique\",\n                  },\n                });\n              },\n              error: (error) => observer.error(error),\n              complete: () => observer.complete(),\n            });\n          });\n        }),\n        new ApolloLink(() => of(data)),\n      ]);\n\n      const result = ApolloLink.execute(\n        chain,\n        uniqueOperation,\n        defaultExecuteContext\n      );\n      const stream = new ObservableStream(result);\n\n      await expect(stream).toEmitTypedValue({\n        data: {\n          ...data.data,\n          modification: \"unique\",\n        },\n      });\n      await expect(stream).toComplete();\n    });\n\n    it(\"should chain together a function with links\", async () => {\n      const add1 = new ApolloLink(\n        (\n          operation: ApolloLink.Operation,\n          forward: ApolloLink.ForwardFunction\n        ) => {\n          operation.setContext((context: { num: number }) => ({\n            num: context.num + 1,\n          }));\n          return forward(operation);\n        }\n      );\n      const add1Link = new ApolloLink((operation, forward) => {\n        operation.setContext((context: { num: number }) => ({\n          num: context.num + 1,\n        }));\n        return forward(operation);\n      });\n\n      const link = ApolloLink.from([\n        add1,\n        add1,\n        add1Link,\n        add1,\n        add1Link,\n        new ApolloLink((operation) => of({ data: operation.getContext() })),\n      ]);\n\n      const stream = new ObservableStream(\n        execute(\n          link,\n          { query: sampleQuery, context: { num: 0 } },\n          defaultExecuteContext\n        )\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { num: 5 } });\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"split\", () => {\n    it(\"conditionally routes request to the proper link\", async () => {\n      const context = { add: 1 };\n      const returnOne = new SetContextLink(() => context);\n      const link1 = returnOne.concat(\n        new ApolloLink((operation, forward) =>\n          of({ data: { count: operation.getContext().add + 1 } })\n        )\n      );\n      const link2 = returnOne.concat(\n        new ApolloLink((operation, forward) =>\n          of({ data: { count: operation.getContext().add + 2 } })\n        )\n      );\n      const link = returnOne.split(\n        (operation) => operation.getContext().add === 1,\n        link1,\n        link2\n      );\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n\n      context.add = 2;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 4 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"allows concat after split to be joined\", async () => {\n      const context = { test: true, add: 1 };\n      const start = new SetContextLink(() => ({ ...context }));\n      const link = start\n        .split(\n          (operation) => operation.getContext().test,\n          new ApolloLink((operation, forward) => {\n            operation.setContext((context: { add: number }) => ({\n              add: context.add + 1,\n            }));\n            return forward(operation);\n          }),\n          new ApolloLink((operation, forward) => {\n            operation.setContext((context: { add: number }) => ({\n              add: context.add + 2,\n            }));\n            return forward(operation);\n          })\n        )\n        .concat(\n          new ApolloLink((operation) =>\n            of({ data: { count: operation.getContext().add } })\n          )\n        );\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 3 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"should allow default right to be empty or passthrough when forward available\", async () => {\n      // Silence warning about `right` link calling forward\n      using _ = spyOnConsole(\"warn\");\n      let context = { test: true };\n      const start = new SetContextLink(() => context);\n      const link = start.split(\n        (operation) => operation.getContext().test,\n        new ApolloLink(() =>\n          of({\n            data: {\n              count: 1,\n            },\n          })\n        )\n      );\n      const concat = link.concat(\n        new ApolloLink(() =>\n          of({\n            data: {\n              count: 2,\n            },\n          })\n        )\n      );\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery }, defaultExecuteContext)\n        );\n\n        await expect(stream).toComplete();\n      }\n\n      {\n        const stream = new ObservableStream(\n          execute(concat, { query: sampleQuery }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"should create filter when single link passed in\", async () => {\n      // Silence warning about `right` link calling forward\n      using _ = spyOnConsole(\"warn\");\n      const link = ApolloLink.split(\n        (operation) => operation.getContext().test,\n        new ApolloLink(() => of({ data: { count: 1 } }))\n      );\n\n      let context = { test: true };\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"should split two Links\", async () => {\n      const link = ApolloLink.split(\n        (operation) => operation.getContext().test,\n        new ApolloLink(() => of({ data: { count: 1 } })),\n        new ApolloLink(() => of({ data: { count: 2 } }))\n      );\n\n      let context = { test: true };\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"should allow concat after split to be join\", async () => {\n      const context = { test: true };\n      const link = ApolloLink.split(\n        (operation) => operation.getContext().test,\n        new ApolloLink((operation, forward) =>\n          (\n            forward(operation) as Observable<FormattedExecutionResult<any>>\n          ).pipe(\n            map((data) => ({\n              data: { count: data.data!.count + 1 },\n            }))\n          )\n        )\n      ).concat(new ApolloLink(() => of({ data: { count: 1 } })));\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    it(\"should allow default right to be passthrough\", async () => {\n      const context = { test: true };\n      const link = ApolloLink.split(\n        (operation) => operation.getContext().test,\n        new ApolloLink(() => of({ data: { count: 2 } }))\n      ).concat(new ApolloLink(() => of({ data: { count: 1 } })));\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 2 } });\n        await expect(stream).toComplete();\n      }\n\n      context.test = false;\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query: sampleQuery, context }, defaultExecuteContext)\n        );\n\n        await expect(stream).toEmitTypedValue({ data: { count: 1 } });\n        await expect(stream).toComplete();\n      }\n    });\n\n    test(\"warns when `split` test function returns non-boolean value\", async () => {\n      using consoleSpy = spyOnConsole(\"warn\");\n\n      const empty = new ApolloLink(() => of());\n\n      [undefined, \"truthy\", 0].forEach((value) => {\n        consoleSpy.warn.mockClear();\n        const link = ApolloLink.split(() => value as any, empty, empty);\n\n        execute(link, { query: sampleQuery }, defaultExecuteContext);\n        expect(console.warn).toHaveBeenCalledTimes(1);\n        expect(console.warn).toHaveBeenCalledWith(\n          \"[ApolloLink.split]: The test function returned a non-boolean value which could result in subtle bugs (e.g. such as using an `async` function which always returns a truthy value). Got `%o`.\",\n          value\n        );\n      });\n    });\n\n    test(\"warns when `split` test function uses async function\", async () => {\n      using _ = spyOnConsole(\"warn\");\n\n      const left = new ApolloLink(() => of({ data: { link: \"left\" } }));\n      const right = new ApolloLink(() => of({ data: { link: \"right\" } }));\n      const link = ApolloLink.split((async () => false) as any, left, right);\n\n      const stream = new ObservableStream(\n        execute(link, { query: sampleQuery }, defaultExecuteContext)\n      );\n\n      // This demonstrates that the \"left\" link is used because of the async\n      // function even though it seems like it should use the \"right\" link\n      await expect(stream).toEmitTypedValue({ data: { link: \"left\" } });\n      await expect(stream).toComplete();\n\n      expect(console.warn).toHaveBeenCalledTimes(1);\n      expect(console.warn).toHaveBeenCalledWith(\n        \"[ApolloLink.split]: The test function returned a non-boolean value which could result in subtle bugs (e.g. such as using an `async` function which always returns a truthy value). Got `%o`.\",\n        expect.anything()\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/core/concat.ts",
    "content": "import { ApolloLink } from \"./ApolloLink.js\";\n\n/**\n * @deprecated Use `ApolloLink.from` instead. `concat` will be removed in a\n * future major version.\n */\nexport const concat = ApolloLink.concat;\n"
  },
  {
    "path": "src/link/core/deprecated.ts",
    "content": "import type { ApolloLink } from \"./ApolloLink.js\";\n\n/** @deprecated Use `ApolloLink.Request` instead */\nexport type GraphQLRequest = ApolloLink.Request;\n\n/** @deprecated Use `ApolloLink.Operation` instead */\nexport type Operation = ApolloLink.Operation;\n\n/** @deprecated Use `ApolloLink.RequestHandler` instead */\nexport type RequestHandler = ApolloLink.RequestHandler;\n\n/** @deprecated Use `ApolloLink.Result` instead */\nexport type FetchResult<\n  TData = Record<string, any>,\n  TExtensions = Record<string, any>,\n> = ApolloLink.Result<TData, TExtensions>;\n"
  },
  {
    "path": "src/link/core/empty.ts",
    "content": "import { ApolloLink } from \"./ApolloLink.js\";\n\n/**\n * @deprecated Use `ApolloLink.empty` instead. `empty` will be removed in a\n * future major version.\n */\nexport const empty = ApolloLink.empty;\n"
  },
  {
    "path": "src/link/core/execute.ts",
    "content": "import { ApolloLink } from \"./ApolloLink.js\";\n\nexport const execute = ApolloLink.execute;\n"
  },
  {
    "path": "src/link/core/from.ts",
    "content": "import { ApolloLink } from \"./ApolloLink.js\";\n\n/**\n * @deprecated Use `ApolloLink.from` instead. `from` will be removed in a\n * future major version.\n */\nexport const from = ApolloLink.from;\n"
  },
  {
    "path": "src/link/core/split.ts",
    "content": "import { ApolloLink } from \"./ApolloLink.js\";\n\n/**\n * @deprecated Use `ApolloLink.split` instead. `split` will be removed in a\n * future major version.\n */\nexport const split = ApolloLink.split;\n"
  },
  {
    "path": "src/link/core/types.ts",
    "content": "import type { FormattedExecutionResult, GraphQLFormattedError } from \"graphql\";\n\nexport interface ApolloPayloadResult<\n  TData = Record<string, any>,\n  TExtensions = Record<string, any>,\n> {\n  payload: FormattedExecutionResult<TData, TExtensions> | null;\n  // Transport layer errors (as distinct from GraphQL or NetworkErrors),\n  // these are fatal errors that will include done: true.\n  errors?: ReadonlyArray<GraphQLFormattedError>;\n}\n"
  },
  {
    "path": "src/link/error/__tests__/index.ts",
    "content": "import type { GraphQLFormattedError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { Observable, of } from \"rxjs\";\n\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n  PROTOCOL_ERRORS_SYMBOL,\n  ServerError,\n  UnconventionalError,\n} from \"@apollo/client/errors\";\nimport {\n  Defer20220824Handler,\n  GraphQL17Alpha9Handler,\n} from \"@apollo/client/incremental\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { ErrorLink } from \"@apollo/client/link/error\";\nimport {\n  executeWithDefaultContext as execute,\n  mockDefer20220824,\n  mockDeferStreamGraphQL17Alpha9,\n  mockMultipartSubscriptionStream,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { isFormattedExecutionResult } from \"@apollo/client/utilities\";\n\ndescribe(\"error handling\", () => {\n  it(\"calls onError when GraphQL errors are returned\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const error: GraphQLFormattedError = { message: \"resolver blew up\" };\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => of({ errors: [error] }));\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ errors: [error] });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({ query, variables: {} }),\n      result: { errors: [error] },\n      error: new CombinedGraphQLErrors({ errors: [error] }),\n    });\n  });\n\n  it(\"calls onError with error when thrown from request handler\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const error = new Error(\"app is crashing\");\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      throw error;\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error,\n    });\n  });\n\n  it(\"calls onError with error emitted from observable\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const error = new Error(\"app is crashing\");\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error(error);\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error,\n    });\n  });\n\n  test(\"wraps strings emitted from terminating link in Error\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        observer.error(\"Oops\");\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    // Let core wrap the error as it sees fit. Only onError should see the\n    // wrapped error.\n    await expect(stream).toEmitError(\"Oops\");\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error: new Error(\"Oops\"),\n    });\n  });\n\n  test(\"wraps unconventional error types in UnconventionalError\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    for (const type of [Symbol(), { message: \"This is an error\" }, [\"Error\"]]) {\n      const callback = jest.fn();\n      const errorLink = new ErrorLink(callback);\n\n      const mockLink = new ApolloLink(() => {\n        return new Observable((observer) => {\n          observer.error(type);\n        });\n      });\n\n      const link = errorLink.concat(mockLink);\n      const stream = new ObservableStream(execute(link, { query }));\n\n      // Let core wrap the error as it sees fit. Only onError should see the\n      // wrapped error\n      await expect(stream).toEmitError(type);\n\n      expect(callback).toHaveBeenCalledTimes(1);\n      expect(callback).toHaveBeenLastCalledWith({\n        forward: expect.any(Function),\n        operation: expect.objectContaining({\n          query,\n          operationName: \"Foo\",\n          variables: {},\n        }),\n        error: new UnconventionalError(type),\n      });\n    }\n  });\n\n  it(\"handles errors emitted in incremental chunks with Defer20220824Handler\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          ... @defer {\n            bar\n          }\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const { httpLink, enqueueInitialChunk, enqueueErrorChunk } =\n      mockDefer20220824();\n    const link = errorLink.concat(httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    const stream = new ObservableStream(execute(link, { query }, { client }));\n\n    enqueueInitialChunk({\n      hasNext: true,\n      data: { foo: {} },\n    });\n\n    enqueueErrorChunk([\n      {\n        message: \"could not read data\",\n        extensions: {\n          code: \"INCREMENTAL_ERROR\",\n        },\n      },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: {} },\n      hasNext: true,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      hasNext: true,\n      incremental: [\n        {\n          errors: [\n            {\n              message: \"could not read data\",\n              extensions: {\n                code: \"INCREMENTAL_ERROR\",\n              },\n            },\n          ],\n        },\n      ],\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error: new CombinedGraphQLErrors({\n        errors: [\n          {\n            message: \"could not read data\",\n            extensions: {\n              code: \"INCREMENTAL_ERROR\",\n            },\n          },\n        ],\n      }),\n      result: {\n        hasNext: true,\n        incremental: [\n          {\n            errors: [\n              {\n                message: \"could not read data\",\n                extensions: {\n                  code: \"INCREMENTAL_ERROR\",\n                },\n              },\n            ],\n          },\n        ],\n      },\n    });\n  });\n\n  it(\"handles errors emitted in incremental chunks with GraphQL17Alpha9Handler\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          ... @defer {\n            bar\n          }\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDeferStreamGraphQL17Alpha9();\n    const link = errorLink.concat(httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    const stream = new ObservableStream(execute(link, { query }, { client }));\n\n    enqueueInitialChunk({\n      hasNext: true,\n      data: { foo: {} },\n      pending: [{ id: \"0\", path: [\"foo\"] }],\n    });\n\n    enqueueSubsequentChunk({\n      incremental: [\n        {\n          id: \"0\",\n          data: { bar: null },\n          errors: [\n            {\n              message: \"could not read data\",\n              extensions: {\n                code: \"INCREMENTAL_ERROR\",\n              },\n              path: [\"foo\", \"bar\"],\n            },\n          ],\n        },\n      ],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      hasNext: true,\n      data: { foo: {} },\n      // @ts-ignore our tests expect the defer20220824 format\n      pending: [{ id: \"0\", path: [\"foo\"] }],\n    });\n\n    await expect(stream).toEmitTypedValue({\n      // @ts-ignore our tests expect the defer20220824 format\n      incremental: [\n        {\n          // @ts-ignore our tests expect the defer20220824 format\n          id: \"0\",\n          data: { bar: null },\n          errors: [\n            {\n              message: \"could not read data\",\n              extensions: {\n                code: \"INCREMENTAL_ERROR\",\n              },\n              path: [\"foo\", \"bar\"],\n            },\n          ],\n        },\n      ],\n      hasNext: false,\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error: new CombinedGraphQLErrors({\n        errors: [\n          {\n            message: \"could not read data\",\n            extensions: {\n              code: \"INCREMENTAL_ERROR\",\n            },\n            path: [\"foo\", \"bar\"],\n          },\n        ],\n      }),\n      result: {\n        incremental: [\n          {\n            id: \"0\",\n            data: { bar: null },\n            errors: [\n              {\n                message: \"could not read data\",\n                extensions: {\n                  code: \"INCREMENTAL_ERROR\",\n                },\n                path: [\"foo\", \"bar\"],\n              },\n            ],\n          },\n        ],\n        hasNext: false,\n      },\n    });\n  });\n\n  it(\"handles errors emitted in completed subsequent chunk with GraphQL17Alpha9Handler\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          ... @defer {\n            bar\n          }\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDeferStreamGraphQL17Alpha9();\n    const link = errorLink.concat(httpLink);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    const stream = new ObservableStream(execute(link, { query }, { client }));\n\n    enqueueInitialChunk({\n      hasNext: true,\n      data: { foo: {} },\n      pending: [{ id: \"0\", path: [\"foo\"] }],\n    });\n\n    enqueueSubsequentChunk({\n      completed: [\n        {\n          id: \"0\",\n          errors: [\n            {\n              message: \"could not read data\",\n              extensions: {\n                code: \"INCREMENTAL_ERROR\",\n              },\n            },\n          ],\n        },\n      ],\n      hasNext: false,\n    });\n\n    await expect(stream).toEmitTypedValue({\n      hasNext: true,\n      data: { foo: {} },\n      // @ts-ignore our tests expect the defer20220824 format\n      pending: [{ id: \"0\", path: [\"foo\"] }],\n    });\n\n    await expect(stream).toEmitTypedValue({\n      // @ts-ignore our tests expect the defer20220824 format\n      completed: [\n        {\n          id: \"0\",\n          errors: [\n            {\n              message: \"could not read data\",\n              extensions: {\n                code: \"INCREMENTAL_ERROR\",\n              },\n            },\n          ],\n        },\n      ],\n      hasNext: false,\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error: new CombinedGraphQLErrors({\n        errors: [\n          {\n            message: \"could not read data\",\n            extensions: {\n              code: \"INCREMENTAL_ERROR\",\n            },\n          },\n        ],\n      }),\n      result: {\n        completed: [\n          {\n            id: \"0\",\n            errors: [\n              {\n                message: \"could not read data\",\n                extensions: {\n                  code: \"INCREMENTAL_ERROR\",\n                },\n              },\n            ],\n          },\n        ],\n        hasNext: false,\n      },\n    });\n  });\n\n  it(\"calls onError with protocol errors from multipart subscriptions\", async () => {\n    const subscription = gql`\n      subscription MySubscription {\n        aNewDieWasCreated {\n          die {\n            roll\n            sides\n            color\n          }\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const { httpLink, enqueuePayloadResult, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const link = errorLink.concat(httpLink);\n    const stream = new ObservableStream(execute(link, { query: subscription }));\n\n    enqueuePayloadResult({\n      data: { aNewDieWasCreated: { die: { color: \"red\", roll: 1, sides: 4 } } },\n    });\n\n    enqueueProtocolErrors([\n      { message: \"Error field\", extensions: { code: \"INTERNAL_SERVER_ERROR\" } },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { aNewDieWasCreated: { die: { color: \"red\", roll: 1, sides: 4 } } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      extensions: {\n        [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n          {\n            extensions: {\n              code: \"INTERNAL_SERVER_ERROR\",\n            },\n            message: \"Error field\",\n          },\n        ]),\n      } as Record<string, unknown>,\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query: subscription,\n        operationName: \"MySubscription\",\n        variables: {},\n      }),\n      result: {\n        extensions: {\n          [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n            {\n              extensions: {\n                code: \"INTERNAL_SERVER_ERROR\",\n              },\n              message: \"Error field\",\n            },\n          ]),\n        },\n      },\n      error: new CombinedProtocolErrors([\n        {\n          message: \"Error field\",\n          extensions: { code: \"INTERNAL_SERVER_ERROR\" },\n        },\n      ]),\n    });\n  });\n\n  it(\"captures errors within links\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const error = new Error(\"app is crashing\");\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable(() => {\n        throw error;\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error,\n    });\n  });\n\n  it(\"captures networkError.statusCode within links\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n    const error = new ServerError(\"app is crashing\", {\n      response: new Response(\"\", { status: 500 }),\n      bodyText: \"ServerError\",\n    });\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable(() => {\n        throw error;\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      error,\n    });\n\n    const capturedError = callback.mock.calls[0][0].error as ServerError;\n    expect(capturedError.statusCode).toBe(500);\n  });\n\n  it(\"completes if no errors\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return of({ data: { foo: { id: 1 } } });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n\n    expect(callback).not.toHaveBeenCalled();\n  });\n\n  it(\"allows an error to be ignored\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const errorLink = new ErrorLink(({ result }) => {\n      // ignore errors\n      if (isFormattedExecutionResult(result)) {\n        delete result!.errors;\n      }\n    });\n\n    const mockLink = new ApolloLink(() => {\n      return of({\n        data: { foo: { id: 1 } },\n        errors: [{ message: \"ignore\" }],\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: { id: 1 } },\n    });\n    await expect(stream).toComplete();\n  });\n\n  it(\"can be unsubscribed\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable((obs) => {\n        setTimeout(() => {\n          obs.next({ data: { foo: { id: 1 } } });\n          obs.complete();\n        }, 5);\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    stream.unsubscribe();\n\n    await wait(10);\n\n    expect(callback).not.toHaveBeenCalled();\n  });\n\n  it(\"includes the operation and any data along with a graphql error\", async () => {\n    const query = gql`\n      query Foo {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const error: GraphQLFormattedError = { message: \"resolver blew up\" };\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() =>\n      of({\n        data: { foo: true },\n        errors: [error],\n      })\n    );\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(\n      execute(link, { query, context: { bar: true } })\n    );\n\n    await expect(stream).toEmitTypedValue({\n      data: { foo: true },\n      errors: [{ message: \"resolver blew up\" }],\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query,\n        operationName: \"Foo\",\n        variables: {},\n      }),\n      result: { data: { foo: true }, errors: [error] },\n      error: new CombinedGraphQLErrors({\n        data: { foo: true },\n        errors: [error],\n      }),\n    });\n\n    const operation = callback.mock.calls[0][0]\n      .operation as ApolloLink.Operation;\n    expect(operation.getContext().bar).toBe(true);\n  });\n});\n\ndescribe(\"error handling with class\", () => {\n  it(\"has an easy way to handle GraphQL errors\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const error: GraphQLFormattedError = { message: \"resolver blew up\" };\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => of({ errors: [error] }));\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ errors: [error] });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({ query, variables: {} }),\n      result: { errors: [error] },\n      error: new CombinedGraphQLErrors({ errors: [error] }),\n    });\n  });\n\n  it(\"has an easy way to log client side (network) errors\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const error = new Error(\"app is crashing\");\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      throw error;\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({ query }),\n      error,\n    });\n  });\n\n  it(\"handles protocol errors (multipart subscription)\", async () => {\n    const subscription = gql`\n      subscription MySubscription {\n        aNewDieWasCreated {\n          die {\n            roll\n            sides\n            color\n          }\n        }\n      }\n    `;\n\n    const { httpLink, enqueuePayloadResult, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const link = errorLink.concat(httpLink);\n    const stream = new ObservableStream(execute(link, { query: subscription }));\n\n    enqueuePayloadResult({\n      data: { aNewDieWasCreated: { die: { color: \"red\", roll: 1, sides: 4 } } },\n    });\n\n    enqueueProtocolErrors([\n      { message: \"Error field\", extensions: { code: \"INTERNAL_SERVER_ERROR\" } },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      data: { aNewDieWasCreated: { die: { color: \"red\", roll: 1, sides: 4 } } },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      extensions: {\n        [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n          {\n            extensions: {\n              code: \"INTERNAL_SERVER_ERROR\",\n            },\n            message: \"Error field\",\n          },\n        ]),\n      } as Record<string, unknown>,\n    });\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({\n        query: subscription,\n        operationName: \"MySubscription\",\n        variables: {},\n      }),\n      result: {\n        extensions: {\n          [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n            {\n              extensions: {\n                code: \"INTERNAL_SERVER_ERROR\",\n              },\n              message: \"Error field\",\n            },\n          ]),\n        },\n      },\n      error: new CombinedProtocolErrors([\n        {\n          message: \"Error field\",\n          extensions: {\n            code: \"INTERNAL_SERVER_ERROR\",\n          },\n        },\n      ]),\n    });\n  });\n\n  it(\"captures errors within links\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const error = new Error(\"app is crashing\");\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable(() => {\n        throw error;\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(error);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n    expect(callback).toHaveBeenLastCalledWith({\n      forward: expect.any(Function),\n      operation: expect.objectContaining({ query, variables: {} }),\n      error,\n    });\n  });\n\n  it(\"completes if no errors\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return of({ data: { foo: { id: 1 } } });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n\n    expect(callback).not.toHaveBeenCalled();\n  });\n\n  it(\"can be unsubscribed\", async () => {\n    const query = gql`\n      {\n        foo {\n          bar\n        }\n      }\n    `;\n\n    const callback = jest.fn();\n    const errorLink = new ErrorLink(callback);\n\n    const mockLink = new ApolloLink(() => {\n      return new Observable((obs) => {\n        setTimeout(() => {\n          obs.next({ data: { foo: { id: 1 } } });\n          obs.complete();\n        }, 5);\n      });\n    });\n\n    const link = errorLink.concat(mockLink);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    stream.unsubscribe();\n\n    await wait(10);\n\n    expect(callback).not.toHaveBeenCalled();\n  });\n});\n\ndescribe(\"support for request retrying\", () => {\n  const QUERY = gql`\n    query Foo {\n      foo {\n        bar\n      }\n    }\n  `;\n  const ERROR_RESPONSE = {\n    errors: [{ message: \"resolver blew up\" }],\n  } satisfies ApolloLink.Result;\n  const GOOD_RESPONSE = {\n    data: { foo: true },\n  } satisfies ApolloLink.Result;\n  const NETWORK_ERROR = new Error(\"some other error\");\n\n  it(\"returns the retried request when forward(operation) is called\", async () => {\n    let timesCalled = 0;\n    const mockHttpLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        if (timesCalled++ === 0) {\n          // simulate the first request being an error\n          observer.next(ERROR_RESPONSE);\n          observer.complete();\n        } else {\n          observer.next(GOOD_RESPONSE);\n          observer.complete();\n        }\n      });\n    });\n\n    const callback = jest\n      .fn()\n      .mockImplementationOnce(({ operation, forward }) => forward(operation));\n\n    const errorLink = new ErrorLink(callback);\n    const link = errorLink.concat(mockHttpLink);\n\n    const stream = new ObservableStream(\n      execute(link, { query: QUERY, context: { bar: true } })\n    );\n\n    await expect(stream).toEmitTypedValue(GOOD_RESPONSE);\n    await expect(stream).toComplete();\n\n    expect(callback).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"supports retrying when the initial request had networkError\", async () => {\n    let timesCalled = 0;\n    const mockHttpLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        if (timesCalled++ === 0) {\n          // simulate the first request being an error\n          observer.error(NETWORK_ERROR);\n        } else {\n          observer.next(GOOD_RESPONSE);\n          observer.complete();\n        }\n      });\n    });\n\n    const callback = jest\n      .fn()\n      .mockImplementationOnce(({ forward, operation }) => forward(operation));\n\n    const errorLink = new ErrorLink(callback);\n    const link = errorLink.concat(mockHttpLink);\n\n    const stream = new ObservableStream(\n      execute(link, { query: QUERY, context: { bar: true } })\n    );\n\n    await expect(stream).toEmitTypedValue(GOOD_RESPONSE);\n    await expect(stream).toComplete();\n\n    expect(callback).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"supports retrying when the initial request had protocol errors\", async () => {\n    const { httpLink, enqueuePayloadResult, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n\n    const callback = jest\n      .fn()\n      .mockImplementationOnce(({ forward, operation }) => forward(operation));\n\n    const errorLink = new ErrorLink(callback);\n\n    const link = errorLink.concat(httpLink);\n    const stream = new ObservableStream(\n      execute(link, {\n        query: gql`\n          subscription Foo {\n            foo {\n              bar\n            }\n          }\n        `,\n      })\n    );\n\n    enqueuePayloadResult({ data: { foo: { bar: true } } });\n\n    await expect(stream).toEmitTypedValue({ data: { foo: { bar: true } } });\n\n    enqueueProtocolErrors([\n      {\n        message: \"cannot read message from websocket\",\n        extensions: {\n          code: \"WEBSOCKET_MESSAGE_ERROR\",\n        },\n      },\n    ]);\n\n    enqueuePayloadResult({ data: { foo: { bar: true } } }, false);\n\n    // Ensure the error result is not emitted but rather the retried result\n    await expect(stream).toEmitTypedValue({ data: { foo: { bar: true } } });\n    await expect(stream).toComplete();\n\n    expect(callback).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"returns errors from retried requests\", async () => {\n    let timesCalled = 0;\n    const mockHttpLink = new ApolloLink(() => {\n      return new Observable((observer) => {\n        if (timesCalled++ === 0) {\n          // simulate the first request being an error\n          observer.next(ERROR_RESPONSE);\n          observer.complete();\n        } else {\n          observer.error(NETWORK_ERROR);\n        }\n      });\n    });\n\n    const callback = jest\n      .fn()\n      .mockImplementationOnce(({ forward, operation }) => forward(operation));\n\n    const errorLink = new ErrorLink(callback);\n    const link = errorLink.concat(mockHttpLink);\n\n    const stream = new ObservableStream(\n      execute(link, { query: QUERY, context: { bar: true } })\n    );\n\n    await expect(stream).toEmitError(NETWORK_ERROR);\n\n    expect(callback).toHaveBeenCalledTimes(1);\n  });\n});\n"
  },
  {
    "path": "src/link/error/index.ts",
    "content": "import type { Subscription } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nimport type { ErrorLike } from \"@apollo/client\";\nimport {\n  CombinedGraphQLErrors,\n  graphQLResultHasProtocolErrors,\n  PROTOCOL_ERRORS_SYMBOL,\n  toErrorLike,\n} from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\n\nexport declare namespace ErrorLink {\n  // Using a different namespace name to avoid clash with\n  // `ApolloLink.DocumentationTypes`\n  export namespace ErrorLinkDocumentationTypes {\n    /**\n     * Callback that is called by `ErrorLink` when an error occurs from a\n     * downstream link in link chain.\n     *\n     * @param options - The options object provided by `ErrorLink` to the error\n     * handler when an error occurs.\n     */\n    export function ErrorHandler(\n      options: ErrorHandlerOptions\n    ): Observable<ApolloLink.Result> | void;\n  }\n\n  /** {@inheritDoc @apollo/client/link/error!ErrorLink.ErrorLinkDocumentationTypes.ErrorHandler:function(1)} */\n  export interface ErrorHandler {\n    (options: ErrorHandlerOptions): Observable<ApolloLink.Result> | void;\n  }\n\n  /**\n   * The object provided to the `ErrorHandler` callback function.\n   */\n  export interface ErrorHandlerOptions {\n    /**\n     * The error that occurred during the operation execution. This can be a\n     * `CombinedGraphQLErrors` instance (for GraphQL errors) or another error\n     * type (for network errors).\n     *\n     * Use `CombinedGraphQLErrors.is(error)` to check if it's a GraphQL error with an `errors` array.\n     */\n    error: ErrorLike;\n    /**\n     * The raw GraphQL result from the server (if available), which may include\n     * partial data alongside errors.\n     */\n    result?: ApolloLink.Result;\n\n    /** The details of the GraphQL operation that produced an error. */\n    operation: ApolloLink.Operation;\n\n    /**\n     * A function that calls the next link in the link chain. Calling\n     * `return forward(operation)` in your `ErrorLink` callback\n     * [retries the operation](../../data/error-handling#retrying-operations), returning a new observable for the\n     * upstream link to subscribe to.\n     */\n    forward: ApolloLink.ForwardFunction;\n  }\n}\n\n/**\n * @deprecated\n * Use `ErrorLink` from `@apollo/client/link/error` instead.\n */\nexport function onError(errorHandler: ErrorLink.ErrorHandler) {\n  return new ErrorLink(errorHandler);\n}\n\n/**\n * Use the `ErrorLink` to perform custom logic when a [GraphQL or network error](https://apollographql.com/docs/react/data/error-handling)\n * occurs.\n *\n * @remarks\n *\n * This link is used after the GraphQL operation completes and execution is\n * moving back up your [link chain](https://apollographql.com/docs/react/api/link/introduction#handling-a-response). The `errorHandler` function should\n * not return a value unless you want to [retry the operation](https://apollographql.com/docs/react/data/error-handling#retrying-operations).\n *\n * For more information on the types of errors that might be encountered, see\n * the guide on [error handling](https://apollographql.com/docs/react/data/error-handling).\n *\n * @example\n *\n * ```ts\n * import { ErrorLink } from \"@apollo/client/link/error\";\n * import {\n *   CombinedGraphQLErrors,\n *   CombinedProtocolErrors,\n * } from \"@apollo/client/errors\";\n *\n * // Log any GraphQL errors, protocol errors, or network error that occurred\n * const errorLink = new ErrorLink(({ error, operation }) => {\n *   if (CombinedGraphQLErrors.is(error)) {\n *     error.errors.forEach(({ message, locations, path }) =>\n *       console.log(\n *         `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`\n *       )\n *     );\n *   } else if (CombinedProtocolErrors.is(error)) {\n *     error.errors.forEach(({ message, extensions }) =>\n *       console.log(\n *         `[Protocol error]: Message: ${message}, Extensions: ${JSON.stringify(\n *           extensions\n *         )}`\n *       )\n *     );\n *   } else {\n *     console.error(`[Network error]: ${error}`);\n *   }\n * });\n * ```\n */\nexport class ErrorLink extends ApolloLink {\n  constructor(errorHandler: ErrorLink.ErrorHandler) {\n    super((operation, forward) => {\n      return new Observable((observer) => {\n        let sub: Subscription | undefined;\n        let retriedSub: Subscription | undefined;\n        let retriedResult: ReturnType<ErrorLink.ErrorHandler>;\n\n        try {\n          sub = forward(operation).subscribe({\n            next: (result) => {\n              const handler =\n                operation.client[\"queryManager\"].incrementalHandler;\n              const errors =\n                handler.isIncrementalResult(result) ?\n                  handler.extractErrors(result)\n                : result.errors;\n              if (errors) {\n                retriedResult = errorHandler({\n                  error: new CombinedGraphQLErrors(result, errors),\n                  result,\n                  operation,\n                  forward,\n                });\n              } else if (graphQLResultHasProtocolErrors(result)) {\n                retriedResult = errorHandler({\n                  error: result.extensions[PROTOCOL_ERRORS_SYMBOL],\n                  result,\n                  operation,\n                  forward,\n                });\n              }\n\n              retriedSub = retriedResult?.subscribe(observer);\n\n              if (!retriedSub) {\n                observer.next(result);\n              }\n            },\n            error: (error) => {\n              retriedResult = errorHandler({\n                operation,\n                error: toErrorLike(error),\n                forward,\n              });\n              retriedSub = retriedResult?.subscribe(observer);\n\n              if (!retriedSub) {\n                observer.error(error);\n              }\n            },\n            complete: () => {\n              // disable the previous sub from calling complete on observable\n              // if retry is in flight.\n              if (!retriedResult) {\n                observer.complete();\n              }\n            },\n          });\n        } catch (e) {\n          errorHandler({ error: toErrorLike(e), operation, forward });\n          observer.error(e);\n        }\n\n        return () => {\n          if (sub) sub.unsubscribe();\n          if (retriedSub) retriedSub.unsubscribe();\n        };\n      });\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/http/BaseHttpLink.ts",
    "content": "import type { ASTNode, print } from \"graphql\";\nimport { Observable } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { filterOperationVariables } from \"@apollo/client/link/utils\";\nimport {\n  isMutationOperation,\n  isSubscriptionOperation,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { compact } from \"@apollo/client/utilities/internal\";\nimport { maybe } from \"@apollo/client/utilities/internal/globals\";\n\nimport { checkFetcher } from \"./checkFetcher.js\";\nimport {\n  parseAndCheckHttpResponse,\n  readMultipartBody,\n} from \"./parseAndCheckHttpResponse.js\";\nimport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\nimport {\n  defaultPrinter,\n  fallbackHttpConfig,\n  selectHttpOptionsAndBodyInternal,\n} from \"./selectHttpOptionsAndBody.js\";\nimport { selectURI } from \"./selectURI.js\";\n\nconst backupFetch = maybe(() => fetch);\nfunction noop() {}\n\nexport declare namespace BaseHttpLink {\n  /**\n   * Options passed to `BaseHttpLink` through [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context). Previous\n   * non-terminating links in the link chain also can set these values to\n   * customize the behavior of `BaseHttpLink` for each operation.\n   *\n   * > [!NOTE]\n   * > Some of these values can also be provided to the `HttpLink` constructor.\n   * > If a value is provided to both, the value in `context` takes precedence.\n   */\n  interface ContextOptions {\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#uri:member} */\n    uri?: string | BaseHttpLink.UriFunction;\n\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#headers:member} */\n    headers?: Record<string, string>;\n\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#credentials:member} */\n    credentials?: RequestCredentials;\n\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#fetchOptions:member} */\n    fetchOptions?: RequestInit;\n\n    /**\n     * An object that configures advanced functionality, such as support for\n     * persisted queries.\n     */\n    http?: BaseHttpLink.HttpOptions;\n  }\n\n  /**\n   * Options passed to `BaseHttpLink` through the `http` property of a request\n   * context.\n   */\n  export interface HttpOptions {\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#includeExtensions:member} */\n    includeExtensions?: boolean;\n\n    /**\n     * If `false`, the GraphQL query string is not included in the request. Set\n     * this option if you're sending a request that uses a [persisted query](https://www.apollographql.com/docs/react/api/link/persisted-queries/).\n     *\n     * @defaultValue `true`\n     */\n    includeQuery?: boolean;\n\n    /** {@inheritDoc @apollo/client/link/http!BaseHttpLink.Shared.Options#preserveHeaderCase:member} */\n    preserveHeaderCase?: boolean;\n\n    /**\n     * A list of additional `accept` headers to include in the request,\n     * as defined in https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2\n     *\n     * @example\n     *\n     * ```json\n     * [\"application/custom+json;q=1.0\"]\n     * ```\n     */\n    accept?: string[];\n  }\n\n  export namespace Shared {\n    /** These options are shared between `BaseHttpLink` and `BaseBatchHttpLink` */\n    export interface Options {\n      /**\n       * The URL of the GraphQL endpoint to send requests to. Can also be a\n       * function that accepts an `ApolloLink.Operation` object and returns the\n       * string URL to use for that operation.\n       *\n       * @defaultValue \"/graphql\"\n       */\n      uri?: string | BaseHttpLink.UriFunction;\n\n      /**\n       * If `true`, includes the `extensions` field in operations sent to your\n       * GraphQL endpoint.\n       *\n       * @defaultValue true\n       */\n      includeExtensions?: boolean;\n\n      /**\n       * A function to use instead of calling the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) directly\n       * when sending HTTP requests to your GraphQL endpoint. The function must\n       * conform to the signature of `fetch`.\n       *\n       * By default, the Fetch API is used unless it isn't available in your\n       * runtime environment.\n       *\n       * See [Customizing `fetch`](https://apollographql.com/docs/react/api/link/introduction#customizing-fetch).\n       */\n      fetch?: typeof fetch;\n\n      /**\n       * An object representing headers to include in every HTTP request.\n       *\n       * @example\n       *\n       * ```json\n       * {\n       *   \"Authorization\": \"Bearer 1234\"\n       * }\n       * ```\n       */\n      headers?: Record<string, string>;\n\n      /**\n       * If `true`, header names won't be automatically normalized to lowercase.\n       * This allows for non-http-spec-compliant servers that might expect\n       * capitalized header names.\n       *\n       * @defaultValue false\n       */\n      preserveHeaderCase?: boolean;\n\n      /**\n       * The credentials policy to use for each `fetch` call.\n       */\n      credentials?: RequestCredentials;\n\n      /**\n       * Any overrides of the fetch options argument to pass to the fetch call.\n       *\n       * An object containing options to use for each call to `fetch`. If a\n       * particular option is not included in this object, the default value of\n       * that option is used.\n       *\n       * > [!NOTE]\n       * > If you set `fetchOptions.method` to `GET`, `HttpLink` follows [standard\n       * > GraphQL HTTP GET encoding](http://graphql.org/learn/serving-over-http/#get-request).\n       *\n       * See [available options](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)\n       */\n      fetchOptions?: RequestInit;\n\n      /**\n       * If `true`, unused variables from the operation will not be stripped from\n       * the request and will instead be sent to the GraphQL endpoint.\n       *\n       * @remarks\n       * Unused variables are likely to trigger server-side validation errors,\n       * per https://spec.graphql.org/draft/#sec-All-Variables-Used.\n       * `includeUnusedVariables` can be useful if your server deviates\n       * from the GraphQL specification by not strictly enforcing that rule.\n       *\n       * @defaultValue false\n       */\n      includeUnusedVariables?: boolean;\n      /**\n       * A function to use when transforming a GraphQL document into a string. It\n       * accepts an `ASTNode` (typically a `DocumentNode`) and the original `print`\n       * function as arguments, and is expected to return a string. This option\n       * enables you to, for example, use `stripIgnoredCharacters` to remove\n       * whitespace from queries.\n       *\n       * By default the [GraphQL `print` function](https://graphql.org/graphql-js/language/#print) is used.\n       *\n       * @example\n       *\n       * ```ts\n       * import { stripIgnoredCharacters } from \"graphql\";\n       *\n       * const httpLink = new HttpLink({\n       *   uri: \"/graphql\",\n       *   print: (ast, originalPrint) => stripIgnoredCharacters(originalPrint(ast)),\n       * });\n       * ```\n       */\n      print?: BaseHttpLink.Printer;\n    }\n  }\n\n  /**\n   * Options provided to the `BaseHttpLink` constructor.\n   *\n   * > [!NOTE]\n   * > Some of these options are also available to override in [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context).\n   * > Context options override the options passed to the constructor. Treat\n   * > these options as default values that are used when the request context\n   * > does not override the value.\n   */\n  interface Options extends Shared.Options {\n    /**\n     * If `true`, the link uses an HTTP `GET` request when sending query\n     * operations to your GraphQL endpoint. Mutation operations continue to use\n     * `POST` requests. If you want all operations to use `GET` requests,\n     * set `fetchOptions.method` instead.\n     *\n     * @defaultValue false\n     */\n    useGETForQueries?: boolean;\n  }\n\n  interface Body {\n    query?: string;\n    operationName?: string;\n    variables?: Record<string, any>;\n    extensions?: Record<string, any>;\n  }\n\n  type Printer = (node: ASTNode, originalPrint: typeof print) => string;\n  type UriFunction = (operation: ApolloLink.Operation) => string;\n}\n\n/**\n * `BaseHttpLink` is a terminating link that sends a GraphQL operation to a\n * remote endpoint over HTTP. It serves as a base link to `HttpLink`.\n *\n * @remarks\n *\n * `BaseHttpLink` supports both POST and GET requests, and you can configure\n * HTTP options on a per-operation basis. You can use these options for\n * authentication, persisted queries, dynamic URIs, and other granular updates.\n *\n * > [!NOTE]\n * > Prefer using `HttpLink` over `BaseHttpLink`. Use `BaseHttpLink` when you\n * > need to disable client awareness features and would like to tree-shake\n * > the implementation of `ClientAwarenessLink` out of your app bundle.\n *\n * @example\n *\n * ```ts\n * import { BaseHttpLink } from \"@apollo/client/link/http\";\n *\n * const link = new BaseHttpLink({\n *   uri: \"http://localhost:4000/graphql\",\n *   headers: {\n *     authorization: `Bearer ${token}`,\n *   },\n * });\n * ```\n */\nexport class BaseHttpLink extends ApolloLink {\n  constructor(options: BaseHttpLink.Options = {}) {\n    let {\n      uri = \"/graphql\",\n      // use default global fetch if nothing passed in\n      fetch: preferredFetch,\n      print = defaultPrinter,\n      includeExtensions,\n      preserveHeaderCase,\n      useGETForQueries,\n      includeUnusedVariables = false,\n      ...requestOptions\n    } = options;\n\n    if (__DEV__) {\n      // Make sure at least one of preferredFetch, window.fetch, or backupFetch is\n      // defined, so requests won't fail at runtime.\n      checkFetcher(preferredFetch || backupFetch);\n    }\n\n    const linkConfig = {\n      http: compact({ includeExtensions, preserveHeaderCase }),\n      options: requestOptions.fetchOptions,\n      credentials: requestOptions.credentials,\n      headers: requestOptions.headers,\n    };\n\n    super((operation) => {\n      let chosenURI = selectURI(operation, uri);\n\n      const context = operation.getContext();\n\n      const http = { ...context.http };\n      if (isSubscriptionOperation(operation.query)) {\n        http.accept = [\n          \"multipart/mixed;boundary=graphql;subscriptionSpec=1.0\",\n          ...(http.accept || []),\n        ];\n      }\n\n      const contextConfig = {\n        http,\n        options: context.fetchOptions,\n        credentials: context.credentials,\n        headers: context.headers,\n      };\n\n      //uses fallback, link, and then context to build options\n      const { options, body } = selectHttpOptionsAndBodyInternal(\n        operation,\n        print,\n        fallbackHttpConfig,\n        linkConfig,\n        contextConfig\n      );\n\n      if (body.variables && !includeUnusedVariables) {\n        body.variables = filterOperationVariables(\n          body.variables,\n          operation.query\n        );\n      }\n\n      let controller: AbortController | undefined = new AbortController();\n      let cleanupController = () => {\n        controller = undefined;\n      };\n      if (options.signal) {\n        const externalSignal: AbortSignal = options.signal;\n        // in an ideal world we could use `AbortSignal.any` here, but\n        // React Native uses https://github.com/mysticatea/abort-controller as\n        // a polyfill for `AbortController`, and it does not support `AbortSignal.any`.\n\n        const listener = () => {\n          controller?.abort(externalSignal.reason);\n        };\n        externalSignal.addEventListener(\"abort\", listener, { once: true });\n        cleanupController = () => {\n          controller?.signal.removeEventListener(\"abort\", cleanupController);\n          controller = undefined;\n          // on cleanup, we need to stop listening to `options.signal` to avoid memory leaks\n          externalSignal.removeEventListener(\"abort\", listener);\n          cleanupController = noop;\n        };\n        // react native also does not support the addEventListener `signal` option\n        // so we have to simulate that ourself\n        controller.signal.addEventListener(\"abort\", cleanupController, {\n          once: true,\n        });\n      }\n      options.signal = controller.signal;\n\n      if (useGETForQueries && !isMutationOperation(operation.query)) {\n        options.method = \"GET\";\n      }\n\n      return new Observable((observer) => {\n        if (options.method === \"GET\") {\n          const { newURI, parseError } = rewriteURIForGET(chosenURI, body);\n          if (parseError) {\n            throw parseError;\n          }\n          chosenURI = newURI;\n        } else {\n          options.body = JSON.stringify(body);\n        }\n        // Prefer linkOptions.fetch (preferredFetch) if provided, and otherwise\n        // fall back to the *current* global window.fetch function (see issue\n        // #7832), or (if all else fails) the backupFetch function we saved when\n        // this module was first evaluated. This last option protects against the\n        // removal of window.fetch, which is unlikely but not impossible.\n        const currentFetch =\n          preferredFetch || maybe(() => fetch) || backupFetch;\n\n        const observerNext = observer.next.bind(observer);\n        currentFetch!(chosenURI, options)\n          .then((response) => {\n            operation.setContext({ response });\n            const ctype = response.headers?.get(\"content-type\");\n\n            if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n              return readMultipartBody(response, observerNext);\n            } else {\n              return parseAndCheckHttpResponse(operation)(response).then(\n                observerNext\n              );\n            }\n          })\n          .then(() => {\n            cleanupController();\n            observer.complete();\n          })\n          .catch((err) => {\n            cleanupController();\n            observer.error(err);\n          });\n\n        return () => {\n          // XXX support canceling this request\n          // https://developers.google.com/web/updates/2017/09/abortable-fetch\n          if (controller) controller.abort();\n        };\n      });\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/http/HttpLink.ts",
    "content": "import { ApolloLink } from \"@apollo/client/link\";\nimport { ClientAwarenessLink } from \"@apollo/client/link/client-awareness\";\n\nimport { BaseHttpLink } from \"./BaseHttpLink.js\";\n\nexport declare namespace HttpLink {\n  /**\n   * Options passed to `HttpLink` through [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context). Previous\n   * non-terminating links in the link chain also can set these values to\n   * customize the behavior of `HttpLink` for each operation.\n   *\n   * > [!NOTE]\n   * > Some of these values can also be provided to the `HttpLink` constructor.\n   * > If a value is provided to both, the value in `context` takes precedence.\n   */\n  interface ContextOptions\n    extends BaseHttpLink.ContextOptions,\n      ClientAwarenessLink.ContextOptions {}\n\n  /**\n   * Options provided to the `HttpLink` constructor.\n   *\n   * > [!NOTE]\n   * > Some of these options are also available to override in [request context](https://apollographql.com/docs/react/api/link/introduction#managing-context).\n   * > Context options override the options passed to the constructor. Treat\n   * > these options as default values that are used when the request context\n   * > does not override the value.\n   */\n  interface Options extends BaseHttpLink.Options, ClientAwarenessLink.Options {}\n}\n\n/**\n * `HttpLink` is a terminating link that sends a GraphQL operation to a remote\n * endpoint over HTTP. It combines the functionality of `BaseHttpLink` and\n * `ClientAwarenessLink` into a single link.\n *\n * @remarks\n *\n * `HttpLink` supports both POST and GET requests, and you can configure HTTP\n * options on a per-operation basis. You can use these options for\n * authentication, persisted queries, dynamic URIs, and other granular updates.\n *\n * @example\n *\n * ```ts\n * import { HttpLink } from \"@apollo/client\";\n *\n * const link = new HttpLink({\n *   uri: \"http://localhost:4000/graphql\",\n *   // Additional options\n * });\n * ```\n */\nexport class HttpLink extends ApolloLink {\n  constructor(options: HttpLink.Options = {}) {\n    const { left, right, request } = ApolloLink.from([\n      new ClientAwarenessLink(options),\n      new BaseHttpLink(options),\n    ]);\n    super(request);\n    Object.assign(this, { left, right });\n  }\n}\n\n/**\n * @deprecated\n * Use `HttpLink` from `@apollo/client/link/http` instead.\n */\nexport const createHttpLink = (options: HttpLink.Options = {}) =>\n  new HttpLink(options);\n"
  },
  {
    "path": "src/link/http/__tests__/HttpLink.ts",
    "content": "import { TextDecoder } from \"util\";\n\nimport fetchMock from \"fetch-mock\";\nimport type { ASTNode } from \"graphql\";\nimport { print, stripIgnoredCharacters } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Observer, Subscription } from \"rxjs\";\nimport { map, Observable, Subject, tap } from \"rxjs\";\nimport type { ReadableStreamLike } from \"web-streams-polyfill\";\nimport { ReadableStream as RS } from \"web-streams-polyfill\";\n\nimport {\n  ApolloClient,\n  InMemoryCache,\n  ServerError,\n  version,\n} from \"@apollo/client\";\nimport {\n  CombinedProtocolErrors,\n  PROTOCOL_ERRORS_SYMBOL,\n  ServerParseError,\n} from \"@apollo/client/errors\";\nimport {\n  Defer20220824Handler,\n  GraphQL17Alpha9Handler,\n} from \"@apollo/client/incremental\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { BaseHttpLink, HttpLink } from \"@apollo/client/link/http\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\nimport { voidFetchDuringEachTest } from \"./helpers.js\";\n\n// Work around an inconsistency between `web-streams-polyfill` and `undici` typings\nconst Response = globalThis.Response as typeof globalThis.Response;\nconst ReadableStream = RS as any as typeof globalThis.ReadableStream & {\n  from<R>(\n    asyncIterable: Iterable<R> | AsyncIterable<R> | ReadableStreamLike<R>\n  ): globalThis.ReadableStream<R>;\n};\n\nconst sampleQuery = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\nconst sampleMutation = gql`\n  mutation SampleMutation {\n    stub {\n      id\n    }\n  }\n`;\n\nconst sampleDeferredQuery = gql`\n  query SampleDeferredQuery {\n    stub {\n      id\n      ... on Stub @defer {\n        name\n      }\n    }\n  }\n`;\n\nconst sampleStreamedQuery = gql`\n  query SampleDeferredQuery {\n    stubs @stream {\n      id\n      name\n    }\n  }\n`;\n\nconst sampleQueryCustomDirective = gql`\n  query SampleDeferredQuery {\n    stub {\n      id\n      ... on Stub @deferCustomDirective {\n        name\n      }\n    }\n  }\n`;\n\nconst sampleSubscription = gql`\n  subscription MySubscription {\n    aNewDieWasCreated {\n      die {\n        roll\n        sides\n        color\n      }\n    }\n  }\n`;\n\nconst sampleSubscriptionWithDefer = gql`\n  subscription MySubscription {\n    aNewDieWasCreated {\n      die {\n        roll\n        sides\n        ... on Stub @defer {\n          color\n        }\n      }\n    }\n  }\n`;\n\nfunction convertBatchedBody(body: BodyInit | null | undefined) {\n  return JSON.parse(body as string);\n}\n\ndescribe(\"HttpLink\", () => {\n  describe(\"General\", () => {\n    const data = { data: { hello: \"world\" } };\n    const data2 = { data: { hello: \"everyone\" } };\n    const mockError = { throws: new TypeError(\"mock me\") };\n    let subscriber: Observer<any>;\n    const subscriptions = new Set<Subscription>();\n\n    beforeEach(() => {\n      fetchMock.restore();\n      fetchMock.post(\"begin:/data2\", Promise.resolve(data2));\n      fetchMock.post(\"begin:/data\", Promise.resolve(data));\n      fetchMock.post(\"begin:/error\", mockError);\n      fetchMock.post(\"begin:/apollo\", Promise.resolve(data));\n\n      fetchMock.get(\"begin:/data\", Promise.resolve(data));\n      fetchMock.get(\"begin:/data2\", Promise.resolve(data2));\n\n      const next = jest.fn();\n      const error = jest.fn();\n      const complete = jest.fn();\n\n      subscriber = {\n        next,\n        error,\n        complete,\n      };\n\n      subscriptions.clear();\n    });\n\n    afterEach(() => {\n      fetchMock.restore();\n      if (subscriptions.size) {\n        // Tests within this describe block can add subscriptions to this Set\n        // that they want to be canceled/unsubscribed after the test finishes.\n        subscriptions.forEach((sub) => sub.unsubscribe());\n      }\n    });\n\n    it(\"does not need any constructor arguments\", () => {\n      expect(() => new HttpLink()).not.toThrow();\n    });\n\n    it(\"constructor creates link that can call next and then complete\", async () => {\n      const link = new HttpLink({ uri: \"/data\" });\n      const observable = execute(link, {\n        query: sampleQuery,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n    });\n\n    it(\"supports using a GET request\", async () => {\n      const variables = { params: \"stub\" };\n      const extensions = { myExtension: \"foo\" };\n\n      const link = new HttpLink({\n        uri: \"/data\",\n        fetchOptions: { method: \"GET\" },\n        includeExtensions: true,\n        includeUnusedVariables: true,\n      });\n\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n        extensions,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n\n      expect(body).toBeUndefined();\n      expect(method).toBe(\"GET\");\n\n      expect(uri).toBe(\n        `/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D&operationName=SampleQuery&variables=%7B%22params%22%3A%22stub%22%7D&extensions=%7B%22clientLibrary%22%3A%7B%22name%22%3A%22%40apollo%2Fclient%22%2C%22version%22%3A%22${version}%22%7D%2C%22myExtension%22%3A%22foo%22%7D`\n      );\n    });\n\n    it(\"supports using a GET request with search\", async () => {\n      const variables = { params: \"stub\" };\n\n      const link = new HttpLink({\n        uri: \"/data?foo=bar\",\n        fetchOptions: { method: \"GET\" },\n      });\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n\n      expect(body).toBeUndefined();\n      expect(method).toBe(\"GET\");\n      expect(uri).toBe(\n        `/data?foo=bar&query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D&operationName=SampleQuery&variables=%7B%7D&extensions=%7B%22clientLibrary%22%3A%7B%22name%22%3A%22%40apollo%2Fclient%22%2C%22version%22%3A%22${version}%22%7D%7D`\n      );\n    });\n\n    it(\"supports using a GET request on the context\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"/data\",\n      });\n\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n        context: {\n          fetchOptions: { method: \"GET\" },\n        },\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n\n      expect(body).toBeUndefined();\n      expect(method).toBe(\"GET\");\n      expect(uri).toBe(\n        `/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D&operationName=SampleQuery&variables=%7B%7D&extensions=%7B%22clientLibrary%22%3A%7B%22name%22%3A%22%40apollo%2Fclient%22%2C%22version%22%3A%22${version}%22%7D%7D`\n      );\n    });\n\n    it(\"uses GET with useGETForQueries\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"/data\",\n        useGETForQueries: true,\n      });\n\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n      expect(body).toBeUndefined();\n      expect(method).toBe(\"GET\");\n      expect(uri).toBe(\n        `/data?query=query%20SampleQuery%20%7B%0A%20%20stub%20%7B%0A%20%20%20%20id%0A%20%20%7D%0A%7D&operationName=SampleQuery&variables=%7B%7D&extensions=%7B%22clientLibrary%22%3A%7B%22name%22%3A%22%40apollo%2Fclient%22%2C%22version%22%3A%22${version}%22%7D%7D`\n      );\n    });\n\n    it(\"uses POST for mutations with useGETForQueries\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"/data\",\n        useGETForQueries: true,\n      });\n\n      const observable = execute(link, {\n        query: sampleMutation,\n        variables,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n\n      expect(body).toBeDefined();\n      expect(method).toBe(\"POST\");\n      expect(uri).toBe(\"/data\");\n    });\n\n    it(\"strips unused variables, respecting nested fragments\", async () => {\n      const link = new HttpLink({ uri: \"/data\" });\n\n      const query = gql`\n        query PEOPLE($declaredAndUsed: String, $declaredButUnused: Int) {\n          people(surprise: $undeclared, noSurprise: $declaredAndUsed) {\n            ... on Doctor {\n              specialty(var: $usedByInlineFragment)\n            }\n            ...LawyerFragment\n          }\n        }\n        fragment LawyerFragment on Lawyer {\n          caseCount(var: $usedByNamedFragment)\n        }\n      `;\n\n      const variables = {\n        unused: \"strip\",\n        declaredButUnused: \"strip\",\n        declaredAndUsed: \"keep\",\n        undeclared: \"keep\",\n        usedByInlineFragment: \"keep\",\n        usedByNamedFragment: \"keep\",\n      };\n\n      const observable = execute(link, {\n        query,\n        variables,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [uri, options] = fetchMock.lastCall()!;\n      const { method, body } = options!;\n\n      expect(JSON.parse(body as string)).toEqual({\n        operationName: \"PEOPLE\",\n        query: print(query),\n        variables: {\n          declaredAndUsed: \"keep\",\n          undeclared: \"keep\",\n          usedByInlineFragment: \"keep\",\n          usedByNamedFragment: \"keep\",\n        },\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n        },\n      });\n      expect(method).toBe(\"POST\");\n      expect(uri).toBe(\"/data\");\n    });\n\n    it(\"should not add empty client awareness settings to request headers\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"/data\",\n      });\n\n      const hasOwn = Object.prototype.hasOwnProperty;\n      const clientAwareness = {};\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n        context: {\n          clientAwareness,\n        },\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      const [, options] = fetchMock.lastCall()!;\n      const { headers } = options as any;\n      expect(hasOwn.call(headers, \"apollographql-client-name\")).toBe(false);\n      expect(hasOwn.call(headers, \"apollographql-client-version\")).toBe(false);\n    });\n\n    it(\"throws for GET if the variables can't be stringified\", async () => {\n      const link = new HttpLink({\n        uri: \"/data\",\n        useGETForQueries: true,\n        includeUnusedVariables: true,\n      });\n\n      let b;\n      const a: any = { b };\n      b = { a };\n      a.b = b;\n      const variables = {\n        a,\n        b,\n      };\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      const error = await stream.takeError();\n\n      expect(error.message).toMatch(/Converting circular structure to JSON/);\n    });\n\n    it(\"throws for GET if the extensions can't be stringified\", async () => {\n      const link = new HttpLink({\n        uri: \"/data\",\n        useGETForQueries: true,\n        includeExtensions: true,\n      });\n\n      let b;\n      const a: any = { b };\n      b = { a };\n      a.b = b;\n      const extensions = {\n        a,\n        b,\n      };\n      const observable = execute(link, { query: sampleQuery, extensions });\n      const stream = new ObservableStream(observable);\n\n      const error = await stream.takeError();\n\n      expect(error.message).toMatch(/Converting circular structure to JSON/);\n    });\n\n    it(\"does not need any constructor arguments\", () => {\n      expect(() => new HttpLink()).not.toThrow();\n    });\n\n    it(\"calls next and then complete\", async () => {\n      const link = new HttpLink({ uri: \"data\" });\n      const observable = execute(link, {\n        query: sampleQuery,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n    });\n\n    it(\"calls error when fetch fails\", async () => {\n      const link = new HttpLink({ uri: \"error\" });\n      const observable = execute(link, {\n        query: sampleQuery,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(mockError.throws);\n    });\n\n    it(\"calls error when fetch fails\", async () => {\n      const link = new HttpLink({ uri: \"error\" });\n      const observable = execute(link, {\n        query: sampleMutation,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(mockError.throws);\n    });\n\n    it(\"unsubscribes without calling subscriber\", async () => {\n      const link = new HttpLink({ uri: \"data\" });\n      const observable = execute(link, {\n        query: sampleQuery,\n      });\n      const subscription = observable.subscribe(\n        () => {\n          throw new Error(\"next should not have been called\");\n        },\n        (error) => {\n          throw error;\n        },\n        () => {\n          throw \"complete should not have been called\";\n        }\n      );\n      subscription.unsubscribe();\n\n      expect(subscription.closed).toBe(true);\n\n      // Ensure none of the callbacks throw after our assertion\n      await wait(10);\n    });\n\n    const verifyRequest = async (\n      link: ApolloLink,\n      includeExtensions: boolean\n    ) => {\n      const context = { info: \"stub\" };\n      const variables = { params: \"stub\" };\n\n      const observable = execute(link, {\n        query: sampleMutation,\n        context,\n        variables,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n\n      let body = convertBatchedBody(fetchMock.lastCall()![1]!.body);\n      expect(body.query).toBe(print(sampleMutation));\n      expect(body.variables).toEqual({});\n      expect(body.context).not.toBeDefined();\n      if (includeExtensions) {\n        expect(body.extensions).toBeDefined();\n      } else {\n        expect(body.extensions).not.toBeDefined();\n      }\n    };\n\n    it(\"passes all arguments to multiple fetch body including extensions\", async () => {\n      const link = new HttpLink({ uri: \"data\", includeExtensions: true });\n\n      await verifyRequest(link, true);\n      await verifyRequest(link, true);\n    });\n\n    it(\"passes all arguments to multiple fetch body excluding extensions\", async () => {\n      const link = new HttpLink({ uri: \"data\", includeExtensions: false });\n\n      await verifyRequest(link, false);\n      await verifyRequest(link, false);\n    });\n\n    it(\"calls multiple subscribers\", async () => {\n      const link = new HttpLink({ uri: \"data\" });\n      const context = { info: \"stub\" };\n      const variables = { params: \"stub\" };\n\n      const observable = execute(link, {\n        query: sampleMutation,\n        context,\n        variables,\n      });\n      observable.subscribe(subscriber);\n      observable.subscribe(subscriber);\n\n      await wait(50);\n\n      expect(subscriber.next).toHaveBeenCalledTimes(2);\n      expect(subscriber.complete).toHaveBeenCalledTimes(2);\n      expect(subscriber.error).not.toHaveBeenCalled();\n      expect(fetchMock.calls().length).toBe(2);\n    });\n\n    it(\"calls remaining subscribers after unsubscribe\", async () => {\n      const link = new HttpLink({ uri: \"data\" });\n      const context = { info: \"stub\" };\n      const variables = { params: \"stub\" };\n\n      const observable = execute(link, {\n        query: sampleMutation,\n        context,\n        variables,\n      });\n\n      observable.subscribe(subscriber);\n\n      await wait(10);\n\n      const subscription = observable.subscribe(subscriber);\n      subscription.unsubscribe();\n\n      await wait(50);\n\n      expect(subscriber.next).toHaveBeenCalledTimes(1);\n      expect(subscriber.complete).toHaveBeenCalledTimes(1);\n      expect(subscriber.error).not.toHaveBeenCalled();\n    });\n\n    it(\"allows for dynamic endpoint setting\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({ uri: \"data\" });\n\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n        context: { uri: \"data2\" },\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data2);\n    });\n\n    it(\"adds headers to the request from the context\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          headers: { authorization: \"1234\" },\n        });\n        return forward(operation).pipe(\n          map((result) => {\n            const { headers } = operation.getContext();\n            expect(headers).toBeDefined();\n\n            return result;\n          })\n        );\n      });\n      const link = middleware.concat(new HttpLink({ uri: \"data\" }));\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const headers = fetchMock.lastCall()![1]!.headers as any;\n\n      expect(headers.authorization).toBe(\"1234\");\n      expect(headers[\"content-type\"]).toBe(\"application/json\");\n      expect(headers.accept).toBe(\n        \"application/graphql-response+json,application/json;q=0.9\"\n      );\n    });\n\n    it(\"adds headers to the request from the setup\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"data\",\n        headers: { authorization: \"1234\" },\n      });\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const headers = fetchMock.lastCall()![1]!.headers as any;\n      expect(headers.authorization).toBe(\"1234\");\n      expect(headers[\"content-type\"]).toBe(\"application/json\");\n      expect(headers.accept).toBe(\n        \"application/graphql-response+json,application/json;q=0.9\"\n      );\n    });\n\n    it(\"prioritizes context headers over setup headers\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          headers: { authorization: \"1234\" },\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(\n        new HttpLink({ uri: \"data\", headers: { authorization: \"no user\" } })\n      );\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const headers = fetchMock.lastCall()![1]!.headers as any;\n      expect(headers.authorization).toBe(\"1234\");\n      expect(headers[\"content-type\"]).toBe(\"application/json\");\n      expect(headers.accept).toBe(\n        \"application/graphql-response+json,application/json;q=0.9\"\n      );\n    });\n\n    it(\"adds headers to the request from the context on an operation\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({ uri: \"data\" });\n\n      const context = {\n        headers: { authorization: \"1234\" },\n      };\n      const observable = execute(link, {\n        query: sampleQuery,\n        variables,\n        context,\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const headers = fetchMock.lastCall()![1]!.headers as any;\n      expect(headers.authorization).toBe(\"1234\");\n      expect(headers[\"content-type\"]).toBe(\"application/json\");\n      expect(headers.accept).toBe(\n        \"application/graphql-response+json,application/json;q=0.9\"\n      );\n    });\n\n    it(\"adds creds to the request from the context\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          credentials: \"same-team-yo\",\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(new HttpLink({ uri: \"data\" }));\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const creds = fetchMock.lastCall()![1]!.credentials;\n      expect(creds).toBe(\"same-team-yo\");\n    });\n\n    it(\"adds creds to the request from the setup\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({ uri: \"data\", credentials: \"include\" });\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const creds = fetchMock.lastCall()![1]!.credentials;\n      expect(creds).toBe(\"include\");\n    });\n\n    it(\"prioritizes creds from the context over the setup\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          credentials: \"omit\",\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(\n        new HttpLink({ uri: \"data\", credentials: \"include\" })\n      );\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const creds = fetchMock.lastCall()![1]!.credentials;\n      expect(creds).toBe(\"omit\");\n    });\n\n    it(\"adds uri to the request from the context\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          uri: \"data\",\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(new HttpLink());\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const uri = fetchMock.lastUrl();\n      expect(uri).toBe(\"/data\");\n    });\n\n    it(\"adds uri to the request from the setup\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({ uri: \"data\" });\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const uri = fetchMock.lastUrl();\n      expect(uri).toBe(\"/data\");\n    });\n\n    it(\"prioritizes context uri over setup uri\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          uri: \"apollo\",\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(\n        new HttpLink({ uri: \"data\", credentials: \"include\" })\n      );\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const uri = fetchMock.lastUrl();\n      expect(uri).toBe(\"/apollo\");\n    });\n\n    it(\"allows uri to be a function\", async () => {\n      const variables = { params: \"stub\" };\n      const customFetch: typeof fetch = (uri, options) => {\n        const { operationName } = convertBatchedBody(options!.body);\n        expect(operationName).toBe(\"SampleQuery\");\n\n        return fetch(\"dataFunc\", options);\n      };\n\n      const link = new HttpLink({ fetch: customFetch });\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      expect(fetchMock.lastUrl()).toBe(\"/dataFunc\");\n    });\n\n    it(\"adds fetchOptions to the request from the setup\", async () => {\n      const variables = { params: \"stub\" };\n      const link = new HttpLink({\n        uri: \"data\",\n        fetchOptions: { mode: \"no-cors\" },\n      });\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const { mode, headers } = fetchMock.lastCall()![1] as any;\n      expect(mode).toBe(\"no-cors\");\n      expect(headers[\"content-type\"]).toBe(\"application/json\");\n    });\n\n    it(\"adds fetchOptions to the request from the context\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          fetchOptions: {\n            someOption: \"foo\",\n          },\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(new HttpLink({ uri: \"data\" }));\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const { someOption } = fetchMock.lastCall()![1] as any;\n      expect(someOption).toBe(\"foo\");\n    });\n\n    it(\"uses the latest window.fetch function if options.fetch not configured\", async () => {\n      const httpLink = new HttpLink({ uri: \"data\" });\n\n      const fetch = window.fetch;\n      expect(typeof fetch).toBe(\"function\");\n\n      const fetchSpy = jest.spyOn(window, \"fetch\");\n      fetchSpy.mockImplementation(() =>\n        Promise.resolve(Response.json({ data: { hello: \"from spy\" } }))\n      );\n\n      const spyFn = window.fetch;\n      expect(spyFn).not.toBe(fetch);\n\n      const stream = new ObservableStream(\n        execute(httpLink, { query: sampleQuery })\n      );\n\n      await expect(stream).toEmitTypedValue({ data: { hello: \"from spy\" } });\n      expect(fetchSpy).toHaveBeenCalledTimes(1);\n\n      fetchSpy.mockRestore();\n      expect(window.fetch).toBe(fetch);\n\n      const stream2 = new ObservableStream(\n        execute(httpLink, { query: sampleQuery })\n      );\n\n      await expect(stream2).toEmitTypedValue({ data: { hello: \"world\" } });\n    });\n\n    it(\"uses the print option function when defined\", async () => {\n      const customPrinter = jest.fn(\n        (ast: ASTNode, originalPrint: typeof print) => {\n          return stripIgnoredCharacters(originalPrint(ast));\n        }\n      );\n\n      const httpLink = new HttpLink({ uri: \"data\", print: customPrinter });\n\n      const observable = execute(httpLink, {\n        query: sampleQuery,\n        context: {\n          fetchOptions: { method: \"GET\" },\n        },\n      });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      expect(customPrinter).toHaveBeenCalledTimes(1);\n      const [uri] = fetchMock.lastCall()!;\n      expect(uri).toBe(\n        `/data?query=query%20SampleQuery%7Bstub%7Bid%7D%7D&operationName=SampleQuery&variables=%7B%7D&extensions=%7B%22clientLibrary%22%3A%7B%22name%22%3A%22%40apollo%2Fclient%22%2C%22version%22%3A%22${version}%22%7D%7D`\n      );\n    });\n\n    it(\"prioritizes context over setup\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          fetchOptions: {\n            mode: \"cors\",\n          },\n        });\n        return forward(operation);\n      });\n      const link = middleware.concat(\n        new HttpLink({ uri: \"data\", fetchOptions: { mode: \"no-cors\" } })\n      );\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      const { mode } = fetchMock.lastCall()![1] as any;\n      expect(mode).toBe(\"cors\");\n    });\n\n    it(\"allows for not sending the query with the request\", async () => {\n      const variables = { params: \"stub\" };\n      const middleware = new ApolloLink((operation, forward) => {\n        operation.setContext({\n          http: {\n            includeQuery: false,\n            includeExtensions: true,\n          },\n        });\n        operation.extensions.persistedQuery = { hash: \"1234\" };\n        return forward(operation);\n      });\n      const link = middleware.concat(new HttpLink({ uri: \"data\" }));\n\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n\n      let body = convertBatchedBody(fetchMock.lastCall()![1]!.body);\n\n      expect(body.query).not.toBeDefined();\n      expect(body.extensions).toEqual({\n        persistedQuery: { hash: \"1234\" },\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n      });\n    });\n\n    it(\"sets the raw response on context\", async () => {\n      const middleware = new ApolloLink((operation, forward) => {\n        return new Observable((ob) => {\n          const op = forward(operation);\n          const sub = op.subscribe({\n            next: ob.next.bind(ob),\n            error: ob.error.bind(ob),\n            complete: () => {\n              expect(operation.getContext().response.headers).toBeDefined();\n              ob.complete();\n            },\n          });\n\n          return () => {\n            sub.unsubscribe();\n          };\n        });\n      });\n\n      const link = middleware.concat(new HttpLink({ uri: \"data\", fetch }));\n\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue(data);\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"Dev warnings\", () => {\n    voidFetchDuringEachTest();\n\n    it(\"warns if fetch is undeclared\", async () => {\n      expect(() => new HttpLink({ uri: \"data\" })).toThrow(\n        /has not been found globally/\n      );\n    });\n\n    it(\"warns if fetch is undefined\", async () => {\n      window.fetch = undefined as any;\n\n      expect(() => new HttpLink({ uri: \"data\" })).toThrow(\n        /has not been found globally/\n      );\n    });\n\n    it(\"does not warn if fetch is undeclared but a fetch is passed\", () => {\n      expect(() => {\n        new HttpLink({ uri: \"data\", fetch: (() => {}) as any });\n      }).not.toThrow();\n    });\n  });\n\n  describe(\"Error handling\", () => {\n    it(\"throws an error if response code is > 300\", async () => {\n      const response = Response.json({}, { status: 400 });\n\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: \"{}\",\n        })\n      );\n    });\n\n    it(\"throws an error if response code is > 300 and handles string response body\", async () => {\n      const response = new Response(\"Error! Foo bar\", { status: 302 });\n\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 302\", {\n          response,\n          bodyText: \"Error! Foo bar\",\n        })\n      );\n    });\n\n    it(\"throws an error if response code is > 300 and returns data\", async () => {\n      const result = {\n        data: { stub: { id: 1 } },\n        errors: [{ message: \"dangit\" }],\n      };\n      const response = Response.json(result, { status: 400 });\n\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: JSON.stringify(result),\n        })\n      );\n    });\n\n    it(\"throws an error if only errors are returned\", async () => {\n      const result = { errors: [{ message: \"dangit\" }] };\n      const response = Response.json(result, { status: 400 });\n\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: JSON.stringify(result),\n        })\n      );\n    });\n\n    it(\"throws an error if empty response from the server \", async () => {\n      const response = Response.json({ body: \"boo\" }, { status: 200 });\n\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\n          \"Server response was malformed for query 'SampleQuery'.\",\n          { response, bodyText: JSON.stringify({ body: \"boo\" }) }\n        )\n      );\n    });\n\n    it(\"throws if the body can't be stringified\", async () => {\n      const link = new HttpLink({\n        uri: \"data\",\n        fetch: async () => new Response(\"\"),\n        includeUnusedVariables: true,\n      });\n\n      let b;\n      const a: any = { b };\n      b = { a };\n      a.b = b;\n      const variables = {\n        a,\n        b,\n      };\n      const observable = execute(link, { query: sampleQuery, variables });\n      const stream = new ObservableStream(observable);\n\n      const error = await stream.takeError();\n\n      expect(error.message).toMatch(/Converting circular structure to JSON/);\n    });\n\n    describe(\"AbortController\", () => {\n      const originalAbortController = globalThis.AbortController;\n      afterEach(() => {\n        globalThis.AbortController = originalAbortController;\n      });\n\n      function trackGlobalAbortControllers() {\n        const instances: AbortController[] = [];\n        class AbortControllerMock {\n          constructor() {\n            const instance = new originalAbortController();\n            instances.push(instance);\n            return instance;\n          }\n        }\n\n        globalThis.AbortController = AbortControllerMock as any;\n        return instances;\n      }\n\n      const failingObserver: Observer<ApolloLink.Result> = {\n        next: () => {\n          fail(\"result should not have been called\");\n        },\n        error: (e) => {\n          fail(e);\n        },\n        complete: () => {\n          fail(\"complete should not have been called\");\n        },\n      };\n\n      it(\"aborts the request when unsubscribing before the request has completed\", () => {\n        const fetch = async () =>\n          Response.json({ data: { stub: { id: \"foo\" } } }, { status: 200 });\n        const abortControllers = trackGlobalAbortControllers();\n\n        const link = new HttpLink({ uri: \"data\", fetch });\n\n        const sub = execute(link, { query: sampleQuery }).subscribe(\n          failingObserver\n        );\n        sub.unsubscribe();\n\n        expect(abortControllers.length).toBe(1);\n        expect(abortControllers[0].signal.aborted).toBe(true);\n      });\n\n      it(\"a passed-in signal that is aborted will fail the observable with an `AbortError`\", async () => {\n        try {\n          fetchMock.restore();\n          fetchMock.postOnce(\n            \"data\",\n            async () => '{ \"data\": { \"stub\": { \"id\": \"foo\" } } }',\n            { delay: 100 }\n          );\n\n          const externalAbortController = new AbortController();\n          const abortControllers = trackGlobalAbortControllers();\n\n          const link = new HttpLink({\n            uri: \"/data\",\n          });\n\n          const observable = execute(link, {\n            query: sampleQuery,\n            context: {\n              fetchOptions: { signal: externalAbortController.signal },\n            },\n          });\n\n          const internalAbortController = abortControllers[0];\n\n          const stream = new ObservableStream(observable);\n          const externalReason = new Error(\"External abort reason\");\n\n          externalAbortController.abort(externalReason);\n\n          await expect(stream).toEmitError(\n            // this not being `externalReason` is a quirk of `fetch-mock`:\n            // https://github.com/wheresrhys/fetch-mock/blob/605ec0afa6a5ff35066b9e01a9bcd688f3c25ce0/packages/fetch-mock/src/Router.ts#L164-L167\n            new DOMException(\"The operation was aborted.\", \"AbortError\")\n          );\n\n          expect(externalAbortController).not.toBe(internalAbortController);\n          expect(externalAbortController.signal.aborted).toBe(true);\n          expect(externalAbortController.signal.reason).toBe(externalReason);\n          expect(internalAbortController.signal.aborted).toBe(true);\n          expect(internalAbortController.signal.reason).toBe(externalReason);\n        } finally {\n          fetchMock.restore();\n        }\n      });\n\n      it(\"a passed-in signal will not fully overwrite the internally created one\", () => {\n        try {\n          const externalAbortController = new AbortController();\n          const abortControllers = trackGlobalAbortControllers();\n\n          fetchMock.restore();\n          fetchMock.postOnce(\n            \"data\",\n            async () => '{ \"data\": { \"stub\": { \"id\": \"foo\" } } }'\n          );\n\n          const link = new HttpLink({\n            uri: \"/data\",\n          });\n\n          const sub = execute(link, {\n            query: sampleQuery,\n            context: {\n              fetchOptions: { signal: externalAbortController.signal },\n            },\n          }).subscribe(failingObserver);\n          const internalAbortController = abortControllers[0];\n\n          sub.unsubscribe();\n\n          expect(externalAbortController.signal.aborted).toBe(false);\n          expect(internalAbortController.signal.aborted).toBe(true);\n        } finally {\n          fetchMock.restore();\n        }\n      });\n\n      it(\"resolving fetch does not cause the AbortController to be aborted\", async () => {\n        const fetch = async () =>\n          Response.json({ data: { hello: \"world\" } }, { status: 200 });\n        const abortControllers = trackGlobalAbortControllers();\n\n        // (the request is already finished at that point)\n        const link = new HttpLink({ uri: \"data\", fetch });\n\n        await new Promise<void>((resolve) =>\n          execute(link, { query: sampleQuery }).subscribe({\n            complete: resolve,\n          })\n        );\n\n        expect(abortControllers.length).toBe(1);\n        expect(abortControllers[0].signal.aborted).toBe(false);\n      });\n\n      it(\"an unsuccessful fetch does not cause the AbortController to be aborted\", async () => {\n        const fetch = async () => {\n          throw new Error(\"This is an error!\");\n        };\n\n        const abortControllers = trackGlobalAbortControllers();\n        // the request would be closed by the browser in the case of an error anyways\n        const link = new HttpLink({ uri: \"data\", fetch });\n\n        await new Promise<void>((resolve) =>\n          execute(link, { query: sampleQuery }).subscribe({\n            error: resolve,\n          })\n        );\n\n        expect(abortControllers.length).toBe(1);\n        expect(abortControllers[0].signal.aborted).toBe(false);\n      });\n    });\n\n    it(\"throws a Server error if response is > 300 with unparsable json\", async () => {\n      const body = \"{\";\n      const response = new Response(body, {\n        status: 400,\n        headers: { \"content-type\": \"application/json\" },\n      });\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: body,\n        })\n      );\n    });\n\n    it(\"throws a ServerParseError if response is 200 with unparsable json\", async () => {\n      const body = \"{\";\n      const response = new Response(body, {\n        status: 200,\n        headers: { \"content-type\": \"application/json\" },\n      });\n      const link = new HttpLink({ uri: \"data\", fetch: async () => response });\n\n      const observable = execute(link, { query: sampleQuery });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitError(\n        new ServerParseError(\n          new Error(\n            \"Expected property name or '}' in JSON at position 1 (line 1 column 2)\"\n          ),\n          { response, bodyText: body }\n        )\n      );\n    });\n  });\n\n  describe(\"Multipart responses\", () => {\n    let originalTextDecoder: any;\n    beforeAll(() => {\n      originalTextDecoder = TextDecoder;\n      (globalThis as any).TextDecoder = TextDecoder;\n    });\n\n    afterAll(() => {\n      globalThis.TextDecoder = originalTextDecoder;\n    });\n\n    describe(\"@defer\", () => {\n      const body = [\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 43\",\n        \"\",\n        '{\"data\":{\"stub\":{\"id\":\"0\"}},\"hasNext\":true}',\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 58\",\n        \"\",\n        // Intentionally using the boundary value `---` within the “name” to\n        // validate that boundary delimiters are not parsed within the response\n        // data itself, only read at the beginning of each chunk.\n        '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby---\"},\"path\":[\"stub\"],\"extensions\":{\"timestamp\":1633038919}}]}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      const bodyAlpha9 = [\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 43\",\n        \"\",\n        '{\"data\":{\"stub\":{\"id\":\"0\"}},\"pending\":[{\"id\":\"0\",\"path\":[\"stub\"]}],\"hasNext\":true}',\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 58\",\n        \"\",\n        // Intentionally using the boundary value `---` within the “name” to\n        // validate that boundary delimiters are not parsed within the response\n        // data itself, only read at the beginning of each chunk.\n        '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby---\"},\"id\":\"0\",\"extensions\":{\"timestamp\":1633038919}}]}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      const streamBody = [\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 43\",\n        \"\",\n        '{\"data\":{\"stubs\":[]},\"hasNext\":true}',\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 58\",\n        \"\",\n        // Intentionally using the boundary value `---` within the “name” to\n        // validate that boundary delimiters are not parsed within the response\n        // data itself, only read at the beginning of each chunk.\n        '{\"hasNext\":false, \"incremental\": [{\"data\":{\"id\":\"1\",\"name\":\"stubby---\"},\"path\":[\"stubs\", 1],\"extensions\":{\"timestamp\":1633038919}}]}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      const streamBodyAlpha9 = [\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 43\",\n        \"\",\n        '{\"data\":{\"stubs\":[]},\"pending\": [{\"id\":\"0\",\"path\":[\"stubs\"]}], \"hasNext\":true}',\n        \"---\",\n        \"Content-Type: application/json; charset=utf-8\",\n        \"Content-Length: 58\",\n        \"\",\n        // Intentionally using the boundary value `---` within the “name” to\n        // validate that boundary delimiters are not parsed within the response\n        // data itself, only read at the beginning of each chunk.\n        '{\"hasNext\":false, \"incremental\": [{\"items\":[{\"id\":\"1\",\"name\":\"stubby---\"}],\"id\":\"0\",\"extensions\":{\"timestamp\":1633038919}}],\"completed\":[{\"id\":\"0\"}]}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      const finalChunkOnlyHasNextFalse = [\n        \"--graphql\",\n        \"content-type: application/json\",\n        \"\",\n        '{\"data\":{\"allProducts\":[null,null,null]},\"errors\":[{\"message\":\"Cannot return null for non-nullable field Product.nonNullErrorField.\"},{\"message\":\"Cannot return null for non-nullable field Product.nonNullErrorField.\"},{\"message\":\"Cannot return null for non-nullable field Product.nonNullErrorField.\"}],\"hasNext\":true}',\n        \"--graphql\",\n        \"content-type: application/json\",\n        \"\",\n        '{\"hasNext\":false}',\n        \"--graphql--\",\n      ].join(\"\\r\\n\");\n\n      it(\"whatwg stream bodies\", async () => {\n        const stream = new ReadableStream({\n          async start(controller) {\n            const lines = body.split(\"\\r\\n\");\n            try {\n              for (const line of lines) {\n                await new Promise((resolve) => setTimeout(resolve, 10));\n                controller.enqueue(line + \"\\r\\n\");\n              }\n            } finally {\n              controller.close();\n            }\n          },\n        });\n\n        const link = new HttpLink({\n          fetch: async () => {\n            return new Response(stream, {\n              status: 200,\n              headers: new Headers({ \"content-type\": \"multipart/mixed\" }),\n            });\n          },\n        });\n\n        const observableStream = new ObservableStream(\n          execute(link, { query: sampleDeferredQuery })\n        );\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            stub: {\n              id: \"0\",\n            },\n          },\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              data: {\n                name: \"stubby---\",\n              },\n              extensions: {\n                timestamp: 1633038919,\n              },\n              path: [\"stub\"],\n            },\n          ],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n      });\n\n      // Verify that observable completes if final chunk does not contain\n      // incremental array.\n      it(\"whatwg stream bodies, final chunk of { hasNext: false }\", async () => {\n        const stream = new ReadableStream({\n          async start(controller) {\n            const lines = finalChunkOnlyHasNextFalse.split(\"\\r\\n\");\n            try {\n              for (const line of lines) {\n                await new Promise((resolve) => setTimeout(resolve, 10));\n                controller.enqueue(line + \"\\r\\n\");\n              }\n            } finally {\n              controller.close();\n            }\n          },\n        });\n\n        const link = new HttpLink({\n          fetch: async () => {\n            return new Response(stream, {\n              status: 200,\n              headers: new Headers({\n                \"Content-Type\":\n                  'multipart/mixed;boundary=\"graphql\";deferSpec=20220824',\n              }),\n            });\n          },\n        });\n\n        const observableStream = new ObservableStream(\n          execute(link, { query: sampleDeferredQuery })\n        );\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            allProducts: [null, null, null],\n          },\n          errors: [\n            {\n              message:\n                \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n            },\n            {\n              message:\n                \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n            },\n            {\n              message:\n                \"Cannot return null for non-nullable field Product.nonNullErrorField.\",\n            },\n          ],\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          hasNext: false,\n        });\n\n        // the second chunk contains only hasNext: false which is not emitted as\n        // a `next` event so the link completes.\n\n        await expect(observableStream).toComplete();\n      });\n\n      it(\"sets correct accept header on request with deferred query\", async () => {\n        const stream = ReadableStream.from(\n          body.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n\n        const { link, observableStream } = pipeLinkToObservableStream(\n          new HttpLink({ fetch })\n        );\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          incrementalHandler: new Defer20220824Handler(),\n        });\n        void client.query({ query: sampleDeferredQuery });\n\n        await expect(observableStream).toEmitTypedValue({\n          data: { stub: { id: \"0\" } },\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              data: { name: \"stubby---\" },\n              path: [\"stub\"],\n              extensions: { timestamp: 1633038919 },\n            },\n          ],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              \"content-type\": \"application/json\",\n              accept:\n                \"multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\",\n            },\n          })\n        );\n      });\n\n      it(\"sets correct accept header on request with deferred query using GraphQL17Alpha9Handler\", async () => {\n        const stream = ReadableStream.from(\n          bodyAlpha9.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n\n        const { link, observableStream } = pipeLinkToObservableStream(\n          new HttpLink({ fetch })\n        );\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          incrementalHandler: new GraphQL17Alpha9Handler(),\n        });\n        void client.query({ query: sampleDeferredQuery });\n\n        await expect(observableStream).toEmitTypedValue({\n          data: { stub: { id: \"0\" } },\n          // @ts-ignore\n          pending: [{ id: \"0\", path: [\"stub\"] }],\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              data: { name: \"stubby---\" },\n              // @ts-ignore\n              id: \"0\",\n              extensions: { timestamp: 1633038919 },\n            },\n          ],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              \"content-type\": \"application/json\",\n              accept:\n                \"multipart/mixed;incrementalSpec=v0.2,application/graphql-response+json,application/json;q=0.9\",\n            },\n          })\n        );\n      });\n\n      it(\"sets correct accept header on request with streamed query\", async () => {\n        const stream = ReadableStream.from(\n          streamBody.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n\n        const { link, observableStream } = pipeLinkToObservableStream(\n          new HttpLink({ fetch })\n        );\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          incrementalHandler: new Defer20220824Handler(),\n        });\n        void client.query({ query: sampleStreamedQuery });\n\n        await expect(observableStream).toEmitTypedValue({\n          data: { stubs: [] },\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              data: { id: \"1\", name: \"stubby---\" },\n              path: [\"stubs\", 1],\n              extensions: { timestamp: 1633038919 },\n            },\n          ],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              \"content-type\": \"application/json\",\n              accept:\n                \"multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\",\n            },\n          })\n        );\n      });\n\n      it(\"sets correct accept header on request with streamed query using GraphQL17Alpha9Handler\", async () => {\n        const stream = ReadableStream.from(\n          streamBodyAlpha9.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n\n        const { link, observableStream } = pipeLinkToObservableStream(\n          new HttpLink({ fetch })\n        );\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          incrementalHandler: new GraphQL17Alpha9Handler(),\n        });\n        void client.query({ query: sampleStreamedQuery });\n\n        await expect(observableStream).toEmitTypedValue({\n          data: { stubs: [] },\n          // @ts-ignore\n          pending: [{ id: \"0\", path: [\"stubs\"] }],\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              // @ts-ignore\n              items: [{ id: \"1\", name: \"stubby---\" }],\n              id: \"0\",\n              extensions: { timestamp: 1633038919 },\n            },\n          ],\n          completed: [{ id: \"0\" }],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              \"content-type\": \"application/json\",\n              accept:\n                \"multipart/mixed;incrementalSpec=v0.2,application/graphql-response+json,application/json;q=0.9\",\n            },\n          })\n        );\n      });\n\n      // ensure that custom directives beginning with '@defer..' do not trigger\n      // custom accept header for multipart responses\n      it(\"sets does not set accept header on query with custom directive begging with @defer\", async () => {\n        const stream = ReadableStream.from(\n          body.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n        const link = new HttpLink({ fetch });\n        const observable = execute(link, { query: sampleQueryCustomDirective });\n        const observableStream = new ObservableStream(observable);\n\n        await expect(observableStream).toEmitTypedValue({\n          data: { stub: { id: \"0\" } },\n          hasNext: true,\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          incremental: [\n            {\n              data: { name: \"stubby---\" },\n              path: [\"stub\"],\n              extensions: { timestamp: 1633038919 },\n            },\n          ],\n          hasNext: false,\n        });\n\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              accept:\n                \"application/graphql-response+json,application/json;q=0.9\",\n              \"content-type\": \"application/json\",\n            },\n          })\n        );\n      });\n    });\n\n    describe(\"subscriptions\", () => {\n      const subscriptionsBody = [\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        \"{}\",\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        '{\"payload\":{\"data\":{\"aNewDieWasCreated\":{\"die\":{\"color\":\"red\",\"roll\":1,\"sides\":4}}}}}',\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        \"{}\",\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        '{\"payload\":{\"data\":{\"aNewDieWasCreated\":{\"die\":{\"color\":\"blue\",\"roll\":2,\"sides\":5}}}}}',\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        '{\"payload\": null}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      const subscriptionsBodyError = [\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        \"{}\",\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        '{\"payload\":{\"data\":{\"aNewDieWasCreated\":{\"die\":{\"color\":\"red\",\"roll\":1,\"sides\":4}}}}}',\n        \"---\",\n        \"Content-Type: application/json\",\n        \"\",\n        '{\"payload\": null, \"errors\": [{\"message\":\"Error field\",\"extensions\":{\"code\":\"INTERNAL_SERVER_ERROR\"}}]}',\n        \"-----\",\n      ].join(\"\\r\\n\");\n\n      it(\"whatwg stream bodies\", async () => {\n        const stream = new ReadableStream({\n          async start(controller) {\n            const lines = subscriptionsBody.split(\"\\r\\n\");\n            try {\n              for (const line of lines) {\n                await new Promise((resolve) => setTimeout(resolve, 10));\n                controller.enqueue(line + \"\\r\\n\");\n              }\n            } finally {\n              controller.close();\n            }\n          },\n        });\n\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n\n        const link = new HttpLink({ fetch });\n\n        const observableStream = new ObservableStream(\n          execute(link, { query: sampleSubscription })\n        );\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            aNewDieWasCreated: {\n              die: {\n                color: \"red\",\n                roll: 1,\n                sides: 4,\n              },\n            },\n          },\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            aNewDieWasCreated: {\n              die: {\n                color: \"blue\",\n                roll: 2,\n                sides: 5,\n              },\n            },\n          },\n        });\n\n        await expect(observableStream).toComplete();\n      });\n\n      test(\"whatwg stream bodies combined with @defer, lets server handle erroring\", async () => {\n        const error = {\n          errors: [\n            {\n              message:\n                \"value retrieval failed: Federation error: @defer is not supported on subscriptions\",\n              extensions: { code: \"INTERNAL_SERVER_ERROR\" },\n            },\n          ],\n        };\n        const response = Response.json(error, {\n          status: 500,\n          headers: { \"content-type\": \"application/json\" },\n        });\n        const fetch = jest.fn(async () => {\n          return response;\n        });\n\n        const link = new HttpLink({ fetch });\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          incrementalHandler: new Defer20220824Handler(),\n        });\n\n        const stream = new ObservableStream(\n          client.subscribe({ query: sampleSubscriptionWithDefer })\n        );\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              accept:\n                \"multipart/mixed;boundary=graphql;subscriptionSpec=1.0,multipart/mixed;deferSpec=20220824,application/graphql-response+json,application/json;q=0.9\",\n              \"content-type\": \"application/json\",\n            },\n          })\n        );\n\n        await expect(stream).toEmitTypedValue({\n          data: undefined,\n          error: new ServerError(\n            \"Response not successful: Received status code 500\",\n            {\n              bodyText: JSON.stringify(error),\n              response,\n            }\n          ),\n        });\n      });\n\n      it(\"with errors\", async () => {\n        const stream = ReadableStream.from(\n          subscriptionsBodyError.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n        const link = new HttpLink({ fetch });\n\n        const observableStream = new ObservableStream(\n          execute(link, { query: sampleSubscription })\n        );\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            aNewDieWasCreated: {\n              die: {\n                color: \"red\",\n                roll: 1,\n                sides: 4,\n              },\n            },\n          },\n        });\n\n        await expect(observableStream).toEmitTypedValue({\n          extensions: {\n            [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n              {\n                extensions: {\n                  code: \"INTERNAL_SERVER_ERROR\",\n                },\n                message: \"Error field\",\n              },\n            ]),\n          } as Record<string, unknown>,\n        });\n\n        await expect(observableStream).toComplete();\n      });\n\n      it(\"sets correct accept header on request with subscription\", async () => {\n        const stream = ReadableStream.from(\n          subscriptionsBody.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n        );\n        const fetch = jest.fn(async () => {\n          return new Response(stream, {\n            status: 200,\n            headers: { \"content-type\": \"multipart/mixed\" },\n          });\n        });\n        const link = new HttpLink({ fetch });\n        const observable = execute(link, { query: sampleSubscription });\n        const observableStream = new ObservableStream(observable);\n\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            aNewDieWasCreated: { die: { color: \"red\", roll: 1, sides: 4 } },\n          },\n        });\n        await expect(observableStream).toEmitTypedValue({\n          data: {\n            aNewDieWasCreated: { die: { color: \"blue\", roll: 2, sides: 5 } },\n          },\n        });\n        await expect(observableStream).toComplete();\n\n        expect(fetch).toHaveBeenCalledWith(\n          \"/graphql\",\n          expect.objectContaining({\n            headers: {\n              \"content-type\": \"application/json\",\n              accept:\n                \"multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/graphql-response+json,application/json;q=0.9\",\n            },\n          })\n        );\n      });\n    });\n  });\n\n  describe(\"GraphQL over HTTP\", () => {\n    test(\"emits result when content-type is not set with well formed GraphQL response\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json({ data: { foo: true } }, { status: 200 });\n      response.headers.delete(\"content-type\");\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitTypedValue({ data: { foo: true } });\n      await expect(stream).toComplete();\n    });\n\n    test(\"emits ServerError when content-type is not set with malformed GraphQL response\", async () => {\n      const query = gql`\n        query Foo {\n          foo\n        }\n      `;\n\n      const response = Response.json({ foo: true }, { status: 200 });\n      response.headers.delete(\"content-type\");\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Server response was malformed for query 'Foo'.\", {\n          response,\n          bodyText: JSON.stringify({ foo: true }),\n        })\n      );\n    });\n\n    test(\"emits ServerParseError when content-type is not set with unparsable JSON body\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = new Response(\"This is a response\", { status: 200 });\n      response.headers.delete(\"content-type\");\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitError(\n        new ServerParseError(\n          new Error(\n            `Unexpected token 'T', \"This is a response\" is not valid JSON`\n          ),\n          {\n            response,\n            bodyText: \"This is a response\",\n          }\n        )\n      );\n    });\n\n    test(\"emits ServerError when content-type is not set with well formed GraphQL response and non-200 status code\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: null, errors: [{ message: \"Something went wrong\" }] },\n        { status: 400 }\n      );\n      response.headers.delete(\"content-type\");\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: JSON.stringify({\n            data: null,\n            errors: [{ message: \"Something went wrong\" }],\n          }),\n        })\n      );\n    });\n\n    test(\"emits ServerError when responding with application/json and non-200 status code with malformed GraphQL response\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { error: \"Could not process request\" },\n        {\n          status: 400,\n          headers: { \"content-type\": \"application/json\" },\n        }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: JSON.stringify({\n            error: \"Could not process request\",\n          }),\n        })\n      );\n    });\n\n    test(\"emits ServerError when responding with application/json and non-200 status code with well-formed GraphQL response\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: null, errors: [{ message: \"Could not process request\" }] },\n        { status: 400, headers: { \"content-type\": \"application/json\" } }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitError(\n        new ServerError(\"Response not successful: Received status code 400\", {\n          response,\n          bodyText: JSON.stringify({\n            data: null,\n            errors: [{ message: \"Could not process request\" }],\n          }),\n        })\n      );\n    });\n\n    test(\"emits result when responding with a non-json mime type and 200 response with well formed GraphQL response\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: null, errors: [{ message: \"Could not process request\" }] },\n        {\n          status: 200,\n          headers: { \"content-type\": \"text/plain\" },\n        }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitTypedValue({\n        data: null,\n        errors: [{ message: \"Could not process request\" }],\n      });\n      await expect(stream).toComplete();\n    });\n\n    test(\"handles 200 response with application/graphql-response+json\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: { foo: \"bar\" } },\n        {\n          status: 200,\n          headers: { \"content-type\": \"application/graphql-response+json\" },\n        }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitTypedValue({ data: { foo: \"bar\" } });\n      await expect(stream).toComplete();\n    });\n\n    test(\"parses non-200 response with application/graphql-response+json\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: null, errors: [{ message: \"Could not process request\" }] },\n        {\n          status: 400,\n          headers: { \"content-type\": \"application/graphql-response+json\" },\n        }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitTypedValue({\n        data: null,\n        errors: [{ message: \"Could not process request\" }],\n      });\n      await expect(stream).toComplete();\n    });\n\n    test(\"parses 200 response with application/graphql-response+json and errors\", async () => {\n      const query = gql`\n        query {\n          foo\n        }\n      `;\n\n      const response = Response.json(\n        { data: null, errors: [{ message: \"Could not process request\" }] },\n        {\n          status: 200,\n          headers: { \"content-type\": \"application/graphql-response+json\" },\n        }\n      );\n\n      const link = new HttpLink({\n        uri: \"/graphql\",\n        fetch: async () => response,\n      });\n\n      const stream = new ObservableStream(execute(link, { query }));\n\n      await expect(stream).toEmitTypedValue({\n        data: null,\n        errors: [{ message: \"Could not process request\" }],\n      });\n      await expect(stream).toComplete();\n    });\n  });\n\n  describe(\"client awareness\", () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n    const response = {\n      data: { hello: \"world\" },\n    };\n    const uri = \"https://example.com/graphql\";\n    afterEach(() => fetchMock.reset());\n\n    test(\"is part of `HttpLink`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new HttpLink({\n          uri,\n        }),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({ query });\n      const headers = fetchMock.lastCall()![1]?.headers;\n      expect(headers).toStrictEqual({\n        accept: \"application/graphql-response+json,application/json;q=0.9\",\n        \"content-type\": \"application/json\",\n        \"apollographql-client-name\": \"test-client\",\n        \"apollographql-client-version\": \"1.0.0\",\n      });\n    });\n\n    test(\"is not part of `BaseHttpLink`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new BaseHttpLink({\n          uri,\n        }),\n        cache: new InMemoryCache(),\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({ query });\n      const headers = fetchMock.lastCall()![1]?.headers;\n      expect(headers).toStrictEqual({\n        accept: \"application/graphql-response+json,application/json;q=0.9\",\n        \"content-type\": \"application/json\",\n      });\n    });\n\n    test(\"`HttpLink` options have priority over `ApolloClient` options\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new HttpLink({\n          uri,\n          clientAwareness: {\n            name: \"overridden-client\",\n            version: \"2.0.0\",\n          },\n        }),\n        cache: new InMemoryCache(),\n\n        clientAwareness: {\n          name: \"test-client\",\n          version: \"1.0.0\",\n        },\n      });\n\n      void client.query({ query });\n      const headers = fetchMock.lastCall()![1]?.headers;\n      expect(headers).toStrictEqual({\n        accept: \"application/graphql-response+json,application/json;q=0.9\",\n        \"content-type\": \"application/json\",\n        \"apollographql-client-name\": \"overridden-client\",\n        \"apollographql-client-version\": \"2.0.0\",\n      });\n    });\n  });\n\n  describe(\"enhanced client awareness\", () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n    const response = {\n      data: { hello: \"world\" },\n    };\n    const uri = \"https://example.com/graphql\";\n    afterEach(() => fetchMock.reset());\n\n    test(\"is part of `HttpLink`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new HttpLink({\n          uri,\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({ query });\n      const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n      expect(body.extensions).toStrictEqual({\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n      });\n    });\n\n    test(\"is not part of `BaseHttpLink`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new BaseHttpLink({\n          uri,\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({ query });\n      const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n      expect(body.extensions).not.toBeDefined();\n    });\n\n    test(\"can be disabled from `HttpLink`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new HttpLink({\n          uri,\n          enhancedClientAwareness: { transport: false },\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({ query });\n      const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n      expect(body.extensions).not.toBeDefined();\n    });\n\n    test(\"can also be disabled by disabling `includeExtensions`\", () => {\n      fetchMock.postOnce(uri, response);\n      const client = new ApolloClient({\n        link: new HttpLink({\n          uri,\n          includeExtensions: false,\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      void client.query({ query });\n      const body = JSON.parse(fetchMock.lastCall()![1]?.body as string);\n      expect(body.extensions).not.toBeDefined();\n    });\n  });\n});\n\nfunction pipeLinkToObservableStream(link: ApolloLink) {\n  const sink = new Subject<ApolloLink.Result>();\n  const observableStream = new ObservableStream(sink);\n  const pipedLink = new ApolloLink((operation, forward) =>\n    forward(operation).pipe(\n      tap({\n        next: (result) => {\n          sink.next(structuredClone(result));\n        },\n        error: sink.error.bind(sink),\n        complete: sink.complete.bind(sink),\n      })\n    )\n  ).concat(link);\n  return {\n    observableStream,\n    link: pipedLink,\n  };\n}\n"
  },
  {
    "path": "src/link/http/__tests__/checkFetcher.ts",
    "content": "import { checkFetcher } from \"@apollo/client/link/http\";\n\nimport { voidFetchDuringEachTest } from \"./helpers.js\";\n\ndescribe(\"checkFetcher\", () => {\n  voidFetchDuringEachTest();\n\n  it(\"throws if no fetch is present\", () => {\n    expect(() => checkFetcher(undefined)).toThrow(\n      /has not been found globally/\n    );\n  });\n\n  it(\"does not throws if no fetch is present but a fetch is passed\", () => {\n    expect(() => checkFetcher((() => {}) as any)).not.toThrow();\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/headerNormalization.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport {\n  fallbackHttpConfig,\n  selectHttpOptionsAndBody,\n} from \"@apollo/client/link/http\";\nimport { createOperationWithDefaultContext as createOperation } from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"headerNormalization\", () => {\n  it(\"normalizes HTTP header names to lower case by default\", () => {\n    const config = {\n      headers: {\n        accept: \"text/html\",\n        ACCEPT: \"text/html\",\n        \"content-type\": \"application/graphql\",\n        \"CONTENT-TYPE\": \"application/graphql\",\n      },\n    };\n\n    const { options, body } = selectHttpOptionsAndBody(\n      createOperation({ query }),\n      fallbackHttpConfig,\n      config\n    );\n\n    expect(body).toHaveProperty(\"query\");\n    expect(body).not.toHaveProperty(\"extensions\");\n\n    expect(options.headers).toEqual({\n      accept: \"text/html\",\n      \"content-type\": \"application/graphql\",\n    });\n  });\n\n  it(\"preserves HTTP header name capitalization when enabled\", () => {\n    const config = {\n      headers: {\n        accept: \"text/html\",\n        ACCEPT: \"text/html\",\n        \"content-type\": \"application/graphql\",\n        \"CONTENT-TYPE\": \"application/graphql\",\n      },\n      http: { preserveHeaderCase: true },\n    };\n\n    const { options } = selectHttpOptionsAndBody(\n      createOperation({ query }),\n      fallbackHttpConfig,\n      config\n    );\n\n    expect(options.headers).toEqual({\n      ACCEPT: \"text/html\",\n      \"CONTENT-TYPE\": \"application/graphql\",\n    });\n  });\n\n  it(\"ensures context preserveHeaderCase overrides link config (true->false)\", () => {\n    const linkConfig = {\n      headers: {\n        accept: \"text/html\",\n        ACCEPT: \"text/html\",\n      },\n      http: { preserveHeaderCase: true },\n    };\n    const contextConfig = {\n      headers: {\n        \"content-type\": \"application/graphql\",\n        \"CONTENT-TYPE\": \"application/graphql\",\n      },\n      http: { preserveHeaderCase: false },\n    };\n    const { options } = selectHttpOptionsAndBody(\n      createOperation({ query }),\n      fallbackHttpConfig,\n      linkConfig,\n      contextConfig\n    );\n\n    expect(options.headers).toEqual({\n      accept: \"text/html\",\n      \"content-type\": \"application/graphql\",\n    });\n  });\n\n  it(\"ensures context preserveHeaderCase overrides link config (false->true)\", () => {\n    const linkConfig = {\n      headers: {\n        accept: \"text/html\",\n        ACCEPT: \"text/html\",\n      },\n      http: { preserveHeaderCase: false },\n    };\n    const contextConfig = {\n      headers: {\n        \"content-type\": \"application/graphql\",\n        \"CONTENT-TYPE\": \"application/graphql\",\n      },\n      http: { preserveHeaderCase: true },\n    };\n    const { options } = selectHttpOptionsAndBody(\n      createOperation({ query }),\n      fallbackHttpConfig,\n      linkConfig,\n      contextConfig\n    );\n\n    expect(options.headers).toEqual({\n      ACCEPT: \"text/html\",\n      \"CONTENT-TYPE\": \"application/graphql\",\n    });\n  });\n\n  it(\"ensures link headerNormalization affects context headers\", () => {\n    const linkConfig = {\n      headers: {\n        accept: \"text/html\",\n        ACCEPT: \"text/html\",\n      },\n      http: { preserveHeaderCase: true },\n    };\n    const contextConfig = {\n      headers: {\n        \"content-type\": \"application/graphql\",\n        \"CONTENT-TYPE\": \"application/graphql\",\n      },\n    };\n\n    const { options } = selectHttpOptionsAndBody(\n      createOperation({ query }),\n      fallbackHttpConfig,\n      linkConfig,\n      contextConfig\n    );\n\n    expect(options.headers).toEqual({\n      ACCEPT: \"text/html\",\n      \"CONTENT-TYPE\": \"application/graphql\",\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/helpers.ts",
    "content": "export function voidFetchDuringEachTest() {\n  let fetchDesc = Object.getOwnPropertyDescriptor(window, \"fetch\");\n\n  beforeEach(() => {\n    fetchDesc = fetchDesc || Object.getOwnPropertyDescriptor(window, \"fetch\");\n    if (fetchDesc?.configurable) {\n      delete (window as any).fetch;\n    }\n  });\n\n  afterEach(() => {\n    if (fetchDesc?.configurable) {\n      Object.defineProperty(window, \"fetch\", fetchDesc);\n    }\n  });\n}\n\ndescribe(\"voidFetchDuringEachTest\", () => {\n  voidFetchDuringEachTest();\n\n  it(\"hides the global.fetch function\", () => {\n    expect(window.fetch).toBe(void 0);\n    expect(() => fetch).toThrow(ReferenceError);\n  });\n\n  it(\"globalThis === window\", () => {\n    expect(globalThis).toBe(window);\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/parseAndCheckHttpResponse.ts",
    "content": "import fetchMock from \"fetch-mock\";\nimport { gql } from \"graphql-tag\";\n\nimport { parseAndCheckHttpResponse } from \"@apollo/client/link/http\";\nimport { createOperationWithDefaultContext as createOperation } from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"parseAndCheckResponse\", () => {\n  beforeEach(() => {\n    fetchMock.restore();\n  });\n\n  const operations = [createOperation({ query })];\n\n  it(\"throws a Server error when response is > 300 with unparsable json\", async () => {\n    const status = 400;\n    fetchMock.mock(\"begin:/error\", {\n      status,\n      headers: { \"content-type\": \"application/json\" },\n    });\n\n    const error = await fetch(\"error\")\n      .then(parseAndCheckHttpResponse(operations))\n      .catch((error) => error);\n\n    expect(error.statusCode).toBe(status);\n    expect(error.name).toBe(\"ServerError\");\n    expect(error).toHaveProperty(\"response\");\n    expect(error.bodyText).toBe(\"\");\n  });\n\n  it(\"throws a ServerParse error when response is 200 with unparsable json\", async () => {\n    const status = 200;\n    fetchMock.mock(\"begin:/error\", {\n      status,\n      headers: { \"content-type\": \"application/json\" },\n    });\n    const error = await fetch(\"error\")\n      .then(parseAndCheckHttpResponse(operations))\n      .catch((error) => error);\n\n    expect(error.statusCode).toBe(status);\n    expect(error.name).toBe(\"ServerParseError\");\n    expect(error).toHaveProperty(\"response\");\n    expect(error).toHaveProperty(\"bodyText\");\n  });\n\n  it(\"throws a network error with a status code and result\", async () => {\n    const status = 403;\n    const body = { data: \"fail\" }; //does not contain data or errors\n    fetchMock.mock(\"begin:/error\", {\n      body,\n      status,\n    });\n    const error = await fetch(\"error\")\n      .then(parseAndCheckHttpResponse(operations))\n      .catch((error) => error);\n\n    expect(error.statusCode).toBe(status);\n    expect(error.name).toBe(\"ServerError\");\n    expect(error).toHaveProperty(\"response\");\n    expect(error).toHaveProperty(\"bodyText\");\n  });\n\n  it(\"throws a server error on incorrect data\", async () => {\n    const data = { hello: \"world\" }; //does not contain data or errors\n    fetchMock.mock(\"begin:/incorrect\", data);\n    const error = await fetch(\"incorrect\")\n      .then(parseAndCheckHttpResponse(operations))\n      .catch((error) => error);\n\n    expect(error.statusCode).toBe(200);\n    expect(error.name).toBe(\"ServerError\");\n    expect(error).toHaveProperty(\"response\");\n    expect(error.bodyText).toEqual(JSON.stringify(data));\n  });\n\n  it(\"is able to return a correct GraphQL result\", async () => {\n    const errors = [\"\", \"\" + new Error(\"hi\")];\n    const data = { data: { hello: \"world\" }, errors };\n\n    fetchMock.mock(\"begin:/data\", {\n      body: data,\n    });\n\n    {\n      const { data, errors: e } = await fetch(\"data\").then(\n        parseAndCheckHttpResponse(operations)\n      );\n\n      expect(data).toEqual({ hello: \"world\" });\n      expect(e.length).toEqual(errors.length);\n      expect(e).toEqual(errors);\n    }\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/responseIterator.ts",
    "content": "import { Readable } from \"stream\";\nimport { TextDecoder } from \"util\";\n\nimport { gql } from \"graphql-tag\";\nimport { ReadableStream } from \"web-streams-polyfill\";\n\nimport { HttpLink } from \"@apollo/client/link/http\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nconst sampleDeferredQuery = gql`\n  query SampleDeferredQuery {\n    stub {\n      id\n      ... on Stub @defer {\n        name\n      }\n    }\n  }\n`;\n\nconst BOUNDARY = \"gc0p4Jq0M2Yt08jU534c0p\";\n\ndescribe(\"multipart responses\", () => {\n  let originalTextDecoder: any;\n  beforeAll(() => {\n    originalTextDecoder = TextDecoder;\n    (globalThis as any).TextDecoder = TextDecoder;\n  });\n\n  afterAll(() => {\n    globalThis.TextDecoder = originalTextDecoder;\n  });\n\n  const bodyCustomBoundary = [\n    `--${BOUNDARY}`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 43\",\n    \"\",\n    '{\"data\":{\"stub\":{\"id\":\"0\"}},\"hasNext\":true}',\n    `--${BOUNDARY}`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 58\",\n    \"\",\n    '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby\"},\"path\":[\"stub\"]}]}',\n    `--${BOUNDARY}--`,\n  ].join(\"\\r\\n\");\n\n  const bodyIncorrectChunkType = [\n    `---`,\n    \"Content-Type: foo/bar; charset=utf-8\",\n    \"Content-Length: 43\",\n    \"\",\n    '{\"data\":{\"stub\":{\"id\":\"0\"}},\"hasNext\":true}',\n    `---`,\n    \"Content-Type: foo/bar; charset=utf-8\",\n    \"Content-Length: 58\",\n    \"\",\n    '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby\"},\"path\":[\"stub\"]}]}',\n    `-----`,\n  ].join(\"\\r\\n\");\n\n  const results = [\n    {\n      data: {\n        stub: {\n          id: \"0\",\n        },\n      },\n      hasNext: true,\n    },\n    {\n      incremental: [\n        {\n          data: {\n            name: \"stubby\",\n          },\n          path: [\"stub\"],\n        },\n      ],\n      hasNext: false,\n    },\n  ];\n\n  it(\"can handle whatwg stream bodies\", async () => {\n    const stream = new ReadableStream({\n      async start(controller) {\n        const lines = bodyCustomBoundary.split(\"\\r\\n\");\n        try {\n          for (const line of lines) {\n            controller.enqueue(line + \"\\r\\n\");\n          }\n        } finally {\n          controller.close();\n        }\n      },\n    });\n\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      headers: new Headers({\n        \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n      }),\n    }));\n\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of results) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toComplete();\n  });\n\n  it(\"can handle whatwg stream bodies with arbitrary splits\", async () => {\n    const stream = new ReadableStream({\n      async start(controller) {\n        let chunks: Array<string> = [];\n        let chunkSize = 15;\n        for (let i = 0; i < bodyCustomBoundary.length; i += chunkSize) {\n          chunks.push(bodyCustomBoundary.slice(i, i + chunkSize));\n        }\n\n        try {\n          for (const chunk of chunks) {\n            controller.enqueue(chunk);\n          }\n        } finally {\n          controller.close();\n        }\n      },\n    });\n\n    const fetch = jest.fn(async () => {\n      const val = {\n        status: 200,\n        body: stream,\n        headers: new Headers({\n          \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n        }),\n      };\n\n      return val;\n    });\n\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of results) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toComplete();\n  });\n\n  it(\"throws error on non-streamable body\", async () => {\n    // non-streamable body\n    const body = 12345;\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body,\n      headers: new Headers({\n        \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n      }),\n    }));\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const mockError = {\n      throws: new InvariantError(\n        \"Unknown type for `response.body`. Please use a `fetch` implementation that is WhatWG-compliant and that uses WhatWG ReadableStreams for `body`.\"\n      ),\n    };\n\n    const observableStream = new ObservableStream(observable);\n\n    await expect(observableStream).toEmitError(mockError.throws);\n  });\n\n  // test is still failing as observer.complete is called even after error is thrown\n  it.failing(\"throws error on unsupported patch content type\", async () => {\n    const stream = Readable.from(\n      bodyIncorrectChunkType.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n    );\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      headers: new Headers({\n        \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n      }),\n    }));\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const mockError = {\n      throws: new Error(\n        \"Unsupported patch content type: application/json is required\"\n      ),\n    };\n    const observableStream = new ObservableStream(observable);\n\n    await expect(observableStream).toEmitError(mockError.throws);\n  });\n\n  describe(\"without TextDecoder defined in the environment\", () => {\n    beforeAll(() => {\n      originalTextDecoder = TextDecoder;\n      (globalThis as any).TextDecoder = undefined;\n    });\n\n    afterAll(() => {\n      globalThis.TextDecoder = originalTextDecoder;\n    });\n\n    it(\"throws error if TextDecoder not defined in the environment\", async () => {\n      const stream = Readable.from(\n        bodyIncorrectChunkType.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n      );\n      const fetch = jest.fn(async () => ({\n        status: 200,\n        body: stream,\n        headers: new Headers({\n          \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n        }),\n      }));\n      const link = new HttpLink({\n        fetch: fetch as any,\n      });\n      const observable = execute(link, { query: sampleDeferredQuery });\n      const mockError = {\n        throws: new TypeError(\"TextDecoder is not a constructor\"),\n      };\n\n      const observableStream = new ObservableStream(observable);\n\n      await expect(observableStream).toEmitError(mockError.throws);\n    });\n  });\n\n  describe(\"final boundary handling\", () => {\n    test(\"should handle final boundary correctly\", async () => {\n      const transform = new TransformStream({\n        transform(chunk, controller) {\n          controller.enqueue(chunk.replace(/\\n/g, \"\\r\\n\"));\n        },\n      });\n      const link = new HttpLink({\n        fetch: jest.fn().mockResolvedValue(\n          new Response(transform.readable, {\n            status: 200,\n            headers: new Headers({\n              \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n            }),\n          })\n        ),\n      });\n      const observable = execute(link, { query: sampleDeferredQuery });\n      const observableStream = new ObservableStream(observable);\n      const writer = transform.writable.getWriter();\n      void writer.write(\n        `--${BOUNDARY}\nContent-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}`\n      );\n      await expect(observableStream).toEmitTypedValue(results[0]);\n      void writer.write(\"-\");\n      await expect(observableStream).not.toEmitAnything();\n      void writer.write(\"-\");\n      await expect(observableStream).toComplete();\n      // writer has forcibly been closed by `reader.cancel`\n      await expect(writer.closed).rejects.toBe(undefined);\n    });\n\n    test(\"content after final boundary is ignored\", async () => {\n      const transform = new TransformStream({\n        transform(chunk, controller) {\n          controller.enqueue(chunk.replace(/\\n/g, \"\\r\\n\"));\n        },\n      });\n      const link = new HttpLink({\n        fetch: jest.fn().mockResolvedValue(\n          new Response(transform.readable, {\n            status: 200,\n            headers: new Headers({\n              \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n            }),\n          })\n        ),\n      });\n      const observable = execute(link, { query: sampleDeferredQuery });\n      const observableStream = new ObservableStream(observable);\n      const writer = transform.writable.getWriter();\n      void writer.write(\n        `--${BOUNDARY}\nContent-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}--\nContent-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}--`\n      );\n      await expect(observableStream).toEmitTypedValue(results[0]);\n      await expect(observableStream).toComplete();\n    });\n\n    test(\"stream is closed on final boundary\", async () => {\n      const transform = new TransformStream({\n        transform(chunk, controller) {\n          controller.enqueue(chunk.replace(/\\n/g, \"\\r\\n\"));\n        },\n      });\n      const link = new HttpLink({\n        fetch: jest.fn().mockResolvedValue(\n          new Response(transform.readable, {\n            status: 200,\n            headers: new Headers({\n              \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n            }),\n          })\n        ),\n      });\n      const observable = execute(link, { query: sampleDeferredQuery });\n      const observableStream = new ObservableStream(observable);\n      const writer = transform.writable.getWriter();\n      void writer.write(\n        `--${BOUNDARY}\nContent-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}--`\n      );\n      await expect(observableStream).toEmitTypedValue(results[0]);\n      await expect(observableStream).toComplete();\n      await expect(\n        writer.write(\n          `Content-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}--`\n        )\n      ).rejects.toBe(undefined);\n    });\n\n    test(\"link errors if stream is closed without final boundary\", async () => {\n      const transform = new TransformStream({\n        transform(chunk, controller) {\n          controller.enqueue(chunk.replace(/\\n/g, \"\\r\\n\"));\n        },\n      });\n      const link = new HttpLink({\n        fetch: jest.fn().mockResolvedValue(\n          new Response(transform.readable, {\n            status: 200,\n            headers: new Headers({\n              \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n            }),\n          })\n        ),\n      });\n      const observable = execute(link, { query: sampleDeferredQuery });\n      const observableStream = new ObservableStream(observable);\n      const writer = transform.writable.getWriter();\n      void writer.write(\n        `--${BOUNDARY}\nContent-Type: application/json; charset=utf-8\nContent-Length: 43\n\n${JSON.stringify(results[0])}\n--${BOUNDARY}`\n      );\n      await expect(observableStream).toEmitTypedValue(results[0]);\n      await writer.close();\n      await expect(observableStream).toEmitError(\n        new Error(\"premature end of multipart body\")\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/responseIteratorNoAsyncIterator.ts",
    "content": "import { TextDecoder, TextEncoder } from \"util\";\n\nimport { gql } from \"graphql-tag\";\nimport { ReadableStream } from \"web-streams-polyfill\";\n\nimport { HttpLink } from \"@apollo/client/link/http\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nconst sampleDeferredQuery = gql`\n  query SampleDeferredQuery {\n    stub {\n      id\n      ... on Stub @defer {\n        name\n      }\n    }\n  }\n`;\n\nconst BOUNDARY = \"gc0p4Jq0M2Yt08jU534c0p\";\n\ndescribe(\"multipart responses\", () => {\n  let originalTextDecoder: any;\n  beforeAll(() => {\n    originalTextDecoder = TextDecoder;\n    (globalThis as any).TextDecoder = TextDecoder;\n  });\n\n  afterAll(() => {\n    globalThis.TextDecoder = originalTextDecoder;\n  });\n\n  const bodyCustomBoundary = [\n    `--${BOUNDARY}`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 43\",\n    \"\",\n    '{\"data\":{\"stub\":{\"id\":\"0\"}},\"hasNext\":true}',\n    `--${BOUNDARY}`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 58\",\n    \"\",\n    '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby\"},\"path\":[\"stub\"]}]}',\n    `--${BOUNDARY}--`,\n  ].join(\"\\r\\n\");\n\n  const bodyDefaultBoundary = [\n    `---`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 43\",\n    \"\",\n    '{\"data\":{\"stub\":{\"id\":\"0\"}},\"hasNext\":true}',\n    `---`,\n    \"Content-Type: application/json; charset=utf-8\",\n    \"Content-Length: 58\",\n    \"\",\n    '{\"hasNext\":false, \"incremental\": [{\"data\":{\"name\":\"stubby\"},\"path\":[\"stub\"]}]}',\n    `-----`,\n  ].join(\"\\r\\n\");\n\n  const bodyBatchedResults = [\n    \"--graphql\",\n    \"content-type: application/json\",\n    \"\",\n    '{\"data\":{\"allProducts\":[{\"delivery\":{\"__typename\":\"DeliveryEstimates\"},\"sku\":\"federation\",\"id\":\"apollo-federation\",\"__typename\":\"Product\"},{\"delivery\":{\"__typename\":\"DeliveryEstimates\"},\"sku\":\"studio\",\"id\":\"apollo-studio\",\"__typename\":\"Product\"}]},\"hasNext\":true}',\n    \"--graphql\",\n    \"content-type: application/json\",\n    \"\",\n    '{\"hasNext\":true,\"incremental\":[{\"data\":{\"estimatedDelivery\":\"6/25/2021\",\"fastestDelivery\":\"6/24/2021\",\"__typename\":\"DeliveryEstimates\"},\"path\":[\"allProducts\",0,\"delivery\"]},{\"data\":{\"estimatedDelivery\":\"6/25/2021\",\"fastestDelivery\":\"6/24/2021\",\"__typename\":\"DeliveryEstimates\"},\"path\":[\"allProducts\",1,\"delivery\"]}]}',\n    \"--graphql\",\n    \"content-type: application/json\",\n    \"\",\n    '{\"hasNext\":false}',\n    \"--graphql--\",\n  ].join(\"\\r\\n\");\n\n  const results = [\n    {\n      data: {\n        stub: {\n          id: \"0\",\n        },\n      },\n      hasNext: true,\n    },\n    {\n      incremental: [\n        {\n          data: {\n            name: \"stubby\",\n          },\n          path: [\"stub\"],\n        },\n      ],\n      hasNext: false,\n    },\n  ];\n\n  const batchedResults = [\n    {\n      data: {\n        allProducts: [\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-federation\",\n            sku: \"federation\",\n          },\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-studio\",\n            sku: \"studio\",\n          },\n        ],\n      },\n      hasNext: true,\n    },\n    {\n      hasNext: true,\n      incremental: [\n        {\n          data: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          path: [\"allProducts\", 0, \"delivery\"],\n        },\n        {\n          data: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          path: [\"allProducts\", 1, \"delivery\"],\n        },\n      ],\n    },\n  ];\n\n  it(\"can handle whatwg stream bodies\", async () => {\n    const stream = new ReadableStream({\n      async start(controller) {\n        const lines = bodyCustomBoundary.split(\"\\r\\n\");\n        try {\n          for (const line of lines) {\n            controller.enqueue(line + \"\\r\\n\");\n          }\n        } finally {\n          controller.close();\n        }\n      },\n    });\n\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      headers: new Headers({\n        \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n      }),\n    }));\n\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of results) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toComplete();\n  });\n\n  it(\"can handle whatwg stream bodies with arbitrary splits\", async () => {\n    const stream = new ReadableStream({\n      async start(controller) {\n        let chunks: Array<string> = [];\n        let chunkSize = 15;\n        for (let i = 0; i < bodyCustomBoundary.length; i += chunkSize) {\n          chunks.push(bodyCustomBoundary.slice(i, i + chunkSize));\n        }\n\n        try {\n          for (const chunk of chunks) {\n            controller.enqueue(chunk);\n          }\n        } finally {\n          controller.close();\n        }\n      },\n    });\n\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      headers: new Headers({\n        \"content-type\": `multipart/mixed; boundary=${BOUNDARY}`,\n      }),\n    }));\n\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of results) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toComplete();\n  });\n\n  it(\"can handle node stream bodies (strings) with default boundary\", async () => {\n    const stream = ReadableStream.from(\n      bodyDefaultBoundary.split(\"\\r\\n\").map((line) => line + \"\\r\\n\")\n    );\n\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      // if no boundary is specified, default to -\n      headers: new Headers({\n        \"content-type\": `multipart/mixed`,\n      }),\n    }));\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of results) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toComplete();\n  });\n\n  it(\"can handle node stream bodies (array buffers) with batched results\", async () => {\n    const stream = ReadableStream.from(\n      bodyBatchedResults\n        .split(\"\\r\\n\")\n        .map((line) => new TextEncoder().encode(line + \"\\r\\n\"))\n    );\n\n    const fetch = jest.fn(async () => ({\n      status: 200,\n      body: stream,\n      // if no boundary is specified, default to -\n      headers: new Headers({\n        \"Content-Type\": `multipart/mixed;boundary=\"graphql\";deferSpec=20220824`,\n      }),\n    }));\n    const link = new HttpLink({\n      fetch: fetch as any,\n    });\n\n    const observable = execute(link, { query: sampleDeferredQuery });\n    const observableStream = new ObservableStream(observable);\n\n    for (const result of batchedResults) {\n      await expect(observableStream).toEmitTypedValue(result);\n    }\n\n    await expect(observableStream).toEmitTypedValue({\n      hasNext: false,\n    });\n\n    await expect(observableStream).toComplete();\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/selectHttpOptionsAndBody.ts",
    "content": "import type { ASTNode, print } from \"graphql\";\nimport { stripIgnoredCharacters } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport {\n  fallbackHttpConfig,\n  selectHttpOptionsAndBody,\n  selectHttpOptionsAndBodyInternal,\n} from \"@apollo/client/link/http\";\nimport { createOperationWithDefaultContext as createOperation } from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"selectHttpOptionsAndBody\", () => {\n  it(\"includeQuery allows the query to be ignored\", () => {\n    const { body } = selectHttpOptionsAndBody(createOperation({ query }), {\n      http: { includeQuery: false },\n    });\n    expect(body).not.toHaveProperty(\"query\");\n  });\n\n  it(\"includeExtensions allows the extensions to be added\", () => {\n    const extensions = { yo: \"what up\" };\n    const { body } = selectHttpOptionsAndBody(\n      createOperation({ query, extensions }),\n      { http: { includeExtensions: true } }\n    );\n    expect(body).toHaveProperty(\"extensions\");\n    expect((body as any).extensions).toEqual(extensions);\n  });\n\n  it(\"the fallbackConfig is used if no other configs are specified\", () => {\n    const defaultHeaders = {\n      accept: \"application/graphql-response+json,application/json;q=0.9\",\n      \"content-type\": \"application/json\",\n    };\n\n    const defaultOptions = {\n      method: \"POST\",\n    };\n\n    const extensions = { yo: \"what up\" };\n    const { options, body } = selectHttpOptionsAndBody(\n      createOperation({ query, extensions }),\n      fallbackHttpConfig\n    );\n\n    expect(body).toHaveProperty(\"query\");\n    expect(body.extensions).toStrictEqual(extensions);\n\n    expect(options.headers).toEqual(defaultHeaders);\n    expect(options.method).toEqual(defaultOptions.method);\n  });\n\n  it(\"allows headers, credentials, and setting of method to function correctly\", () => {\n    const headers = {\n      accept: \"application/json\",\n      \"content-type\": \"application/graphql\",\n    };\n\n    const credentials = {\n      \"X-Secret\": \"djmashko\",\n    };\n\n    const opts = {\n      opt: \"hi\",\n    };\n\n    const config = { headers, credentials, options: opts };\n\n    const extensions = { yo: \"what up\" };\n\n    const { options, body } = selectHttpOptionsAndBody(\n      createOperation({ query, extensions }),\n      fallbackHttpConfig,\n      config\n    );\n\n    expect(body).toHaveProperty(\"query\");\n    expect(body.extensions).toStrictEqual(extensions);\n\n    expect(options.headers).toEqual(headers);\n    expect(options.credentials).toEqual(credentials);\n    expect(options.opt).toEqual(\"hi\");\n    expect(options.method).toEqual(\"POST\"); //from default\n  });\n\n  it(\"can explicitly disable `includeExtensions`\", () => {\n    const headers = {\n      accept: \"application/json\",\n      \"content-type\": \"application/graphql\",\n    };\n\n    const credentials = {\n      \"X-Secret\": \"djmashko\",\n    };\n\n    const extensions = { yo: \"what up\" };\n\n    const { options, body } = selectHttpOptionsAndBody(\n      createOperation({ query, extensions }),\n      fallbackHttpConfig,\n      {\n        headers,\n        credentials,\n        http: {\n          includeExtensions: false,\n        },\n        options: { opt: \"hi\" },\n      }\n    );\n\n    expect(body).toHaveProperty(\"query\");\n    expect(body).not.toHaveProperty(\"extensions\");\n\n    expect(options.headers).toEqual(headers);\n    expect(options.credentials).toEqual(credentials);\n    expect(options.opt).toEqual(\"hi\");\n    expect(options.method).toEqual(\"POST\"); //from default\n  });\n\n  it(\"applies custom printer function when provided\", () => {\n    const customPrinter = (ast: ASTNode, originalPrint: typeof print) => {\n      return stripIgnoredCharacters(originalPrint(ast));\n    };\n\n    const { body } = selectHttpOptionsAndBodyInternal(\n      createOperation({ query }),\n      customPrinter,\n      fallbackHttpConfig\n    );\n\n    expect(body.query).toBe(\"query SampleQuery{stub{id}}\");\n  });\n});\n"
  },
  {
    "path": "src/link/http/__tests__/selectURI.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport { selectURI } from \"@apollo/client/link/http\";\nimport { createOperationWithDefaultContext as createOperation } from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"selectURI\", () => {\n  it(\"returns a passed in string\", () => {\n    const uri = \"/somewhere\";\n    const operation = createOperation({ query, context: { uri } });\n    expect(selectURI(operation)).toEqual(uri);\n  });\n\n  it(\"returns a fallback of /graphql\", () => {\n    const uri = \"/graphql\";\n    const operation = createOperation({ query });\n    expect(selectURI(operation)).toEqual(uri);\n  });\n\n  it(\"returns the result of a UriFunction\", () => {\n    const uri = \"/somewhere\";\n    const operation = createOperation({ query });\n    expect(selectURI(operation, () => uri)).toEqual(uri);\n  });\n});\n"
  },
  {
    "path": "src/link/http/checkFetcher.ts",
    "content": "import { invariant } from \"@apollo/client/utilities/invariant\";\n\nexport const checkFetcher = (fetcher: typeof fetch | undefined) => {\n  invariant(\n    fetcher || typeof fetch !== \"undefined\",\n    `\n\"fetch\" has not been found globally and no fetcher has been \\\nconfigured. To fix this, install a fetch package (like \\\nhttps://www.npmjs.com/package/cross-fetch), instantiate the \\\nfetcher, and pass it into your HttpLink constructor. For example:\n\nimport fetch from 'cross-fetch';\nimport { ApolloClient, HttpLink } from '@apollo/client';\nconst client = new ApolloClient({\n  link: new HttpLink({ uri: '/graphql', fetch })\n});\n    `\n  );\n};\n"
  },
  {
    "path": "src/link/http/createSignalIfSupported.ts",
    "content": "/**\n * @deprecated\n * This is not used internally any more and will be removed in\n * the next major version of Apollo Client.\n */\nexport const createSignalIfSupported = () => {\n  if (typeof AbortController === \"undefined\")\n    return { controller: false, signal: false };\n\n  const controller = new AbortController();\n  const signal = controller.signal;\n  return { controller, signal };\n};\n"
  },
  {
    "path": "src/link/http/index.ts",
    "content": "export { parseAndCheckHttpResponse } from \"./parseAndCheckHttpResponse.js\";\nexport {\n  defaultPrinter,\n  fallbackHttpConfig,\n  selectHttpOptionsAndBody,\n  selectHttpOptionsAndBodyInternal, // needed by ../batch-http but not public\n} from \"./selectHttpOptionsAndBody.js\";\nexport { checkFetcher } from \"./checkFetcher.js\";\nexport { createSignalIfSupported } from \"./createSignalIfSupported.js\";\nexport { selectURI } from \"./selectURI.js\";\nexport { BaseHttpLink } from \"./BaseHttpLink.js\";\nexport { createHttpLink, HttpLink } from \"./HttpLink.js\";\nexport { rewriteURIForGET } from \"./rewriteURIForGET.js\";\n"
  },
  {
    "path": "src/link/http/parseAndCheckHttpResponse.ts",
    "content": "import {\n  CombinedProtocolErrors,\n  PROTOCOL_ERRORS_SYMBOL,\n  ServerError,\n  ServerParseError,\n} from \"@apollo/client/errors\";\nimport type { ApolloLink, ApolloPayloadResult } from \"@apollo/client/link\";\nimport { isNonNullObject } from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nconst { hasOwnProperty } = Object.prototype;\n\n/**\n * This function detects an Apollo payload result before it is transformed\n * into a FetchResult via HttpLink; it cannot detect an ApolloPayloadResult\n * once it leaves the link chain.\n */\nfunction isApolloPayloadResult(value: unknown): value is ApolloPayloadResult {\n  return isNonNullObject(value) && \"payload\" in value;\n}\n\nasync function* consumeMultipartBody(\n  response: Response\n): AsyncGenerator<string, void, void> {\n  const decoder = new TextDecoder(\"utf-8\");\n  const contentType = response.headers?.get(\"content-type\");\n\n  // parse boundary value and ignore any subsequent name/value pairs after ;\n  // https://www.rfc-editor.org/rfc/rfc9110.html#name-parameters\n  // e.g. multipart/mixed;boundary=\"graphql\";deferSpec=20220824\n  // if no boundary is specified, default to -\n  const match = contentType?.match(\n    /*\n      ;\\s*boundary=                # Match the boundary parameter\n      (?:                          # either\n        '([^']*)'                  # a string starting with ' doesn't contain ', ends with '\n        |                          # or\n        \"([^\"]*)\"                  # a string starting with \" doesn't contain \", ends with \"\n        |                          # or\n        ([^\"'].*?)                 # a string that doesn't start with ' or \", parsed non-greedily\n        )                          # end of the group\n      \\s*                          # optional whitespace\n      (?:;|$)                        # match a semicolon or end of string\n    */\n    /;\\s*boundary=(?:'([^']+)'|\"([^\"]+)\"|([^\"'].+?))\\s*(?:;|$)/i\n  );\n  const boundary =\n    \"\\r\\n--\" + (match ? match[1] ?? match[2] ?? match[3] ?? \"-\" : \"-\");\n  let buffer = \"\";\n  invariant(\n    response.body && typeof response.body.getReader === \"function\",\n    \"Unknown type for `response.body`. Please use a `fetch` implementation that is WhatWG-compliant and that uses WhatWG ReadableStreams for `body`.\"\n  );\n\n  const stream = response.body;\n  const reader = stream.getReader();\n  let done = false;\n  let encounteredBoundary = false;\n  let value: Uint8Array<ArrayBufferLike> | string | undefined;\n\n  // check to see if we received the final boundary, which is a normal boundary followed by \"--\"\n  // as described in https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1\n  const passedFinalBoundary = () =>\n    encounteredBoundary && buffer[0] == \"-\" && buffer[1] == \"-\";\n\n  try {\n    while (!done) {\n      ({ value, done } = await reader.read());\n      const chunk = typeof value === \"string\" ? value : decoder.decode(value);\n      const searchFrom = buffer.length - boundary.length + 1;\n      buffer += chunk;\n      let bi = buffer.indexOf(boundary, searchFrom);\n      while (bi > -1 && !passedFinalBoundary()) {\n        encounteredBoundary = true;\n        let message: string;\n        [message, buffer] = [\n          buffer.slice(0, bi),\n          buffer.slice(bi + boundary.length),\n        ];\n        const i = message.indexOf(\"\\r\\n\\r\\n\");\n        const headers = parseHeaders(message.slice(0, i));\n        const contentType = headers[\"content-type\"];\n        if (\n          contentType &&\n          contentType.toLowerCase().indexOf(\"application/json\") === -1\n        ) {\n          throw new Error(\n            \"Unsupported patch content type: application/json is required.\"\n          );\n        }\n        // nb: Technically you'd want to slice off the beginning \"\\r\\n\" but since\n        // this is going to be `JSON.parse`d there is no need.\n        const body = message.slice(i);\n\n        if (body) {\n          yield body;\n        }\n        bi = buffer.indexOf(boundary);\n      }\n      if (passedFinalBoundary()) {\n        return;\n      }\n    }\n    throw new Error(\"premature end of multipart body\");\n  } finally {\n    reader.cancel();\n  }\n}\n\nexport async function readMultipartBody<\n  T extends object = Record<string, unknown>,\n>(response: Response, nextValue: (value: T) => void) {\n  for await (const body of consumeMultipartBody(response)) {\n    const result = parseJsonEncoding(response, body);\n    if (Object.keys(result).length == 0) continue;\n    if (isApolloPayloadResult(result)) {\n      if (Object.keys(result).length === 1 && result.payload === null) {\n        return;\n      }\n      let next = { ...result.payload };\n      if (\"errors\" in result) {\n        next.extensions = {\n          ...next.extensions,\n          [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors(\n            result.errors ?? []\n          ),\n        };\n      }\n      nextValue(next as T);\n    } else {\n      nextValue(result);\n    }\n  }\n}\n\nfunction parseHeaders(headerText: string): Record<string, string> {\n  const headersInit: Record<string, string> = {};\n  headerText.split(\"\\n\").forEach((line) => {\n    const i = line.indexOf(\":\");\n    if (i > -1) {\n      // normalize headers to lowercase\n      const name = line.slice(0, i).trim().toLowerCase();\n      const value = line.slice(i + 1).trim();\n      headersInit[name] = value;\n    }\n  });\n  return headersInit;\n}\n\nfunction parseJsonEncoding(response: Response, bodyText: string) {\n  if (response.status >= 300) {\n    throw new ServerError(\n      `Response not successful: Received status code ${response.status}`,\n      { response, bodyText }\n    );\n  }\n\n  try {\n    return JSON.parse(bodyText);\n  } catch (err) {\n    throw new ServerParseError(err, { response, bodyText });\n  }\n}\n\nfunction parseGraphQLResponseJsonEncoding(\n  response: Response,\n  bodyText: string\n) {\n  try {\n    return JSON.parse(bodyText);\n  } catch (err) {\n    throw new ServerParseError(err, { response, bodyText });\n  }\n}\n\nfunction parseResponse(response: Response, bodyText: string) {\n  const contentType = response.headers.get(\"content-type\");\n\n  if (contentType?.includes(\"application/graphql-response+json\")) {\n    return parseGraphQLResponseJsonEncoding(response, bodyText);\n  }\n\n  return parseJsonEncoding(response, bodyText);\n}\n\nexport function parseAndCheckHttpResponse(\n  operations: ApolloLink.Operation | ApolloLink.Operation[]\n) {\n  return (response: Response) =>\n    response.text().then((bodyText) => {\n      const result = parseResponse(response, bodyText);\n\n      if (\n        !Array.isArray(result) &&\n        !hasOwnProperty.call(result, \"data\") &&\n        !hasOwnProperty.call(result, \"errors\")\n      ) {\n        throw new ServerError(\n          `Server response was malformed for query '${\n            Array.isArray(operations) ?\n              operations.map((op) => op.operationName)\n            : operations.operationName\n          }'.`,\n          { response, bodyText }\n        );\n      }\n      return result;\n    });\n}\n"
  },
  {
    "path": "src/link/http/rewriteURIForGET.ts",
    "content": "import type { BaseHttpLink } from \"./BaseHttpLink.js\";\n\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nexport function rewriteURIForGET(chosenURI: string, body: BaseHttpLink.Body) {\n  // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n  // the extra level of JSON serialization!\n  const queryParams: string[] = [];\n  const addQueryParam = (key: string, value: string) => {\n    queryParams.push(`${key}=${encodeURIComponent(value)}`);\n  };\n\n  if (\"query\" in body) {\n    addQueryParam(\"query\", body.query!);\n  }\n  if (body.operationName) {\n    addQueryParam(\"operationName\", body.operationName);\n  }\n  if (body.variables) {\n    let serializedVariables;\n    try {\n      serializedVariables = JSON.stringify(body.variables);\n    } catch (parseError) {\n      return { parseError };\n    }\n    addQueryParam(\"variables\", serializedVariables);\n  }\n  if (body.extensions) {\n    let serializedExtensions;\n    try {\n      serializedExtensions = JSON.stringify(body.extensions);\n    } catch (parseError) {\n      return { parseError };\n    }\n    addQueryParam(\"extensions\", serializedExtensions);\n  }\n\n  // Reconstruct the URI with added query params.\n  // XXX This assumes that the URI is well-formed and that it doesn't\n  //     already contain any of these query params. We could instead use the\n  //     URL API and take a polyfill (whatwg-url@6) for older browsers that\n  //     don't support URLSearchParams. Note that some browsers (and\n  //     versions of whatwg-url) support URL but not URLSearchParams!\n  let fragment = \"\",\n    preFragment = chosenURI;\n  const fragmentStart = chosenURI.indexOf(\"#\");\n  if (fragmentStart !== -1) {\n    fragment = chosenURI.substr(fragmentStart);\n    preFragment = chosenURI.substr(0, fragmentStart);\n  }\n  const queryParamsPrefix = preFragment.indexOf(\"?\") === -1 ? \"?\" : \"&\";\n  const newURI =\n    preFragment + queryParamsPrefix + queryParams.join(\"&\") + fragment;\n  return { newURI };\n}\n"
  },
  {
    "path": "src/link/http/selectHttpOptionsAndBody.ts",
    "content": "import type { ApolloLink } from \"@apollo/client/link\";\nimport { print } from \"@apollo/client/utilities\";\n\nimport type { BaseHttpLink } from \"./BaseHttpLink.js\";\n\ninterface HttpConfig {\n  http?: BaseHttpLink.HttpOptions;\n  options?: any;\n  headers?: Record<string, string>;\n  credentials?: any;\n}\n\nconst defaultHttpOptions: BaseHttpLink.HttpOptions = {\n  includeQuery: true,\n  includeExtensions: true,\n  preserveHeaderCase: false,\n};\n\nconst defaultHeaders = {\n  // headers are case insensitive (https://stackoverflow.com/a/5259004)\n  accept: \"application/graphql-response+json,application/json;q=0.9\",\n  // The content-type header describes the type of the body of the request, and\n  // so it typically only is sent with requests that actually have bodies. One\n  // could imagine that Apollo Client would remove this header when constructing\n  // a GET request (which has no body), but we historically have not done that.\n  // This means that browsers will preflight all Apollo Client requests (even\n  // GET requests). Apollo Server's CSRF prevention feature (introduced in\n  // AS3.7) takes advantage of this fact and does not block requests with this\n  // header. If you want to drop this header from GET requests, then you should\n  // probably replace it with a `apollo-require-preflight` header, or servers\n  // with CSRF prevention enabled might block your GET request. See\n  // https://www.apollographql.com/docs/apollo-server/security/cors/#preventing-cross-site-request-forgery-csrf\n  // for more details.\n  \"content-type\": \"application/json\",\n};\n\nconst defaultOptions = {\n  method: \"POST\",\n};\n\nexport const fallbackHttpConfig = {\n  http: defaultHttpOptions,\n  headers: defaultHeaders,\n  options: defaultOptions,\n};\n\nexport const defaultPrinter: BaseHttpLink.Printer = (ast, printer) =>\n  printer(ast);\n\nexport function selectHttpOptionsAndBody(\n  operation: ApolloLink.Operation,\n  fallbackConfig: HttpConfig,\n  ...configs: Array<HttpConfig>\n) {\n  configs.unshift(fallbackConfig);\n  return selectHttpOptionsAndBodyInternal(\n    operation,\n    defaultPrinter,\n    ...configs\n  );\n}\n\nexport function selectHttpOptionsAndBodyInternal(\n  operation: ApolloLink.Operation,\n  printer: BaseHttpLink.Printer,\n  ...configs: HttpConfig[]\n) {\n  let options = {} as HttpConfig & Record<string, any>;\n  let http = {} as BaseHttpLink.HttpOptions;\n\n  configs.forEach((config) => {\n    options = {\n      ...options,\n      ...config.options,\n      headers: {\n        ...options.headers,\n        ...config.headers,\n      },\n    };\n\n    if (config.credentials) {\n      options.credentials = config.credentials;\n    }\n\n    options.headers!.accept = (config.http?.accept || [])\n      .concat(options.headers!.accept)\n      .join(\",\");\n\n    http = {\n      ...http,\n      ...config.http,\n    };\n  });\n\n  options.headers = removeDuplicateHeaders(\n    options.headers!,\n    http.preserveHeaderCase\n  );\n\n  //The body depends on the http options\n  const { operationName, extensions, variables, query } = operation;\n  const body: BaseHttpLink.Body = { operationName, variables };\n\n  if (http.includeExtensions && Object.keys(extensions || {}).length)\n    (body as any).extensions = extensions;\n\n  // not sending the query (i.e persisted queries)\n  if (http.includeQuery) (body as any).query = printer(query, print);\n\n  return {\n    options,\n    body,\n  };\n}\n\n// Remove potential duplicate header names, preserving last (by insertion order).\n// This is done to prevent unintentionally duplicating a header instead of\n// overwriting it (See #8447 and #8449).\nfunction removeDuplicateHeaders(\n  headers: Record<string, string>,\n  preserveHeaderCase: boolean | undefined\n): typeof headers {\n  // If we're not preserving the case, just remove duplicates w/ normalization.\n  if (!preserveHeaderCase) {\n    const normalizedHeaders: Record<string, string> = {};\n    Object.keys(Object(headers)).forEach((name) => {\n      normalizedHeaders[name.toLowerCase()] = headers[name];\n    });\n    return normalizedHeaders;\n  }\n\n  // If we are preserving the case, remove duplicates w/ normalization,\n  // preserving the original name.\n  // This allows for non-http-spec-compliant servers that expect intentionally\n  // capitalized header names (See #6741).\n  const headerData: Record<string, { originalName: string; value: string }> =\n    {};\n  Object.keys(Object(headers)).forEach((name) => {\n    headerData[name.toLowerCase()] = {\n      originalName: name,\n      value: headers[name],\n    };\n  });\n\n  const normalizedHeaders: Record<string, string> = {};\n  Object.keys(headerData).forEach((name) => {\n    normalizedHeaders[headerData[name].originalName] = headerData[name].value;\n  });\n  return normalizedHeaders;\n}\n"
  },
  {
    "path": "src/link/http/selectURI.ts",
    "content": "import type { ApolloLink } from \"@apollo/client/link\";\n\nexport const selectURI = (\n  operation: ApolloLink.Operation,\n  fallbackURI?: string | ((operation: ApolloLink.Operation) => string)\n) => {\n  const context = operation.getContext();\n  const contextURI = context.uri;\n\n  if (contextURI) {\n    return contextURI;\n  } else if (typeof fallbackURI === \"function\") {\n    return fallbackURI(operation);\n  } else {\n    return (fallbackURI as string) || \"/graphql\";\n  }\n};\n"
  },
  {
    "path": "src/link/index.ts",
    "content": "export type { DocumentNode } from \"graphql\";\n\nexport { empty } from \"./core/empty.js\";\nexport { from } from \"./core/from.js\";\nexport { split } from \"./core/split.js\";\nexport { concat } from \"./core/concat.js\";\nexport { execute } from \"./core/execute.js\";\nexport { ApolloLink } from \"./core/ApolloLink.js\";\n\nexport type { ApolloPayloadResult } from \"./core/types.js\";\n\nexport type {\n  FetchResult,\n  GraphQLRequest,\n  Operation,\n  RequestHandler,\n} from \"./core/deprecated.js\";\n"
  },
  {
    "path": "src/link/persisted-queries/__tests__/persisted-queries.test.ts",
    "content": "import crypto from \"crypto\";\n\nimport fetchMock from \"fetch-mock\";\nimport { OperationTypeNode, print } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { times } from \"lodash\";\nimport { firstValueFrom, Observable, of, throwError } from \"rxjs\";\n\nimport { CombinedGraphQLErrors, ServerError, version } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { HttpLink } from \"@apollo/client/link/http\";\nimport {\n  PersistedQueryLink,\n  VERSION,\n} from \"@apollo/client/link/persisted-queries\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\n\n// Necessary configuration in order to mock multiple requests\n// to a single (/graphql) endpoint\n// see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration\nfetchMock.config.overwriteRoutes = false;\n\nafterAll(() => {\n  fetchMock.config.overwriteRoutes = true;\n});\n\nconst makeAliasFields = (fieldName: string, numAliases: number) =>\n  times(numAliases, (idx) => `${fieldName}${idx}: ${fieldName}`).reduce(\n    (aliasBody, currentAlias) => `${aliasBody}\\n    ${currentAlias}`\n  );\n\nconst query = gql`\n  query Test($id: ID!) {\n    foo(id: $id) {\n      bar\n      ${makeAliasFields(\"title\", 1000)}\n    }\n  }\n`;\n\nconst variables = { id: 1 };\nconst queryString = print(query);\nconst data = {\n  foo: { bar: true },\n};\nconst response = JSON.stringify({ data });\nconst errors = [{ message: \"PersistedQueryNotFound\" }];\nconst errorsWithCode = [\n  {\n    message: \"SomeOtherMessage\",\n    extensions: {\n      code: \"PERSISTED_QUERY_NOT_FOUND\",\n    },\n  },\n];\nconst giveUpErrors = [{ message: \"PersistedQueryNotSupported\" }];\nconst giveUpErrorsWithCode = [\n  {\n    message: \"SomeOtherMessage\",\n    extensions: {\n      code: \"PERSISTED_QUERY_NOT_SUPPORTED\",\n    },\n  },\n];\nconst multipleErrors = [...errors, { message: \"not logged in\" }];\nconst errorResponse = JSON.stringify({ errors });\nconst errorResponseWithCode = JSON.stringify({ errors: errorsWithCode });\nconst giveUpResponse = JSON.stringify({ errors: giveUpErrors });\nconst giveUpResponseWithCode = JSON.stringify({ errors: giveUpErrorsWithCode });\nconst multiResponse = JSON.stringify({ errors: multipleErrors });\n\nfunction sha256(data: string) {\n  const hash = crypto.createHash(\"sha256\");\n  hash.update(data);\n  return hash.digest(\"hex\");\n}\n\nconst hash = sha256(queryString);\n\ndescribe(\"happy path\", () => {\n  beforeEach(async () => {\n    fetchMock.restore();\n  });\n\n  it(\"sends a sha256 hash of the query under extensions\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [uri, request] = fetchMock.lastCall()!;\n\n    expect(uri).toEqual(\"/graphql\");\n    expect(request!.body!).toBe(\n      JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: hash,\n          },\n        },\n      })\n    );\n  });\n\n  test(\"`createPersistedQueryLink` creates a `PersistedQueryLink`\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const pqLink = new PersistedQueryLink({ sha256 });\n    expect(pqLink).toBeInstanceOf(PersistedQueryLink);\n    const link = pqLink.concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [uri, request] = fetchMock.lastCall()!;\n\n    expect(uri).toEqual(\"/graphql\");\n    expect(request!.body!).toBe(\n      JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: hash,\n          },\n        },\n      })\n    );\n  });\n\n  it(\"sends a version along with the request\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [uri, request] = fetchMock.lastCall()!;\n    expect(uri).toEqual(\"/graphql\");\n\n    const parsed = JSON.parse(request!.body!.toString());\n    expect(parsed.extensions.persistedQuery.version).toBe(VERSION);\n  });\n\n  it(\"memoizes between requests\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    const hashSpy = jest.fn(sha256);\n    const link = new PersistedQueryLink({ sha256: hashSpy }).concat(\n      new HttpLink()\n    );\n\n    {\n      const observable = execute(link, { query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({ data });\n      await expect(stream).toComplete();\n      expect(hashSpy).toHaveBeenCalledTimes(1);\n    }\n\n    {\n      const observable = execute(link, { query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({ data });\n      await expect(stream).toComplete();\n      expect(hashSpy).toHaveBeenCalledTimes(1);\n    }\n  });\n\n  it(\"clears the cache when calling `resetHashCache`\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n\n    const hashRefs: WeakRef<String>[] = [];\n    function hash(query: string) {\n      const newHash = new String(query);\n      hashRefs.push(new WeakRef(newHash));\n      return newHash as string;\n    }\n    const persistedLink = new PersistedQueryLink({ sha256: hash });\n    await new Promise<void>((complete) =>\n      execute(persistedLink.concat(new HttpLink()), {\n        query,\n        variables,\n      }).subscribe({ complete })\n    );\n\n    await expect(hashRefs[0]).not.toBeGarbageCollected();\n    persistedLink.resetHashCache();\n    await expect(hashRefs[0]).toBeGarbageCollected();\n  });\n\n  it(\"supports loading the hash from other method\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const generateHash = (query: any) => Promise.resolve(\"foo\");\n    const link = new PersistedQueryLink({ generateHash }).concat(\n      new HttpLink()\n    );\n\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [uri, request] = fetchMock.lastCall()!;\n    expect(uri).toEqual(\"/graphql\");\n\n    const parsed = JSON.parse(request!.body!.toString());\n    expect(parsed.extensions.persistedQuery.sha256Hash).toBe(\"foo\");\n  });\n\n  it(\"errors if unable to convert to sha256\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const link = new PersistedQueryLink({\n      sha256: () => {\n        throw new Error(\"Could not create sha256\");\n      },\n    }).concat(new HttpLink());\n\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    const error = await stream.takeError();\n\n    expect(error.message).toBe(\"Could not create sha256\");\n  });\n\n  it(\"unsubscribes correctly\", async () => {\n    const delay = new ApolloLink(() => {\n      return new Observable((ob) => {\n        setTimeout(() => {\n          ob.next({ data });\n          ob.complete();\n        }, 100);\n      });\n    });\n    const link = new PersistedQueryLink({ sha256 }).concat(delay);\n\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await wait(10);\n\n    stream.unsubscribe();\n\n    await expect(stream).not.toEmitAnything({ timeout: 150 });\n  });\n\n  it(\"should error if `sha256` and `generateHash` options are both missing\", async () => {\n    // @ts-expect-error\n    expect(() => new PersistedQueryLink()).toThrow(\n      'Missing/invalid \"sha256\" or \"generateHash\" function'\n    );\n  });\n\n  it.each([\"sha256\", \"generateHash\"])(\n    \"should error if `%s` option is not a function\",\n    async (option) => {\n      // @ts-expect-error\n      expect(() => new PersistedQueryLink({ [option]: \"ooops\" })).toThrow(\n        'Missing/invalid \"sha256\" or \"generateHash\" function'\n      );\n    }\n  );\n\n  it(\"should work with a synchronous SHA-256 function\", async () => {\n    const crypto = require(\"crypto\");\n    const sha256Hash = crypto.createHmac(\"sha256\", queryString).digest(\"hex\");\n\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const link = new PersistedQueryLink({\n      sha256(data) {\n        return crypto.createHmac(\"sha256\", data).digest(\"hex\");\n      },\n    }).concat(new HttpLink());\n\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [uri, request] = fetchMock.lastCall()!;\n\n    expect(uri).toEqual(\"/graphql\");\n    expect(request!.body!).toBe(\n      JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256Hash,\n          },\n        },\n      })\n    );\n  });\n\n  it(\"preserves existing http context on initial request\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n\n    const contextLink = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        headers: { \"X-Custom-Header\": \"true\" },\n        http: {\n          preserveHeaderCase: true,\n        },\n      });\n      return forward(operation);\n    });\n\n    const link = contextLink\n      .concat(new PersistedQueryLink({ sha256 }))\n      .concat(new HttpLink());\n\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [, request] = fetchMock.lastCall()!;\n    const headers = request!.headers;\n\n    // This would fail if preserveHeaderCase was overwritten,\n    // since headers are lowercased by HttpLink by default\n    expect(headers).toHaveProperty(\"X-Custom-Header\");\n  });\n});\n\ndescribe(\"failure path\", () => {\n  beforeEach(async () => {\n    fetchMock.restore();\n  });\n\n  it.each([\n    [\"error message\", errorResponse],\n    [\"error code\", errorResponseWithCode],\n  ] as const)(\n    \"correctly identifies the error shape from the server (%s)\",\n    async (_description, failingResponse) => {\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: failingResponse })),\n        { repeat: 1 }\n      );\n      // `repeat: 1` simulates a `mockResponseOnce` API with fetch-mock:\n      // it limits the number of times the route can be used,\n      // after which the call to `fetch()` will fall through to be\n      // handled by any other routes defined...\n      // With `overwriteRoutes = false`, this means\n      // subsequent /graphql mocks will be used\n      // see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n      const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n\n      const stream = new ObservableStream(execute(link, { query, variables }));\n\n      await expect(stream).toEmitTypedValue({ data });\n\n      const [[, failure], [, success]] = fetchMock.calls();\n      expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();\n      expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n      expect(\n        JSON.parse(success!.body!.toString()).extensions.persistedQuery\n          .sha256Hash\n      ).toBe(hash);\n    }\n  );\n\n  it(\"sends GET for the first response only with useGETForHashedQueries\", async () => {\n    const params = new URLSearchParams({\n      operationName: \"Test\",\n      variables: JSON.stringify({\n        id: 1,\n      }),\n      extensions: JSON.stringify({\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n        persistedQuery: {\n          version: 1,\n          sha256Hash: hash,\n        },\n      }),\n    }).toString();\n    fetchMock.get(\n      `/graphql?${params}`,\n      () => new Promise((resolve) => resolve({ body: errorResponse }))\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response }))\n    );\n    const link = new PersistedQueryLink({\n      sha256,\n      useGETForHashedQueries: true,\n    }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [[, failure]] = fetchMock.calls();\n\n    expect(failure!.method).toBe(\"GET\");\n    expect(failure!.body).not.toBeDefined();\n\n    const [, [, success]] = fetchMock.calls();\n\n    expect(success!.method).toBe(\"POST\");\n    expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n    expect(\n      JSON.parse(success!.body!.toString()).extensions.persistedQuery.sha256Hash\n    ).toBe(hash);\n  });\n\n  it(\"sends POST for both requests without useGETForHashedQueries\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: errorResponse })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [[, failure]] = fetchMock.calls();\n\n    expect(failure!.method).toBe(\"POST\");\n    expect(JSON.parse(failure!.body!.toString())).toEqual({\n      operationName: \"Test\",\n      variables,\n      extensions: {\n        persistedQuery: {\n          version: VERSION,\n          sha256Hash: hash,\n        },\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n      },\n    });\n\n    const [, [, success]] = fetchMock.calls();\n\n    expect(success!.method).toBe(\"POST\");\n    expect(JSON.parse(success!.body!.toString())).toEqual({\n      operationName: \"Test\",\n      query: queryString,\n      variables,\n      extensions: {\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n        persistedQuery: {\n          version: VERSION,\n          sha256Hash: hash,\n        },\n      },\n    });\n  });\n\n  // https://github.com/apollographql/apollo-client/pull/7456\n  it(\"forces POST request when sending full query\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: giveUpResponse })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    const link = new PersistedQueryLink({\n      sha256,\n      disable({ operation }) {\n        operation.setContext({\n          fetchOptions: {\n            method: \"GET\",\n          },\n        });\n        return true;\n      },\n    }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [[, failure]] = fetchMock.calls();\n\n    expect(failure!.method).toBe(\"POST\");\n    expect(JSON.parse(failure!.body!.toString())).toEqual({\n      operationName: \"Test\",\n      variables,\n      extensions: {\n        persistedQuery: {\n          version: VERSION,\n          sha256Hash: hash,\n        },\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n      },\n    });\n\n    const [, [, success]] = fetchMock.calls();\n\n    expect(success!.method).toBe(\"POST\");\n    expect(JSON.parse(success!.body!.toString())).toEqual({\n      operationName: \"Test\",\n      query: queryString,\n      variables,\n      extensions: {\n        clientLibrary: {\n          name: \"@apollo/client\",\n          version,\n        },\n      },\n    });\n  });\n\n  it.each([\n    [\"error message\", giveUpResponse],\n    [\"error code\", giveUpResponseWithCode],\n  ] as const)(\n    \"does not try again after receiving NotSupported error (%s)\",\n    async (_description, failingResponse) => {\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: failingResponse })),\n        { repeat: 1 }\n      );\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n      // mock it again so we can verify it doesn't try anymore\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n      const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query, variables })\n        );\n\n        await expect(stream).toEmitTypedValue({ data });\n\n        const [[, failure]] = fetchMock.calls();\n        expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();\n        const [, [, success]] = fetchMock.calls();\n        expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n        expect(JSON.parse(success!.body!.toString()).extensions).toStrictEqual({\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n        });\n      }\n\n      {\n        const stream = new ObservableStream(\n          execute(link, { query, variables })\n        );\n\n        await expect(stream).toEmitTypedValue({ data });\n\n        const [, , [, success]] = fetchMock.calls();\n        expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n        expect(JSON.parse(success!.body!.toString()).extensions).toStrictEqual({\n          clientLibrary: { name: \"@apollo/client\", version },\n        });\n      }\n    }\n  );\n\n  it.each([\n    // TODO(fixme): test flake on CI https://github.com/apollographql/apollo-client/issues/11782\n    // [\"error message\", giveUpResponse],\n    [\"error code\", giveUpResponseWithCode],\n  ] as const)(\n    \"clears the cache when receiving NotSupported error (%s)\",\n    async (_description, failingResponse) => {\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: failingResponse })),\n        { repeat: 1 }\n      );\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n\n      const hashRefs: WeakRef<String>[] = [];\n      function hash(query: string) {\n        const newHash = new String(query);\n        hashRefs.push(new WeakRef(newHash));\n        return newHash as string;\n      }\n      const persistedLink = new PersistedQueryLink({ sha256: hash });\n      await new Promise<void>((complete) =>\n        execute(persistedLink.concat(new HttpLink()), {\n          query,\n          variables,\n        }).subscribe({ complete })\n      );\n      // fetch-mock holds a history of all options it has been called with\n      // that includes the `signal` option, which (with the native `AbortController`)\n      // has a reference to the `Request` instance, which will somehow reference our\n      // hash object\n      fetchMock.resetHistory();\n      await expect(hashRefs[0]).toBeGarbageCollected();\n    }\n  );\n\n  it(\"works with multiple errors\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: multiResponse })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n    const observable = execute(link, { query, variables });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    const [[, failure]] = fetchMock.calls();\n\n    expect(JSON.parse(failure!.body!.toString()).query).not.toBeDefined();\n\n    const [, [, success]] = fetchMock.calls();\n\n    expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n    expect(\n      JSON.parse(success!.body!.toString()).extensions.persistedQuery.sha256Hash\n    ).toBe(hash);\n  });\n\n  describe.each([[400], [500]])(\"status %s\", (status) => {\n    it(`handles a ${status} network with a \"PERSISTED_QUERY_NOT_FOUND\" error and still retries`, async () => {\n      let requestCount = 0;\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n\n      // mock it again so we can verify it doesn't try anymore\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 5 }\n      );\n\n      const fetcher = (...args: any[]) => {\n        if (++requestCount % 2) {\n          return Promise.resolve(\n            new Response(errorResponseWithCode, { status })\n          );\n        }\n        // @ts-expect-error\n        return global.fetch.apply(null, args);\n      };\n      const link = new PersistedQueryLink({ sha256 }).concat(\n        new HttpLink({ fetch: fetcher } as any)\n      );\n\n      {\n        const observable = execute(link, { query, variables });\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({ data });\n\n        const [[, success]] = fetchMock.calls();\n\n        expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n        expect(\n          JSON.parse(success!.body!.toString()).extensions.persistedQuery\n            .sha256Hash\n        ).toBe(hash);\n      }\n\n      {\n        const observable = execute(link, { query, variables });\n        const stream = new ObservableStream(observable);\n\n        await expect(stream).toEmitTypedValue({ data });\n\n        const [, [, success]] = fetchMock.calls();\n\n        expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n        expect(\n          JSON.parse(success!.body!.toString()).extensions.persistedQuery\n            .sha256Hash\n        ).toBe(hash);\n      }\n    });\n\n    it(`will fail on an unrelated ${status} network error, but still send a hash the next request`, async () => {\n      let failed = false;\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n\n      // mock it again so we can verify it doesn't try anymore\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n\n      const fetcher = (...args: any[]) => {\n        if (!failed) {\n          failed = true;\n          return Promise.resolve(new Response(\"THIS WILL BLOW UP\", { status }));\n        }\n        // @ts-expect-error\n        return global.fetch.apply(null, args);\n      };\n      const link = new PersistedQueryLink({ sha256 }).concat(\n        new HttpLink({ fetch: fetcher } as any)\n      );\n\n      const failingAttempt = firstValueFrom(\n        execute(link, { query, variables })\n      );\n      await expect(failingAttempt).rejects.toThrow();\n      expect(fetchMock.calls().length).toBe(0);\n\n      const successfullAttempt = firstValueFrom(\n        execute(link, { query, variables })\n      );\n      await expect(successfullAttempt).resolves.toEqual({ data });\n      const [[, success]] = fetchMock.calls();\n      expect(JSON.parse(success!.body!.toString()).query).toBeUndefined();\n      expect(\n        JSON.parse(success!.body!.toString()).extensions.persistedQuery\n          .sha256Hash\n      ).toBe(hash);\n    });\n\n    it(`handles ${status} response network error and graphql error without disabling persistedQuery support`, async () => {\n      let failed = false;\n      fetchMock.post(\n        \"/graphql\",\n        () => new Promise((resolve) => resolve({ body: response })),\n        { repeat: 1 }\n      );\n\n      const fetcher = (...args: any[]) => {\n        if (!failed) {\n          failed = true;\n          return Promise.resolve(new Response(errorResponse, { status }));\n        }\n        // @ts-expect-error\n        return global.fetch.apply(null, args);\n      };\n\n      const link = new PersistedQueryLink({ sha256 }).concat(\n        new HttpLink({ fetch: fetcher } as any)\n      );\n\n      const observable = execute(link, { query, variables });\n      const stream = new ObservableStream(observable);\n\n      await expect(stream).toEmitTypedValue({ data });\n\n      const [[, success]] = fetchMock.calls();\n\n      expect(JSON.parse(success!.body!.toString()).query).toBe(queryString);\n      expect(\n        JSON.parse(success!.body!.toString()).extensions\n      ).not.toBeUndefined();\n    });\n  });\n\n  it(\"preserves existing http context on retry\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: errorResponse })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n\n    let httpContextOnRetry: HttpLink.ContextOptions[\"http\"];\n\n    const contextLink = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        http: {\n          preserveHeaderCase: true,\n        },\n      });\n      return forward(operation);\n    });\n\n    const checkContextLink = new ApolloLink((operation, forward) => {\n      httpContextOnRetry = operation.getContext().http;\n      return forward(operation);\n    });\n\n    const link = contextLink\n      .concat(new PersistedQueryLink({ sha256 }))\n      .concat(checkContextLink)\n      .concat(new HttpLink());\n\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(httpContextOnRetry).toStrictEqualTyped({\n      preserveHeaderCase: true,\n      includeQuery: true,\n      includeExtensions: true,\n    });\n  });\n\n  it(\"preserves existing fetchOptions context on retry\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: errorResponse })),\n      { repeat: 1 }\n    );\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n\n    let fetchOptionsOnRetry: HttpLink.ContextOptions[\"fetchOptions\"];\n\n    const contextLink = new ApolloLink((operation, forward) => {\n      operation.setContext({\n        fetchOptions: {\n          credentials: \"include\",\n        },\n      });\n      return forward(operation);\n    });\n\n    const checkContextLink = new ApolloLink((operation, forward) => {\n      fetchOptionsOnRetry = operation.getContext().fetchOptions;\n      return forward(operation);\n    });\n\n    const link = contextLink\n      .concat(new PersistedQueryLink({ sha256 }))\n      .concat(checkContextLink)\n      .concat(new HttpLink());\n\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(fetchOptionsOnRetry).toStrictEqualTyped({\n      credentials: \"include\",\n      method: \"POST\",\n    });\n  });\n});\n\ntest(\"disables persisted queries from future requests when `disable` returns true\", async () => {\n  const fetch = jest.fn(async () => Response.json({ data }));\n\n  fetch.mockImplementationOnce(async () =>\n    Promise.resolve(\n      Response.json(\n        {\n          errors: [\n            {\n              message: \"Not found\",\n              extensions: {\n                code: \"PERSISTED_QUERY_NOT_FOUND\",\n              },\n            },\n          ],\n        },\n        { status: 500 }\n      )\n    )\n  );\n\n  const link = new PersistedQueryLink({ sha256, disable: () => true }).concat(\n    new HttpLink({ fetch })\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(fetch).toHaveBeenCalledTimes(2);\n    expect(fetch).toHaveBeenNthCalledWith(\n      1,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n            persistedQuery: {\n              version: VERSION,\n              sha256Hash: sha256(queryString),\n            },\n          },\n        }),\n      })\n    );\n    expect(fetch).toHaveBeenNthCalledWith(\n      2,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n          },\n          query: queryString,\n        }),\n      })\n    );\n  }\n\n  fetch.mockClear();\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(fetch).toHaveBeenCalledTimes(1);\n    expect(fetch).toHaveBeenNthCalledWith(\n      1,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n          },\n          query: queryString,\n        }),\n      })\n    );\n  }\n});\n\ntest(\"continues working with persisted queries for future requests when `disable` returns false\", async () => {\n  const fetch = jest.fn(async () => Response.json({ data }));\n\n  fetch.mockImplementationOnce(async () =>\n    Promise.resolve(\n      Response.json(\n        {\n          errors: [\n            {\n              message: \"Not found\",\n              extensions: {\n                code: \"PERSISTED_QUERY_NOT_FOUND\",\n              },\n            },\n          ],\n        },\n        { status: 500 }\n      )\n    )\n  );\n\n  const link = new PersistedQueryLink({\n    sha256,\n    disable: () => false,\n  }).concat(new HttpLink({ fetch }));\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(fetch).toHaveBeenCalledTimes(2);\n    expect(fetch).toHaveBeenNthCalledWith(\n      1,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n            persistedQuery: {\n              version: VERSION,\n              sha256Hash: sha256(queryString),\n            },\n          },\n        }),\n      })\n    );\n    expect(fetch).toHaveBeenNthCalledWith(\n      2,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n            persistedQuery: {\n              version: VERSION,\n              sha256Hash: sha256(queryString),\n            },\n          },\n          query: queryString,\n        }),\n      })\n    );\n  }\n\n  fetch.mockClear();\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({ data });\n\n    expect(fetch).toHaveBeenCalledTimes(1);\n    expect(fetch).toHaveBeenNthCalledWith(\n      1,\n      \"/graphql\",\n      expect.objectContaining({\n        body: JSON.stringify({\n          operationName: \"Test\",\n          variables,\n          extensions: {\n            clientLibrary: { name: \"@apollo/client\", version },\n            persistedQuery: {\n              version: VERSION,\n              sha256Hash: sha256(queryString),\n            },\n          },\n        }),\n      })\n    );\n  }\n});\n\ntest(\"calls `disable` with error emitted from link chain\", async () => {\n  const terminatingLink = new ApolloLink(() => {\n    return throwError(() => new Error(\"Something went wrong\"));\n  });\n\n  const disable = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, disable }).concat(\n    terminatingLink\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitError(new Error(\"Something went wrong\"));\n\n  expect(disable).toHaveBeenCalledTimes(1);\n  expect(disable).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new Error(\"Something went wrong\"),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n  });\n});\n\ntest(\"calls `disable` with ServerError when response has non-2xx status code\", async () => {\n  const response = new Response(\"Something went wrong\", { status: 500 });\n  const fetch = jest.fn(async () => response);\n\n  const disable = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, disable }).concat(\n    new HttpLink({ fetch })\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  const serverError = new ServerError(\n    \"Response not successful: Received status code 500\",\n    {\n      response,\n      bodyText: \"Something went wrong\",\n    }\n  );\n\n  await expect(stream).toEmitError(serverError);\n\n  expect(disable).toHaveBeenCalledTimes(1);\n  expect(disable).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        clientLibrary: { name: \"@apollo/client\", version },\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: serverError,\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n  });\n});\n\ntest(\"calls `disable` with GraphQL errors when returned in response\", async () => {\n  const terminatingLink = new ApolloLink(() => {\n    return of({ errors: [{ message: \"Something went wrong\" }] });\n  });\n\n  const disable = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, disable }).concat(\n    terminatingLink\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(disable).toHaveBeenCalledTimes(1);\n  expect(disable).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    }),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n    result: {\n      errors: [{ message: \"Something went wrong\" }],\n    },\n  });\n});\n\ntest(\"calls `disable` with GraphQL errors when parsed from non-2xx response\", async () => {\n  const response = Response.json(\n    { errors: [{ message: \"Something went wrong\" }] },\n    { status: 500 }\n  );\n  const fetch = jest.fn(async () => response);\n\n  const disable = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, disable }).concat(\n    new HttpLink({ fetch })\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  const serverError = new ServerError(\n    \"Response not successful: Received status code 500\",\n    {\n      response,\n      bodyText: JSON.stringify({\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n    }\n  );\n\n  await expect(stream).toEmitError(serverError);\n\n  expect(disable).toHaveBeenCalledTimes(1);\n  expect(disable).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        clientLibrary: { name: \"@apollo/client\", version },\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    }),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n    result: {\n      errors: [{ message: \"Something went wrong\" }],\n    },\n  });\n});\n\ntest(\"retries when `retry` returns true\", async () => {\n  const fetch = jest.fn(async () => Response.json({ data }));\n\n  fetch.mockImplementationOnce(async () =>\n    Promise.resolve(\n      Response.json(\n        {\n          errors: [\n            {\n              message: \"Not found\",\n              extensions: {\n                code: \"PERSISTED_QUERY_NOT_FOUND\",\n              },\n            },\n          ],\n        },\n        { status: 500 }\n      )\n    )\n  );\n\n  const link = new PersistedQueryLink({\n    sha256,\n    retry: () => true,\n  }).concat(new HttpLink({ fetch }));\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({ data });\n\n  expect(fetch).toHaveBeenCalledTimes(2);\n  expect(fetch).toHaveBeenNthCalledWith(\n    1,\n    \"/graphql\",\n    expect.objectContaining({\n      body: JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: { name: \"@apollo/client\", version },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256(queryString),\n          },\n        },\n      }),\n    })\n  );\n  expect(fetch).toHaveBeenNthCalledWith(\n    2,\n    \"/graphql\",\n    expect.objectContaining({\n      body: JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: { name: \"@apollo/client\", version },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256(queryString),\n          },\n        },\n        query: queryString,\n      }),\n    })\n  );\n});\n\ntest(\"only retries query once\", async () => {\n  const fetch = jest.fn(async () =>\n    Response.json({\n      errors: [\n        {\n          message: \"Not found\",\n          extensions: {\n            code: \"PERSISTED_QUERY_NOT_FOUND\",\n          },\n        },\n      ],\n    })\n  );\n\n  const link = new PersistedQueryLink({\n    sha256,\n    retry: () => true,\n  }).concat(new HttpLink({ fetch }));\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    errors: [\n      {\n        message: \"Not found\",\n        extensions: { code: \"PERSISTED_QUERY_NOT_FOUND\" },\n      },\n    ],\n  });\n\n  expect(fetch).toHaveBeenCalledTimes(2);\n  expect(fetch).toHaveBeenNthCalledWith(\n    1,\n    \"/graphql\",\n    expect.objectContaining({\n      body: JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: { name: \"@apollo/client\", version },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256(queryString),\n          },\n        },\n      }),\n    })\n  );\n  expect(fetch).toHaveBeenNthCalledWith(\n    2,\n    \"/graphql\",\n    expect.objectContaining({\n      body: JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: { name: \"@apollo/client\", version },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256(queryString),\n          },\n        },\n        query: queryString,\n      }),\n    })\n  );\n});\n\ntest(\"does not retry when `retry` returns false\", async () => {\n  const fetch = jest.fn(async () =>\n    Response.json({\n      errors: [\n        {\n          message: \"Not found\",\n          extensions: {\n            code: \"PERSISTED_QUERY_NOT_FOUND\",\n          },\n        },\n      ],\n    })\n  );\n\n  const link = new PersistedQueryLink({\n    sha256,\n    retry: () => false,\n  }).concat(new HttpLink({ fetch }));\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    errors: [\n      {\n        message: \"Not found\",\n        extensions: { code: \"PERSISTED_QUERY_NOT_FOUND\" },\n      },\n    ],\n  });\n\n  expect(fetch).toHaveBeenCalledTimes(1);\n  expect(fetch).toHaveBeenNthCalledWith(\n    1,\n    \"/graphql\",\n    expect.objectContaining({\n      body: JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: { name: \"@apollo/client\", version },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: sha256(queryString),\n          },\n        },\n      }),\n    })\n  );\n});\n\ntest(\"calls `retry` with error emitted from link chain\", async () => {\n  const terminatingLink = new ApolloLink(() => {\n    return throwError(() => new Error(\"Something went wrong\"));\n  });\n\n  const retry = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, retry }).concat(\n    terminatingLink\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitError(new Error(\"Something went wrong\"));\n\n  expect(retry).toHaveBeenCalledTimes(1);\n  expect(retry).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new Error(\"Something went wrong\"),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n  });\n});\n\ntest(\"calls `retry` with ServerError when response has non-2xx status code\", async () => {\n  const response = new Response(\"Something went wrong\", { status: 500 });\n  const fetch = jest.fn(async () => response);\n\n  const retry = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, retry }).concat(\n    new HttpLink({ fetch })\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  const serverError = new ServerError(\n    \"Response not successful: Received status code 500\",\n    {\n      response,\n      bodyText: \"Something went wrong\",\n    }\n  );\n\n  await expect(stream).toEmitError(serverError);\n\n  expect(retry).toHaveBeenCalledTimes(1);\n  expect(retry).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        clientLibrary: { name: \"@apollo/client\", version },\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: serverError,\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n  });\n});\n\ntest(\"calls `retry` with GraphQL errors when returned in response\", async () => {\n  const terminatingLink = new ApolloLink(() => {\n    return of({ errors: [{ message: \"Something went wrong\" }] });\n  });\n\n  const retry = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, retry }).concat(\n    terminatingLink\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(retry).toHaveBeenCalledTimes(1);\n  expect(retry).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    }),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n    result: {\n      errors: [{ message: \"Something went wrong\" }],\n    },\n  });\n});\n\ntest(\"calls `retry` with GraphQL errors when parsed from non-2xx response\", async () => {\n  const response = Response.json(\n    { errors: [{ message: \"Something went wrong\" }] },\n    { status: 500 }\n  );\n  const fetch = jest.fn(async () => response);\n\n  const retry = jest.fn(() => false);\n\n  const link = new PersistedQueryLink({ sha256, retry }).concat(\n    new HttpLink({ fetch })\n  );\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  const serverError = new ServerError(\n    \"Response not successful: Received status code 500\",\n    {\n      response,\n      bodyText: JSON.stringify({\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n    }\n  );\n\n  await expect(stream).toEmitError(serverError);\n\n  expect(retry).toHaveBeenCalledTimes(1);\n  expect(retry).toHaveBeenCalledWith({\n    operation: {\n      query,\n      variables,\n      operationName: \"Test\",\n      operationType: OperationTypeNode.QUERY,\n      extensions: {\n        clientLibrary: { name: \"@apollo/client\", version },\n        persistedQuery: { version: VERSION, sha256Hash: sha256(queryString) },\n      },\n    },\n    error: new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    }),\n    meta: {\n      persistedQueryNotFound: false,\n      persistedQueryNotSupported: false,\n    },\n    result: {\n      errors: [{ message: \"Something went wrong\" }],\n    },\n  });\n});\n"
  },
  {
    "path": "src/link/persisted-queries/__tests__/react.test.tsx",
    "content": "/** @jest-environment node */\nimport crypto from \"crypto\";\n\nimport fetchMock from \"fetch-mock\";\nimport { print } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom/server\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport { ApolloClient, version } from \"@apollo/client\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport { HttpLink } from \"@apollo/client/link/http\";\nimport {\n  PersistedQueryLink,\n  VERSION,\n} from \"@apollo/client/link/persisted-queries\";\nimport { ApolloProvider, useQuery } from \"@apollo/client/react\";\nimport { getDataFromTree } from \"@apollo/client/react/ssr\";\nimport { addTypenameToDocument } from \"@apollo/client/utilities\";\n\nfunction sha256(data: string) {\n  const hash = crypto.createHash(\"sha256\");\n  hash.update(data);\n  return hash.digest(\"hex\");\n}\n\n// Necessary configuration in order to mock multiple requests\n// to a single (/graphql) endpoint\n// see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration\nfetchMock.config.overwriteRoutes = false;\n\nafterAll(() => {\n  fetchMock.config.overwriteRoutes = true;\n});\n\nconst query = gql`\n  query Test($filter: FilterObject) {\n    foo(filter: $filter) {\n      bar\n    }\n  }\n`;\n\nconst variables = {\n  filter: {\n    $filter: \"smash\",\n  },\n};\nconst variables2 = {\n  filter: null,\n};\nconst data = {\n  foo: { bar: true },\n};\nconst data2 = {\n  foo: { bar: false },\n};\nconst response = JSON.stringify({ data });\nconst response2 = JSON.stringify({ data: data2 });\nconst queryString = print(addTypenameToDocument(query));\n\nconst hash = sha256(queryString);\n\ndescribe(\"react application\", () => {\n  beforeEach(async () => {\n    fetchMock.restore();\n  });\n  it(\"works on a simple tree\", async () => {\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response })),\n      { repeat: 1 }\n    );\n    // `repeat: 1` simulates a `mockResponseOnce` API with fetch-mock:\n    // it limits the number of times the route can be used,\n    // after which the call to `fetch()` will fall through to be\n    // handled by any other routes defined...\n    // With `overwriteRoutes = false`, this means\n    // subsequent /graphql mocks will be used\n    // see: http://www.wheresrhys.co.uk/fetch-mock/#usageconfiguration\n    fetchMock.post(\n      \"/graphql\",\n      () => new Promise((resolve) => resolve({ body: response2 })),\n      { repeat: 1 }\n    );\n\n    const link = new PersistedQueryLink({ sha256 }).concat(new HttpLink());\n\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n      ssrMode: true,\n    });\n\n    const Query = ({\n      children,\n      variables,\n    }: {\n      children: React.ReactNode;\n      variables: OperationVariables;\n    }) => {\n      const { data, loading } = useQuery(query, { variables });\n      if (loading) return null;\n\n      return (\n        <div>\n          {(data as any).foo.bar && \"data was returned!\"}\n          {children}\n        </div>\n      );\n    };\n    const app = (\n      <ApolloProvider client={client}>\n        <Query variables={variables}>\n          <h1>Hello!</h1>\n        </Query>\n      </ApolloProvider>\n    );\n\n    // preload all the data for client side request (with filter)\n    const result = await getDataFromTree(app);\n    expect(result).toContain(\"data was returned\");\n    const [[, request]] = fetchMock.calls();\n    expect(request!.body).toBe(\n      JSON.stringify({\n        operationName: \"Test\",\n        variables,\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: hash,\n          },\n        },\n      })\n    );\n\n    // reset client and try with different input object\n    const client2 = new ApolloClient({\n      link,\n      cache: new Cache(),\n      ssrMode: true,\n    });\n\n    const app2 = (\n      <ApolloProvider client={client2}>\n        <Query variables={variables2}>\n          <h1>Hello!</h1>\n        </Query>\n      </ApolloProvider>\n    );\n\n    // change filter object to different variables and SSR\n    await getDataFromTree(app2);\n    const view = ReactDOM.renderToString(app2);\n\n    const [, [, request2]] = fetchMock.calls();\n\n    expect(view).not.toContain(\"data was returned\");\n    expect(request2!.body).toBe(\n      JSON.stringify({\n        operationName: \"Test\",\n        variables: variables2,\n        extensions: {\n          clientLibrary: {\n            name: \"@apollo/client\",\n            version,\n          },\n          persistedQuery: {\n            version: VERSION,\n            sha256Hash: hash,\n          },\n        },\n      })\n    );\n  });\n});\n"
  },
  {
    "path": "src/link/persisted-queries/index.ts",
    "content": "import type {\n  DocumentNode,\n  FormattedExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql\";\nimport type { Observer, Subscription } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nimport type { ErrorLike } from \"@apollo/client\";\nimport {\n  CombinedGraphQLErrors,\n  ServerError,\n  toErrorLike,\n} from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { print } from \"@apollo/client/utilities\";\nimport {\n  cacheSizes,\n  isFormattedExecutionResult,\n} from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  AutoCleanedWeakCache,\n  compact,\n  isNonEmptyArray,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\n\nexport const VERSION = 1;\n\nexport declare namespace PersistedQueryLink {\n  namespace PersistedQueryLinkDocumentationTypes {\n    /**\n     * A SHA-256 hash function for hashing query strings.\n     *\n     * @param queryString - The query string to hash\n     * @returns The SHA-256 hash or a promise that resolves to the SHA-256 hash\n     *\n     * @example\n     *\n     * ```ts\n     * import { sha256 } from \"crypto-hash\";\n     *\n     * const link = new PersistedQueryLink({ sha256 });\n     * ```\n     */\n    function SHA256Function(queryString: string): string | PromiseLike<string>;\n\n    /**\n     * A function that generates a hash for a GraphQL document.\n     *\n     * @param document - The GraphQL document to hash\n     * @returns The hash string or a promise that resolves to the hash string\n     *\n     * @example\n     *\n     * ```ts\n     * import { print } from \"graphql\";\n     * import { sha256 } from \"crypto-hash\";\n     *\n     * const link = new PersistedQueryLink({\n     *   generateHash: async (document) => {\n     *     const query = print(document);\n     *     return sha256(query);\n     *   },\n     * });\n     * ```\n     */\n    function GenerateHashFunction(\n      document: DocumentNode\n    ): string | PromiseLike<string>;\n  }\n\n  namespace Base {\n    /**\n     * Base options shared between SHA256 and custom hash configurations.\n     */\n    interface Options {\n      /**\n       * A function to disable persisted queries for the current session.\n       *\n       * This function is called when an error occurs and determines whether\n       * to disable persisted queries for all future requests in this session.\n       *\n       * @defaultValue Disables on `PersistedQueryNotSupported` errors\n       */\n      disable?: (options: PersistedQueryLink.DisableFunctionOptions) => boolean;\n\n      /**\n       * A function to determine whether to retry a request with the full query.\n       *\n       * When a persisted query fails, this function determines whether to\n       * retry the request with the full query text included.\n       *\n       * @defaultValue Retries on `PersistedQueryNotSupported` or `PersistedQueryNotFound` errors\n       */\n      retry?: (options: PersistedQueryLink.RetryFunctionOptions) => boolean;\n\n      /**\n       * Whether to use HTTP GET for hashed queries (excluding mutations).\n       *\n       * > [!NOTE]\n       * > If you want to use `GET` for non-mutation queries whether or not they\n       * > are hashed, pass `useGETForQueries: true` option to `HttpLink`\n       * > instead. If you want to use GET for all requests, pass `fetchOptions: {method: 'GET'}`\n       * > to `HttpLink`.\n       *\n       * @defaultValue `false`\n       */\n      useGETForHashedQueries?: boolean;\n    }\n  }\n\n  /**\n   * Metadata about persisted query errors extracted from the response.\n   */\n  export interface ErrorMeta {\n    /**\n     * Whether the server responded with a \"PersistedQueryNotSupported\" error.\n     *\n     * When `true`, indicates the server doesn't support persisted queries\n     * or has disabled them for this client.\n     */\n    persistedQueryNotSupported: boolean;\n\n    /**\n     * Whether the server responded with a \"PersistedQueryNotFound\" error.\n     *\n     * When `true`, indicates the server doesn't recognize the query hash\n     * and needs the full query text.\n     */\n    persistedQueryNotFound: boolean;\n  }\n\n  /** {@inheritDoc @apollo/client/link/persisted-queries!PersistedQueryLink.PersistedQueryLinkDocumentationTypes.GenerateHashFunction:function(1)} */\n  export type GenerateHashFunction = (\n    document: DocumentNode\n  ) => string | PromiseLike<string>;\n\n  /** {@inheritDoc @apollo/client/link/persisted-queries!PersistedQueryLink.PersistedQueryLinkDocumentationTypes.SHA256Function:function(1)} */\n  export type SHA256Function = (\n    queryString: string\n  ) => string | PromiseLike<string>;\n\n  /**\n   * Options for using SHA-256 hashing with persisted queries.\n   *\n   * Use this configuration when you want the link to handle query\n   * printing and hashing using a SHA-256 function.\n   */\n  export interface SHA256Options extends Base.Options {\n    /**\n     * The SHA-256 hash function to use for hashing queries. This function\n     * receives the printed query string and should return a SHA-256 hash. Can\n     * be synchronous or asynchronous.\n     */\n    sha256: PersistedQueryLink.SHA256Function;\n    generateHash?: never;\n  }\n\n  /**\n   * Options for using custom hash generation with persisted queries.\n   *\n   * Use this configuration when you need custom control over how\n   * query hashes are generated (e.g., using pre-computed hashes).\n   */\n  export interface GenerateHashOptions extends Base.Options {\n    sha256?: never;\n    /**\n     * A custom function for generating query hashes. This function receives\n     * the GraphQL document and should return a hash. Useful for custom hashing\n     * strategies or when using build-time generated hashes.\n     */\n    generateHash: PersistedQueryLink.GenerateHashFunction;\n  }\n\n  /**\n   * Configuration options for creating a `PersistedQueryLink`.\n   *\n   * You must provide either a `sha256` function or a custom `generateHash`\n   * function, but not both.\n   */\n  export type Options =\n    | PersistedQueryLink.SHA256Options\n    | PersistedQueryLink.GenerateHashOptions;\n\n  /**\n   * Options passed to the `retry` function when a persisted query request\n   * fails.\n   */\n  export interface RetryFunctionOptions {\n    /**\n     * The error that occurred during the request.\n     */\n    error: ErrorLike;\n\n    /**\n     * The GraphQL operation that failed.\n     */\n    operation: ApolloLink.Operation;\n\n    /**\n     * Metadata about the persisted query error.\n     */\n    meta: PersistedQueryLink.ErrorMeta;\n\n    /**\n     * The GraphQL result, if available.\n     */\n    result?: FormattedExecutionResult;\n  }\n\n  /**\n   * Options passed to the `disable` function when a persisted query request\n   * fails.\n   */\n  export interface DisableFunctionOptions\n    extends PersistedQueryLink.RetryFunctionOptions {}\n}\n\nfunction processErrors(\n  graphQLErrors:\n    | GraphQLFormattedError[]\n    | ReadonlyArray<GraphQLFormattedError>\n    | undefined\n): PersistedQueryLink.ErrorMeta {\n  const byMessage: Record<string, GraphQLFormattedError> = {},\n    byCode: Record<string, GraphQLFormattedError> = {};\n\n  if (isNonEmptyArray(graphQLErrors)) {\n    graphQLErrors.forEach((error) => {\n      byMessage[error.message] = error;\n      if (typeof error.extensions?.code == \"string\")\n        byCode[error.extensions.code] = error;\n    });\n  }\n  return {\n    persistedQueryNotSupported: !!(\n      byMessage.PersistedQueryNotSupported ||\n      byCode.PERSISTED_QUERY_NOT_SUPPORTED\n    ),\n    persistedQueryNotFound: !!(\n      byMessage.PersistedQueryNotFound || byCode.PERSISTED_QUERY_NOT_FOUND\n    ),\n  };\n}\n\nconst defaultOptions: Required<PersistedQueryLink.Base.Options> = {\n  disable: ({ meta }) => meta.persistedQueryNotSupported,\n  retry: ({ meta }) =>\n    meta.persistedQueryNotSupported || meta.persistedQueryNotFound,\n  useGETForHashedQueries: false,\n};\n\nfunction operationDefinesMutation(operation: ApolloLink.Operation) {\n  return operation.query.definitions.some(\n    (d) => d.kind === \"OperationDefinition\" && d.operation === \"mutation\"\n  );\n}\n\n/**\n * @deprecated\n * Use `PersistedQueryLink` from `@apollo/client/link/persisted-queries` instead.\n */\nexport const createPersistedQueryLink = (options: PersistedQueryLink.Options) =>\n  new PersistedQueryLink(options);\n\n/**\n * `PersistedQueryLink` is a non-terminating link that enables the use of\n * persisted queries, a technique that reduces bandwidth by sending query hashes\n * instead of full query strings.\n *\n * @example\n *\n * ```ts\n * import { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\n * import { sha256 } from \"crypto-hash\";\n *\n * const link = new PersistedQueryLink({\n *   sha256: (queryString) => sha256(queryString),\n * });\n * ```\n */\nexport class PersistedQueryLink extends ApolloLink {\n  constructor(options: PersistedQueryLink.Options) {\n    let hashesByQuery:\n      | AutoCleanedWeakCache<DocumentNode, Promise<string>>\n      | undefined;\n    function resetHashCache() {\n      hashesByQuery = undefined;\n    }\n    // Ensure a SHA-256 hash function is provided, if a custom hash\n    // generation function is not provided. We don't supply a SHA-256 hash\n    // function by default, to avoid forcing one as a dependency. Developers\n    // should pick the most appropriate SHA-256 function (sync or async) for\n    // their needs/environment, or provide a fully custom hash generation\n    // function (via the `generateHash` option) if they want to handle\n    // hashing with something other than SHA-256.\n    invariant(\n      options &&\n        (typeof options.sha256 === \"function\" ||\n          typeof options.generateHash === \"function\"),\n      'Missing/invalid \"sha256\" or \"generateHash\" function. Please ' +\n        'configure one using the \"createPersistedQueryLink(options)\" options ' +\n        \"parameter.\"\n    );\n\n    const {\n      sha256,\n      // If both a `sha256` and `generateHash` option are provided, the\n      // `sha256` option will be ignored. Developers can configure and\n      // use any hashing approach they want in a custom `generateHash`\n      // function; they aren't limited to SHA-256.\n      generateHash = (query: DocumentNode) =>\n        Promise.resolve<string>(sha256!(print(query))),\n      disable,\n      retry,\n      useGETForHashedQueries,\n    } = compact(defaultOptions, options);\n\n    let enabled = true;\n\n    const getHashPromise = (query: DocumentNode) =>\n      new Promise<string>((resolve) => resolve(generateHash(query)));\n\n    function getQueryHash(query: DocumentNode): Promise<string> {\n      if (!query || typeof query !== \"object\") {\n        // If the query is not an object, we won't be able to store its hash as\n        // a property of query[hashesKey], so we let generateHash(query) decide\n        // what to do with the bogus query.\n        return getHashPromise(query);\n      }\n      if (!hashesByQuery) {\n        hashesByQuery = new AutoCleanedWeakCache(\n          cacheSizes[\"PersistedQueryLink.persistedQueryHashes\"] ||\n            defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"]\n        );\n      }\n      let hash = hashesByQuery.get(query);\n      if (!hash) hashesByQuery.set(query, (hash = getHashPromise(query)));\n      return hash;\n    }\n\n    super((operation, forward) => {\n      invariant(\n        forward,\n        \"PersistedQueryLink cannot be the last link in the chain.\"\n      );\n\n      const { query } = operation;\n\n      return new Observable((observer) => {\n        let subscription: Subscription | undefined;\n        let retried = false;\n        let originalFetchOptions: any;\n        let setFetchOptions = false;\n\n        function handleRetry(\n          options: PersistedQueryLink.RetryFunctionOptions,\n          cb: () => void\n        ) {\n          if (retried) {\n            return cb();\n          }\n\n          retried = true;\n\n          // if the server doesn't support persisted queries, don't try anymore\n          enabled = !disable(options);\n          if (!enabled) {\n            delete operation.extensions.persistedQuery;\n            // clear hashes from cache, we don't need them anymore\n            resetHashCache();\n          }\n\n          // if its not found, we can try it again, otherwise just report the error\n          if (retry(options)) {\n            // need to recall the link chain\n            if (subscription) subscription.unsubscribe();\n            // actually send the query this time\n            operation.setContext(\n              ({ http: prevHttp, fetchOptions: prevFetchOptions }) => ({\n                http: {\n                  ...prevHttp,\n                  includeQuery: true,\n                  ...(enabled ? { includeExtensions: true } : {}),\n                },\n                fetchOptions: {\n                  // Since we're including the full query, which may be\n                  // large, we should send it in the body of a POST request.\n                  // See issue #7456.\n                  ...prevFetchOptions,\n                  method: \"POST\",\n                },\n              })\n            );\n            if (setFetchOptions) {\n              operation.setContext({ fetchOptions: originalFetchOptions });\n            }\n            subscription = forward(operation).subscribe(handler);\n\n            return;\n          }\n\n          cb();\n        }\n\n        const handler: Observer<ApolloLink.Result> = {\n          next: (result) => {\n            if (!isFormattedExecutionResult(result) || !result.errors) {\n              return observer.next(result);\n            }\n\n            handleRetry(\n              {\n                operation,\n                error: new CombinedGraphQLErrors(result),\n                meta: processErrors(result.errors),\n                result,\n              },\n              () => observer.next(result)\n            );\n          },\n          error: (incomingError) => {\n            const error = toErrorLike(incomingError);\n            const callback = () => observer.error(incomingError);\n\n            // This is persisted-query specific (see #9410) and deviates from the\n            // GraphQL-over-HTTP spec for application/json responses.\n            // This is intentional.\n            if (ServerError.is(error) && error.bodyText) {\n              try {\n                const result = JSON.parse(error.bodyText);\n\n                if (isFormattedExecutionResult(result)) {\n                  return handleRetry(\n                    {\n                      error: new CombinedGraphQLErrors(result),\n                      result,\n                      operation,\n                      meta: processErrors(result.errors),\n                    },\n                    callback\n                  );\n                }\n              } catch {}\n            }\n\n            handleRetry(\n              {\n                error,\n                operation,\n                meta: {\n                  persistedQueryNotSupported: false,\n                  persistedQueryNotFound: false,\n                },\n              },\n              callback\n            );\n          },\n          complete: observer.complete.bind(observer),\n        };\n\n        // don't send the query the first time\n        operation.setContext(({ http: prevHttp }) => ({\n          http:\n            enabled ?\n              { ...prevHttp, includeQuery: false, includeExtensions: true }\n            : prevHttp,\n        }));\n\n        // If requested, set method to GET if there are no mutations. Remember the\n        // original fetchOptions so we can restore them if we fall back to a\n        // non-hashed request.\n        if (\n          useGETForHashedQueries &&\n          enabled &&\n          !operationDefinesMutation(operation)\n        ) {\n          operation.setContext(\n            ({ fetchOptions = {} }: { fetchOptions: Record<string, any> }) => {\n              originalFetchOptions = fetchOptions;\n              return {\n                fetchOptions: {\n                  ...fetchOptions,\n                  method: \"GET\",\n                },\n              };\n            }\n          );\n          setFetchOptions = true;\n        }\n\n        if (enabled) {\n          getQueryHash(query)\n            .then((sha256Hash) => {\n              operation.extensions.persistedQuery = {\n                version: VERSION,\n                sha256Hash,\n              };\n              subscription = forward(operation).subscribe(handler);\n            })\n            .catch(observer.error!.bind(observer));\n        } else {\n          subscription = forward(operation).subscribe(handler);\n        }\n\n        return () => {\n          if (subscription) subscription.unsubscribe();\n        };\n      });\n    });\n    if (__DEV__) {\n      Object.assign(this, {\n        getMemoryInternals() {\n          return {\n            PersistedQueryLink: {\n              persistedQueryHashes: hashesByQuery?.size ?? 0,\n            },\n          };\n        },\n      });\n    }\n    this.resetHashCache = resetHashCache;\n  }\n\n  resetHashCache: () => void;\n}\n"
  },
  {
    "path": "src/link/remove-typename/__tests__/removeTypenameFromVariables.ts",
    "content": "import type { FormattedExecutionResult } from \"graphql\";\nimport { OperationTypeNode } from \"graphql\";\nimport { firstValueFrom, of } from \"rxjs\";\n\nimport { gql } from \"@apollo/client\";\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport {\n  KEEP,\n  RemoveTypenameFromVariablesLink,\n} from \"@apollo/client/link/remove-typename\";\nimport { createOperationWithDefaultContext as createOperation } from \"@apollo/client/testing/internal\";\n\ntype PartialOperation = Partial<Pick<ApolloLink.Operation, \"variables\">> &\n  Pick<ApolloLink.Operation, \"query\">;\n\n// Since this link modifies the `operation` and we only care to test against\n// the changed operation, we use a custom `execute` helper here instead of the\n// version exported by the `core` module, which expects a well-formed response.\nasync function execute(link: ApolloLink, operation: PartialOperation) {\n  function forward(operation: ApolloLink.Operation) {\n    // use the `data` key to satisfy the TypeScript types required by\n    // `forward`'s' return value\n    return of({ data: operation });\n  }\n\n  const { data } = (await firstValueFrom(\n    link.request(createOperation(operation), forward)!\n  )) as { data: FormattedExecutionResult };\n\n  return data as ApolloLink.Operation;\n}\n\ntest(\"strips all __typename keys by default\", async () => {\n  const query = gql`\n    query Test($foo: FooInput!, $bar: BarInput!) {\n      someField(foo: $foo, bar: $bar)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink();\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        foo: true,\n        bar: \"Bar\",\n        baz: { __typename: \"Baz\", baz: true },\n        qux: [{ __typename: \"Qux\", qux: 0 }],\n      },\n      bar: [{ __typename: \"Bar\", bar: true }],\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      foo: true,\n      bar: \"Bar\",\n      baz: { baz: true },\n      qux: [{ qux: 0 }],\n    },\n    bar: [{ bar: true }],\n  });\n});\n\ntest(\"does nothing when no variables are passed\", async () => {\n  const query = gql`\n    query Test {\n      foo {\n        bar\n      }\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink();\n\n  const resultOperation = await execute(link, { query });\n\n  expect(resultOperation).toStrictEqualTyped({\n    query,\n    variables: {},\n    extensions: {},\n    operationName: \"Test\",\n    operationType: OperationTypeNode.QUERY,\n  });\n});\n\ntest(\"does nothing when no variables are passed even if variables are declared in the document\", async () => {\n  const query = gql`\n    query Test($unused: Boolean) {\n      foo {\n        bar\n      }\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink();\n\n  const resultOperation = await execute(link, { query });\n\n  expect(resultOperation).toStrictEqualTyped({\n    query,\n    variables: {},\n    extensions: {},\n    operationName: \"Test\",\n    operationType: OperationTypeNode.QUERY,\n  });\n});\n\ntest(\"keeps __typename for variables with types defined by `except`\", async () => {\n  const query = gql`\n    query Test($foo: JSON, $bar: BarInput) {\n      someField(foo: $foo, bar: $bar)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        foo: true,\n        baz: { __typename: \"Baz\", baz: true },\n      },\n      bar: { __typename: \"Bar\", bar: true },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      __typename: \"Foo\",\n      foo: true,\n      baz: { __typename: \"Baz\", baz: true },\n    },\n    bar: { bar: true },\n  });\n});\n\ntest(\"keeps __typename in all variables with types configured with `except`\", async () => {\n  const query = gql`\n    query Test($foo: JSON, $bar: Config, $baz: BazInput) {\n      someField(foo: $foo, bar: $bar, baz: $baz)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n      Config: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: { __typename: \"Foo\", foo: true },\n      bar: { __typename: \"Bar\", bar: true },\n      baz: { __typename: \"Baz\", baz: true },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: { __typename: \"Foo\", foo: true },\n    bar: { __typename: \"Bar\", bar: true },\n    baz: { baz: true },\n  });\n});\n\ntest(\"handles variable declarations declared as non null and list types\", async () => {\n  const query = gql`\n    query Test($foo: JSON!, $bar: [JSON], $baz: [JSON!]!, $qux: QuxInput!) {\n      someField(foo: $foo, bar: $bar, baz: $baz)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: { __typename: \"Foo\", foo: true },\n      bar: [\n        { __typename: \"Bar\", bar: true, baz: { __typename: \"Baz\", baz: true } },\n      ],\n      baz: [\n        { __typename: \"Baz\", baz: true },\n        { __typename: \"Baz\", baz: true },\n      ],\n      qux: { __typename: \"Qux\", qux: true },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: { __typename: \"Foo\", foo: true },\n    bar: [\n      { __typename: \"Bar\", bar: true, baz: { __typename: \"Baz\", baz: true } },\n    ],\n    baz: [\n      { __typename: \"Baz\", baz: true },\n      { __typename: \"Baz\", baz: true },\n    ],\n    qux: { qux: true },\n  });\n});\n\ntest(\"keeps __typename at configured fields under input object types\", async () => {\n  const query = gql`\n    query Test($foo: FooInput) {\n      someField(foo: $foo)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      FooInput: {\n        bar: KEEP,\n        baz: KEEP,\n      },\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        aa: true,\n        bar: {\n          __typename: \"Bar\",\n          bb: true,\n        },\n        baz: {\n          __typename: \"Baz\",\n          cc: true,\n        },\n        qux: {\n          __typename: \"Qux\",\n          dd: true,\n        },\n      },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      aa: true,\n      bar: {\n        __typename: \"Bar\",\n        bb: true,\n      },\n      baz: {\n        __typename: \"Baz\",\n        cc: true,\n      },\n      qux: {\n        dd: true,\n      },\n    },\n  });\n});\n\ntest(\"keeps __typename at a deeply nested field\", async () => {\n  const query = gql`\n    query Test($foo: FooInput) {\n      someField(foo: $foo)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      FooInput: {\n        bar: {\n          baz: {\n            qux: KEEP,\n          },\n        },\n      },\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        bar: {\n          __typename: \"Bar\",\n          baz: {\n            __typename: \"Baz\",\n            qux: {\n              __typename: \"Qux\",\n              quux: true,\n            },\n          },\n        },\n      },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      bar: {\n        baz: {\n          qux: {\n            __typename: \"Qux\",\n            quux: true,\n          },\n        },\n      },\n    },\n  });\n});\n\ntest(\"handles configured fields varying nesting levels\", async () => {\n  const query = gql`\n    query Test($foo: FooInput) {\n      someField(foo: $foo)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      FooInput: {\n        bar: KEEP,\n        baz: {\n          qux: KEEP,\n        },\n      },\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        bar: {\n          __typename: \"Bar\",\n          aa: true,\n        },\n        baz: {\n          __typename: \"Baz\",\n          qux: {\n            __typename: \"Qux\",\n            quux: true,\n          },\n        },\n      },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      bar: {\n        __typename: \"Bar\",\n        aa: true,\n      },\n      baz: {\n        qux: {\n          __typename: \"Qux\",\n          quux: true,\n        },\n      },\n    },\n  });\n});\n\ntest(\"handles multiple configured types with fields\", async () => {\n  const query = gql`\n    query Test($foo: FooInput, $baz: BazInput) {\n      someField(foo: $foo, baz: $baz)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      FooInput: {\n        bar: KEEP,\n      },\n      BazInput: {\n        qux: KEEP,\n      },\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        bar: {\n          __typename: \"Bar\",\n          aa: true,\n        },\n      },\n      baz: {\n        __typename: \"Bar\",\n        qux: {\n          __typename: \"Qux\",\n          bb: true,\n        },\n      },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      bar: {\n        __typename: \"Bar\",\n        aa: true,\n      },\n    },\n    baz: {\n      qux: {\n        __typename: \"Qux\",\n        bb: true,\n      },\n    },\n  });\n});\n\ntest(\"handles when __typename is not present in all paths\", async () => {\n  const query = gql`\n    query Test($foo: JSON, $bar: BarInput) {\n      someField(foo: $foo, bar: $bar)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        foo: true,\n        baz: { __typename: \"Baz\", baz: true },\n      },\n      bar: { bar: true },\n      qux: { __typename: \"Qux\", bar: true },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      foo: true,\n      baz: { __typename: \"Baz\", baz: true },\n    },\n    bar: { bar: true },\n    qux: { bar: true },\n  });\n});\n\ntest(\"handles when __typename is not present in variables\", async () => {\n  const query = gql`\n    query Test($foo: JSON, $bar: BarInput) {\n      someField(foo: $foo, bar: $bar)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        foo: true,\n        baz: { baz: true },\n      },\n      bar: { bar: true },\n      qux: [{ foo: true }],\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      foo: true,\n      baz: { baz: true },\n    },\n    bar: { bar: true },\n    qux: [{ foo: true }],\n  });\n});\n\ntest(\"handles when declared variables are unused\", async () => {\n  const query = gql`\n    query Test($foo: FooInput, $unused: JSON) {\n      someField(foo: $foo, bar: $bar)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink({\n    except: {\n      JSON: KEEP,\n    },\n  });\n\n  const { variables } = await execute(link, {\n    query,\n    variables: {\n      foo: {\n        __typename: \"Foo\",\n        foo: true,\n        baz: { __typename: \"Bar\", baz: true },\n      },\n    },\n  });\n\n  expect(variables).toStrictEqual({\n    foo: {\n      foo: true,\n      baz: { baz: true },\n    },\n  });\n});\n\ntest(\"ensures operation.getContext and operation.setContext functions are properly forwarded\", async () => {\n  const query = gql`\n    query Test($foo: FooInput) {\n      someField(foo: $foo)\n    }\n  `;\n\n  const link = new RemoveTypenameFromVariablesLink();\n\n  const operationWithoutVariables = await execute(link, { query });\n  const operationWithVariables = await execute(link, {\n    query,\n    variables: { foo: { __typename: \"FooInput\", bar: true } },\n  });\n\n  expect(typeof operationWithoutVariables.getContext).toBe(\"function\");\n  expect(typeof operationWithoutVariables.setContext).toBe(\"function\");\n  expect(typeof operationWithVariables.getContext).toBe(\"function\");\n  expect(typeof operationWithVariables.setContext).toBe(\"function\");\n});\n"
  },
  {
    "path": "src/link/remove-typename/index.ts",
    "content": "export {\n  KEEP,\n  removeTypenameFromVariables,\n  RemoveTypenameFromVariablesLink,\n} from \"./removeTypenameFromVariables.js\";\n"
  },
  {
    "path": "src/link/remove-typename/removeTypenameFromVariables.ts",
    "content": "import { WeakCache } from \"@wry/caches\";\nimport type { DocumentNode, TypeNode } from \"graphql\";\nimport { Kind, visit } from \"graphql\";\nimport { wrap } from \"optimism\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { cacheSizes, stripTypename } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { bindCacheKey, isPlainObject } from \"@apollo/client/utilities/internal\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\n\n/**\n * Sentinel value used to indicate that `__typename` fields should be kept\n * for a specific field or input type.\n *\n * @remarks\n * Use this value in the `except` configuration to preserve `__typename`\n * fields in JSON scalar fields or other cases where you need to retain\n * the typename information.\n *\n * @example\n *\n * ```ts\n * import {\n *   RemoveTypenameFromVariablesLink,\n *   KEEP,\n * } from \"@apollo/client/link/remove-typename\";\n *\n * const link = new RemoveTypenameFromVariablesLink({\n *   except: {\n *     JSON: KEEP, // Keep __typename for all JSON scalar variables\n *     DashboardInput: {\n *       config: KEEP, // Keep __typename only for the config field\n *     },\n *   },\n * });\n * ```\n */\nexport const KEEP = \"__KEEP\";\n\nexport declare namespace RemoveTypenameFromVariablesLink {\n  /**\n   * Configuration object that specifies which input types and fields should\n   * retain their `__typename` fields.\n   *\n   * @remarks\n   * This is a recursive configuration where:\n   *\n   * - Keys represent GraphQL input type names or field names\n   * - Values can be either the `KEEP` sentinel to preserve all `__typename`\n   *   fields, or a nested `KeepTypenameConfig` to preserve `__typename` fields on\n   *   a specific field name.\n   *\n   * @example\n   *\n   * ```ts\n   * const config: KeepTypenameConfig = {\n   *   // Keep __typename for all JSON scalar variables\n   *   JSON: KEEP,\n   *\n   *   // For DashboardInput, only keep __typename on the config field\n   *   DashboardInput: {\n   *     config: KEEP,\n   *   },\n   *\n   *   // Nested configuration for complex input types\n   *   UserInput: {\n   *     profile: {\n   *       settings: KEEP,\n   *     },\n   *   },\n   * };\n   * ```\n   */\n  export interface KeepTypenameConfig {\n    [key: string]:\n      | typeof KEEP\n      | RemoveTypenameFromVariablesLink.KeepTypenameConfig;\n  }\n\n  /**\n   * Options for configuring the `RemoveTypenameFromVariablesLink`.\n   */\n  export interface Options {\n    /**\n     * Configuration that determines which input types should retain `__typename`\n     * fields.\n     *\n     * Maps GraphQL input type names to configurations. Each configuration can\n     * either be the `KEEP` sentinel, to preserve all `__typename` fields, or\n     * a nested object that specifies which fields should retain `__typename`.\n     *\n     * @example\n     *\n     * ```ts\n     * {\n     *   except: {\n     *     // Keep __typename for all JSON scalar variables\n     *     JSON: KEEP,\n     *\n     *     // For DashboardInput, remove __typename except for config field\n     *     DashboardInput: {\n     *       config: KEEP,\n     *     },\n     *\n     *     // Complex nested configuration\n     *     UserProfileInput: {\n     *       settings: {\n     *         preferences: KEEP,\n     *       },\n     *     },\n     *   },\n     * }\n     * ```\n     */\n    except?: RemoveTypenameFromVariablesLink.KeepTypenameConfig;\n  }\n}\n\n/**\n * @deprecated\n * Use `RemoveTypenameFromVariablesLink` from `@apollo/client/link/remove-typename` instead.\n */\nexport function removeTypenameFromVariables(\n  options?: RemoveTypenameFromVariablesLink.Options\n) {\n  return new RemoveTypenameFromVariablesLink(options);\n}\n\n/**\n * `RemoveTypenameFromVariablesLink` is a non-terminating link that automatically\n * removes `__typename` fields from operation variables to prevent GraphQL\n * validation errors.\n *\n * @remarks\n *\n * When reusing data from a query as input to another GraphQL operation,\n * `__typename` fields can cause server-side validation errors because input\n * types don't accept fields that start with double underscores (`__`).\n * `RemoveTypenameFromVariablesLink` automatically strips these fields from all\n * operation variables.\n *\n * @example\n *\n * ```ts\n * import { RemoveTypenameFromVariablesLink } from \"@apollo/client/link/remove-typename\";\n *\n * const link = new RemoveTypenameFromVariablesLink();\n * ```\n */\nexport class RemoveTypenameFromVariablesLink extends ApolloLink {\n  constructor(options: RemoveTypenameFromVariablesLink.Options = {}) {\n    super((operation, forward) => {\n      const { except } = options;\n      const { query, variables } = operation;\n\n      if (variables) {\n        operation.variables =\n          except ?\n            this.maybeStripTypenameUsingConfig(query, variables, except)\n          : stripTypename(variables);\n      }\n\n      return forward(operation);\n    });\n    return Object.assign(\n      this,\n      __DEV__ ?\n        {\n          getMemoryInternals(this: RemoveTypenameFromVariablesLink) {\n            return {\n              removeTypenameFromVariables: {\n                getVariableDefinitions: this.getVariableDefinitions?.size ?? 0,\n              },\n            };\n          },\n        }\n      : {}\n    );\n  }\n\n  private maybeStripTypenameUsingConfig(\n    query: DocumentNode,\n    variables: OperationVariables,\n    config: RemoveTypenameFromVariablesLink.KeepTypenameConfig\n  ) {\n    const variableDefinitions = this.getVariableDefinitions(query);\n\n    return Object.fromEntries(\n      Object.entries(variables).map((keyVal) => {\n        const [key, value] = keyVal;\n        const typename = variableDefinitions[key];\n        const typenameConfig = config[typename];\n\n        keyVal[1] =\n          typenameConfig ?\n            this.maybeStripTypename(value, typenameConfig)\n          : stripTypename(value);\n\n        return keyVal;\n      })\n    );\n  }\n\n  private maybeStripTypename(\n    value: JSONValue,\n    config: RemoveTypenameFromVariablesLink.KeepTypenameConfig[string]\n  ): JSONValue {\n    if (config === KEEP) {\n      return value;\n    }\n\n    if (Array.isArray(value)) {\n      return value.map((item) => this.maybeStripTypename(item, config));\n    }\n\n    if (isPlainObject(value)) {\n      const modified: Record<string, any> = {};\n\n      Object.keys(value).forEach((key) => {\n        const child = value[key];\n\n        if (key === \"__typename\") {\n          return;\n        }\n\n        const fieldConfig = config[key];\n\n        modified[key] =\n          fieldConfig ?\n            this.maybeStripTypename(child, fieldConfig)\n          : stripTypename(child);\n      });\n\n      return modified;\n    }\n\n    return value;\n  }\n\n  private getVariableDefinitions = wrap(\n    (document: DocumentNode) => {\n      const definitions: Record<string, string> = {};\n\n      visit(document, {\n        VariableDefinition(node) {\n          definitions[node.variable.name.value] = unwrapType(node.type);\n        },\n      });\n\n      return definitions;\n    },\n    {\n      max:\n        cacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"] ||\n        defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"],\n      cache: WeakCache,\n      makeCacheKey: bindCacheKey(this),\n    }\n  );\n}\n\ntype JSONPrimitive = string | number | null | boolean;\ntype JSONValue = JSONPrimitive | JSONValue[] | { [key: string]: JSONValue };\n\nfunction unwrapType(node: TypeNode): string {\n  switch (node.kind) {\n    case Kind.NON_NULL_TYPE:\n      return unwrapType(node.type);\n    case Kind.LIST_TYPE:\n      return unwrapType(node.type);\n    case Kind.NAMED_TYPE:\n      return node.name.value;\n  }\n}\n"
  },
  {
    "path": "src/link/retry/__tests__/delayFunction.ts",
    "content": "// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { buildDelayFunction } from \"../delayFunction.js\";\n\ndescribe(\"buildDelayFunction\", () => {\n  // For easy testing of just the delay component, which is all we care about in\n  // the default implementation.\n  interface SimpleDelayFunction {\n    (count: number): number;\n  }\n\n  function delayRange(delayFunction: SimpleDelayFunction, count: number) {\n    const results = [];\n    for (let i = 1; i <= count; i++) {\n      results.push(delayFunction(i));\n    }\n    return results;\n  }\n\n  describe(\"without jitter\", () => {\n    it(\"grows exponentially up to maxDelay\", () => {\n      const delayFunction = buildDelayFunction({\n        jitter: false,\n        initial: 100,\n        max: 1000,\n      }) as SimpleDelayFunction;\n\n      expect(delayRange(delayFunction, 6)).toEqual([\n        100, 200, 400, 800, 1000, 1000,\n      ]);\n    });\n  });\n\n  describe(\"with jitter\", () => {\n    let mockRandom: any, origRandom: any;\n    beforeEach(() => {\n      mockRandom = jest.fn();\n      origRandom = Math.random;\n      Math.random = mockRandom;\n    });\n\n    afterEach(() => {\n      Math.random = origRandom;\n    });\n\n    it(\"jitters, on average, exponentially up to maxDelay\", () => {\n      const delayFunction = buildDelayFunction({\n        jitter: true,\n        initial: 100,\n        max: 1000,\n      }) as SimpleDelayFunction;\n\n      mockRandom.mockReturnValue(0.5);\n      expect(delayRange(delayFunction, 5)).toEqual([100, 200, 400, 500, 500]);\n    });\n\n    it(\"can have instant retries as the low end of the jitter range\", () => {\n      const delayFunction = buildDelayFunction({\n        jitter: true,\n        initial: 100,\n        max: 1000,\n      }) as SimpleDelayFunction;\n\n      mockRandom.mockReturnValue(0);\n      expect(delayRange(delayFunction, 5)).toEqual([0, 0, 0, 0, 0]);\n    });\n\n    it(\"uses double the calculated delay as the high end of the jitter range, up to maxDelay\", () => {\n      const delayFunction = buildDelayFunction({\n        jitter: true,\n        initial: 100,\n        max: 1000,\n      }) as SimpleDelayFunction;\n\n      mockRandom.mockReturnValue(1);\n      expect(delayRange(delayFunction, 5)).toEqual([200, 400, 800, 1000, 1000]);\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/retry/__tests__/retryFunction.ts",
    "content": "import type { ApolloLink } from \"@apollo/client/link\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { buildRetryFunction } from \"../retryFunction.js\";\n\ndescribe(\"buildRetryFunction\", () => {\n  const operation = { operationName: \"foo\" } as ApolloLink.Operation;\n\n  it(\"stops after hitting maxTries\", () => {\n    const error = new Error();\n    const retryFunction = buildRetryFunction({ max: 3 });\n\n    expect(retryFunction(2, operation, error)).toEqual(true);\n    expect(retryFunction(3, operation, error)).toEqual(false);\n    expect(retryFunction(4, operation, error)).toEqual(false);\n  });\n\n  it(\"supports custom predicates, but only if max is not exceeded\", () => {\n    const error = new Error();\n    const stub = jest.fn(() => true);\n    const retryFunction = buildRetryFunction({ max: 3, retryIf: stub });\n\n    expect(retryFunction(2, operation, error)).toEqual(true);\n    expect(retryFunction(3, operation, error)).toEqual(false);\n  });\n\n  it(\"passes the error and operation through to custom predicates\", () => {\n    const stub = jest.fn(() => true);\n    const retryFunction = buildRetryFunction({ max: 3, retryIf: stub });\n\n    const error = new Error(\"bewm\");\n    void retryFunction(1, operation, error);\n    expect(stub).toHaveBeenCalledWith(error, operation);\n  });\n});\n"
  },
  {
    "path": "src/link/retry/__tests__/retryLink.ts",
    "content": "import { gql } from \"graphql-tag\";\nimport { Observable, of, throwError } from \"rxjs\";\n\nimport { CombinedProtocolErrors } from \"@apollo/client\";\nimport { PROTOCOL_ERRORS_SYMBOL } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { RetryLink } from \"@apollo/client/link/retry\";\nimport {\n  executeWithDefaultContext as execute,\n  mockMultipartSubscriptionStream,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  {\n    sample {\n      id\n    }\n  }\n`;\n\nconst standardError = new Error(\"I never work\");\n\ndescribe(\"RetryLink\", () => {\n  it(\"fails for unreachable endpoints\", async () => {\n    const max = 10;\n    const retry = new RetryLink({ delay: { initial: 1 }, attempts: { max } });\n    const stub = jest.fn(() => throwError(() => standardError)) as any;\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(standardError, { timeout: 1000 });\n\n    expect(stub).toHaveBeenCalledTimes(max);\n  });\n\n  it(\"returns data from the underlying link on a successful operation\", async () => {\n    const retry = new RetryLink();\n    const data = { data: { hello: \"world\" } };\n    const stub = jest.fn(() => of(data));\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    expect(stub).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"returns data from the underlying link on a successful retry\", async () => {\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: { max: 2 },\n    });\n    const data = { data: { hello: \"world\" } };\n    const stub = jest.fn();\n    stub.mockReturnValueOnce(throwError(() => standardError));\n    stub.mockReturnValueOnce(of(data));\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue(data);\n    await expect(stream).toComplete();\n\n    expect(stub).toHaveBeenCalledTimes(2);\n  });\n\n  it(\"calls unsubscribe on the appropriate downstream observable\", async () => {\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: { max: 2 },\n    });\n    const data = { data: { hello: \"world\" } };\n    const unsubscribeStub = jest.fn();\n\n    const firstTry = throwError(() => standardError);\n    // Hold the test hostage until we're hit\n    let secondTry;\n    const untilSecondTry = new Promise<void>((resolve) => {\n      secondTry = {\n        subscribe(observer: any) {\n          resolve(); // Release hold on test.\n\n          void Promise.resolve().then(() => {\n            observer.next(data);\n            observer.complete();\n          });\n          return { unsubscribe: unsubscribeStub };\n        },\n      };\n    });\n\n    const stub = jest.fn();\n    stub.mockReturnValueOnce(firstTry);\n    stub.mockReturnValueOnce(secondTry);\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n\n    const subscription = execute(link, { query }).subscribe({});\n    await untilSecondTry;\n    subscription.unsubscribe();\n    expect(unsubscribeStub).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"multiple subscribers will trigger multiple requests\", async () => {\n    const subscriber = {\n      next: jest.fn(),\n      error: jest.fn(),\n      complete: jest.fn(),\n    };\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: { max: 5 },\n    });\n    const data = { data: { hello: \"world\" } };\n    const stub = jest.fn();\n    stub.mockReturnValueOnce(throwError(() => standardError));\n    stub.mockReturnValueOnce(throwError(() => standardError));\n    stub.mockReturnValueOnce(of(data));\n    stub.mockReturnValueOnce(throwError(() => standardError));\n    stub.mockReturnValueOnce(throwError(() => standardError));\n    stub.mockReturnValueOnce(of(data));\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n\n    const observable = execute(link, { query });\n    observable.subscribe(subscriber);\n    observable.subscribe(subscriber);\n    await new Promise((resolve) => setTimeout(resolve, 3500));\n    expect(subscriber.next).toHaveBeenNthCalledWith(1, data);\n    expect(subscriber.next).toHaveBeenNthCalledWith(2, data);\n    expect(subscriber.complete).toHaveBeenCalledTimes(2);\n    expect(stub).toHaveBeenCalledTimes(6);\n  });\n\n  it(\"retries independently for concurrent requests\", async () => {\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: { max: 5 },\n    });\n    const stub = jest.fn(() => throwError(() => standardError)) as any;\n    const link = ApolloLink.from([retry, new ApolloLink(stub)]);\n    const stream1 = new ObservableStream(execute(link, { query }));\n    const stream2 = new ObservableStream(execute(link, { query }));\n\n    await Promise.all([\n      expect(stream1).toEmitError(standardError),\n      expect(stream2).toEmitError(standardError),\n    ]);\n\n    expect(stub).toHaveBeenCalledTimes(10);\n  });\n\n  it(\"supports custom delay functions\", async () => {\n    const delayStub = jest.fn(() => 1);\n    const retry = new RetryLink({ delay: delayStub, attempts: { max: 3 } });\n    const linkStub = jest.fn(() => throwError(() => standardError)) as any;\n    const link = ApolloLink.from([retry, new ApolloLink(linkStub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(standardError);\n\n    const operation = (delayStub.mock.calls[0] as any)[1];\n    expect(delayStub.mock.calls).toEqual([\n      [1, operation, standardError],\n      [2, operation, standardError],\n    ]);\n  });\n\n  it(\"supports custom attempt functions\", async () => {\n    const attemptStub = jest.fn();\n    attemptStub.mockReturnValueOnce(true);\n    attemptStub.mockReturnValueOnce(true);\n    attemptStub.mockReturnValueOnce(false);\n\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: attemptStub,\n    });\n    const linkStub = jest.fn(() => throwError(() => standardError)) as any;\n    const link = ApolloLink.from([retry, new ApolloLink(linkStub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(standardError);\n\n    const operation = attemptStub.mock.calls[0][1];\n    expect(attemptStub.mock.calls).toEqual([\n      [1, operation, standardError],\n      [2, operation, standardError],\n      [3, operation, standardError],\n    ]);\n  });\n\n  it(\"supports custom attempt functions that return either Promises or booleans\", async () => {\n    const attemptStub = jest.fn();\n    attemptStub.mockReturnValueOnce(true);\n    attemptStub.mockReturnValueOnce(Promise.resolve(true));\n    attemptStub.mockReturnValueOnce(Promise.resolve(false));\n\n    const retry = new RetryLink({\n      delay: { initial: 1 },\n      attempts: attemptStub,\n    });\n    const linkStub = jest.fn(\n      () => new Observable((o) => o.error(standardError))\n    ) as any;\n    const link = ApolloLink.from([retry, new ApolloLink(linkStub)]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(standardError);\n\n    const operation = attemptStub.mock.calls[0][1];\n    expect(attemptStub.mock.calls).toEqual([\n      [1, operation, standardError],\n      [2, operation, standardError],\n      [3, operation, standardError],\n    ]);\n  });\n\n  it(\"handles protocol errors from multipart subscriptions\", async () => {\n    const subscription = gql`\n      subscription MySubscription {\n        aNewDieWasCreated {\n          die {\n            roll\n            sides\n            color\n          }\n        }\n      }\n    `;\n\n    const attemptStub = jest.fn();\n    attemptStub.mockReturnValueOnce(true);\n\n    const retryLink = new RetryLink({\n      delay: { initial: 1 },\n      attempts: attemptStub,\n    });\n\n    const { httpLink, enqueuePayloadResult, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n    const link = ApolloLink.from([retryLink, httpLink]);\n    const stream = new ObservableStream(execute(link, { query: subscription }));\n\n    enqueueProtocolErrors([\n      { message: \"Error field\", extensions: { code: \"INTERNAL_SERVER_ERROR\" } },\n    ]);\n\n    enqueuePayloadResult({\n      data: {\n        aNewDieWasCreated: { die: { color: \"blue\", roll: 2, sides: 6 } },\n      },\n    });\n\n    await expect(stream).toEmitTypedValue({\n      data: {\n        aNewDieWasCreated: { die: { color: \"blue\", roll: 2, sides: 6 } },\n      },\n    });\n\n    expect(attemptStub).toHaveBeenCalledTimes(1);\n    expect(attemptStub).toHaveBeenCalledWith(\n      1,\n      expect.objectContaining({\n        operationName: \"MySubscription\",\n        query: subscription,\n      }),\n      new CombinedProtocolErrors([\n        {\n          message: \"Error field\",\n          extensions: { code: \"INTERNAL_SERVER_ERROR\" },\n        },\n      ])\n    );\n  });\n\n  it(\"calls observer.next when not retrying a protocol error\", async () => {\n    const subscription = gql`\n      subscription MySubscription {\n        aNewDieWasCreated {\n          die {\n            roll\n            sides\n            color\n          }\n        }\n      }\n    `;\n\n    const retryLink = new RetryLink({\n      delay: { initial: 1 },\n      attempts: {\n        retryIf: () => false,\n      },\n    });\n\n    const { httpLink, enqueueProtocolErrors } =\n      mockMultipartSubscriptionStream();\n    const link = ApolloLink.from([retryLink, httpLink]);\n    const stream = new ObservableStream(execute(link, { query: subscription }));\n\n    enqueueProtocolErrors([\n      { message: \"Error field\", extensions: { code: \"INTERNAL_SERVER_ERROR\" } },\n    ]);\n\n    await expect(stream).toEmitTypedValue({\n      extensions: {\n        [PROTOCOL_ERRORS_SYMBOL]: new CombinedProtocolErrors([\n          {\n            message: \"Error field\",\n            extensions: { code: \"INTERNAL_SERVER_ERROR\" },\n          },\n        ]),\n      } as any,\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/retry/delayFunction.ts",
    "content": "import type { RetryLink } from \"./retryLink.js\";\n\nexport function buildDelayFunction(\n  delayOptions?: RetryLink.DelayOptions\n): RetryLink.DelayFunction {\n  const { initial = 300, jitter = true, max = Infinity } = delayOptions || {};\n  // If we're jittering, baseDelay is half of the maximum delay for that\n  // attempt (and is, on average, the delay we will encounter).\n  // If we're not jittering, adjust baseDelay so that the first attempt\n  // lines up with initialDelay, for everyone's sanity.\n  const baseDelay = jitter ? initial : initial / 2;\n\n  return function delayFunction(count: number) {\n    let delay = Math.min(max, baseDelay * 2 ** count);\n    if (jitter) {\n      // We opt for a full jitter approach for a mostly uniform distribution,\n      // but bound it within initialDelay and delay for everyone's sanity.\n      delay = Math.random() * delay;\n    }\n\n    return delay;\n  };\n}\n"
  },
  {
    "path": "src/link/retry/index.ts",
    "content": "export { RetryLink } from \"./retryLink.js\";\n"
  },
  {
    "path": "src/link/retry/retryFunction.ts",
    "content": "import type { RetryLink } from \"./retryLink.js\";\n\nexport function buildRetryFunction(\n  retryOptions?: RetryLink.AttemptsOptions\n): RetryLink.AttemptsFunction {\n  const { retryIf, max = 5 } =\n    retryOptions || ({} as RetryLink.AttemptsOptions);\n  return function retryFunction(count, operation, error) {\n    if (count >= max) return false;\n    return retryIf ? retryIf(error, operation) : !!error;\n  };\n}\n"
  },
  {
    "path": "src/link/retry/retryLink.ts",
    "content": "import type { Subscription } from \"rxjs\";\nimport type { Observer } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nimport type { ErrorLike } from \"@apollo/client\";\nimport {\n  graphQLResultHasProtocolErrors,\n  PROTOCOL_ERRORS_SYMBOL,\n  toErrorLike,\n} from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\n\nimport { buildDelayFunction } from \"./delayFunction.js\";\nimport { buildRetryFunction } from \"./retryFunction.js\";\n\nexport declare namespace RetryLink {\n  namespace RetryLinkDocumentationTypes {\n    /**\n     * A function used to determine whether to retry the current operation.\n     *\n     * @param attempt - The current attempt number\n     * @param operation - The current `ApolloLink.Operation` for the request\n     * @param error - The error that triggered the retry attempt\n     * @returns A boolean to indicate whether to retry the current operation\n     */\n    function AttemptsFunction(\n      attempt: number,\n      operation: ApolloLink.Operation,\n      error: ErrorLike\n    ): boolean | Promise<boolean>;\n\n    /**\n     * A function used to determine the delay for a retry attempt.\n     *\n     * @param attempt - The current attempt number\n     * @param operation - The current `ApolloLink.Operation` for the request\n     * @param error - The error that triggered the retry attempt\n     * @returns The delay in milliseconds before attempting the request again\n     */\n    function DelayFunction(\n      attempt: number,\n      operation: ApolloLink.Operation,\n      error: ErrorLike\n    ): number;\n  }\n\n  /** {@inheritDoc @apollo/client/link/retry!RetryLink.RetryLinkDocumentationTypes.DelayFunction:function(1)} */\n  export type DelayFunction = (\n    attempt: number,\n    operation: ApolloLink.Operation,\n    error: ErrorLike\n  ) => number;\n\n  /**\n   * Configuration options for the standard retry delay strategy.\n   */\n  export interface DelayOptions {\n    /**\n     * The number of milliseconds to wait before attempting the first retry.\n     *\n     * Delays will increase exponentially for each attempt. E.g. if this is\n     * set to 100, subsequent retries will be delayed by 200, 400, 800, etc,\n     * until they reach the maximum delay.\n     *\n     * Note that if jittering is enabled, this is the average delay.\n     *\n     * @defaultValue `300`\n     */\n    initial?: number;\n\n    /**\n     * The maximum number of milliseconds that the link should wait for any\n     * retry.\n     *\n     * @defaultValue `Infinity`\n     */\n    max?: number;\n\n    /**\n     * Whether delays between attempts should be randomized.\n     *\n     * This helps avoid [thundering herd](https://en.wikipedia.org/wiki/Thundering_herd_problem)\n     * type situations by better distributing load during major outages. Without\n     * these strategies, when your server comes back up it will be hit by all\n     * of your clients at once, possibly causing it to go down again.\n     *\n     * @defaultValue `true`\n     */\n    jitter?: boolean;\n  }\n\n  /** {@inheritDoc @apollo/client/link/retry!RetryLink.RetryLinkDocumentationTypes.AttemptsFunction:function(1)} */\n  export type AttemptsFunction = (\n    attempt: number,\n    operation: ApolloLink.Operation,\n    error: ErrorLike\n  ) => boolean | Promise<boolean>;\n\n  /**\n   * Configuration options for the standard retry attempt strategy.\n   */\n  export interface AttemptsOptions {\n    /**\n     * The max number of times to try a single operation before giving up.\n     *\n     * Note that this INCLUDES the initial request as part of the count.\n     * E.g. `max` of 1 indicates no retrying should occur.\n     *\n     * Pass `Infinity` for infinite retries.\n     *\n     * @defaultValue `5`\n     */\n    max?: number;\n\n    /**\n     * Predicate function that determines whether a particular error should\n     * trigger a retry.\n     *\n     * For example, you may want to not retry 4xx class HTTP errors.\n     *\n     * @defaultValue `() => true`\n     */\n    retryIf?: (\n      error: ErrorLike,\n      operation: ApolloLink.Operation\n    ) => boolean | Promise<boolean>;\n  }\n\n  /**\n   * Options provided to the `RetryLink` constructor.\n   */\n  export interface Options {\n    /**\n     * Configuration for the delay strategy to use, or a custom delay strategy.\n     */\n    delay?: RetryLink.DelayOptions | RetryLink.DelayFunction;\n\n    /**\n     * Configuration for the retry strategy to use, or a custom retry strategy.\n     */\n    attempts?: RetryLink.AttemptsOptions | RetryLink.AttemptsFunction;\n  }\n}\n\nclass RetryableOperation {\n  private retryCount: number = 0;\n  private currentSubscription: Subscription | null = null;\n  private timerId: ReturnType<typeof setTimeout> | undefined;\n\n  constructor(\n    private observer: Observer<ApolloLink.Result>,\n    private operation: ApolloLink.Operation,\n    private forward: ApolloLink.ForwardFunction,\n    private delayFor: RetryLink.DelayFunction,\n    private retryIf: RetryLink.AttemptsFunction\n  ) {\n    this.try();\n  }\n\n  /**\n   * Stop retrying for the operation, and cancel any in-progress requests.\n   */\n  public cancel() {\n    if (this.currentSubscription) {\n      this.currentSubscription.unsubscribe();\n    }\n    clearTimeout(this.timerId);\n    this.timerId = undefined;\n    this.currentSubscription = null;\n  }\n\n  private try() {\n    this.currentSubscription = this.forward(this.operation).subscribe({\n      next: (result) => {\n        if (graphQLResultHasProtocolErrors(result)) {\n          this.onError(result.extensions[PROTOCOL_ERRORS_SYMBOL], () =>\n            // Pretend like we never encountered this error and move the result\n            // along for Apollo Client core to handle this error.\n            this.observer.next(result)\n          );\n          // Unsubscribe from the current subscription to prevent the `complete`\n          // handler to be called as a result of the stream closing.\n          this.currentSubscription?.unsubscribe();\n          return;\n        }\n\n        this.observer.next(result);\n      },\n      error: (error) => this.onError(error, () => this.observer.error(error)),\n      complete: this.observer.complete.bind(this.observer),\n    });\n  }\n\n  private onError = async (error: unknown, onContinue: () => void) => {\n    this.retryCount += 1;\n    const errorLike = toErrorLike(error);\n\n    const shouldRetry = await this.retryIf(\n      this.retryCount,\n      this.operation,\n      errorLike\n    );\n    if (shouldRetry) {\n      this.scheduleRetry(\n        this.delayFor(this.retryCount, this.operation, errorLike)\n      );\n      return;\n    }\n\n    onContinue();\n  };\n\n  private scheduleRetry(delay: number) {\n    if (this.timerId) {\n      throw new Error(`RetryLink BUG! Encountered overlapping retries`);\n    }\n\n    this.timerId = setTimeout(() => {\n      this.timerId = undefined;\n      this.try();\n    }, delay);\n  }\n}\n\n/**\n * `RetryLink` is a non-terminating link that attempts to retry operations that\n * fail due to network errors. It enables resilient GraphQL operations by\n * automatically retrying failed requests with configurable delay and retry\n * strategies.\n *\n * @remarks\n *\n * `RetryLink` is particularly useful for handling unreliable network conditions\n * where you would rather wait longer than explicitly fail an operation. It\n * provides exponential backoff and jitters delays between attempts by default.\n *\n * > [!NOTE]\n * > This link does not handle retries for GraphQL errors in the response. Use\n * > `ErrorLink` to retry an operation after a GraphQL error. For more\n * > information, see the [Error handling documentation](https://apollographql.com/docs/react/data/error-handling#on-graphql-errors).\n *\n * @example\n *\n * ```ts\n * import { RetryLink } from \"@apollo/client/link/retry\";\n *\n * const link = new RetryLink();\n * ```\n */\nexport class RetryLink extends ApolloLink {\n  private delayFor: RetryLink.DelayFunction;\n  private retryIf: RetryLink.AttemptsFunction;\n\n  constructor(options?: RetryLink.Options) {\n    super();\n    const { attempts, delay } = options || ({} as RetryLink.Options);\n    this.delayFor =\n      typeof delay === \"function\" ? delay : buildDelayFunction(delay);\n    this.retryIf =\n      typeof attempts === \"function\" ? attempts : buildRetryFunction(attempts);\n  }\n\n  public request(\n    operation: ApolloLink.Operation,\n    forward: ApolloLink.ForwardFunction\n  ): Observable<ApolloLink.Result> {\n    return new Observable((observer) => {\n      const retryable = new RetryableOperation(\n        observer,\n        operation,\n        forward,\n        this.delayFor,\n        this.retryIf\n      );\n      return () => {\n        retryable.cancel();\n      };\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/schema/__tests__/schemaLink.ts",
    "content": "import { makeExecutableSchema } from \"@graphql-tools/schema\";\nimport { gql } from \"graphql-tag\";\n\nimport { SchemaLink } from \"@apollo/client/link/schema\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nconst sampleQuery = gql`\n  query SampleQuery {\n    sampleQuery {\n      id\n    }\n  }\n`;\n\nconst typeDefs = `\ntype Stub {\n  id: String\n}\n\ntype Query {\n  sampleQuery: Stub\n}\n`;\n\nconst schema = makeExecutableSchema({ typeDefs });\n\ndescribe(\"SchemaLink\", () => {\n  it(\"throws if no arguments given\", () => {\n    expect(() => new (SchemaLink as any)()).toThrow();\n  });\n\n  it(\"correctly receives the constructor arguments\", () => {\n    let rootValue = {};\n    let link = new SchemaLink({ schema, rootValue });\n    expect(link.rootValue).toEqual(rootValue);\n    expect(link.schema).toEqual(schema);\n  });\n\n  it(\"calls next and then complete\", async () => {\n    const link = new SchemaLink({ schema });\n    const observable = execute(link, {\n      query: sampleQuery,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n  });\n\n  it(\"calls error when fetch fails\", async () => {\n    const link = new SchemaLink({\n      validate: true,\n      schema: makeExecutableSchema({\n        typeDefs,\n        resolvers: {\n          Query: {\n            sampleQuery() {\n              throw new Error(\"Unauthorized\");\n            },\n          },\n        },\n      }),\n    });\n    const observable = execute(link, {\n      query: sampleQuery,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue({\n      data: { sampleQuery: null },\n      errors: [{ message: \"Unauthorized\", path: [\"sampleQuery\"] }],\n    });\n  });\n\n  it(\"supports query which is executed synchronously\", async () => {\n    const link = new SchemaLink({ schema });\n    const introspectionQuery = gql`\n      query IntrospectionQuery {\n        __schema {\n          types {\n            name\n          }\n        }\n      }\n    `;\n    const observable = execute(link, {\n      query: introspectionQuery,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n  });\n\n  it(\"passes operation context into execute with context function\", async () => {\n    const contextValue = { some: \"value\" };\n    const contextProvider = jest.fn((operation) => operation.getContext());\n    const resolvers = {\n      Query: {\n        sampleQuery: (root: any, args: any, context: any) => {\n          expect(context).toEqual(contextValue);\n        },\n      },\n    };\n    const schemaWithResolvers = makeExecutableSchema({\n      typeDefs,\n      resolvers,\n    });\n    const link = new SchemaLink({\n      schema: schemaWithResolvers,\n      context: contextProvider,\n    });\n    const observable = execute(link, {\n      query: sampleQuery,\n      context: contextValue,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n    expect(contextProvider).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"passes static context into execute\", async () => {\n    const contextValue = { some: \"value\" };\n    const resolver = jest.fn((root, args, context) => {\n      expect(context).toEqual(contextValue);\n    });\n\n    const resolvers = {\n      Query: {\n        sampleQuery: resolver,\n      },\n    };\n    const schemaWithResolvers = makeExecutableSchema({\n      typeDefs,\n      resolvers,\n    });\n    const link = new SchemaLink({\n      schema: schemaWithResolvers,\n      context: contextValue,\n    });\n    const observable = execute(link, {\n      query: sampleQuery,\n    });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitNext();\n    await expect(stream).toComplete();\n    expect(resolver).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"reports errors for unknown queries\", async () => {\n    const link = new SchemaLink({\n      validate: true,\n      schema: makeExecutableSchema({\n        typeDefs,\n      }),\n    });\n    const observable = execute(link, {\n      query: gql`\n        query {\n          unknown\n        }\n      `,\n    });\n    const stream = new ObservableStream(observable);\n    await expect(stream).toEmitTypedValue({\n      errors: [{ message: 'Cannot query field \"unknown\" on type \"Query\".' }],\n    });\n  });\n});\n"
  },
  {
    "path": "src/link/schema/index.ts",
    "content": "import type { GraphQLSchema } from \"graphql\";\nimport { execute, validate } from \"graphql\";\nimport { Observable } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\n\nexport declare namespace SchemaLink {\n  export namespace SchemaLinkDocumentationTypes {\n    /**\n     * A function that returns the resolver context for a given operation.\n     *\n     * This function is called for each operation and allows you to create\n     * operation-specific context. This is useful when you need to include\n     * information from the operation (like headers, variables, etc.) in the\n     * resolver context.\n     *\n     * @param operation - The Apollo Link operation\n     * @returns The resolver context object or a promise that resolves to the context\n     *\n     * @example\n     *\n     * ```ts\n     * const link = new SchemaLink({\n     *   schema,\n     *   context: (operation) => {\n     *     return {\n     *       userId: operation.getContext().userId,\n     *       dataSources: {\n     *         userAPI: new UserAPI(),\n     *       },\n     *     };\n     *   },\n     * });\n     * ```\n     */\n    export function ResolverContextFunction(\n      operation: ApolloLink.Operation\n    ): SchemaLink.ResolverContext | PromiseLike<SchemaLink.ResolverContext>;\n  }\n  /**\n   * The resolver context object passed to GraphQL resolvers.\n   *\n   * This context object is passed as the third parameter to GraphQL resolvers\n   * and typically contains data-fetching connectors, authentication information,\n   * and other request-specific data.\n   */\n  export type ResolverContext = Record<string, any>;\n\n  /** {@inheritDoc @apollo/client/link/schema!SchemaLink.SchemaLinkDocumentationTypes.ResolverContextFunction:function(1)} */\n  export type ResolverContextFunction = (\n    operation: ApolloLink.Operation\n  ) => SchemaLink.ResolverContext | PromiseLike<SchemaLink.ResolverContext>;\n\n  /**\n   * Options for configuring the `SchemaLink`.\n   */\n  export interface Options {\n    /**\n     * An executable GraphQL schema to use for operation execution.\n     *\n     * @remarks\n     *\n     * This should be a complete, executable GraphQL schema created using\n     * tools like `makeExecutableSchema` from `@graphql-tools/schema` or\n     * `buildSchema` from `graphql`.\n     *\n     * @example\n     *\n     * ```ts\n     * import { makeExecutableSchema } from \"@graphql-tools/schema\";\n     *\n     * const schema = makeExecutableSchema({\n     *   typeDefs,\n     *   resolvers,\n     * });\n     *\n     * const link = new SchemaLink({ schema });\n     * ```\n     */\n    schema: GraphQLSchema;\n\n    /**\n     * The root value passed to root-level resolvers. It's typically not used in\n     * most schemas but can be useful for certain advanced patterns.\n     */\n    rootValue?: any;\n\n    /**\n     * Context object or function that returns the context object to provide to\n     * resolvers. The context is passed as the third parameter to all GraphQL\n     * resolvers.\n     *\n     * - If a static object is provided, the same context will be used for all\n     *   operations\n     * - If a function is provided, the function is called for each operation to\n     *   generate operation-specific context\n     */\n    context?: SchemaLink.ResolverContext | SchemaLink.ResolverContextFunction;\n\n    /**\n     * Whether to validate incoming queries against the schema before execution.\n     *\n     * When enabled, queries will be validated against the schema before execution,\n     * and validation errors will be returned in the result's `errors` array,\n     * just like a remote GraphQL server would.\n     *\n     * This is useful for testing and development to catch query errors early,\n     * but may add overhead in production environments.\n     *\n     * @defaultValue false\n     */\n    validate?: boolean;\n  }\n}\n\n/**\n * `SchemaLink` is a terminating link that executes GraphQL operations against\n * a local GraphQL schema instead of making network requests. This is commonly\n * used for server-side rendering (SSR) and mocking data.\n *\n * > [!NOTE]\n * > While `SchemaLink` can provide GraphQL results on the client, the GraphQL\n * > execution layer is [quite large](https://bundlephobia.com/result?p=graphql) for practical client-side use.\n * > For client-side state management, consider Apollo Client's [local state management](https://apollographql.com/docs/react/local-state/local-state-management/)\n * > functionality instead, which integrates with the Apollo Client cache.\n *\n * @example\n *\n * ```ts\n * import { SchemaLink } from \"@apollo/client/link/schema\";\n * import schema from \"./path/to/your/schema\";\n *\n * const link = new SchemaLink({ schema });\n * ```\n */\nexport class SchemaLink extends ApolloLink {\n  public schema: SchemaLink.Options[\"schema\"];\n  public rootValue: SchemaLink.Options[\"rootValue\"];\n  public context: SchemaLink.Options[\"context\"];\n  public validate: boolean;\n\n  constructor(options: SchemaLink.Options) {\n    super();\n    this.schema = options.schema;\n    this.rootValue = options.rootValue;\n    this.context = options.context;\n    this.validate = !!options.validate;\n  }\n\n  public request(\n    operation: ApolloLink.Operation\n  ): Observable<ApolloLink.Result> {\n    return new Observable<ApolloLink.Result>((observer) => {\n      new Promise<SchemaLink.ResolverContext>((resolve) =>\n        resolve(\n          typeof this.context === \"function\" ?\n            this.context(operation)\n          : this.context\n        )\n      )\n        .then((context) => {\n          if (this.validate) {\n            const validationErrors = validate(this.schema, operation.query);\n            if (validationErrors.length > 0) {\n              return { errors: validationErrors };\n            }\n          }\n\n          return execute({\n            schema: this.schema,\n            document: operation.query,\n            rootValue: this.rootValue,\n            contextValue: context,\n            variableValues: operation.variables,\n            operationName: operation.operationName,\n          });\n        })\n        .then((data) => {\n          if (!observer.closed) {\n            observer.next(data);\n            observer.complete();\n          }\n        })\n        .catch((error) => {\n          if (!observer.closed) {\n            observer.error(error);\n          }\n        });\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/subscriptions/__tests__/graphqlWsLink.ts",
    "content": "import type { ExecutionResult } from \"graphql\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { Client } from \"graphql-ws\";\nimport type { Observable } from \"rxjs\";\n\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\nconst mutation = gql`\n  mutation SampleMutation {\n    stub {\n      id\n    }\n  }\n`;\n\nconst subscription = gql`\n  subscription SampleSubscription {\n    stub {\n      id\n    }\n  }\n`;\n\nfunction mockClient(subscribe: Client[\"subscribe\"]): Client {\n  return {\n    subscribe,\n    // GraphQLWsLink doesn't use these methods\n    iterate: () => (async function* iterator() {})(),\n    on: () => () => {},\n    dispose: () => {},\n    terminate: () => {},\n  };\n}\n\nasync function observableToArray<T>(o: Observable<T>): Promise<T[]> {\n  const out: T[] = [];\n  await o.forEach((v) => out.push(v));\n  return out;\n}\n\ndescribe(\"GraphQLWSlink\", () => {\n  it(\"constructs\", () => {\n    const client = mockClient(() => () => {});\n    expect(() => new GraphQLWsLink(client)).not.toThrow();\n  });\n\n  // TODO some sort of dependency injection\n\n  // it('should pass the correct initialization parameters to the Subscription Client', () => {\n  // });\n\n  it(\"should call subscribe on the client for a query\", async () => {\n    const result = { data: { data: \"result\" } } as ExecutionResult<any, any>;\n    const subscribe: Client[\"subscribe\"] = (_, sink) => {\n      sink.next(result);\n      sink.complete();\n      return () => {};\n    };\n    const client = mockClient(subscribe);\n    const link = new GraphQLWsLink(client);\n\n    const obs = execute(link, { query });\n    await expect(observableToArray(obs)).resolves.toEqual([result]);\n  });\n\n  it(\"should call subscribe on the client for a mutation\", async () => {\n    const result = { data: { data: \"result\" } } as ExecutionResult<any, any>;\n    const subscribe: Client[\"subscribe\"] = (_, sink) => {\n      sink.next(result);\n      sink.complete();\n      return () => {};\n    };\n    const client = mockClient(subscribe);\n    const link = new GraphQLWsLink(client);\n\n    const obs = execute(link, { query: mutation });\n    await expect(observableToArray(obs)).resolves.toEqual([result]);\n  });\n\n  it(\"should call next with multiple results for subscription\", async () => {\n    const results = [\n      { data: { data: \"result1\" } },\n      { data: { data: \"result2\" } },\n    ] as ExecutionResult<any, any>[];\n    const subscribe: Client[\"subscribe\"] = (_, sink) => {\n      const copy = [...results];\n      for (const r of copy) {\n        sink.next(r);\n      }\n      sink.complete();\n      return () => {};\n    };\n    const client = mockClient(subscribe);\n    const link = new GraphQLWsLink(client);\n\n    const obs = execute(link, { query: subscription });\n    await expect(observableToArray(obs)).resolves.toEqual(results);\n  });\n\n  describe(\"should reject\", () => {\n    it(\"with Error on subscription error via Error\", async () => {\n      const subscribe: Client[\"subscribe\"] = (_, sink) => {\n        sink.error(new Error(\"an error occurred\"));\n        return () => {};\n      };\n      const client = mockClient(subscribe);\n      const link = new GraphQLWsLink(client);\n\n      const obs = execute(link, { query: subscription });\n      await expect(observableToArray(obs)).rejects.toEqual(\n        new Error(\"an error occurred\")\n      );\n    });\n\n    it(\"with Error on subscription error via CloseEvent\", async () => {\n      const subscribe: Client[\"subscribe\"] = (_, sink) => {\n        // A WebSocket close event receives a CloseEvent\n        // See: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event\n        sink.error(\n          new CloseEvent(\"an error occurred\", {\n            code: 1006,\n            reason: \"abnormally closed\",\n          })\n        );\n        return () => {};\n      };\n      const client = mockClient(subscribe);\n      const link = new GraphQLWsLink(client);\n\n      const obs = execute(link, { query: subscription });\n      await expect(observableToArray(obs)).rejects.toEqual(\n        new Error(\"Socket closed with event 1006 abnormally closed\")\n      );\n    });\n\n    it(\"with Error on subscription error via Event (network disconnected)\", async () => {\n      const subscribe: Client[\"subscribe\"] = (_, sink) => {\n        // A WebSocket error event receives a generic Event\n        // See: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\n        sink.error({ target: { readyState: WebSocket.CLOSED } });\n        return () => {};\n      };\n      const client = mockClient(subscribe);\n      const link = new GraphQLWsLink(client);\n\n      const obs = execute(link, { query: subscription });\n      await expect(observableToArray(obs)).rejects.toEqual(\n        new Error(\"Socket closed\")\n      );\n    });\n\n    it(\"with CombinedGraphQLErrors on subscription error via GraphQLError[]\", async () => {\n      const subscribe: Client[\"subscribe\"] = (_, sink) => {\n        sink.error([new GraphQLError(\"Foo bar.\")]);\n        return () => {};\n      };\n      const client = mockClient(subscribe);\n      const link = new GraphQLWsLink(client);\n\n      const obs = execute(link, { query: subscription });\n      await expect(observableToArray(obs)).rejects.toEqual(\n        new CombinedGraphQLErrors({ errors: [{ message: \"Foo bar.\" }] })\n      );\n    });\n  });\n});\n\n// https://github.com/apollographql/apollo-client/issues/12946\ntest(\"sends only known keys to the GraphQLWsLink\", async () => {\n  const knownKeys = [\n    \"query\",\n    \"variables\",\n    \"operationName\",\n    \"extensions\",\n  ].sort();\n\n  type SubscribeFn = Client[\"subscribe\"];\n  const subscribe = jest.fn<ReturnType<SubscribeFn>, Parameters<SubscribeFn>>(\n    (_payload, sink) => {\n      sink.complete();\n      return () => {};\n    }\n  );\n  const client = mockClient(subscribe);\n  const link = new GraphQLWsLink(client);\n\n  const stream = new ObservableStream(execute(link, { query: subscription }));\n  await stream.takeComplete();\n\n  expect(subscribe).toHaveBeenCalledTimes(1);\n\n  const payload = subscribe.mock.calls[0][0];\n  expect(Object.keys(payload).sort()).toStrictEqual(knownKeys);\n});\n"
  },
  {
    "path": "src/link/subscriptions/index.ts",
    "content": "// This file is adapted from the graphql-ws npm package:\n// https://github.com/enisdenjo/graphql-ws\n//\n// Most of the file comes from that package's README; some other parts (such as\n// isLikeCloseEvent) come from its source.\n//\n// Here's the license of the original code:\n//\n// The MIT License (MIT)\n//\n// Copyright (c) 2020-2021 Denis Badurina\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\nimport type { FormattedExecutionResult } from \"graphql\";\nimport type { Client, Sink } from \"graphql-ws\";\nimport { Observable } from \"rxjs\";\n\nimport { CombinedGraphQLErrors } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { print } from \"@apollo/client/utilities\";\nimport { isNonNullObject } from \"@apollo/client/utilities/internal\";\n\n// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close_event\nfunction isLikeCloseEvent(val: unknown): val is CloseEvent {\n  return isNonNullObject(val) && \"code\" in val && \"reason\" in val;\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/error_event\nfunction isLikeErrorEvent(err: unknown): err is Event {\n  return isNonNullObject(err) && err.target?.readyState === WebSocket.CLOSED;\n}\n\n/**\n * The `GraphQLWsLink` is a terminating link sends GraphQL operations over a\n * WebSocket connection using the [`graphql-ws`](https://www.npmjs.com/package/graphql-ws) library. It's used most\n * commonly with GraphQL [subscriptions](https://apollographql.com/docs/react/data/subscriptions/),\n *\n * > [!NOTE]\n * > This link works with the `graphql-ws` library. If your server uses\n * > the deprecated `subscriptions-transport-ws` library, use the deprecated\n * > [`WebSocketLink`](https://apollographql.com/docs/react/api/link/apollo-link-ws) link instead.\n *\n * @example\n *\n * ```ts\n * import { GraphQLWsLink } from \"@apollo/client/link/subscriptions\";\n * import { createClient } from \"graphql-ws\";\n *\n * const link = new GraphQLWsLink(\n *   createClient({\n *     url: \"ws://localhost:3000/subscriptions\",\n *   })\n * );\n * ```\n */\nexport class GraphQLWsLink extends ApolloLink {\n  constructor(public readonly client: Client) {\n    super();\n  }\n\n  public request(\n    operation: ApolloLink.Operation\n  ): Observable<ApolloLink.Result> {\n    return new Observable((observer) => {\n      const { query, variables, operationName, extensions } = operation;\n      return this.client.subscribe<ApolloLink.Result>(\n        { variables, operationName, extensions, query: print(query) },\n        {\n          next: observer.next.bind(observer),\n          complete: observer.complete.bind(observer),\n          error: (err) => {\n            if (err instanceof Error) {\n              return observer.error(err);\n            }\n            const likeClose = isLikeCloseEvent(err);\n            if (likeClose || isLikeErrorEvent(err)) {\n              return observer.error(\n                // reason will be available on clean closes\n                new Error(\n                  `Socket closed${likeClose ? ` with event ${err.code}` : \"\"}${\n                    likeClose ? ` ${err.reason}` : \"\"\n                  }`\n                )\n              );\n            }\n\n            return observer.error(\n              new CombinedGraphQLErrors({\n                errors: Array.isArray(err) ? err : [err],\n              })\n            );\n          },\n          // casting around a wrong type in graphql-ws, which incorrectly expects `Sink<ExecutionResult>`\n        } satisfies Sink<FormattedExecutionResult> as any\n      );\n    });\n  }\n}\n"
  },
  {
    "path": "src/link/utils/__tests__/filterOperationVariables.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport { filterOperationVariables } from \"@apollo/client/link/utils\";\n\nconst sampleQueryWithVariables = gql`\n  query MyQuery($a: Int!) {\n    stub(a: $a) {\n      id\n    }\n  }\n`;\n\nconst sampleQueryWithoutVariables = gql`\n  query MyQuery {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"filterOperationVariables\", () => {\n  it(\"filters unused variables\", () => {\n    const variables = { a: 1, b: 2, c: 3 };\n    const result = filterOperationVariables(\n      variables,\n      sampleQueryWithoutVariables\n    );\n    expect(result).toEqual({});\n  });\n\n  it(\"does not filter used variables\", () => {\n    const variables = { a: 1, b: 2, c: 3 };\n    const result = filterOperationVariables(\n      variables,\n      sampleQueryWithVariables\n    );\n    expect(result).toEqual({ a: 1 });\n  });\n});\n"
  },
  {
    "path": "src/link/utils/createOperation.ts",
    "content": "import type { ApolloLink } from \"@apollo/client/link\";\nimport {\n  getOperationDefinition,\n  getOperationName,\n} from \"@apollo/client/utilities/internal\";\n\nexport function createOperation(\n  request: ApolloLink.Request,\n  { client }: ApolloLink.ExecuteContext\n): ApolloLink.Operation {\n  const operation = {\n    query: request.query,\n    variables: request.variables || {},\n    extensions: request.extensions || {},\n    operationName: getOperationName(request.query),\n    operationType: getOperationDefinition(request.query)!.operation,\n  } satisfies Omit<\n    ApolloLink.Operation,\n    \"client\" | \"getContext\" | \"setContext\"\n  > as ApolloLink.Operation;\n\n  let context = { ...request.context };\n\n  const setContext: ApolloLink.Operation[\"setContext\"] = (next) => {\n    if (typeof next === \"function\") {\n      context = { ...context, ...next(getContext()) };\n    } else {\n      context = { ...context, ...next };\n    }\n  };\n  const getContext: ApolloLink.Operation[\"getContext\"] = () =>\n    Object.freeze({ ...context });\n\n  Object.defineProperty(operation, \"setContext\", {\n    enumerable: false,\n    value: setContext,\n  });\n\n  Object.defineProperty(operation, \"getContext\", {\n    enumerable: false,\n    value: getContext,\n  });\n\n  Object.defineProperty(operation, \"client\", {\n    enumerable: false,\n    value: client,\n  });\n\n  return operation;\n}\n"
  },
  {
    "path": "src/link/utils/filterOperationVariables.ts",
    "content": "import type { DocumentNode, VariableDefinitionNode } from \"graphql\";\nimport { visit } from \"graphql\";\n\nexport function filterOperationVariables(\n  variables: Record<string, any>,\n  query: DocumentNode\n) {\n  const result = { ...variables };\n  const unusedNames = new Set(Object.keys(variables));\n  visit(query, {\n    Variable(node, _key, parent) {\n      // A variable type definition at the top level of a query is not\n      // enough to silence server-side errors about the variable being\n      // unused, so variable definitions do not count as usage.\n      // https://spec.graphql.org/draft/#sec-All-Variables-Used\n      if (\n        parent &&\n        (parent as VariableDefinitionNode).kind !== \"VariableDefinition\"\n      ) {\n        unusedNames.delete(node.name.value);\n      }\n    },\n  });\n  unusedNames.forEach((name) => {\n    delete result![name];\n  });\n  return result;\n}\n"
  },
  {
    "path": "src/link/utils/index.ts",
    "content": "export { createOperation } from \"./createOperation.js\";\nexport { filterOperationVariables } from \"./filterOperationVariables.js\";\n"
  },
  {
    "path": "src/link/ws/__tests__/webSocketLink.ts",
    "content": "import type { ExecutionResult } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { Observable, of } from \"rxjs\";\nimport { SubscriptionClient } from \"subscriptions-transport-ws\";\n\nimport { WebSocketLink } from \"@apollo/client/link/ws\";\nimport {\n  executeWithDefaultContext as execute,\n  ObservableStream,\n} from \"@apollo/client/testing/internal\";\n\nconst query = gql`\n  query SampleQuery {\n    stub {\n      id\n    }\n  }\n`;\n\nconst mutation = gql`\n  mutation SampleMutation {\n    stub {\n      id\n    }\n  }\n`;\n\nconst subscription = gql`\n  subscription SampleSubscription {\n    stub {\n      id\n    }\n  }\n`;\n\ndescribe(\"WebSocketLink\", () => {\n  it(\"constructs\", () => {\n    const client: any = {};\n    client.__proto__ = SubscriptionClient.prototype;\n    expect(() => new WebSocketLink(client)).not.toThrow();\n  });\n\n  // TODO some sort of dependency injection\n\n  // it('should pass the correct initialization parameters to the Subscription Client', () => {\n  // });\n\n  it(\"should call request on the client for a query\", async () => {\n    const result = { data: { data: \"result\" } };\n    const client: any = {};\n    const observable = of(result);\n    client.__proto__ = SubscriptionClient.prototype;\n    client.request = jest.fn();\n    client.request.mockReturnValueOnce(observable);\n    const link = new WebSocketLink(client);\n\n    const obs = execute(link, { query });\n    expect(obs).toEqual(observable);\n\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue(result);\n    expect(client.request).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should call query on the client for a mutation\", async () => {\n    const result = { data: { data: \"result\" } };\n    const client: any = {};\n    const observable = of(result);\n    client.__proto__ = SubscriptionClient.prototype;\n    client.request = jest.fn();\n    client.request.mockReturnValueOnce(observable);\n    const link = new WebSocketLink(client);\n\n    const obs = execute(link, { query: mutation });\n    expect(obs).toEqual(observable);\n\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue(result);\n    expect(client.request).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should call request on the subscriptions client for subscription\", async () => {\n    const result = { data: { data: \"result\" } };\n    const client: any = {};\n    const observable = of(result);\n    client.__proto__ = SubscriptionClient.prototype;\n    client.request = jest.fn();\n    client.request.mockReturnValueOnce(observable);\n    const link = new WebSocketLink(client);\n\n    const obs = execute(link, { query: subscription });\n    expect(obs).toEqual(observable);\n\n    const stream = new ObservableStream(obs);\n\n    await expect(stream).toEmitTypedValue(result);\n    expect(client.request).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should call next with multiple results for subscription\", async () => {\n    const results = [\n      { data: { data: \"result1\" } },\n      { data: { data: \"result2\" } },\n    ];\n    const client: any = {};\n    client.__proto__ = SubscriptionClient.prototype;\n    client.request = jest.fn(() => {\n      const copy = [...results];\n      return new Observable<ExecutionResult>((observer) => {\n        observer.next(copy[0]);\n        observer.next(copy[1]);\n      });\n    });\n\n    const link = new WebSocketLink(client);\n\n    const observable = execute(link, { query: subscription });\n    const stream = new ObservableStream(observable);\n\n    await expect(stream).toEmitTypedValue(results.shift()!);\n    await expect(stream).toEmitTypedValue(results.shift()!);\n\n    expect(client.request).toHaveBeenCalledTimes(1);\n    expect(results).toHaveLength(0);\n  });\n});\n"
  },
  {
    "path": "src/link/ws/index.ts",
    "content": "import type { Observable } from \"rxjs\";\nimport type { ClientOptions } from \"subscriptions-transport-ws\";\nimport { SubscriptionClient } from \"subscriptions-transport-ws\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nexport declare namespace WebSocketLink {\n  /**\n   * Configuration options for creating a `WebSocketLink` instance.\n   *\n   * @remarks\n   *\n   * These configuration options are used when creating a `WebSocketLink` without\n   * providing an existing `SubscriptionClient` instance. The options are passed\n   * directly to the `SubscriptionClient` constructor from the `subscriptions-transport-ws`\n   * library.\n   */\n  export interface Configuration {\n    /**\n     * The WebSocket endpoint URI to connect to.\n     *\n     * This should be a valid WebSocket URI (starting with `ws://` or `wss://`)\n     * that points to your GraphQL subscription endpoint.\n     *\n     * @example \"ws://localhost:4000/subscriptions\"\n     * @example \"wss://api.example.com/graphql\"\n     */\n    uri: string;\n\n    /**\n     * Configuration options passed to the underlying `SubscriptionClient`.\n     *\n     * These options configure the WebSocket connection behavior, including\n     * reconnection settings, connection parameters, and event handlers.\n     *\n     * For a complete list of available options, see the\n     * [supported `subscriptions-transport-ws` options](https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/client.ts#L61-L71).\n     */\n    options?: ClientOptions;\n\n    /**\n     * A custom WebSocket implementation to use for the connection.\n     *\n     * This is useful in environments that don't have native WebSocket support.\n     * You can provide a WebSocket polyfill or implementation that conforms to\n     * the W3C WebSocket API.\n     *\n     * @example\n     *\n     * ```ts\n     * import WebSocket from \"ws\";\n     *\n     * const wsLink = new WebSocketLink({\n     *   uri: \"ws://localhost:4000/subscriptions\",\n     *   webSocketImpl: WebSocket,\n     * });\n     * ```\n     */\n    webSocketImpl?: any;\n  }\n}\n\n/**\n * `WebSocketLink` is a terminating link that executes GraphQL operations over\n * WebSocket connections using the `subscriptions-transport-ws` library. It's\n * primarily used for GraphQL subscriptions but can also handle queries and\n * mutations.\n *\n * @example\n *\n * ```ts\n * import { WebSocketLink } from \"@apollo/client/link/ws\";\n * import { SubscriptionClient } from \"subscriptions-transport-ws\";\n *\n * const wsLink = new WebSocketLink(\n *   new SubscriptionClient(\"ws://localhost:4000/subscriptions\", {\n *     reconnect: true,\n *   })\n * );\n * ```\n *\n * @deprecated `WebSocketLink` uses the deprecated and unmaintained\n * `subscriptions-transport-ws` library. This link is no longer maintained and\n * will be removed in a future major version of Apollo Client. We recommend\n * switching to `GraphQLWsLink`, which uses the [`graphql-ws` library](https://the-guild.dev/graphql/ws) to\n * send GraphQL operations through WebSocket connections.\n */\nexport class WebSocketLink extends ApolloLink {\n  private subscriptionClient: SubscriptionClient;\n\n  constructor(\n    paramsOrClient: WebSocketLink.Configuration | SubscriptionClient\n  ) {\n    super();\n\n    if (__DEV__) {\n      invariant.warn(\n        \"`WebSocketLink` uses the deprecated and unmaintained `subscriptions-transport-ws` library. This link is no longer maintained and will be removed in a future major version of Apollo Client. We recommend switching to `GraphQLWsLink` which uses the `graphql-ws` library to send GraphQL operations through WebSocket connections (https://the-guild.dev/graphql/ws).\"\n      );\n    }\n\n    if (paramsOrClient instanceof SubscriptionClient) {\n      this.subscriptionClient = paramsOrClient;\n    } else {\n      this.subscriptionClient = new SubscriptionClient(\n        paramsOrClient.uri,\n        paramsOrClient.options,\n        paramsOrClient.webSocketImpl\n      );\n    }\n  }\n\n  public request(\n    operation: ApolloLink.Operation\n  ): Observable<ApolloLink.Result> {\n    return this.subscriptionClient.request(\n      operation\n    ) as Observable<ApolloLink.Result>;\n  }\n}\n"
  },
  {
    "path": "src/local-state/LocalState.ts",
    "content": "import type {\n  ASTNode,\n  DirectiveNode,\n  DocumentNode,\n  ExecutableDefinitionNode,\n  FieldNode,\n  FormattedExecutionResult,\n  FragmentSpreadNode,\n  GraphQLError,\n  GraphQLFormattedError,\n  OperationDefinitionNode,\n  SelectionNode,\n  SelectionSetNode,\n} from \"graphql\";\nimport { isSelectionNode, Kind, visit } from \"graphql\";\n\nimport type {\n  ApolloCache,\n  ApolloClient,\n  Cache,\n  DefaultContext,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport { cacheSlot } from \"@apollo/client/cache\";\nimport { LocalStateError, toErrorLike } from \"@apollo/client/errors\";\nimport { stripTypename } from \"@apollo/client/utilities\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  FragmentMap,\n  NoInfer,\n  RemoveIndexSignature,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  argumentsObjectFromField,\n  createFragmentMap,\n  dealias,\n  getFragmentDefinitions,\n  getMainDefinition,\n  hasDirectives,\n  mergeDeep,\n  mergeDeepArray,\n  resultKeyNameFromField,\n  shouldInclude,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\ninterface ExecContext {\n  client: ApolloClient;\n  operationDefinition: OperationDefinitionNode;\n  fragmentMap: FragmentMap;\n  context: unknown;\n  variables: OperationVariables;\n  exportedVariables: OperationVariables;\n  onlyRunForcedResolvers: boolean;\n  selectionsToResolve: Set<SelectionNode>;\n  errors: GraphQLFormattedError[];\n  phase: \"exports\" | \"resolve\";\n  exportedVariableDefs: Record<string, ExportedVariable>;\n  diff: Cache.DiffResult<any>;\n  returnPartialData: boolean;\n  fetchPolicy?: WatchQueryFetchPolicy;\n}\n\n/**\n * Information about an exported variable defined by an `@export` directive.\n */\ninterface ExportedVariable {\n  /**\n   * Defines whether an exported variable is a required variable (i.e. a non-null variable)\n   */\n  required: boolean;\n  /**\n   * The `FieldNode` where the exported variable is defined.\n   */\n  field?: FieldNode;\n\n  /**\n   * Ancestor nodes (parent, grandparent, etc.) that contain the `@export`\n   * directive node. This is useful to get access to nested fields that contain\n   * an `@export` directive if a parent resolver throws or returns\n   * `null`/`undefined` that would otherwise prevent us from traversing the\n   * node.\n   */\n  ancestors: WeakSet<ASTNode>;\n}\n\n/**\n * Tracks and caches information related to a GraphQL document by traversing the\n * document the first time its seen and collecting information about it.\n */\ninterface TraverseCacheEntry {\n  /**\n   * Tracks information about the variable definition for any variables defined\n   * by an `@export` directive.\n   */\n  exportedVariableDefs: Record<string, ExportedVariable>;\n\n  /**\n   * SelectionNodes that either directly contain or include an `@export` field\n   * in its selection set. This allows us to avoid traversing subtrees that do\n   * not contain `@export` fields.\n   */\n  exportsToResolve: Set<SelectionNode>;\n\n  /**\n   * SelectionNodes that either directly contain or include an `@client` field\n   * in its selection set. This allows us to avoid traversing subtrees that do\n   * not contain `@client` fields.\n   */\n  selectionsToResolve: Set<SelectionNode>;\n}\n\ntype InferContextValueFromResolvers<TResolvers> =\n  TResolvers extends { [typename: string]: infer TFieldResolvers } ?\n    TFieldResolvers extends (\n      { [field: string]: LocalState.Resolver<any, any, infer TContext, any> }\n    ) ?\n      unknown extends TContext ?\n        DefaultContext\n      : TContext\n    : DefaultContext\n  : DefaultContext;\n\ntype MaybeRequireContextFunction<TContext> =\n  {} extends RemoveIndexSignature<TContext> ? {}\n  : { context: LocalState.ContextFunction<TContext> };\n\nexport declare namespace LocalState {\n  // `rootValue` can be any value, but using `any` or `unknown` does not allow\n  // the ability to add a function signature to this definition. The generic\n  // allows us to provide the function signature while allowing any value.\n\n  /**\n   * Configuration options for LocalState.\n   *\n   * @template TResolvers - The type of resolvers map to use for type checking\n   * @template TContext - The type of context value returned by the context function. Defaults to `DefaultContext` when not provided.\n   */\n  export type Options<\n    TResolvers extends Resolvers = Resolvers,\n    TContext = DefaultContext,\n  > = {\n    context?: ContextFunction<TContext>;\n\n    /**\n     * The map of resolvers used to provide values for `@local` fields.\n     */\n    resolvers?: TResolvers;\n  } & MaybeRequireContextFunction<TContext>;\n\n  export interface RootValueFunctionContext {\n    document: DocumentNode;\n    client: ApolloClient;\n    context: DefaultContext;\n    phase: \"exports\" | \"resolve\";\n    variables: OperationVariables;\n  }\n\n  export type ContextFunction<TContext> = (\n    options: ContextFunctionOptions\n  ) => TContext;\n\n  export interface ContextFunctionOptions {\n    document: DocumentNode;\n    client: ApolloClient;\n    phase: \"exports\" | \"resolve\";\n    variables: OperationVariables;\n    requestContext: DefaultContext;\n  }\n\n  export type RootValueFunction<TRootValue> = (\n    context: RootValueFunctionContext\n  ) => TRootValue;\n\n  /**\n   * A map of GraphQL types to their field resolvers.\n   *\n   * @example\n   *\n   * ```ts\n   * const resolvers: Resolvers = {\n   *   Query: {\n   *     isLoggedIn: () => !!localStorage.getItem(\"token\"),\n   *   },\n   *   Mutation: {\n   *     login: (_, { token }) => {\n   *       localStorage.setItem(\"token\", token);\n   *       return true;\n   *     },\n   *   },\n   * };\n   * ```\n   */\n  export interface Resolvers<TContext = any> {\n    [typename: string]: {\n      [field: string]: Resolver<any, any, TContext, any>;\n    };\n  }\n\n  /**\n   * A function that resolves the value for a single GraphQL field marked with `@client`.\n   *\n   * Resolver functions receive four parameters:\n   *\n   * - `rootValue`: The parent object containing the result from the resolver on the parent field\n   * - `args`: Arguments passed to the field\n   * - `context`: Contains `requestContext`, `client`, and `phase` properties\n   * - `info`: Information about the field being resolved\n   *\n   * @template TResult - The type of value returned by the resolver\n   * @template TParent - The type of the parent object\n   * @template TContext - The type of the request context\n   * @template TArgs - The type of the field arguments\n   *\n   * @example\n   *\n   * ```ts\n   * const isLoggedInResolver: Resolver<boolean> = () => {\n   *   return !!localStorage.getItem(\"token\");\n   * };\n   * ```\n   */\n  export type Resolver<\n    TResult = unknown,\n    TParent = unknown,\n    TContext = DefaultContext,\n    TArgs = Record<string, unknown>,\n  > = (\n    rootValue: TParent,\n    args: TArgs,\n    context: {\n      requestContext: TContext;\n      client: ApolloClient;\n      phase: \"exports\" | \"resolve\";\n    },\n    info: {\n      field: FieldNode;\n      fragmentMap: FragmentMap;\n      path: Path;\n    }\n  ) => TResult | Promise<TResult>;\n\n  export type Path = Array<string | number>;\n}\n\n/**\n * LocalState enables the use of `@client` fields in GraphQL operations.\n *\n * `@client` fields are resolved locally using resolver functions rather than\n * being sent to the GraphQL server. This allows you to mix local and remote\n * data in a single query.\n *\n * @example\n *\n * ```ts\n * import { LocalState } from \"@apollo/client/local-state\";\n *\n * const localState = new LocalState({\n *   resolvers: {\n *     Query: {\n *       isLoggedIn: () => !!localStorage.getItem(\"token\"),\n *     },\n *   },\n * });\n *\n * const client = new ApolloClient({\n *   cache: new InMemoryCache(),\n *   localState,\n * });\n * ```\n *\n * @template TResolvers - The type of resolvers map for type checking\n * @template TContext - The type of context value for resolvers\n */\nexport class LocalState<\n  TResolvers extends\n    LocalState.Resolvers = LocalState.Resolvers<DefaultContext>,\n  TContext = InferContextValueFromResolvers<TResolvers>,\n> {\n  private context?: LocalState.ContextFunction<TContext>;\n  private resolvers: LocalState.Resolvers = {};\n  private traverseCache = new WeakMap<\n    ExecutableDefinitionNode,\n    TraverseCacheEntry\n  >();\n\n  constructor(\n    ...[options]: {} extends TResolvers ?\n      [options?: LocalState.Options<TResolvers, NoInfer<TContext>>]\n    : [\n        options: LocalState.Options<TResolvers, NoInfer<TContext>> & {\n          resolvers: TResolvers;\n        },\n      ]\n  ) {\n    this.context = options?.context;\n\n    if (options?.resolvers) {\n      this.addResolvers(options.resolvers);\n    }\n  }\n\n  /**\n   * Add resolvers to the local state. New resolvers will be merged with\n   * existing ones, with new resolvers taking precedence over existing ones\n   * for the same field.\n   *\n   * @param resolvers - The resolvers to add\n   *\n   * @example\n   *\n   * ```ts\n   * localState.addResolvers({\n   *   Query: {\n   *     newField: () => \"Hello World\",\n   *   },\n   * });\n   * ```\n   */\n  public addResolvers(resolvers: TResolvers) {\n    this.resolvers = mergeDeep(this.resolvers, resolvers);\n  }\n\n  public async execute<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    document,\n    client,\n    context,\n    remoteResult,\n    variables = {} as TVariables,\n    onlyRunForcedResolvers = false,\n    returnPartialData = false,\n    fetchPolicy,\n  }: {\n    document: DocumentNode | TypedDocumentNode<TData, TVariables>;\n    client: ApolloClient;\n    context: DefaultContext | undefined;\n    // undefined is meant for client-only queries where there is no remote result\n    remoteResult: FormattedExecutionResult<any> | undefined;\n    variables: TVariables | undefined;\n    onlyRunForcedResolvers?: boolean;\n    returnPartialData?: boolean;\n    fetchPolicy: WatchQueryFetchPolicy;\n  }): Promise<FormattedExecutionResult<TData>> {\n    if (__DEV__) {\n      invariant(\n        hasDirectives([\"client\"], document),\n        \"Expected document to contain `@client` fields.\"\n      );\n\n      validateCacheImplementation(client.cache);\n    }\n\n    // note: if `remoteResult` is `undefined`, we will execute resolvers since\n    // undefined remote data reflects a client-only query. We specifically want\n    // to avoid trying to run local resolvers if the server returned `data` as\n    // `null`.\n    if (remoteResult?.data === null) {\n      return remoteResult;\n    }\n\n    const {\n      selectionsToResolve,\n      exportedVariableDefs,\n      operationDefinition,\n      fragmentMap,\n    } = this.collectQueryDetail(document);\n\n    const rootValue = remoteResult ? remoteResult.data : {};\n\n    const diff: Cache.DiffResult<Record<string, any>> =\n      fetchPolicy === \"no-cache\" ?\n        { result: null, complete: false }\n      : client.cache.diff<Record<string, any>>({\n          query: toQueryOperation(document),\n          variables,\n          returnPartialData: true,\n          optimistic: false,\n        });\n\n    const requestContext = { ...client.defaultContext, ...context };\n    const execContext: ExecContext = {\n      client,\n      operationDefinition,\n      fragmentMap,\n      context:\n        this.context?.({\n          requestContext,\n          document,\n          client,\n          phase: \"resolve\",\n          variables: variables ?? {},\n        }) ?? (requestContext as TContext),\n      variables,\n      exportedVariables: {},\n      selectionsToResolve,\n      onlyRunForcedResolvers,\n      errors: [],\n      phase: \"resolve\",\n      exportedVariableDefs,\n      diff,\n      returnPartialData,\n      fetchPolicy,\n    };\n\n    const localResult = await this.resolveSelectionSet(\n      operationDefinition.selectionSet,\n      false,\n      rootValue,\n      execContext,\n      []\n    );\n\n    const errors = (remoteResult?.errors ?? []).concat(execContext.errors);\n\n    const result: FormattedExecutionResult<any> = {\n      ...remoteResult,\n      data: mergeDeep(rootValue, localResult),\n    };\n\n    if (errors.length > 0) {\n      result.errors = errors;\n    }\n\n    return result;\n  }\n\n  public async getExportedVariables<\n    TVariables extends OperationVariables = OperationVariables,\n  >({\n    document,\n    client,\n    context,\n    variables,\n  }: {\n    document: DocumentNode | TypedDocumentNode<any, TVariables>;\n    client: ApolloClient;\n    context: DefaultContext | undefined;\n    variables: Partial<NoInfer<TVariables>>;\n  }): Promise<TVariables> {\n    if (__DEV__) {\n      invariant(\n        hasDirectives([\"client\"], document),\n        \"Expected document to contain `@client` fields.\"\n      );\n      validateCacheImplementation(client.cache);\n    }\n    const {\n      exportsToResolve,\n      exportedVariableDefs,\n      fragmentMap,\n      operationDefinition,\n    } = this.collectQueryDetail(document);\n\n    const diff = client.cache.diff<Record<string, any>>({\n      query: toQueryOperation(document),\n      variables,\n      returnPartialData: true,\n      optimistic: false,\n    });\n\n    const requestContext = { ...client.defaultContext, ...context };\n    const execContext: ExecContext = {\n      client,\n      operationDefinition,\n      fragmentMap,\n      context:\n        this.context?.({\n          requestContext,\n          document,\n          client,\n          phase: \"resolve\",\n          variables: variables ?? {},\n        }) ?? (requestContext as TContext),\n      variables,\n      exportedVariables: {},\n      selectionsToResolve: exportsToResolve,\n      onlyRunForcedResolvers: false,\n      errors: [],\n      phase: \"exports\",\n      exportedVariableDefs,\n      diff,\n      returnPartialData: false,\n    };\n\n    await this.resolveSelectionSet(\n      operationDefinition.selectionSet,\n      false,\n      diff.result,\n      execContext,\n      []\n    );\n\n    return stripTypename({\n      ...variables,\n      ...execContext.exportedVariables,\n    }) as TVariables;\n  }\n\n  private async resolveSelectionSet(\n    selectionSet: SelectionSetNode,\n    isClientFieldDescendant: boolean,\n    rootValue: Record<string, any> | null | undefined,\n    execContext: ExecContext,\n    path: LocalState.Path\n  ) {\n    const { client, fragmentMap, variables, operationDefinition } = execContext;\n    const { cache } = client;\n    const resultsToMerge: Array<Record<string, any>> = [];\n\n    const execute = async (selection: SelectionNode): Promise<void> => {\n      if (\n        !isClientFieldDescendant &&\n        !execContext.selectionsToResolve.has(selection)\n      ) {\n        // Skip selections without @client directives\n        // (still processing if one of the ancestors or one of the child fields has @client directive)\n        return;\n      }\n      if (!shouldInclude(selection, variables)) {\n        // Skip this entirely.\n        return;\n      }\n\n      if (selection.kind === Kind.FIELD) {\n        const isRootField = selectionSet === operationDefinition.selectionSet;\n        const isClientField =\n          isClientFieldDescendant ||\n          (selection.directives?.some((d) => d.name.value === \"client\") ??\n            false);\n\n        const fieldResult =\n          isClientField ?\n            await this.resolveClientField(\n              selection,\n              isClientFieldDescendant,\n              rootValue,\n              execContext,\n              selectionSet,\n              path.concat(selection.name.value)\n            )\n          : await this.resolveServerField(\n              selection,\n              rootValue,\n              execContext,\n              path.concat(selection.name.value)\n            );\n\n        // Don't attempt to merge the client field result if the server result\n        // was null\n        if (fieldResult !== undefined && (!isRootField || rootValue !== null)) {\n          resultsToMerge.push({\n            [resultKeyNameFromField(selection)]: fieldResult,\n          });\n        }\n\n        return;\n      }\n\n      if (\n        selection.kind === Kind.INLINE_FRAGMENT &&\n        selection.typeCondition &&\n        rootValue?.__typename &&\n        cache.fragmentMatches(selection, rootValue.__typename)\n      ) {\n        const fragmentResult = await this.resolveSelectionSet(\n          selection.selectionSet,\n          isClientFieldDescendant,\n          rootValue,\n          execContext,\n          path\n        );\n\n        if (fragmentResult) {\n          resultsToMerge.push(fragmentResult);\n        }\n\n        return;\n      }\n\n      if (selection.kind === Kind.FRAGMENT_SPREAD) {\n        const fragment = fragmentMap[selection.name.value];\n        invariant(fragment, \"No fragment named %s\", selection.name.value);\n\n        const typename = rootValue?.__typename;\n        const typeCondition = fragment.typeCondition.name.value;\n\n        const matches =\n          typename === typeCondition ||\n          cache.fragmentMatches(fragment, typename ?? \"\");\n\n        if (matches) {\n          const fragmentResult = await this.resolveSelectionSet(\n            fragment.selectionSet,\n            isClientFieldDescendant,\n            rootValue,\n            execContext,\n            path\n          );\n\n          if (fragmentResult) {\n            resultsToMerge.push(fragmentResult);\n          }\n        }\n\n        return;\n      }\n    };\n\n    await Promise.all(selectionSet.selections.map(execute));\n\n    return resultsToMerge.length > 0 ?\n        mergeDeepArray(resultsToMerge)\n      : rootValue;\n  }\n\n  private resolveServerField(\n    field: FieldNode,\n    rootValue: Record<string, any> | null | undefined,\n    execContext: ExecContext,\n    path: LocalState.Path\n  ) {\n    const result = rootValue?.[resultKeyNameFromField(field)];\n\n    if (!field.selectionSet) {\n      return result;\n    }\n\n    if (result == null) {\n      if (execContext.phase === \"exports\") {\n        for (const [name, def] of Object.entries(\n          execContext.exportedVariableDefs\n        )) {\n          if (def.ancestors.has(field) && def.required) {\n            throw new LocalStateError(\n              `${\"Field\"} '${field.name.value}' is \\`${result}\\` which contains exported required variable '${name}'. Ensure this value is in the cache or make the variable optional.`,\n              { path }\n            );\n          }\n        }\n      }\n\n      return result;\n    }\n\n    if (Array.isArray(result)) {\n      return this.resolveSubSelectedArray(\n        field,\n        false,\n        result,\n        execContext,\n        path\n      );\n    }\n\n    return this.resolveSelectionSet(\n      field.selectionSet,\n      false,\n      result,\n      execContext,\n      path\n    );\n  }\n\n  private async resolveClientField(\n    field: FieldNode,\n    isClientFieldDescendant: boolean,\n    rootValue: Record<string, any> | null | undefined,\n    execContext: ExecContext,\n    parentSelectionSet: SelectionSetNode,\n    path: LocalState.Path\n  ): Promise<any> {\n    const {\n      client,\n      diff,\n      variables,\n      operationDefinition,\n      phase,\n      onlyRunForcedResolvers,\n      fetchPolicy,\n    } = execContext;\n    let { returnPartialData } = execContext;\n    const isRootField = parentSelectionSet === operationDefinition.selectionSet;\n    const fieldName = field.name.value;\n    const typename =\n      isRootField ?\n        rootValue?.__typename || inferRootTypename(operationDefinition)\n      : rootValue?.__typename;\n    const resolverName = `${typename}.${fieldName}`;\n\n    function readField() {\n      const fieldResult = rootValue?.[fieldName];\n\n      if (fieldResult !== undefined) {\n        return fieldResult;\n      }\n\n      return getCacheResultAtPath(diff, path);\n    }\n\n    const defaultResolver =\n      isClientFieldDescendant ? readField\n        // We expect a resolver to be defined for all `@client` root fields.\n        // Warn when a resolver is not defined.\n      : (\n        () => {\n          const fieldFromCache = getCacheResultAtPath(diff, path);\n\n          if (fieldFromCache !== undefined) {\n            return fieldFromCache;\n          }\n\n          if (client.cache.resolvesClientField?.(typename, fieldName)) {\n            if (fetchPolicy === \"no-cache\") {\n              invariant.warn(\n                \"The '%s' field resolves the value from the cache, for example from a 'read' function, but a 'no-cache' fetch policy was used. The field value has been set to `null`. Either define a local resolver or use a fetch policy that uses the cache to ensure the field is resolved correctly.\",\n                resolverName\n              );\n              return null;\n            }\n\n            // assume the cache will handle returning the correct value\n            returnPartialData = true;\n            return;\n          }\n\n          if (!returnPartialData) {\n            invariant.warn(\n              \"Could not find a resolver for the '%s' field nor does the cache resolve the field. The field value has been set to `null`. Either define a resolver for the field or ensure the cache can resolve the value, for example, by adding a 'read' function to a field policy in 'InMemoryCache'.\",\n              resolverName\n            );\n            return null;\n          }\n        }\n      );\n\n    const resolver = this.getResolver(typename, fieldName);\n    let result: unknown;\n\n    try {\n      // Avoid running the resolver if we are only trying to run forced\n      // resolvers. Fallback to read the value from the root field or the cache\n      // value\n      if (!onlyRunForcedResolvers || isForcedResolver(field)) {\n        result =\n          resolver ?\n            await Promise.resolve(\n              // In case the resolve function accesses reactive variables,\n              // set cacheSlot to the current cache instance.\n              cacheSlot.withValue(client.cache, resolver, [\n                rootValue ? dealias(rootValue, parentSelectionSet) : {},\n                (argumentsObjectFromField(field, variables) ?? {}) as Record<\n                  string,\n                  unknown\n                >,\n                { requestContext: execContext.context as any, client, phase },\n                { field, fragmentMap: execContext.fragmentMap, path },\n              ])\n            )\n          : defaultResolver();\n      } else {\n        result = readField();\n      }\n    } catch (e) {\n      if (phase === \"exports\") {\n        for (const [name, def] of Object.entries(\n          execContext.exportedVariableDefs\n        )) {\n          if (def.ancestors.has(field)) {\n            throw new LocalStateError(\n              `An error was thrown from resolver '${resolverName}' while resolving ${\n                def.required ? \"required\" : \"optional\"\n              } variable '${name}'. Use a try/catch and return \\`undefined\\` to suppress this error and omit the variable from the request.`,\n              { path, sourceError: e }\n            );\n          }\n        }\n      }\n\n      this.addError(toErrorLike(e), path, execContext, {\n        resolver: resolverName,\n        cause: e,\n      });\n      return null;\n    }\n\n    if (phase === \"exports\") {\n      field.directives?.forEach((directive) => {\n        if (directive.name.value !== \"export\") {\n          return;\n        }\n\n        const name = getExportedVariableName(directive);\n\n        if (!name) {\n          return;\n        }\n\n        if (result !== undefined) {\n          execContext.exportedVariables[name] = result;\n        }\n      });\n\n      if (result == null) {\n        for (const [name, def] of Object.entries(\n          execContext.exportedVariableDefs\n        )) {\n          if (def.ancestors.has(field) && def.required) {\n            throw new LocalStateError(\n              `${\n                resolver ? \"Resolver\" : \"Field\"\n              } '${resolverName}' returned \\`${result}\\` ${\n                def.field === field ? \"for\" : \"which contains exported\"\n              } required variable '${name}'.`,\n              { path }\n            );\n          }\n        }\n      }\n    }\n\n    if (result === undefined && !returnPartialData) {\n      if (__DEV__ && phase === \"resolve\") {\n        if (resolver && !onlyRunForcedResolvers) {\n          invariant.warn(\n            \"The '%s' resolver returned `undefined` instead of a value. This is likely a bug in the resolver. If you didn't mean to return a value, return `null` instead.\",\n            resolverName\n          );\n        } else if (onlyRunForcedResolvers) {\n          invariant.warn(\n            \"The '%s' field had no cached value and only forced resolvers were run. The value was set to `null`.\",\n            resolverName\n          );\n        } else {\n          invariant.warn(\n            \"The '%s' field on object %o returned `undefined` instead of a value. The parent resolver did not include the property in the returned value and there was no resolver defined for the field.\",\n            fieldName,\n            rootValue\n          );\n        }\n      }\n\n      result = null;\n    }\n\n    if (result == null || !field.selectionSet) {\n      return result;\n    }\n\n    if (Array.isArray(result)) {\n      return this.resolveSubSelectedArray(\n        field,\n        true,\n        result,\n        execContext,\n        path\n      );\n    }\n\n    if (phase === \"resolve\" && !(result as any).__typename) {\n      this.addError(\n        newInvariantError(\n          \"Could not resolve __typename on object %o returned from resolver '%s'. '__typename' needs to be returned to properly resolve child fields.\",\n          result,\n          resolverName\n        ),\n        path,\n        execContext,\n        { resolver: resolverName }\n      );\n\n      return null;\n    }\n\n    return this.resolveSelectionSet(\n      field.selectionSet,\n      true,\n      result,\n      execContext,\n      path\n    );\n  }\n\n  private addError(\n    error: ErrorLike,\n    path: LocalState.Path,\n    execContext: ExecContext,\n    meta: { [key: string]: any; resolver: string }\n  ) {\n    execContext.errors.push(\n      addExtension(\n        isGraphQLError(error) ?\n          { ...error.toJSON(), path }\n        : { message: error.message, path },\n        meta\n      )\n    );\n  }\n\n  private getResolver(\n    typename: string,\n    fieldName: string\n  ): LocalState.Resolver | undefined {\n    return this.resolvers[typename]?.[fieldName];\n  }\n\n  private resolveSubSelectedArray(\n    field: FieldNode,\n    isClientFieldDescendant: boolean,\n    result: any[],\n    execContext: ExecContext,\n    path: LocalState.Path\n  ): any {\n    return Promise.all(\n      result.map((item, idx) => {\n        if (item === null) {\n          return null;\n        }\n\n        // This is a nested array, recurse.\n        if (Array.isArray(item)) {\n          return this.resolveSubSelectedArray(\n            field,\n            isClientFieldDescendant,\n            item,\n            execContext,\n            path.concat(idx)\n          );\n        }\n\n        // This is an object, run the selection set on it.\n        if (field.selectionSet) {\n          return this.resolveSelectionSet(\n            field.selectionSet,\n            isClientFieldDescendant,\n            item,\n            execContext,\n            path.concat(idx)\n          );\n        }\n      })\n    );\n  }\n\n  // Collect selection nodes on paths from document root down to all @client directives.\n  // This function takes into account transitive fragment spreads.\n  // Complexity equals to a single `visit` over the full document.\n  private collectQueryDetail(document: DocumentNode): TraverseCacheEntry & {\n    operationDefinition: OperationDefinitionNode;\n    fragmentMap: FragmentMap;\n  } {\n    const operationDefinition = getMainDefinition(\n      document\n    ) as OperationDefinitionNode;\n    const fragments = getFragmentDefinitions(document);\n    const fragmentMap = createFragmentMap(fragments);\n\n    const isSingleASTNode = (\n      node: ASTNode | readonly ASTNode[]\n    ): node is ASTNode => !Array.isArray(node);\n    const fields: Array<FieldNode> = [];\n    let rootClientField: FieldNode | undefined;\n\n    function getCurrentPath() {\n      return fields.map((field) => field.name.value);\n    }\n\n    const traverse = (definitionNode: ExecutableDefinitionNode) => {\n      if (this.traverseCache.has(definitionNode)) {\n        return this.traverseCache.get(definitionNode)!;\n      }\n\n      // Track a separate list of all variable definitions since not all variable\n      // definitions are used as exports of an `@export` field.\n      const allVariableDefinitions: TraverseCacheEntry[\"exportedVariableDefs\"] =\n        {};\n\n      const cache: TraverseCacheEntry = {\n        exportedVariableDefs: {},\n        exportsToResolve: new Set<SelectionNode>(),\n        selectionsToResolve: new Set<SelectionNode>(),\n      };\n      this.traverseCache.set(definitionNode, cache);\n\n      visit(definitionNode, {\n        VariableDefinition: (definition) => {\n          allVariableDefinitions[definition.variable.name.value] = {\n            required: definition.type.kind === Kind.NON_NULL_TYPE,\n            ancestors: new WeakSet(),\n          };\n        },\n        Field: {\n          enter(field) {\n            fields.push(field);\n          },\n          leave() {\n            const removed = fields.pop();\n\n            if (removed === rootClientField) {\n              rootClientField = undefined;\n            }\n          },\n        },\n        Directive(node: DirectiveNode, _, __, ___, ancestors) {\n          const field = fields.at(-1);\n\n          if (!field) {\n            return;\n          }\n\n          if (\n            node.name.value === \"export\" &&\n            // Ignore export directives that aren't inside client fields.\n            // These will get sent to the server\n            rootClientField\n          ) {\n            const fieldName = field.name.value;\n            const variableName = getExportedVariableName(node);\n            if (!variableName) {\n              throw new LocalStateError(\n                `Cannot determine the variable name from the \\`@export\\` directive used on field '${fieldName}'. Perhaps you forgot the \\`as\\` argument?`,\n                { path: getCurrentPath() }\n              );\n            }\n            if (!allVariableDefinitions[variableName]) {\n              throw new LocalStateError(\n                `\\`@export\\` directive on field '${fieldName}' cannot export the '$${variableName}' variable as it is missing in the ${operationDefinition.operation} definition.`,\n                { path: getCurrentPath() }\n              );\n            }\n            cache.exportedVariableDefs[variableName] = {\n              ...allVariableDefinitions[variableName],\n              field,\n            };\n            ancestors.forEach((node) => {\n              if (isSingleASTNode(node) && isSelectionNode(node)) {\n                cache.exportsToResolve.add(node);\n                cache.exportedVariableDefs[variableName].ancestors.add(node);\n              }\n            });\n          }\n          if (node.name.value === \"client\") {\n            rootClientField ??= field;\n            ancestors.forEach((node) => {\n              if (isSingleASTNode(node) && isSelectionNode(node)) {\n                cache.selectionsToResolve.add(node);\n              }\n            });\n          }\n        },\n        FragmentSpread(spread: FragmentSpreadNode, _, __, ___, ancestors) {\n          const fragment = fragmentMap[spread.name.value];\n          invariant(fragment, `No fragment named %s`, spread.name.value);\n\n          const { selectionsToResolve: fragmentSelections } =\n            traverse(fragment);\n\n          if (fragmentSelections.size > 0) {\n            // Fragment for this spread contains @client directive (either directly or transitively)\n            // Collect selection nodes on paths from the root down to fields with the @client directive\n            ancestors.forEach((node) => {\n              if (isSingleASTNode(node) && isSelectionNode(node)) {\n                cache.selectionsToResolve.add(node);\n              }\n            });\n            cache.selectionsToResolve.add(spread);\n            fragmentSelections.forEach((selection) => {\n              cache.selectionsToResolve.add(selection);\n            });\n          }\n        },\n      });\n\n      return cache;\n    };\n\n    return {\n      ...traverse(operationDefinition),\n      operationDefinition,\n      fragmentMap,\n    };\n  }\n}\n\nfunction inferRootTypename({ operation }: OperationDefinitionNode) {\n  return operation.charAt(0).toUpperCase() + operation.slice(1);\n}\n\n// eslint-disable-next-line @typescript-eslint/no-restricted-types\nfunction isGraphQLError(error: ErrorLike): error is GraphQLError {\n  return (\n    error.name === \"GraphQLError\" &&\n    // Check to see if the error contains keys returned in toJSON. The values\n    // might be `undefined` if not set, but we don't care about those as we\n    // can be reasonably sure this is a GraphQLError if all of these properties\n    // exist on the error\n    \"path\" in error &&\n    \"locations\" in error &&\n    \"extensions\" in error\n  );\n}\n\nfunction addExtension(error: GraphQLFormattedError, meta: Record<string, any>) {\n  return {\n    ...error,\n    extensions: {\n      ...error.extensions,\n      localState: meta,\n    },\n  };\n}\n\nfunction getExportedVariableName(directive: DirectiveNode) {\n  if (directive.arguments) {\n    for (const arg of directive.arguments) {\n      if (arg.name.value === \"as\" && arg.value.kind === Kind.STRING) {\n        return arg.value.value;\n      }\n    }\n  }\n}\n\nfunction validateCacheImplementation(cache: ApolloCache) {\n  invariant(\n    cache.fragmentMatches,\n    \"The configured cache does not support fragment matching which will lead to incorrect results when executing local resolvers. Please use a cache that implements `fragmetMatches`.\"\n  );\n}\n\nfunction getCacheResultAtPath(\n  diff: Cache.DiffResult<any>,\n  path: LocalState.Path\n) {\n  if (diff.result === null) {\n    // Intentionally return undefined to signal we have no cache data\n    return;\n  }\n\n  return path.reduce((value, segment) => value?.[segment], diff.result);\n}\n\nfunction isForcedResolver(field: FieldNode) {\n  return (\n    field.directives?.some((directive) => {\n      if (directive.name.value !== \"client\" || !directive.arguments) {\n        return false;\n      }\n\n      return directive.arguments.some(\n        (arg) =>\n          arg.name.value === \"always\" &&\n          arg.value.kind === \"BooleanValue\" &&\n          arg.value.value === true\n      );\n    }) ?? false\n  );\n}\n\n// If the incoming document is a query, return it as is. Otherwise, build a\n// new document containing a query operation based on the selection set\n// of the previous main operation.\nfunction toQueryOperation(document: DocumentNode): DocumentNode {\n  const definition = getMainDefinition(document);\n  const definitionOperation = (definition as OperationDefinitionNode).operation;\n\n  if (definitionOperation === \"query\") {\n    // Already a query, so return the existing document.\n    return document;\n  }\n\n  // Build a new query using the selection set of the main operation.\n  const modifiedDoc = visit(document, {\n    OperationDefinition: {\n      enter(node) {\n        return {\n          ...node,\n          operation: \"query\",\n        };\n      },\n    },\n  });\n  return modifiedDoc;\n}\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/aliases.test.ts",
    "content": "import { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"resolves @client fields mixed with aliased server fields\", async () => {\n  const document = gql`\n    query Aliased {\n      foo @client {\n        bar\n      }\n      baz: bar {\n        foo\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      baz: { foo: true, __typename: \"Bar\" },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true, __typename: \"Foo\" }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      remoteResult,\n      variables: {},\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { bar: true, __typename: \"Foo\" },\n      baz: { foo: true, __typename: \"Bar\" },\n    },\n  });\n});\n\ntest(\"resolves aliased @client fields\", async () => {\n  const document = gql`\n    query Test {\n      fie: foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fie = jest.fn();\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true, __typename: \"Foo\" }),\n        fie,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { fie: { bar: true, __typename: \"Foo\" } },\n  });\n\n  expect(fie).not.toHaveBeenCalled();\n});\n\ntest(\"resolves deeply nested aliased @client fields\", async () => {\n  const document = gql`\n    query Test {\n      user {\n        id\n        bestFriend {\n          first: firstName\n          last: lastName\n          name: fullName @client\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          first: \"Test\",\n          last: \"User\",\n        },\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      User: {\n        fullName: (user) => `${user.firstName} ${user.lastName}`,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      remoteResult,\n      variables: {},\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          first: \"Test\",\n          last: \"User\",\n          name: \"Test User\",\n        },\n      },\n    },\n  });\n});\n\ntest(\"respects aliases for *nested fields* on the @client-tagged node\", async () => {\n  const document = gql`\n    query Test {\n      fie: foo @client {\n        fum: bar\n      }\n      baz: bar {\n        foo\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = { data: { baz: { foo: true, __typename: \"Baz\" } } };\n\n  const fie = jest.fn();\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true, __typename: \"Foo\" }),\n        fie,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      remoteResult,\n      variables: {},\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      fie: { fum: true, __typename: \"Foo\" },\n      baz: { foo: true, __typename: \"Baz\" },\n    },\n  });\n\n  expect(fie).not.toHaveBeenCalled();\n});\n\ntest(\"does not confuse fields aliased to each other\", async () => {\n  const document = gql`\n    query Test {\n      fie: foo @client {\n        fum: bar\n        bar: fum\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: \"fum\", fum: \"bar\", __typename: \"Foo\" }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      fie: { fum: \"fum\", bar: \"bar\", __typename: \"Foo\" },\n    },\n  });\n});\n\ntest(\"does not confuse fields aliased to each other with boolean values\", async () => {\n  const document = gql`\n    query Test {\n      fie: foo @client {\n        fum: bar\n        bar: fum\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true, fum: false, __typename: \"Foo\" }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      fie: { fum: true, bar: false, __typename: \"Foo\" },\n    },\n  });\n});\n\ntest(\"resolves client fields that are child fields of aliased server fields\", async () => {\n  const document = gql`\n    query Test {\n      fie: foo {\n        bar\n        baz @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      fie: { bar: true, __typename: \"Foo\" },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Foo: {\n        baz: () => true,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      client,\n      document,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      fie: { bar: true, baz: true, __typename: \"Foo\" },\n    },\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/async.test.ts",
    "content": "import { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { wait } from \"@apollo/client/testing/internal\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"supports async @client resolvers\", async () => {\n  const document = gql`\n    query Member {\n      isLoggedIn @client\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        async isLoggedIn() {\n          return Promise.resolve(true);\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { isLoggedIn: true },\n  });\n});\n\ntest(\"handles nested asynchronous @client resolvers\", async () => {\n  const document = gql`\n    query DeveloperTicketComments($id: ID) {\n      developer(id: $id) @client {\n        id\n        handle\n        tickets @client {\n          id\n          comments @client {\n            id\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  async function randomDelay(range: number) {\n    await wait(Math.round(Math.random() * range));\n  }\n\n  function uuid() {\n    return Math.random().toString(36).slice(2);\n  }\n\n  const developerId = uuid();\n\n  function times<T>(n: number, thunk: () => T): T[] {\n    const result: T[] = [];\n    for (let i = 0; i < n; ++i) {\n      result.push(thunk());\n    }\n    return result;\n  }\n\n  const ticketsPerDev = 5;\n  const commentsPerTicket = 5;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        async developer(_, { id }) {\n          await randomDelay(50);\n          expect(id).toBe(developerId);\n          return {\n            __typename: \"Developer\",\n            id,\n            handle: \"@benjamn\",\n          };\n        },\n      },\n      Developer: {\n        async tickets(developer) {\n          await randomDelay(50);\n          expect(developer.__typename).toBe(\"Developer\");\n\n          return Promise.all(\n            times(ticketsPerDev, () => ({\n              __typename: \"Ticket\",\n              id: uuid(),\n            }))\n          );\n        },\n      },\n      Ticket: {\n        async comments(ticket) {\n          await randomDelay(50);\n          expect(ticket.__typename).toBe(\"Ticket\");\n\n          return Promise.all(\n            times(commentsPerTicket, () => ({\n              __typename: \"Comment\",\n              id: uuid(),\n            }))\n          );\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: { id: developerId },\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      developer: {\n        __typename: \"Developer\",\n        id: developerId,\n        handle: \"@benjamn\",\n        tickets: times(ticketsPerDev, () => ({\n          __typename: \"Ticket\",\n          id: expect.any(String),\n          comments: times(commentsPerTicket, () => ({\n            __typename: \"Comment\",\n            id: expect.any(String),\n          })),\n        })),\n      },\n    },\n  });\n});\n\ntest(\"supports async @client resolvers mixed with remotely resolved data\", async () => {\n  const document = gql`\n    query Member {\n      member {\n        name\n        sessionCount @client\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testMember = {\n    name: \"John Smithsonian\",\n    isLoggedIn: true,\n    sessionCount: 10,\n  };\n\n  const remoteResult = {\n    data: {\n      member: {\n        name: testMember.name,\n        __typename: \"Member\",\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Member: {\n        async isLoggedIn() {\n          return Promise.resolve(testMember.isLoggedIn);\n        },\n        sessionCount() {\n          return testMember.sessionCount;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      member: {\n        name: testMember.name,\n        isLoggedIn: testMember.isLoggedIn,\n        sessionCount: testMember.sessionCount,\n        __typename: \"Member\",\n      },\n    },\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/base.test.ts",
    "content": "import { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport { gql, WARNINGS } from \"./testUtils.js\";\n\ntest(\"runs resolvers for @client queries\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true } },\n  });\n});\n\ntest(\"can add resolvers after LocalState is instantiated\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  localState.addResolvers({\n    Query: {\n      foo: () => ({ __typename: \"Foo\", bar: true }),\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true } },\n  });\n});\n\ntest(\"handles queries with a mix of @client and server fields\", async () => {\n  const document = gql`\n    query Mixed {\n      foo @client {\n        bar\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const remoteResult = { data: { bar: { __typename: \"Bar\", baz: true } } };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { __typename: \"Foo\", bar: true },\n      bar: { __typename: \"Bar\", baz: true },\n    },\n  });\n});\n\ntest(\"runs resolvers for deeply nested @client fields\", async () => {\n  const document = gql`\n    query Test {\n      user {\n        id\n        bestFriend {\n          firstName\n          lastName\n          fullName @client\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          firstName: \"Test\",\n          lastName: \"User\",\n        },\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      User: {\n        fullName: (user) => `${user.firstName} ${user.lastName}`,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          firstName: \"Test\",\n          lastName: \"User\",\n          fullName: \"Test User\",\n        },\n      },\n    },\n  });\n});\n\ntest(\"has access to query variables in @client resolvers\", async () => {\n  const document = gql`\n    query WithVariables($id: ID!) {\n      foo @client {\n        bar(fromVariable: $id)\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: (_, { fromVariable }) => fromVariable,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: { id: 1 },\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: 1 } },\n  });\n});\n\ntest(\"combines local @client resolver results with server results, for the same field\", async () => {\n  const document = gql`\n    query author {\n      author {\n        name\n        stats {\n          totalPosts\n          postsToday @client\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      author: {\n        name: \"John Smith\",\n        stats: {\n          totalPosts: 100,\n          __typename: \"Stats\",\n        },\n        __typename: \"Author\",\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Stats: {\n        postsToday: () => 10,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      author: {\n        __typename: \"Author\",\n        name: \"John Smith\",\n        stats: {\n          __typename: \"Stats\",\n          totalPosts: 100,\n          postsToday: 10,\n        },\n      },\n    },\n  });\n});\n\ntest(\"handles resolvers that return booleans\", async () => {\n  const document = gql`\n    query CartDetails {\n      isInCart @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        isInCart: () => false,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { isInCart: false },\n  });\n});\n\ntest(\"does not run resolvers without @client directive\", async () => {\n  const document = gql`\n    query Mixed {\n      foo @client {\n        bar\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = { data: { bar: { __typename: \"Bar\", baz: true } } };\n\n  const barResolver = jest.fn(() => ({ __typename: `Bar`, baz: false }));\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: `Foo`, bar: true }),\n        bar: barResolver,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { __typename: \"Foo\", bar: true },\n      bar: { __typename: \"Bar\", baz: true },\n    },\n  });\n\n  expect(barResolver).not.toHaveBeenCalled();\n});\n\ntest(\"does not run resolvers without @client directive with nested field\", async () => {\n  const document = gql`\n    query Mixed {\n      foo {\n        bar\n        baz @client {\n          qux\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = { data: { foo: { __typename: \"Foo\", bar: true } } };\n\n  const barResolver = jest.fn(() => true);\n  const fooResolver = jest.fn(() => ({\n    __typename: \"Foo\",\n    bar: false,\n  }));\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: fooResolver,\n      },\n      Foo: {\n        bar: barResolver,\n        baz: () => ({ __typename: \"Baz\", qux: false }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: {\n        __typename: \"Foo\",\n        bar: true,\n        baz: { __typename: \"Baz\", qux: false },\n      },\n    },\n  });\n\n  expect(fooResolver).not.toHaveBeenCalled();\n  expect(barResolver).not.toHaveBeenCalled();\n});\n\ntest(\"allows child resolvers from a parent resolved field from a local resolver\", async () => {\n  const document = gql`\n    query UserData {\n      userData @client {\n        firstName\n        lastName\n        fullName\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        userData() {\n          return {\n            __typename: \"User\",\n            firstName: \"Ben\",\n            lastName: \"Newman\",\n          };\n        },\n      },\n      User: {\n        fullName(data) {\n          return data.firstName + \" \" + data.lastName;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      userData: {\n        __typename: \"User\",\n        firstName: \"Ben\",\n        lastName: \"Newman\",\n        fullName: \"Ben Newman\",\n      },\n    },\n  });\n});\n\ntest(\"can use remote result to resolve @client field\", async () => {\n  const document = gql`\n    query Member {\n      member {\n        firstName\n        lastName\n        fullName @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      member: {\n        __typename: \"Member\",\n        firstName: \"John\",\n        lastName: \"Smithsonian\",\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Member: {\n        fullName(member) {\n          return `${member.firstName} ${member.lastName}`;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      member: {\n        __typename: \"Member\",\n        firstName: \"John\",\n        lastName: \"Smithsonian\",\n        fullName: \"John Smithsonian\",\n      },\n    },\n  });\n});\n\ntest(\"throws error when query does not contain client fields\", async () => {\n  const document = gql`\n    query Member {\n      member {\n        firstName\n        lastName\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      member: {\n        __typename: \"Member\",\n        firstName: \"John\",\n        lastName: \"Smithsonian\",\n      },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {},\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).rejects.toEqual(\n    new InvariantError(\"Expected document to contain `@client` fields.\")\n  );\n});\n\ntest(\"warns and sets value to null when a resolver is missing for an `@client` field and a read function is not defined when using InMemoryCache\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { foo: null } });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"Query.foo\"\n  );\n});\n\ntest(\"does not warn when read function is defined for a `@client` field when using InMemoryCache\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            foo: {\n              read: () => \"Bar\",\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { foo: \"Bar\" } });\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"warns and sets value to null for client child fields of a server field with no resolver or read function\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo {\n        bar @client\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = { data: { foo: { __typename: \"Foo\" } } };\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: null } },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"Foo.bar\"\n  );\n});\n\ntest(\"does not warn when a read function is defined for a child `@client` field from a server field when using InMemoryCache\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo {\n        bar @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Foo: {\n          fields: {\n            bar: {\n              read: () => \"Baz\",\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  const remoteResult = { data: { foo: { __typename: \"Foo\" } } };\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    // The `bar` field is not so that the cache can fill in the field from the\n    // read function.\n    data: { foo: { __typename: \"Foo\" } },\n  });\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"warns when using a no-cache query with a read function but no resolver function\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            foo: {\n              read: () => \"bar\",\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"no-cache\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { foo: null } });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(WARNINGS.NO_CACHE, \"Query.foo\");\n});\n\ntest(\"warns when using a no-cache query with a read function but no resolver function on child @client field\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo {\n        bar @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Foo: {\n          fields: {\n            bar: {\n              read: () => \"baz\",\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { foo: { __typename: \"Foo\" } } },\n      fetchPolicy: \"no-cache\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: null } },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(WARNINGS.NO_CACHE, \"Foo.bar\");\n});\n\ntest(\"warns when a resolver returns undefined and sets value to null\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {},\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { foo: null } });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"The '%s' resolver returned `undefined` instead of a value. This is likely a bug in the resolver. If you didn't mean to return a value, return `null` instead.\",\n    \"Query.foo\"\n  );\n});\n\ntest(\"warns if a parent resolver omits a field with no child resolver\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client {\n        bar\n        baz\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true, baz: null } },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"The '%s' field on object %o returned `undefined` instead of a value. The parent resolver did not include the property in the returned value and there was no resolver defined for the field.\",\n    \"baz\",\n    { __typename: \"Foo\", bar: true }\n  );\n});\n\ntest(\"warns if a parent resolver omits a field and child has @client field\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client {\n        bar\n        baz @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true, baz: null } },\n  });\n\n  // We don't want to see the missing resolver warning since the child field\n  // should not be required to define a resolver since its a descendent of\n  // another child field.\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"The '%s' field on object %o returned `undefined` instead of a value. The parent resolver did not include the property in the returned value and there was no resolver defined for the field.\",\n    \"baz\",\n    { __typename: \"Foo\", bar: true }\n  );\n});\n\ntest(\"adds an error when the __typename cannot be resolved\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: `Could not resolve __typename on object ${JSON.stringify(\n          { bar: true },\n          null,\n          2\n        )} returned from resolver 'Query.foo'. '__typename' needs to be returned to properly resolve child fields.`,\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"can return more data than needed in resolver which is accessible by child resolver but omitted in output\", async () => {\n  const document = gql`\n    query {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true, random: true }),\n      },\n      Foo: {\n        bar: (foo) => (foo.random ? \"random\" : \"not random\"),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: \"random\" } },\n  });\n});\n\ntest(\"does not execute child resolver when parent is null\", async () => {\n  const document = gql`\n    query {\n      currentUser {\n        id\n        foo @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const foo = jest.fn(() => true);\n  const remoteResult = { data: { currentUser: null } };\n  const localState = new LocalState({\n    resolvers: {\n      User: {\n        foo,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { currentUser: null },\n  });\n\n  expect(foo).not.toHaveBeenCalled();\n});\n\ntest(\"does not execute root scalar resolver data when remote data returns null\", async () => {\n  const document = gql`\n    query {\n      foo @client\n      bar {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  };\n\n  let fooCount = 0;\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          fooCount++;\n          return true;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(fooCount).toBe(0);\n});\n\ntest(\"does not run object resolver when remote data returns null\", async () => {\n  const document = gql`\n    query {\n      foo @client {\n        baz\n      }\n      bar {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  };\n\n  let fooCount = 0;\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          fooCount++;\n          return { __typename: \"Foo\", baz: true };\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(fooCount).toBe(0);\n});\n\ntest(\"does not run root resolvers when multiple client fields are defined when remote data returns null\", async () => {\n  const document = gql`\n    query {\n      foo @client {\n        baz\n      }\n      bar @client {\n        baz\n      }\n      baz {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  };\n\n  let fooCount = 0;\n  let barCount = 0;\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          fooCount++;\n          return { __typename: \"Foo\", baz: true };\n        },\n        bar: () => {\n          barCount++;\n          return { __typename: \"Bar\", baz: false };\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(fooCount).toBe(0);\n  expect(barCount).toBe(0);\n});\n\ntest(\"does not execute resolver if client field is a child of a server field when data returns `null`\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      baz {\n        id\n        foo @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  };\n\n  const foo = jest.fn(() => true);\n  const localState = new LocalState({\n    resolvers: {\n      Baz: {\n        foo,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: null,\n    errors: [{ message: \"Something went wrong\" }],\n  });\n\n  expect(foo).not.toHaveBeenCalled();\n  expect(console.warn).not.toHaveBeenCalled();\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/cache.test.ts",
    "content": "import {\n  ApolloClient,\n  ApolloLink,\n  InMemoryCache,\n  isReference,\n} from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\n\nimport { gql, WARNINGS } from \"./testUtils.js\";\n\ntest(\"can write to the cache with a mutation\", async () => {\n  const query = gql`\n    {\n      field\n    }\n  `;\n\n  const mutation = gql`\n    mutation start {\n      start @client\n    }\n  `;\n\n  const localState = new LocalState({\n    resolvers: {\n      Mutation: {\n        start(_data, _args, { client }) {\n          client.cache.writeQuery({ query, data: { field: 1 } });\n          return true;\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  await expect(\n    localState.execute({\n      document: mutation,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { start: true } });\n\n  expect(client.readQuery({ query })).toStrictEqualTyped({ field: 1 });\n});\n\ntest(\"can write to the cache with a mutation using an ID\", async () => {\n  const query = gql`\n    {\n      obj {\n        field\n      }\n    }\n  `;\n\n  const mutation = gql`\n    mutation start {\n      start @client\n    }\n  `;\n\n  const localState = new LocalState({\n    resolvers: {\n      Mutation: {\n        start(_, __, { client }) {\n          client.writeQuery({\n            query,\n            data: {\n              obj: { field: 1, id: \"uniqueId\", __typename: \"Object\" },\n            },\n          });\n\n          client.cache.modify<{ id: string; field: number }>({\n            id: \"Object:uniqueId\",\n            fields: {\n              field(value) {\n                return value + 2;\n              },\n            },\n          });\n\n          return true;\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  await expect(\n    localState.execute({\n      document: mutation,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { start: true } });\n\n  expect(client.readQuery({ query })).toStrictEqualTyped({\n    obj: { __typename: \"Object\", field: 3 },\n  });\n});\n\ntest(\"does not overwrite __typename when writing to the cache with an id\", async () => {\n  const query = gql`\n    {\n      obj @client {\n        field {\n          field2\n        }\n        id\n      }\n    }\n  `;\n\n  const mutation = gql`\n    mutation start {\n      start @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Mutation: {\n        start(_, __, { client }) {\n          client.writeQuery({\n            query,\n            data: {\n              obj: {\n                field: { field2: 1, __typename: \"Field\" },\n                id: \"uniqueId\",\n                __typename: \"Object\",\n              },\n            },\n          });\n          client.cache.modify<{ field: { field2: number } }>({\n            id: \"Object:uniqueId\",\n            fields: {\n              field(value) {\n                if (isReference(value)) {\n                  fail(\"Should not be a reference\");\n                }\n                expect(value.field2).toBe(1);\n                return { ...value, field2: 2 };\n              },\n            },\n          });\n          return true;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document: mutation,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { start: true } });\n\n  expect(client.readQuery({ query })).toStrictEqualTyped({\n    obj: {\n      __typename: \"Object\",\n      field: { __typename: \"Field\", field2: 2 },\n      id: \"uniqueId\",\n    },\n  });\n});\n\ntest(\"reads from the cache on a root scalar field by default if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      count @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      count: 10,\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { count: 10 } });\n});\n\ntest(\"reads from the cache on a root object field by default if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1, name: \"Test User\" } },\n  });\n});\n\ntest(\"handles read functions for root scalar field from cache if resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      count @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            count: {\n              read() {\n                return 10;\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { count: 10 } });\n});\n\ntest(\"handles read functions for root object field from cache if resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            user: {\n              read() {\n                return { __typename: \"User\", id: 1, name: \"Test User\" };\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1, name: \"Test User\" } },\n  });\n});\n\ntest(\"warns if resolver or read function isn't defined if cache does not have value\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      count @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { count: null } });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"Query.count\"\n  );\n});\n\ntest(\"reads from the cache on a nested scalar field by default if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user {\n        id\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        isLoggedIn: true,\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { user: { __typename: \"User\", id: 1 } } },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1, isLoggedIn: true } },\n  });\n});\n\ntest(\"reads from the cache with a read function on a nested scalar field if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user {\n        id\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        User: {\n          fields: {\n            isLoggedIn: {\n              read() {\n                return true;\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        user {\n          id\n        }\n      }\n    `,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\", id: 1 } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1, isLoggedIn: true } },\n  });\n});\n\ntest(\"reads from the cache on a nested object field by default if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user {\n        id\n        bestFriend @client {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          id: 2,\n          name: \"Best Friend\",\n        },\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\", id: 1 } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: { __typename: \"User\", id: 2, name: \"Best Friend\" },\n      },\n    },\n  });\n});\n\ntest(\"reads from the cache with a read function on a nested object field by default if a resolver is not defined\", async () => {\n  const document = gql`\n    query {\n      user {\n        id\n        bestFriend @client {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        User: {\n          fields: {\n            bestFriend: {\n              read() {\n                return { __typename: \"User\", id: 2, name: \"Best Friend\" };\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        user {\n          id\n        }\n      }\n    `,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\", id: 1 } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: { __typename: \"User\", id: 2, name: \"Best Friend\" },\n      },\n    },\n  });\n});\n\ntest(\"reads from the cache on a nested client field on a non-normalized object\", async () => {\n  const document = gql`\n    query {\n      user {\n        bestFriend @client {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        User: {\n          fields: {\n            bestFriend: {\n              read() {\n                return { __typename: \"User\", id: 2, name: \"Best Friend\" };\n              },\n            },\n          },\n        },\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        user {\n          __typename\n        }\n      }\n    `,\n    data: {\n      user: {\n        __typename: \"User\",\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\" } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        bestFriend: { __typename: \"User\", id: 2, name: \"Best Friend\" },\n      },\n    },\n  });\n});\n\ntest(\"does not confuse field missing resolver with root field of same name on a normalized record\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      count @client\n      user {\n        id\n        count @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        count\n      }\n    `,\n    data: {\n      count: 10,\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\", id: 1 } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      count: 10,\n      user: {\n        __typename: \"User\",\n        id: 1,\n        count: null,\n      },\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"User.count\"\n  );\n});\n\ntest(\"does not confuse field missing resolver with root field of same name on a non-normalized record\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      count @client\n      user {\n        count @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        count\n      }\n    `,\n    data: {\n      count: 10,\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\" } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      count: 10,\n      user: {\n        __typename: \"User\",\n        count: null,\n      },\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    WARNINGS.MISSING_RESOLVER,\n    \"User.count\"\n  );\n});\n\ntest(\"warns on undefined value if partial data is written to the cache for an object client field\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      user {\n        id\n        bestFriend @client {\n          id\n          name\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: gql`\n      query {\n        user {\n          id\n          bestFriend {\n            id\n          }\n        }\n      }\n    `,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: { __typename: \"User\", id: 2 },\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: {\n        data: { user: { __typename: \"User\", id: 1 } },\n      },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        bestFriend: {\n          __typename: \"User\",\n          id: 2,\n          name: null,\n        },\n      },\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"The '%s' field on object %o returned `undefined` instead of a value. The parent resolver did not include the property in the returned value and there was no resolver defined for the field.\",\n    \"name\",\n    { __typename: \"User\", id: 2 }\n  );\n});\n\ntest(\"uses a written cache value from a nested client field from parent resolver\", async () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const document = gql`\n    {\n      user @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    },\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        user: () => ({ __typename: \"User\", id: 1 }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1, name: \"Test User\" } },\n  });\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/context.test.ts",
    "content": "import { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"passes client in context to resolvers\", async () => {\n  const document = gql`\n    query WithContext {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const barResolver = jest.fn(() => 1);\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: { bar: barResolver },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: 1 } },\n  });\n\n  expect(barResolver).toHaveBeenCalledWith(\n    { __typename: \"Foo\" },\n    {},\n    { requestContext: {}, client, phase: \"resolve\" },\n    {\n      field: expect.objectContaining({\n        name: { kind: \"Name\", value: \"bar\" },\n      }),\n      fragmentMap: expect.any(Object),\n      path: [\"foo\", \"bar\"],\n    }\n  );\n});\n\ntest(\"can access request context in resolvers\", async () => {\n  const document = gql`\n    query WithContext {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: (_data, _args, { requestContext: { id } }) => id,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: { id: 1 },\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: 1 } },\n  });\n});\n\ntest(\"can access phase in resolver context\", async () => {\n  const document = gql`\n    query WithContext($phase: String!) {\n      foo @client {\n        bar @export(as: \"phase\")\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: (_data, _args, { phase }) => phase,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    phase: \"exports\",\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: \"resolve\" } },\n  });\n});\n\ntest(\"can use custom context function used as request context\", async () => {\n  const document = gql`\n    query WithContext {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    context: () => ({ isBarEnabled: true }),\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: (_data, _args, { requestContext: { isBarEnabled } }) =>\n          isBarEnabled,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true } },\n  });\n});\n\ntest(\"context function can merge request context and custom context\", async () => {\n  const document = gql`\n    query WithContext {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    context: ({ requestContext }) => ({\n      ...requestContext,\n      isBarEnabled: true,\n    }),\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: (\n          _data,\n          _args,\n          { requestContext: { isRequestBarEnabled, isBarEnabled } }\n        ) => isRequestBarEnabled && isBarEnabled,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: { isRequestBarEnabled: true },\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true } },\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/errors.test.ts",
    "content": "import { GraphQLError } from \"graphql\";\n\nimport { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"handles errors thrown in a resolver\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles errors thrown in a child resolver\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: null } },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\", \"bar\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.bar\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"adds errors for each field that throws errors\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n        baz\n        qux\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\" }),\n      },\n      Foo: {\n        bar: () => {\n          throw new Error(\"Bar error\");\n        },\n        baz: () => {\n          throw new Error(\"Baz error\");\n        },\n        qux: () => true,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: null, baz: null, qux: true } },\n    errors: [\n      {\n        message: \"Bar error\",\n        path: [\"foo\", \"bar\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.bar\",\n            cause: new Error(\"Bar error\"),\n          },\n        },\n      },\n      {\n        message: \"Baz error\",\n        path: [\"foo\", \"baz\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.baz\",\n            cause: new Error(\"Baz error\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles errors thrown in a child resolver from parent array\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => [{ __typename: \"Foo\" }, { __typename: \"Foo\" }],\n      },\n      Foo: {\n        bar: () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: [\n        { __typename: \"Foo\", bar: null },\n        { __typename: \"Foo\", bar: null },\n      ],\n    },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\", 0, \"bar\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.bar\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\", 1, \"bar\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.bar\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles errors thrown in a child resolver for an array from a single item\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        id\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => [\n          { __typename: \"Foo\", id: 1 },\n          { __typename: \"Foo\", id: 2 },\n        ],\n      },\n      Foo: {\n        bar: (parent) => {\n          if (parent.id === 2) {\n            throw new Error(\"Something went wrong\");\n          }\n\n          return true;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: [\n        { __typename: \"Foo\", id: 1, bar: true },\n        { __typename: \"Foo\", id: 2, bar: null },\n      ],\n    },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\", 1, \"bar\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.bar\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"serializes a thrown GraphQLError and merges extensions\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          throw new GraphQLError(\"Something went wrong\", {\n            extensions: { custom: true },\n          });\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          custom: true,\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new GraphQLError(\"Something went wrong\", {\n              extensions: { custom: true },\n            }),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"overwrites localState extension from thrown GraphQLError if provided\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          throw new GraphQLError(\"Something went wrong\", {\n            extensions: { localState: { shouldNotBeSeen: true } },\n          });\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new GraphQLError(\"Something went wrong\", {\n              extensions: { localState: { shouldNotBeSeen: true } },\n            }),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"concatenates client errors with server errors\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n      baz {\n        qux\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: { baz: { __typename: \"Baz\", qux: null } },\n    errors: [{ message: \"Could not get qux\", path: [\"baz\", \"qux\"] }],\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null, baz: { __typename: \"Baz\", qux: null } },\n    errors: [\n      { message: \"Could not get qux\", path: [\"baz\", \"qux\"] },\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles errors thrown in async resolvers\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: async () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles rejected promises returned in async resolvers\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: async () => {\n          return Promise.reject(new Error(\"Something went wrong\"));\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: null },\n    errors: [\n      {\n        message: \"Something went wrong\",\n        path: [\"foo\"],\n        extensions: {\n          localState: {\n            resolver: \"Query.foo\",\n            cause: new Error(\"Something went wrong\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles errors thrown for resolvers on fields inside fragments\", async () => {\n  const document = gql`\n    fragment Foo on Foo {\n      bar\n      ...Foo2\n    }\n    fragment Foo2 on Foo {\n      __typename\n      baz @client\n    }\n    query Mixed {\n      foo {\n        ...Foo\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      foo: { bar: true, __typename: `Foo` },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Foo: {\n        baz: () => {\n          throw new Error(\"Could not get baz\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { bar: true, baz: null, __typename: \"Foo\" },\n    },\n    errors: [\n      {\n        message: \"Could not get baz\",\n        path: [\"foo\", \"baz\"],\n        extensions: {\n          localState: {\n            resolver: \"Foo.baz\",\n            cause: new Error(\"Could not get baz\"),\n          },\n        },\n      },\n    ],\n  });\n});\n\ntest(\"handles remote errors with no local resolver errors\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n      baz {\n        qux\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: { baz: { __typename: \"Baz\", qux: null } },\n    errors: [{ message: \"Could not get qux\", path: [\"baz\", \"qux\"] }],\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { __typename: \"Foo\", bar: true },\n      baz: { __typename: \"Baz\", qux: null },\n    },\n    errors: [{ message: \"Could not get qux\", path: [\"baz\", \"qux\"] }],\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/exports.test.ts",
    "content": "import type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { LocalStateError } from \"@apollo/client/errors\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"returns variables from @client fields with @export\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      postCount(authorId: $authorId) @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthorId = 100;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => testAuthorId,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthorId,\n  });\n});\n\ntest(\"stores the @client nested field value in the specified @export variable\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        name\n        authorId @export(as: \"authorId\")\n      }\n      postCount(authorId: $authorId) @client\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    name: \"John Smith\",\n    authorId: 100,\n    __typename: \"Author\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => testAuthor,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthor.authorId,\n  });\n});\n\ntest(\"supports @client @export variables that are nested multiple levels deep\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      appContainer @client {\n        systemDetails {\n          currentAuthor {\n            name\n            authorId @export(as: \"authorId\")\n          }\n        }\n      }\n      postCount(authorId: $authorId)\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const appContainer = {\n    systemDetails: {\n      currentAuthor: {\n        name: \"John Smith\",\n        authorId: 100,\n        __typename: \"Author\",\n      },\n      __typename: \"SystemDetails\",\n    },\n    __typename: \"AppContainer\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        appContainer: () => appContainer,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: appContainer.systemDetails.currentAuthor.authorId,\n  });\n});\n\ntest(\"throws when passing document with no `@client` fields\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor {\n        name\n        authorId\n      }\n      postCount(authorId: $authorId)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Author: {\n        authorId: () => 200,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { authorId: 100 },\n    })\n  ).rejects.toEqual(\n    new InvariantError(\"Expected document to contain `@client` fields.\")\n  );\n});\n\ntest(\"throws when passing document with `@export` but no `@client` field\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor {\n        name\n        authorId @export(as: \"authorId\")\n      }\n      postCount(authorId: $authorId)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Author: {\n        authorId: () => 200,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { authorId: 100 },\n    })\n  ).rejects.toEqual(\n    new InvariantError(\"Expected document to contain `@client` fields.\")\n  );\n});\n\ntest(\"ignores @export directives if not used with @client\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor {\n        name\n        authorId @export(as: \"authorId\")\n      }\n      authorId @client\n      postCount(authorId: $authorId)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        authorId: () => 200,\n      },\n      Author: {\n        authorId: () => 200,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { authorId: 100 },\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: 100,\n  });\n});\n\ntest(\"ignores @export directive if it is not a descendant of a client field\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        name\n        authorId @export(as: \"authorId\")\n      }\n      # This is intentionally after the client-field above since it runs after\n      # currentAuthor. We should not see its value\n      authorId @export(as: \"authorId\")\n      postCount(authorId: $authorId)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    name: \"John Smith\",\n    authorId: 100,\n    __typename: \"Author\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        authorId: () => 1000,\n        currentAuthor: () => testAuthor,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthor.authorId,\n  });\n});\n\ntest(\"returns variable from nested field when data is written to the cache\", async () => {\n  const document = gql`\n    query postRequiringReview($reviewerId: Int!) {\n      postRequiringReview {\n        id\n        title\n        currentReviewer @client {\n          id @export(as: \"reviewerId\")\n        }\n      }\n      reviewerDetails(reviewerId: $reviewerId) {\n        name\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const postRequiringReview = {\n    id: 10,\n    title: \"The Local State Conundrum\",\n    __typename: \"Post\",\n  };\n  const currentReviewer = {\n    id: 100,\n    __typename: \"CurrentReviewer\",\n  };\n  const reviewerDetails = {\n    name: \"John Smith\",\n    __typename: \"Reviewer\",\n  };\n\n  client.writeQuery({\n    query: document,\n    data: { postRequiringReview, reviewerDetails },\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Post: {\n        currentReviewer: () => currentReviewer,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    reviewerId: currentReviewer.id,\n  });\n});\n\ntest(\"throws error when cache data is not available for parent when exporting required variable from nested field\", async () => {\n  const document = gql`\n    query postRequiringReview($reviewerId: Int!) {\n      postRequiringReview {\n        id\n        title\n        currentReviewer @client {\n          id @export(as: \"reviewerId\")\n        }\n      }\n      reviewerDetails(reviewerId: $reviewerId) {\n        name\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const currentReviewer = {\n    id: 100,\n    __typename: \"CurrentReviewer\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Post: {\n        currentReviewer: () => currentReviewer,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Field 'postRequiringReview' is `undefined` which contains exported required variable 'reviewerId'. Ensure this value is in the cache or make the variable optional.\",\n      { path: [\"postRequiringReview\"] }\n    )\n  );\n});\n\ntest(\"allows optional variable when cache data is not available for parent when exporting variable from nested field\", async () => {\n  const document = gql`\n    query postRequiringReview($reviewerId: Int) {\n      postRequiringReview {\n        id\n        title\n        currentReviewer @client {\n          id @export(as: \"reviewerId\")\n        }\n      }\n      reviewerDetails(reviewerId: $reviewerId) {\n        name\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const currentReviewer = {\n    id: 100,\n    __typename: \"CurrentReviewer\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Post: {\n        currentReviewer: () => currentReviewer,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({});\n});\n\ntest(\"throws error if `@export` does not include an `as` argument\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      authorId @client @export\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        author: () => testAuthor,\n        authorId: () => testAuthor.id,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Cannot determine the variable name from the `@export` directive used on field 'authorId'. Perhaps you forgot the `as` argument?\",\n      { path: [\"authorId\"] }\n    )\n  );\n});\n\ntest(\"does not throw error without `as` arg when `@export` is not a client field\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      authorId @client @export(as: \"authorId\")\n      foo @export\n      author(id: $authorId) @export {\n        id\n        name @export\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        authorId: () => testAuthor.id,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({ authorId: testAuthor.id });\n});\n\ntest(\"throws error if `@export` is a client descendent field without an `as` argument\", async () => {\n  const document = gql`\n    query ($authorId: Int!) {\n      author(id: $authorId) @client {\n        id @export\n        name\n      }\n      posts(authorId: $authorId) {\n        id\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        author: () => testAuthor,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Cannot determine the variable name from the `@export` directive used on field 'id'. Perhaps you forgot the `as` argument?\",\n      { path: [\"author\", \"id\"] }\n    )\n  );\n});\n\ntest(\"throws error on @client only queries when the @export directive is used on root field with no associated variable definition\", async () => {\n  const document = gql`\n    {\n      field @client @export(as: \"someVar\")\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        field: () => true,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"`@export` directive on field 'field' cannot export the '$someVar' variable as it is missing in the query definition.\",\n      { path: [\"field\"] }\n    )\n  );\n});\n\ntest(\"throws error on @client only queries when the @export directive is used on nested fields with no associated variable definition\", async () => {\n  const document = gql`\n    {\n      car @client {\n        engine {\n          torque @export(as: \"torque\")\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        car: () => ({\n          __typename: \"Car\",\n          engine: {\n            __typename: \"Engine\",\n            torque: 7200,\n          },\n        }),\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"`@export` directive on field 'torque' cannot export the '$torque' variable as it is missing in the query definition.\",\n      { path: [\"car\", \"engine\", \"torque\"] }\n    )\n  );\n});\n\ntest(\"throws error if `@export` variable does not exist in a variable definition when used with server field\", async () => {\n  const document = gql`\n    query currentAuthorPostCount {\n      authorId @client @export(as: \"authorId\")\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        author: () => testAuthor,\n        authorId: () => testAuthor.id,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"`@export` directive on field 'authorId' cannot export the '$authorId' variable as it is missing in the query definition.\",\n      { path: [\"authorId\"] }\n    )\n  );\n});\n\ntest(\"supports combining @client @export variables, calculated by a local resolver, with remote mutations\", async () => {\n  const mutation = gql`\n    mutation upvotePost($postId: Int!) {\n      topPost @client @export(as: \"postId\")\n      upvotePost(postId: $postId) {\n        title\n        votes\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testPostId = 100;\n\n  const localState = new LocalState({\n    resolvers: {\n      Mutation: {\n        topPost: () => testPostId,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document: mutation,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    postId: testPostId,\n  });\n});\n\ntest(\"removes __typename from @export-ed objects\", async () => {\n  const document = gql`\n    query GetListItems($where: LessonFilter) {\n      currentFilter @client @export(as: \"where\") {\n        title_contains\n        enabled\n      }\n      lessonCollection(where: $where) {\n        items {\n          title\n          slug\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const currentFilter = {\n    title_contains: \"full\",\n    enabled: true,\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentFilter: () => ({ ...currentFilter, __typename: \"LessonFilter\" }),\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    where: currentFilter,\n  });\n});\n\ntest(\"uses the value of the last @export variable defined, if multiple variables are defined with the same name\", async () => {\n  const document = gql`\n    query reviewerPost($reviewerId: Int!) {\n      primaryReviewerId @client @export(as: \"reviewerId\")\n      secondaryReviewerId @client @export(as: \"reviewerId\")\n      post(reviewerId: $reviewerId) {\n        title\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const primaryReviewerId = 100;\n  const secondaryReviewerId = 200;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        primaryReviewerId: () => primaryReviewerId,\n        secondaryReviewerId: () => secondaryReviewerId,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    reviewerId: secondaryReviewerId,\n  });\n});\n\ntest(\"supports reading a value from the cache in a resolver for an @client @export variable, loaded from the cache\", async () => {\n  const cacheQuery: TypedDocumentNode<\n    { loggedInReviewerId: number },\n    Record<string, never>\n  > = gql`\n    query {\n      loggedInReviewerId\n    }\n  `;\n  const document = gql`\n    query postRequiringReview($reviewerId: Int!) {\n      loggedInReviewerId @client @export(as: \"reviewerId\")\n      postRequiringReview {\n        id\n        title\n      }\n      reviewerDetails(reviewerId: $reviewerId) {\n        name\n      }\n    }\n  `;\n\n  const loggedInReviewerId = 100;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        loggedInReviewerId: (_, __, { client }) => {\n          const data = client.readQuery({\n            query: cacheQuery,\n          });\n\n          return data?.loggedInReviewerId;\n        },\n      },\n    },\n  });\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  client.writeQuery({\n    query: cacheQuery,\n    data: {\n      loggedInReviewerId,\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    reviewerId: loggedInReviewerId,\n  });\n});\n\ntest(\"does not execute client resolvers for client subtrees without an export directive\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const currentAuthor = jest.fn(() => ({\n    __typename: \"Author\",\n    id: testAuthor.id,\n  }));\n  const author = jest.fn(() => testAuthor);\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        author,\n        currentAuthor,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthor.id,\n  });\n\n  expect(currentAuthor).toHaveBeenCalledTimes(1);\n  expect(author).toHaveBeenCalledTimes(0);\n});\n\ntest(\"throws error for client-only query when resolver throws error\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => {\n          throw new Error(\"Something went wrong\");\n        },\n        author: (_, { id }) => {\n          return id === undefined ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentAuthorId' while resolving optional variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthorId\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error from client-only query when parent resolver throws with nested export\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int) {\n      currentAuthor @client {\n        id @client @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => {\n          throw new Error(\"Something went wrong\");\n        },\n        author: (_, { id }) => {\n          return id === undefined ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentAuthor' while resolving optional variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthor\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error for first variable when parent resolver throws resolving multiple nested exported variables on client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int, $authorName: String) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n        name @export(as: \"authorName\")\n      }\n      author(id: $authorId, name: $authorName) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => {\n          throw new Error(\"Something went wrong\");\n        },\n        author: (_, { id }) => {\n          return id === undefined ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toStrictEqualTyped(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentAuthor' while resolving optional variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthor\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error from first resolver across different client fields when multiple resolvers throw\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const document = gql`\n    query currentAuthorPostCount($userId: ID, $teamId: ID) {\n      currentUser @client {\n        id @export(as: \"userId\")\n      }\n      favoriteTeam @client {\n        id @export(as: \"teamId\")\n      }\n      user(id: $userId) @client {\n        id\n        name\n      }\n      team(id: $teamId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testUser = {\n    __typename: \"User\",\n    id: 1,\n    name: \"John Smith\",\n  };\n\n  const testTeam = {\n    __typename: \"Team\",\n    id: 1,\n    name: \"Denver Broncos\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentUser: () => {\n          throw new Error(\"Could not get current user\");\n        },\n        favoriteTeam: () => {\n          throw new Error(\"Could not get favorite team\");\n        },\n        user: (_, { id }) => {\n          return id === undefined ? null : testUser;\n        },\n        team: (_, { id }) => {\n          return id === undefined ? null : testTeam;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toStrictEqualTyped(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentUser' while resolving optional variable 'userId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentUser\"],\n        sourceError: new Error(\"Could not get current user\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error for client-only query when child resolver throws\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => ({ __typename: \"Author\" }),\n        author: (_, { id }) => {\n          return id === undefined ? null : testAuthor;\n        },\n      },\n      Author: {\n        id: () => {\n          throw new Error(\"Something went wrong\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Author.id' while resolving optional variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthor\", \"id\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error when a resolver throws while gathering exported variables for a required variable in client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => {\n          throw new Error(\"Something went wrong\");\n        },\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentAuthorId' while resolving required variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthorId\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error when a parent resolver throws while gathering exported variables from child field for a required variable in client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => {\n          throw new Error(\"Something went wrong\");\n        },\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Query.currentAuthor' while resolving required variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthor\"],\n        sourceError: new Error(\"Something went wrong\"),\n      }\n    )\n  );\n});\n\ntest(\"throws error when a child resolver throws while gathering exported variables from child field for a required variable in client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => ({ __typename: \"Author\" }),\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n      Author: {\n        id: () => {\n          throw new Error(\"Could not get id\");\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"An error was thrown from resolver 'Author.id' while resolving required variable 'authorId'. Use a try/catch and return `undefined` to suppress this error and omit the variable from the request.\",\n      {\n        path: [\"currentAuthor\", \"id\"],\n        sourceError: new Error(\"Could not get id\"),\n      }\n    )\n  );\n});\n\ntest(\"errors when resolver returns null for a required variable on client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => null,\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthorId' returned `null` for required variable 'authorId'.\",\n      { path: [\"currentAuthorId\"] }\n    )\n  );\n});\n\ntest(\"errors when nested field is null for a required variable on client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => ({ __typename: \"Author\", id: null }),\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Field 'Author.id' returned `null` for required variable 'authorId'.\",\n      { path: [\"currentAuthor\", \"id\"] }\n    )\n  );\n});\n\ntest(\"errors when nested field is null for a required variable on client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => ({ __typename: \"Author\" }),\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n      Author: {\n        id: () => null,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Author.id' returned `null` for required variable 'authorId'.\",\n      { path: [\"currentAuthor\", \"id\"] }\n    )\n  );\n});\n\ntest(\"throws error when top-level resolver returns null with nested export for required variable\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => null,\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthor' returned `null` which contains exported required variable 'authorId'.\",\n      { path: [\"currentAuthor\"] }\n    )\n  );\n});\n\ntest(\"throws error when top-level resolver returns undefined with nested export for required variable\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        id @export(as: \"authorId\")\n      }\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => {},\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthor' returned `undefined` which contains exported required variable 'authorId'.\",\n      { path: [\"currentAuthor\"] }\n    )\n  );\n});\n\ntest(\"errors when resolver returns undefined for a required variable on client-only query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) @client {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthor = {\n    __typename: \"Author\",\n    id: 100,\n    name: \"John Smith\",\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => {},\n        author: (_, { id }) => {\n          return id === null ? null : testAuthor;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthorId' returned `undefined` for required variable 'authorId'.\",\n      { path: [\"currentAuthorId\"] }\n    )\n  );\n});\n\ntest(\"errors when resolver returns null for a required variable on non-client query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => null,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthorId' returned `null` for required variable 'authorId'.\",\n      { path: [\"currentAuthorId\"] }\n    )\n  );\n});\n\ntest(\"errors when resolver returns undefined for a required variable on non-client query\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => {},\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Resolver 'Query.currentAuthorId' returned `undefined` for required variable 'authorId'.\",\n      { path: [\"currentAuthorId\"] }\n    )\n  );\n});\n\ntest(\"errors when resolver returns object with null field for a required variable\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthor @client {\n        profile {\n          id @export(as: \"authorId\")\n        }\n      }\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthor: () => ({ __typename: \"Author\", profile: null }),\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).rejects.toEqual(\n    new LocalStateError(\n      \"Field 'Author.profile' returned `null` which contains exported required variable 'authorId'.\",\n      { path: [\"currentAuthor\", \"profile\"] }\n    )\n  );\n});\n\ntest(\"does not warn when gathering variable exports for optional variables\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int) {\n      currentAuthorId @client @export(as: \"authorId\")\n      author(id: $authorId) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => {},\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({});\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"exported variables overwrite variables passed to LocalState\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthorId = 100;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => testAuthorId,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { authorId: 200 },\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthorId,\n  });\n});\n\ntest(\"combines exported variables with user-defined variables\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!, $limit: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      posts(authorId: $authorId, limit: $limit) {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthorId = 100;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentAuthorId: () => testAuthorId,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { limit: 10 },\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthorId,\n    limit: 10,\n  });\n});\n\ntest(\"can use context function with exported variables\", async () => {\n  const document = gql`\n    query currentAuthorPostCount($authorId: Int!, $limit: Int!) {\n      currentAuthorId @client @export(as: \"authorId\")\n      posts(authorId: $authorId, limit: $limit) {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const testAuthorId = 100;\n\n  const localState = new LocalState({\n    context: () => ({ useTestAuthor: true }),\n    resolvers: {\n      Query: {\n        currentAuthorId: (_, __, { requestContext }) =>\n          requestContext.useTestAuthor ? testAuthorId : 0,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: { limit: 10 },\n    })\n  ).resolves.toStrictEqualTyped({\n    authorId: testAuthorId,\n    limit: 10,\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fixtures/base-types.ts",
    "content": "// Used to simulate base schema types in an app\n\nexport type Query = {\n  currentUser: User | null;\n};\n\nexport type User = {\n  id: string;\n  name: string;\n};\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fixtures/context-value.ts",
    "content": "import type { DefaultContext } from \"@apollo/client\";\n\nexport interface ContextValue extends DefaultContext {\n  env: \"dev\" | \"prod\";\n}\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fixtures/local-resolvers-without-context-value.ts",
    "content": "/* eslint-disable */\nimport * as BaseSchemaTypes from \"./base-types.js\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { DeepPartial } from \"@apollo/client/utilities\";\nimport { DefaultContext } from \"@apollo/client\";\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = Maybe<T>;\nexport type Exact<T extends { [key: string]: unknown }> = {\n  [K in keyof T]: T[K];\n};\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]?: Maybe<T[SubKey]>;\n};\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]: Maybe<T[SubKey]>;\n};\nexport type MakeEmpty<\n  T extends { [key: string]: unknown },\n  K extends keyof T,\n> = { [_ in K]?: never };\nexport type Incremental<T> =\n  | T\n  | {\n      [P in keyof T]?: P extends \" $fragmentName\" | \"__typename\" ? T[P] : never;\n    };\nexport type RequireFields<T, K extends keyof T> = Omit<T, K> & {\n  [P in K]-?: NonNullable<T[P]>;\n};\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n  ID: { input: string; output: string };\n  String: { input: string; output: string };\n  Boolean: { input: boolean; output: boolean };\n  Int: { input: number; output: number };\n  Float: { input: number; output: number };\n};\n\nexport type Food = {\n  __typename: \"Food\";\n  categories?: Maybe<Array<FoodCategory>>;\n  name?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type FoodCategoriesArgs = {\n  limit?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n  offset: Scalars[\"Int\"][\"input\"];\n};\n\nexport enum FoodCategory {\n  Italian = \"ITALIAN\",\n}\n\nexport type Query = {\n  __typename: \"Query\";\n  currentUserId?: Maybe<Scalars[\"ID\"][\"output\"]>;\n};\n\nexport type User = {\n  __typename: \"User\";\n  favoriteFood?: Maybe<Food>;\n  isLoggedIn: Scalars[\"Boolean\"][\"output\"];\n};\n\n/** Mapping between all available schema types and the resolvers types */\nexport type ResolversTypes = {\n  Boolean: Scalars[\"Boolean\"][\"output\"];\n  Food: Food;\n  FoodCategory: FoodCategory;\n  ID: Scalars[\"ID\"][\"output\"];\n  Int: Scalars[\"Int\"][\"output\"];\n  Query: {};\n  String: Scalars[\"String\"][\"output\"];\n  User: User;\n};\n\n/** Mapping between all available schema types and the resolvers parents */\nexport type ResolversParentTypes = {\n  Boolean: Scalars[\"Boolean\"][\"output\"];\n  Food: Food;\n  ID: Scalars[\"ID\"][\"output\"];\n  Int: Scalars[\"Int\"][\"output\"];\n  Query: Omit<DeepPartial<BaseSchemaTypes.Query>, \"currentUserId\">;\n  String: Scalars[\"String\"][\"output\"];\n  User: Omit<DeepPartial<BaseSchemaTypes.User>, \"isLoggedIn\" | \"favoriteFood\">;\n};\n\nexport type FoodResolvers = {\n  categories?: LocalState.Resolver<\n    Maybe<Array<ResolversTypes[\"FoodCategory\"]>>,\n    ResolversParentTypes[\"Food\"],\n    DefaultContext,\n    RequireFields<FoodCategoriesArgs, \"offset\">\n  >;\n  name?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"String\"]>,\n    ResolversParentTypes[\"Food\"],\n    DefaultContext\n  >;\n};\n\nexport type QueryResolvers = {\n  currentUserId?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"ID\"]>,\n    ResolversParentTypes[\"Query\"],\n    DefaultContext\n  >;\n};\n\nexport type UserResolvers = {\n  favoriteFood?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"Food\"]>,\n    ResolversParentTypes[\"User\"],\n    DefaultContext\n  >;\n  isLoggedIn?: LocalState.Resolver<\n    ResolversTypes[\"Boolean\"],\n    ResolversParentTypes[\"User\"],\n    DefaultContext\n  >;\n};\n\nexport type Resolvers = {\n  Food?: FoodResolvers;\n  Query?: QueryResolvers;\n  User?: UserResolvers;\n};\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fixtures/local-resolvers.ts",
    "content": "/* eslint-disable */\nimport * as BaseSchemaTypes from \"./base-types.js\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { DeepPartial } from \"@apollo/client/utilities\";\nimport { ContextValue } from \"./context-value.js\";\nexport type Maybe<T> = T | null;\nexport type InputMaybe<T> = Maybe<T>;\nexport type Exact<T extends { [key: string]: unknown }> = {\n  [K in keyof T]: T[K];\n};\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]?: Maybe<T[SubKey]>;\n};\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]: Maybe<T[SubKey]>;\n};\nexport type MakeEmpty<\n  T extends { [key: string]: unknown },\n  K extends keyof T,\n> = { [_ in K]?: never };\nexport type Incremental<T> =\n  | T\n  | {\n      [P in keyof T]?: P extends \" $fragmentName\" | \"__typename\" ? T[P] : never;\n    };\nexport type RequireFields<T, K extends keyof T> = Omit<T, K> & {\n  [P in K]-?: NonNullable<T[P]>;\n};\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n  ID: { input: string; output: string };\n  String: { input: string; output: string };\n  Boolean: { input: boolean; output: boolean };\n  Int: { input: number; output: number };\n  Float: { input: number; output: number };\n};\n\nexport type Food = {\n  __typename: \"Food\";\n  categories?: Maybe<Array<FoodCategory>>;\n  name?: Maybe<Scalars[\"String\"][\"output\"]>;\n};\n\nexport type FoodCategoriesArgs = {\n  limit?: InputMaybe<Scalars[\"Int\"][\"input\"]>;\n  offset: Scalars[\"Int\"][\"input\"];\n};\n\nexport enum FoodCategory {\n  Italian = \"ITALIAN\",\n}\n\nexport type Query = {\n  __typename: \"Query\";\n  currentUserId?: Maybe<Scalars[\"ID\"][\"output\"]>;\n};\n\nexport type User = {\n  __typename: \"User\";\n  favoriteFood?: Maybe<Food>;\n  isLoggedIn: Scalars[\"Boolean\"][\"output\"];\n};\n\n/** Mapping between all available schema types and the resolvers types */\nexport type ResolversTypes = {\n  Boolean: Scalars[\"Boolean\"][\"output\"];\n  Food: Food;\n  FoodCategory: FoodCategory;\n  ID: Scalars[\"ID\"][\"output\"];\n  Int: Scalars[\"Int\"][\"output\"];\n  Query: {};\n  String: Scalars[\"String\"][\"output\"];\n  User: User;\n};\n\n/** Mapping between all available schema types and the resolvers parents */\nexport type ResolversParentTypes = {\n  Boolean: Scalars[\"Boolean\"][\"output\"];\n  Food: Food;\n  ID: Scalars[\"ID\"][\"output\"];\n  Int: Scalars[\"Int\"][\"output\"];\n  Query: Omit<DeepPartial<BaseSchemaTypes.Query>, \"currentUserId\">;\n  String: Scalars[\"String\"][\"output\"];\n  User: Omit<DeepPartial<BaseSchemaTypes.User>, \"isLoggedIn\" | \"favoriteFood\">;\n};\n\nexport type FoodResolvers = {\n  categories?: LocalState.Resolver<\n    Maybe<Array<ResolversTypes[\"FoodCategory\"]>>,\n    ResolversParentTypes[\"Food\"],\n    ContextValue,\n    RequireFields<FoodCategoriesArgs, \"offset\">\n  >;\n  name?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"String\"]>,\n    ResolversParentTypes[\"Food\"],\n    ContextValue\n  >;\n};\n\nexport type QueryResolvers = {\n  currentUserId?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"ID\"]>,\n    ResolversParentTypes[\"Query\"],\n    ContextValue\n  >;\n};\n\nexport type UserResolvers = {\n  favoriteFood?: LocalState.Resolver<\n    Maybe<ResolversTypes[\"Food\"]>,\n    ResolversParentTypes[\"User\"],\n    ContextValue\n  >;\n  isLoggedIn?: LocalState.Resolver<\n    ResolversTypes[\"Boolean\"],\n    ResolversParentTypes[\"User\"],\n    ContextValue\n  >;\n};\n\nexport type Resolvers = {\n  Food?: FoodResolvers;\n  Query?: QueryResolvers;\n  User?: UserResolvers;\n};\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fixtures/localSchema.graphql",
    "content": "extend type Query {\n  currentUserId: ID\n}\n\nextend type User {\n  isLoggedIn: Boolean!\n  favoriteFood: Food\n}\n\ntype Food {\n  name: String\n  categories(limit: Int, offset: Int!): [FoodCategory!]\n}\n\nenum FoodCategory {\n  ITALIAN\n}\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/forcedResolvers.test.ts",
    "content": "import { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"runs resolvers marked with @client(always: true)\", async () => {\n  const document = gql`\n    query Author {\n      author {\n        name\n        isLoggedIn @client(always: true)\n      }\n    }\n  `;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      author: {\n        name: \"John Smith\",\n        isLoggedIn: false,\n        __typename: \"Author\",\n      },\n    },\n  });\n\n  const localState = new LocalState();\n\n  // When the resolver isn't defined, there isn't anything to force, so\n  // make sure the query resolves from the cache properly.\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: client.readQuery({ query: document }) },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      author: { __typename: \"Author\", name: \"John Smith\", isLoggedIn: false },\n    },\n  });\n\n  localState.addResolvers({\n    Author: {\n      isLoggedIn() {\n        return true;\n      },\n    },\n  });\n\n  // A resolver is defined, so make sure it's forced, and the result\n  // resolves properly as a combination of cache and local resolver\n  // data.\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: client.readQuery({ query: document }) },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      author: { __typename: \"Author\", name: \"John Smith\", isLoggedIn: true },\n    },\n  });\n});\n\ntest(\"only runs forced resolvers for fields marked with `@client(always: true)`, not all `@client` fields\", async () => {\n  const document = gql`\n    query UserDetails {\n      name @client\n      isLoggedIn @client(always: true)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let nameCount = 0;\n  let isLoggedInCount = 0;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        name() {\n          nameCount += 1;\n          return \"John Smith\";\n        },\n        isLoggedIn() {\n          isLoggedInCount += 1;\n          return true;\n        },\n      },\n    },\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      name: \"John Smith\",\n      isLoggedIn: true,\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      onlyRunForcedResolvers: true,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { name: \"John Smith\", isLoggedIn: true },\n  });\n\n  expect(nameCount).toEqual(0);\n  expect(isLoggedInCount).toEqual(1);\n});\n\ntest(\"runs nested forced resolvers from non-forced client descendant field\", async () => {\n  const document = gql`\n    query UserDetails {\n      user @client {\n        id\n        name\n        isLoggedIn @client(always: true)\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let userCount = 0;\n  let isLoggedInCount = 0;\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        user() {\n          userCount += 1;\n          return { __typename: \"User\", id: 1, name: \"John Smith\" };\n        },\n      },\n      User: {\n        isLoggedIn() {\n          isLoggedInCount += 1;\n          return true;\n        },\n      },\n    },\n  });\n\n  client.writeQuery({\n    query: document,\n    data: {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"John Smith\",\n        isLoggedIn: true,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      onlyRunForcedResolvers: true,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      user: { __typename: \"User\", id: 1, name: \"John Smith\", isLoggedIn: true },\n    },\n  });\n\n  expect(userCount).toEqual(0);\n  expect(isLoggedInCount).toEqual(1);\n});\n\ntest(\"warns for client fields without cached data and resolvers when running forced resolvers and returnPartialData: false\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      user {\n        id\n        name @client\n        isLoggedIn @client(always: true)\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let nameCount = 0;\n  let isLoggedInCount = 0;\n  const localState = new LocalState({\n    resolvers: {\n      User: {\n        name: () => {\n          nameCount++;\n          return \"John Smith\";\n        },\n        isLoggedIn: () => {\n          isLoggedInCount++;\n          return true;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { user: { __typename: \"User\", id: 1 } } },\n      onlyRunForcedResolvers: true,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    // Note: name is null because we are only running forced resolvers and\n    // there is no cached value, but we aren't asking for partial data\n    data: {\n      user: { __typename: \"User\", id: 1, name: null, isLoggedIn: true },\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"The '%s' field had no cached value and only forced resolvers were run. The value was set to `null`.\",\n    \"User.name\"\n  );\n  expect(nameCount).toBe(0);\n  expect(isLoggedInCount).toBe(1);\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/fragments.test.ts",
    "content": "import { ApolloCache, ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"handles @client fields inside fragments\", async () => {\n  const document = gql`\n    fragment Foo on Foo {\n      bar\n      ...Foo2\n    }\n    fragment Foo2 on Foo {\n      __typename\n      baz @client\n    }\n    query Mixed {\n      foo {\n        ...Foo\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = {\n    data: {\n      foo: { bar: true, __typename: \"Foo\" },\n      bar: { baz: true, __typename: \"Bar\" },\n    },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Foo: {\n        baz: () => false,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { bar: true, baz: false, __typename: \"Foo\" },\n      bar: { baz: true, __typename: \"Bar\" },\n    },\n  });\n});\n\ntest(\"handles a mix of @client fields with fragments and server fields\", async () => {\n  const document = gql`\n    fragment client on ClientData {\n      bar\n      __typename\n    }\n\n    query Mixed {\n      foo @client {\n        ...client\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const remoteResult = { data: { bar: { baz: true, __typename: \"Bar\" } } };\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ bar: true, __typename: \"ClientData\" }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { bar: true, __typename: \"ClientData\" },\n      bar: { baz: true, __typename: \"Bar\" },\n    },\n  });\n});\n\nit(\"matches fragments with fragment conditions\", async () => {\n  const document = gql`\n    {\n      foo {\n        ... on Bar {\n          bar @client\n        }\n        ... on Baz {\n          baz @client\n        }\n      }\n    }\n  `;\n\n  const remoteResult = {\n    data: { foo: [{ __typename: \"Bar\" }, { __typename: \"Baz\" }] },\n  };\n\n  const localState = new LocalState({\n    resolvers: {\n      Bar: {\n        bar: () => \"Bar\",\n      },\n      Baz: {\n        baz: () => \"Baz\",\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      possibleTypes: {\n        Foo: [\"Bar\", \"Baz\"],\n      },\n    }),\n    link: ApolloLink.empty(),\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: [\n        { __typename: \"Bar\", bar: \"Bar\" },\n        { __typename: \"Baz\", baz: \"Baz\" },\n      ],\n    },\n  });\n});\n\ntest(\"throws when cache does not implement fragmentMatches\", async () => {\n  // @ts-expect-error we don't care about the cache methods for this test\n  class TestCache extends ApolloCache {}\n\n  const document = gql`\n    fragment Foo on Foo {\n      bar\n    }\n    query {\n      foo @client {\n        ...Foo\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new TestCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).rejects.toEqual(\n    new InvariantError(\n      \"The configured cache does not support fragment matching which will lead to incorrect results when executing local resolvers. Please use a cache that implements `fragmetMatches`.\"\n    )\n  );\n});\n\ntest(\"does not traverse fragment when fragment spread type condition does not match typename\", async () => {\n  const document = gql`\n    fragment FooDetails on Bar {\n      bar\n    }\n    query {\n      foo @client {\n        ...FooDetails\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: () => ({ __typename: \"Foo\", bar: true }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({ data: { foo: { __typename: \"Foo\" } } });\n});\n\ntest(\"can use a fragments on interface types defined by possibleTypes\", async () => {\n  const document = gql`\n    query {\n      currentUser @client {\n        ...ProfileDetails\n      }\n    }\n\n    fragment ProfileDetails on Profile {\n      id\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({ possibleTypes: { Profile: [\"User\"] } }),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        currentUser: () => ({ __typename: \"User\", id: 1 }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      currentUser: { __typename: \"User\", id: 1 },\n    },\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/partialData.test.ts",
    "content": "import { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"omits field and does not warn if resolver not defined when returnPartialData is true\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      user {\n        id\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { user: { __typename: \"User\", id: 1 } } },\n      returnPartialData: true,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { user: { __typename: \"User\", id: 1 } },\n  });\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"omits client fields without cached values when running forced resolvers with returnPartialData: true\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const document = gql`\n    query {\n      user {\n        id\n        name @client\n        isLoggedIn @client(always: true)\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let nameCount = 0;\n  let isLoggedInCount = 0;\n  const localState = new LocalState({\n    resolvers: {\n      User: {\n        name: () => {\n          nameCount++;\n          return \"John Smith\";\n        },\n        isLoggedIn: () => {\n          isLoggedInCount++;\n          return true;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { user: { __typename: \"User\", id: 1 } } },\n      returnPartialData: true,\n      onlyRunForcedResolvers: true,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    // Note: name is omitted because we are only running forced resolvers and\n    // have no cached value for name\n    data: { user: { __typename: \"User\", id: 1, isLoggedIn: true } },\n  });\n\n  expect(console.warn).not.toHaveBeenCalled();\n  expect(nameCount).toBe(0);\n  expect(isLoggedInCount).toBe(1);\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/rootValue.test.ts",
    "content": "import { equal } from \"@wry/equality\";\n\nimport { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { LocalState } from \"@apollo/client/local-state\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"passes parent value as empty object to root resolver for client-only query\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: (rootValue) => ({\n          __typename: \"Foo\",\n          bar: equal(rootValue, {}),\n        }),\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: undefined,\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { foo: { __typename: \"Foo\", bar: true } },\n  });\n});\n\ntest(\"passes rootValue as remote result to root resolver when server fields are present\", async () => {\n  const document = gql`\n    query Test {\n      foo @client {\n        bar\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fooResolver = jest.fn(() => ({\n    __typename: \"Foo\",\n    bar: true,\n  }));\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: fooResolver,\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { bar: { __typename: \"Bar\", baz: true } } },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: {\n      foo: { __typename: \"Foo\", bar: true },\n      bar: { __typename: \"Bar\", baz: true },\n    },\n  });\n\n  expect(fooResolver).toHaveBeenCalledWith(\n    {\n      bar: { __typename: \"Bar\", baz: true },\n    },\n    expect.anything(),\n    expect.anything(),\n    expect.anything()\n  );\n});\n\ntest(\"passes rootValue as empty object when getting exported variables with no cache data\", async () => {\n  const document = gql`\n    query Test($foo: FooInput) {\n      foo @client @export(as: \"foo\") {\n        bar\n      }\n      bar {\n        baz\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fooResolver = jest.fn(() => ({\n    __typename: \"Foo\",\n    bar: true,\n  }));\n  const localState = new LocalState({\n    resolvers: {\n      Query: {\n        foo: fooResolver,\n      },\n    },\n  });\n\n  await expect(\n    localState.getExportedVariables({\n      document,\n      client,\n      context: {},\n      variables: {},\n    })\n  ).resolves.toStrictEqualTyped({ foo: { bar: true } });\n\n  expect(fooResolver).toHaveBeenCalledWith(\n    {},\n    expect.anything(),\n    expect.anything(),\n    expect.anything()\n  );\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/subscriptions.test.ts",
    "content": "import { ApolloClient, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport { gql } from \"./testUtils.js\";\n\ntest(\"throws when given a subscription with no client fields\", async () => {\n  const subscription = gql`\n    subscription {\n      field\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const localState = new LocalState();\n\n  await expect(\n    localState.execute({\n      document: subscription,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { field: 1 } },\n      fetchPolicy: \"cache-first\",\n    })\n  ).rejects.toEqual(\n    new InvariantError(\"Expected document to contain `@client` fields.\")\n  );\n});\n\ntest(\"adds @client fields with subscription results\", async () => {\n  const subscription = gql`\n    subscription {\n      field\n      count @client\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  let subCounter = 0;\n  const localState = new LocalState({\n    resolvers: {\n      Subscription: {\n        count: () => {\n          subCounter += 1;\n          return subCounter;\n        },\n      },\n    },\n  });\n\n  await expect(\n    localState.execute({\n      document: subscription,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { field: 1 } },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { field: 1, count: 1 },\n  });\n\n  await expect(\n    localState.execute({\n      document: subscription,\n      client,\n      context: {},\n      variables: {},\n      remoteResult: { data: { field: 2 } },\n      fetchPolicy: \"cache-first\",\n    })\n  ).resolves.toStrictEqualTyped({\n    data: { field: 2, count: 2 },\n  });\n});\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/testUtils.ts",
    "content": "import { gql as origGql } from \"graphql-tag\";\n\nimport { addTypenameToDocument } from \"@apollo/client/utilities\";\n\nexport const gql = (...args: Parameters<typeof origGql>) =>\n  addTypenameToDocument(origGql(...args));\n\nexport const WARNINGS = {\n  MISSING_RESOLVER:\n    \"Could not find a resolver for the '%s' field nor does the cache resolve the field. The field value has been set to `null`. Either define a resolver for the field or ensure the cache can resolve the value, for example, by adding a 'read' function to a field policy in 'InMemoryCache'.\",\n  NO_CACHE:\n    \"The '%s' field resolves the value from the cache, for example from a 'read' function, but a 'no-cache' fetch policy was used. The field value has been set to `null`. Either define a local resolver or use a fetch policy that uses the cache to ensure the field is resolved correctly.\",\n};\n"
  },
  {
    "path": "src/local-state/__tests__/LocalState/types.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport { LocalState } from \"@apollo/client/local-state\";\n\nimport type { ContextValue } from \"./fixtures/context-value.js\";\n\ntype SetRequired<T, Keys extends keyof T> = { [K in Keys]-?: T[K] } & Omit<\n  T,\n  Keys\n>;\n\ndescribe.skip(\"Type tests\", () => {\n  test(\"allows resolvers of anything with no generic\", () => {\n    interface Food {\n      __typename: \"Food\";\n      name: string;\n    }\n    new LocalState();\n    new LocalState({ resolvers: {} });\n\n    new LocalState({\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({ __typename: \"Food\" }),\n        },\n        Food: {\n          name: (parent: Food) => parent.name,\n          ingredients: () => {},\n        },\n      },\n    });\n\n    new LocalState({\n      // note: the default type of context is `DefaultContext` which is defined\n      // as `DefaultContext extends Record<string, any>` so this type test\n      // demonstrates that we can return keys that aren't explicit in the\n      // `DefaultContext` type.\n      context: () => ({\n        env: \"development\",\n      }),\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({ __typename: \"Food\" }),\n        },\n        Food: {\n          name: (parent: Food) => parent.name,\n          ingredients: () => {},\n        },\n      },\n    });\n  });\n\n  test(\"works with codegen resolver types\", async () => {\n    type Resolvers =\n      import(\"./fixtures/local-resolvers-without-context-value.js\").Resolvers;\n    type Food =\n      import(\"./fixtures/local-resolvers-without-context-value.js\").Food;\n    const { FoodCategory } = await import(\n      \"./fixtures/local-resolvers-without-context-value.js\"\n    );\n\n    type RequiredRootResolver = SetRequired<Resolvers, \"Query\">;\n\n    new LocalState<Resolvers>();\n    // @ts-expect-error missing argument\n    new LocalState<RequiredRootResolver>();\n\n    new LocalState<Resolvers>({});\n    // @ts-expect-error missing resolvers option\n    new LocalState<RequiredRootResolver>({});\n\n    new LocalState<Resolvers>({\n      resolvers: {},\n    });\n    new LocalState<RequiredRootResolver>({\n      // @ts-expect-error missing Query resolver\n      resolvers: {},\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({\n            __typename: \"Food\",\n            name: \"Pasta\",\n            categories: [FoodCategory.Italian],\n          }),\n        },\n        Food: {\n          name: (food) => food.name?.toUpperCase() ?? null,\n          categories: (food, { limit, offset }) => {\n            expectTypeOf(food).toEqualTypeOf<Food>();\n            expectTypeOf(limit).toEqualTypeOf<number | null | undefined>();\n            expectTypeOf(offset).toEqualTypeOf<number>();\n\n            limit = limit ?? 5;\n            return food.categories?.slice(offset, offset + limit) ?? [];\n          },\n        },\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({\n            __typename: \"Food\",\n            name: \"Pasta\",\n            categories: [FoodCategory.Italian],\n          }),\n        },\n        Food: {\n          name: (food) => food.name?.toUpperCase() ?? null,\n          categories: (food, { limit, offset }) => {\n            expectTypeOf(food).toEqualTypeOf<Food>();\n            expectTypeOf(limit).toEqualTypeOf<number | null | undefined>();\n            expectTypeOf(offset).toEqualTypeOf<number>();\n\n            limit = limit ?? 5;\n            return food.categories?.slice(offset, offset + limit) ?? [];\n          },\n        },\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        Query: {},\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        Query: {},\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        Query: {\n          // @ts-expect-error wrong return type\n          currentUserId: () => {\n            return true;\n          },\n        },\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        Query: {\n          // @ts-expect-error wrong return type\n          currentUserId: () => {\n            return true;\n          },\n        },\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        User: {\n          // @ts-expect-error missing __typename\n          favoriteFood: () => ({ name: \"Pizza\" }),\n        },\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        User: {\n          // @ts-expect-error missing __typename\n          favoriteFood: () => ({ name: \"Pizza\" }),\n        },\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({ __typename: \"Food\" }),\n        },\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        Query: {\n          currentUserId: () => \"1\",\n        },\n        User: {\n          favoriteFood: () => ({ __typename: \"Food\" }),\n        },\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        // @ts-expect-error unknown typename\n        Invalid: {},\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        // @ts-expect-error unknown typename\n        Invalid: {},\n      },\n    });\n\n    new LocalState<Resolvers>({\n      resolvers: {\n        Query: {\n          // @ts-expect-error unknown field\n          invalid: () => 1,\n        },\n      },\n    });\n    new LocalState<RequiredRootResolver>({\n      resolvers: {\n        Query: {\n          // @ts-expect-error unknown field\n          invalid: () => 1,\n        },\n      },\n    });\n  });\n\n  test(\"context\", () => {\n    type Resolvers = import(\"./fixtures/local-resolvers.js\").Resolvers;\n\n    // @ts-expect-error missing required context value\n    new LocalState<Resolvers, ContextValue>({\n      resolvers: {},\n    });\n\n    new LocalState<Resolvers, ContextValue>({\n      context: () => ({ env: \"dev\" }),\n      resolvers: {\n        Query: {\n          currentUserId: (rootValue) => rootValue.currentUser?.id ?? null,\n        },\n      },\n    });\n\n    new LocalState<Resolvers, ContextValue>({\n      context: ({ requestContext }) => ({ ...requestContext, env: \"dev\" }),\n      resolvers: {\n        Query: {\n          currentUserId: (rootValue) => rootValue.currentUser?.id ?? null,\n        },\n      },\n    });\n\n    new LocalState<Resolvers, ContextValue>({\n      context: ({ requestContext }) => ({\n        ...requestContext,\n        // @ts-expect-error invalid value\n        env: \"staging\",\n      }),\n      resolvers: {\n        Query: {\n          currentUserId: (_, __, { requestContext }) => requestContext.env,\n        },\n      },\n    });\n\n    new LocalState<Resolvers, ContextValue>({\n      context: () => ({\n        env: \"prod\",\n      }),\n      resolvers: {\n        Query: {\n          // @ts-expect-error requestContext is incorrect type\n          currentUserId: (\n            _,\n            __,\n            { requestContext }: { requestContext: { invalid: boolean } }\n          ) => \"1\",\n        },\n      },\n    });\n\n    new LocalState<Resolvers>({\n      context: () => ({\n        // @ts-expect-error invalid value for env\n        env: \"staging\",\n      }),\n      resolvers: {\n        Query: {\n          currentUserId: (rootValue) => rootValue.currentUser?.id ?? null,\n        },\n      },\n    });\n\n    new LocalState({\n      context: () => ({\n        // @ts-expect-error invalid value for env\n        env: \"staging\",\n      }),\n      resolvers: {\n        Query: {\n          currentUserId: (\n            _,\n            __,\n            { requestContext }: { requestContext: ContextValue }\n          ) => 1,\n        },\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/local-state/index.ts",
    "content": "export { LocalState } from \"./LocalState.js\";\n"
  },
  {
    "path": "src/masking/GraphQLCodegenDataMasking.ts",
    "content": "import type { HKT } from \"@apollo/client/utilities\";\nimport type { IsAny } from \"@apollo/client/utilities/internal\";\n\nimport type {\n  ContainsFragmentsRefs,\n  RemoveFragmentName,\n  UnwrapFragmentRefs,\n} from \"./internal/types.js\";\nexport declare namespace GraphQLCodegenDataMasking {\n  export interface TypeOverrides {\n    FragmentType: HKTImplementation.FragmentType;\n    MaybeMasked: HKTImplementation.MaybeMasked;\n    Unmasked: HKTImplementation.Unmasked;\n  }\n  namespace HKTImplementation {\n    export interface FragmentType extends HKT {\n      arg1: unknown; // TData\n      return: GraphQLCodegenDataMasking.FragmentType<this[\"arg1\"]>;\n    }\n\n    export interface MaybeMasked extends HKT {\n      arg1: unknown; // TData\n      return: GraphQLCodegenDataMasking.MaybeMasked<this[\"arg1\"]>;\n    }\n\n    export interface Unmasked extends HKT {\n      arg1: unknown; // TData\n      return: GraphQLCodegenDataMasking.Unmasked<this[\"arg1\"]>;\n    }\n  }\n\n  export type FragmentType<TData> =\n    [TData] extends [{ \" $fragmentName\"?: infer TKey }] ?\n      TKey extends string ?\n        { \" $fragmentRefs\"?: { [key in TKey]: TData } }\n      : never\n    : never;\n\n  /**\n   * Unwraps the type to its masked type.\n   *\n   * @remarks\n   * GraphQL Codegen generates types as masked types. The implementation is an\n   * identity type.\n   */\n  export type MaybeMasked<TData> = TData;\n\n  /**\n   * Unmasks a type to provide its full result.\n   */\n  export type Unmasked<TData> =\n    true extends IsAny<TData> ? TData\n    : TData extends object ?\n      true extends ContainsFragmentsRefs<TData> ?\n        UnwrapFragmentRefs<RemoveFragmentName<TData>>\n      : TData\n    : TData;\n}\n"
  },
  {
    "path": "src/masking/PreserveTypes.ts",
    "content": "import type { HKT } from \"@apollo/client/utilities\";\n\nexport declare namespace PreserveTypes {\n  export interface TypeOverrides {\n    FragmentType: HKTImplementation.FragmentType;\n    MaybeMasked: HKTImplementation.MaybeMasked;\n    Unmasked: HKTImplementation.Unmasked;\n  }\n  namespace HKTImplementation {\n    export interface FragmentType extends HKT {\n      arg1: unknown; // TData\n      return: never;\n    }\n\n    export interface MaybeMasked extends HKT {\n      arg1: unknown; // TData\n      return: this[\"arg1\"];\n    }\n\n    export interface Unmasked extends HKT {\n      arg1: unknown; // TData\n      return: this[\"arg1\"];\n    }\n  }\n\n  export type FragmentType<_TData> = never;\n  export type MaybeMasked<TData> = TData;\n  export type Unmasked<TData> = TData;\n}\n"
  },
  {
    "path": "src/masking/__benches__/types.bench.ts",
    "content": "import { attest, bench } from \"@ark/attest\";\nimport { setup } from \"@ark/attest\";\nimport { expectTypeOf } from \"expect-type\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport type {\n  FragmentType,\n  MaybeMasked,\n  Unmasked,\n} from \"@apollo/client/masking\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\n\nimport type { ContainsFragmentsRefs } from \"../internal/types.js\";\n\nsetup({\n  updateSnapshots: !process.env.CI,\n});\n\nfunction test(name: string, fn: (name: string) => void) {\n  fn(name + \": \");\n}\n\ntype UnrelatedType = {\n  __typename: \"Unrelated\";\n} & { \" $fragmentName\"?: \"Unrelated\" } & {\n  \" $fragmentRefs\"?: {\n    Unrelated: {\n      __unrelated: boolean;\n    };\n  };\n};\n// @ts-ignore\ntype _TypeCacheWarmup = Unmasked<UnrelatedType> | MaybeMasked<UnrelatedType>;\n\ntest(\"unmasks deeply nested fragments\", (prefix) => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    id: number;\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      NameFieldsFragment: NameFieldsFragment;\n      JobFieldsFragment: JobFieldsFragment;\n    };\n  };\n\n  type NameFieldsFragment = {\n    __typename: \"User\";\n    firstName: string;\n    lastName: string;\n  } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n  type JobFieldsFragment = {\n    __typename: \"User\";\n    job: string;\n  } & { \" $fragmentName\"?: \"JobFieldsFragment\" } & {\n    \" $fragmentRefs\"?: { CareerFieldsFragment: CareerFieldsFragment };\n  };\n\n  type CareerFieldsFragment = {\n    __typename: \"User\";\n    position: string;\n  } & { \" $fragmentName\"?: \"CareerFieldsFragment\" };\n\n  type Source = UserFieldsFragment;\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    expectTypeOf<Unmasked<Source>>().toEqualTypeOf<{\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n      job: string;\n      position: string;\n    }>();\n  });\n});\n\ntest(\"unmasks deeply nested fragments\", (prefix) => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    id: number;\n    age: number;\n    jobs: Array<\n      {\n        __typename: \"Job\";\n        id: string;\n        title: string;\n      } & { \" $fragmentRefs\"?: { JobFieldsFragment: JobFieldsFragment } }\n    >;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      NameFieldsFragment: NameFieldsFragment;\n    };\n  };\n\n  type NameFieldsFragment = {\n    __typename: \"User\";\n    firstName: string;\n    lastName: string;\n  } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n  type JobFieldsFragment = {\n    __typename: \"Job\";\n    job: string;\n  } & { \" $fragmentName\"?: \"JobFieldsFragment\" } & {\n    \" $fragmentRefs\"?: { CareerFieldsFragment: CareerFieldsFragment };\n  };\n\n  type CareerFieldsFragment = {\n    __typename: \"Job\";\n    position: string;\n  } & { \" $fragmentName\"?: \"CareerFieldsFragment\" };\n\n  type Source = UserFieldsFragment;\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    expectTypeOf<Unmasked<Source>>().toEqualTypeOf<{\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n      jobs: Array<{\n        __typename: \"Job\";\n        id: string;\n        title: string;\n        job: string;\n        position: string;\n      }>;\n    }>();\n  });\n});\n\ntest(\"unmasks deeply nested nullable fragments\", (prefix) => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    id: number;\n    age: number;\n    career:\n      | ({\n          __typename: \"Job\";\n          id: string;\n          title: string;\n        } & { \" $fragmentRefs\"?: { JobFieldsFragment: JobFieldsFragment } })\n      | null;\n    jobs: Array<\n      | ({\n          __typename: \"Job\";\n          id: string;\n          title: string;\n        } & { \" $fragmentRefs\"?: { JobFieldsFragment: JobFieldsFragment } })\n      | null\n    >;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      NameFieldsFragment: NameFieldsFragment;\n    };\n  };\n\n  type NameFieldsFragment = {\n    __typename: \"User\";\n    firstName: string;\n    lastName: string;\n  } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n  type JobFieldsFragment = {\n    __typename: \"Job\";\n    job: string;\n  } & { \" $fragmentName\"?: \"JobFieldsFragment\" } & {\n    \" $fragmentRefs\"?: { CareerFieldsFragment: CareerFieldsFragment };\n  };\n\n  type CareerFieldsFragment = {\n    __typename: \"Job\";\n    position: string;\n  } & { \" $fragmentName\"?: \"CareerFieldsFragment\" };\n\n  type Source = UserFieldsFragment;\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    expectTypeOf<Unmasked<Source>>().toEqualTypeOf<{\n      __typename: \"User\";\n      id: number;\n      age: number;\n      firstName: string;\n      lastName: string;\n      career: {\n        __typename: \"Job\";\n        id: string;\n        title: string;\n        job: string;\n        position: string;\n      } | null;\n      jobs: Array<{\n        __typename: \"Job\";\n        id: string;\n        title: string;\n        job: string;\n        position: string;\n      } | null>;\n    }>();\n  });\n});\n\ntest(\"unmasks DeepPartial types\", (prefix) => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    id: number;\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      NameFieldsFragment: NameFieldsFragment;\n    };\n  };\n\n  type NameFieldsFragment = {\n    __typename: \"User\";\n    firstName: string;\n    lastName: string;\n  } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n  type Source = DeepPartial<UserFieldsFragment>;\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    expectTypeOf<Unmasked<Source>>().toEqualTypeOf<{\n      __typename?: \"User\";\n      id?: number;\n      age?: number;\n      firstName?: string;\n      lastName?: string;\n    }>();\n  });\n});\n\ntest(\"Unmasked handles odd types\", (prefix) => {\n  bench(prefix + \"empty type instantiations\", () => {\n    attest<{}, Unmasked<{}>>();\n  }).types([112, \"instantiations\"]);\n\n  bench(prefix + \"empty type functionality\", () => {\n    expectTypeOf<Unmasked<{}>>().toEqualTypeOf<{}>();\n  });\n\n  bench(prefix + \"generic record type instantiations\", () => {\n    attest<Record<string, any>, Unmasked<Record<string, any>>>();\n  }).types([116, \"instantiations\"]);\n\n  bench(prefix + \"generic record type functionality\", () => {\n    expectTypeOf<Unmasked<Record<string, any>>>().toEqualTypeOf<\n      Record<string, any>\n    >();\n  });\n\n  bench(prefix + \"unknown instantiations\", () => {\n    attest<unknown, Unmasked<unknown>>();\n  }).types([46, \"instantiations\"]);\n\n  bench(prefix + \"unknown functionality\", () => {\n    expectTypeOf<Unmasked<unknown>>().toBeUnknown();\n  });\n\n  bench(prefix + \"any instantiations\", () => {\n    attest<any, Unmasked<any>>();\n  }).types([49, \"instantiations\"]);\n\n  bench(prefix + \"any functionality\", () => {\n    expectTypeOf<Unmasked<any>>().toBeAny();\n  });\n});\n\ntest(\"MaybeMasked handles odd types\", (prefix) => {\n  bench(prefix + \"empty type instantiations\", () => {\n    attest<{}, MaybeMasked<{}>>();\n  }).types([41, \"instantiations\"]);\n\n  bench(prefix + \"empty type functionality\", () => {\n    expectTypeOf<MaybeMasked<{}>>().toEqualTypeOf<{}>();\n  });\n\n  bench(prefix + \"generic record type instantiations\", () => {\n    attest<Record<string, any>, MaybeMasked<Record<string, any>>>();\n  }).types([46, \"instantiations\"]);\n  bench(prefix + \"generic record type functionality\", () => {\n    expectTypeOf<MaybeMasked<Record<string, any>>>().toEqualTypeOf<\n      Record<string, any>\n    >();\n  });\n\n  bench(prefix + \"unknown instantiations\", () => {\n    attest<unknown, MaybeMasked<unknown>>();\n  }).types([41, \"instantiations\"]);\n  bench(prefix + \"unknown functionality\", () => {\n    expectTypeOf<MaybeMasked<unknown>>().toBeUnknown();\n  });\n\n  bench(prefix + \"any instantiations\", () => {\n    attest<any, MaybeMasked<any>>();\n  }).types([43, \"instantiations\"]);\n  bench(prefix + \"any functionality\", () => {\n    expectTypeOf<MaybeMasked<any>>().toBeAny();\n  });\n});\n\ntest(\"distributed members on MaybeMasked\", (prefix) => {\n  (function unresolvedGeneric<T>() {\n    bench(prefix + \"one unresolved generic mixed with null|undefined\", () => {\n      attest<\n        [MaybeMasked<T> | null | undefined],\n        [MaybeMasked<T | null | undefined>]\n      >();\n    }).types([49, \"instantiations\"]);\n  })();\n\n  (function unresolvedGenerics<T, V>() {\n    bench(prefix + \"two unresolved generics distribute\", () => {\n      attest<[MaybeMasked<T> | MaybeMasked<V>], [MaybeMasked<T | V>]>();\n    }).types([50, \"instantiations\"]);\n  })();\n});\n\ntest(\"deals with overlapping array from parent fragment\", (prefix) => {\n  type Source = {\n    __typename: \"Track\";\n    /** comment: id */\n    id: number;\n    /** comment: artists */\n    artists?: Array<{\n      __typename: \"Artist\";\n      /** comment: artists.id */\n      id: number;\n      \" $fragmentRefs\"?: {\n        ArtistFragment: ArtistFragment;\n      };\n    }> | null;\n    \" $fragmentRefs\"?: {\n      NestedTrackFragment: NestedTrackFragment;\n    };\n  };\n\n  type ArtistFragment = {\n    \" $fragmentName\"?: \"Fragment__Artist\";\n    __typename: \"Artist\";\n    /** comment: artists.birthday */\n    birthdate: string;\n  };\n\n  type NestedTrackFragment = {\n    \" $fragmentName\"?: \"Fragment__Track\";\n    __typename: \"Track\";\n    artists?: Array<{\n      __typename: \"Artist\";\n      /** comment: artists.lastname */\n      lastname: string;\n    }> | null;\n  };\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as Unmasked<Source>;\n    // some fields for hovering\n    x.id;\n    x.artists;\n    x.artists?.[0]?.id;\n    x.artists?.[0]?.birthdate;\n    x.artists?.[0]?.lastname;\n    expectTypeOf(x).branded.toEqualTypeOf<{\n      __typename: \"Track\";\n      id: number;\n      artists?:\n        | Array<{\n            __typename: \"Artist\";\n            id: number;\n            birthdate: string;\n            lastname: string;\n          }>\n        | null\n        | undefined;\n    }>();\n  });\n});\n\ntest(\"base type, multiple fragments on sub-types\", (prefix) => {\n  type Source = {\n    __typename: \"Track\";\n    id: number;\n    artists?: Array<{\n      __typename: \"Person\" | \"Animatronic\" | \"CartoonCharacter\";\n      id: number;\n      name: string;\n      \" $fragmentRefs\"?: {\n        PersonFragment: PersonFragment;\n        AnimatronicFragment: AnimatronicFragment;\n        CartoonCharacterFragment: CartoonCharacterFragment;\n      };\n    }> | null;\n  };\n\n  type PersonFragment = {\n    \" $fragmentName\"?: \"Fragment__Person\";\n    __typename: \"Person\";\n    birthdate: string;\n  };\n  type AnimatronicFragment = {\n    \" $fragmentName\"?: \"Fragment__Animatronic\";\n    __typename: \"Animatronic\";\n    manufacturer: string;\n    warrantyEndDate: string;\n  };\n  type CartoonCharacterFragment = {\n    \" $fragmentName\"?: \"Fragment__CartoonCharacter\";\n    __typename: \"CartoonCharacter\";\n    animator: string;\n    voiceActor: string;\n  };\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as Unmasked<Source>;\n    expectTypeOf(x).branded.toEqualTypeOf<{\n      __typename: \"Track\";\n      id: number;\n      artists?:\n        | Array<\n            | {\n                __typename: \"Person\";\n                id: number;\n                name: string;\n                birthdate: string;\n              }\n            | {\n                __typename: \"Animatronic\";\n                id: number;\n                name: string;\n                manufacturer: string;\n                warrantyEndDate: string;\n              }\n            | {\n                __typename: \"CartoonCharacter\";\n                id: number;\n                name: string;\n                animator: string;\n                voiceActor: string;\n              }\n          >\n        | null\n        | undefined;\n    }>();\n  });\n});\n\ntest(\"does not detect `$fragmentRefs` if type contains `any`\", (prefix) => {\n  interface Source {\n    foo: { bar: any[] };\n    \" $fragmentName\": \"foo\";\n  }\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as MaybeMasked<Source>;\n  }).types([1, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as MaybeMasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<Source>();\n  });\n});\n\ntest(\"leaves tuples alone\", (prefix) => {\n  interface Source {\n    coords: [long: number, lat: number];\n  }\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as Unmasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<{\n      coords: [long: number, lat: number];\n    }>();\n  });\n});\n\ntest(\"does not detect `$fragmentRefs` if type is a record type\", (prefix) => {\n  interface MetadataItem {\n    foo: string;\n  }\n\n  interface Source {\n    metadata: Record<string, MetadataItem>;\n    \" $fragmentName\": \"Source\";\n  }\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as MaybeMasked<Source>;\n  }).types([1, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as MaybeMasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<Source>();\n  });\n});\n\ntest(\"does not detect `$fragmentRefs` on types with index signatures\", (prefix) => {\n  interface Source {\n    foo: string;\n    \" $fragmentName\": \"Source\";\n    [key: string]: string;\n  }\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as MaybeMasked<Source>;\n  }).types([1, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as MaybeMasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<Source>();\n  });\n});\n\ntest(\"detects `$fragmentRefs` on types with index signatures\", (prefix) => {\n  type Source = {\n    __typename: \"Foo\";\n    id: number;\n    metadata: Record<string, number>;\n    structuredMetadata: StructuredMetadata;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      FooFragment: FooFragment;\n    };\n  };\n\n  interface StructuredMetadata {\n    bar: number;\n    [index: string]: number;\n  }\n\n  type FooFragment = {\n    __typename: \"Foo\";\n    foo: string;\n  } & { \" $fragmentName\"?: \"FooFragment\" };\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as MaybeMasked<Source>;\n  }).types([1, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as Unmasked<Source>;\n    const y = {} as ContainsFragmentsRefs<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<{\n      __typename: \"Foo\";\n      id: number;\n      metadata: Record<string, number>;\n      foo: string;\n      structuredMetadata: StructuredMetadata;\n    }>();\n    expectTypeOf(y).toEqualTypeOf<true>();\n  });\n});\n\ntest(\"recursive types: no error 'Type instantiation is excessively deep and possibly infinite.'\", (prefix) => {\n  // this type is self-recursive\n  type Source = import(\"graphql\").IntrospectionQuery;\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as MaybeMasked<Source>;\n  }).types([1, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as MaybeMasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<Source>();\n  });\n});\n\ntest(\"MaybeMasked can be called with a generic if `mode` is not set to `unmask`\", (prefix) => {\n  function withGenericResult<T extends { [key: string]: string }>(\n    arg: TypedDocumentNode<T, {}>\n  ) {\n    bench(prefix + \"Result generic - instantiations\", () => {\n      const maybeMasked: MaybeMasked<typeof arg> = arg;\n      return maybeMasked;\n    }).types([1, \"instantiations\"]);\n\n    bench(prefix + \"Result generic - functionality\", () => {\n      const maybeMasked: MaybeMasked<typeof arg> = arg;\n      expectTypeOf(maybeMasked).toEqualTypeOf(arg);\n    });\n  }\n  function withGenericDocument<T extends TypedDocumentNode>(arg: T) {\n    bench(prefix + \"Result generic - instantiations\", () => {\n      const maybeMasked: MaybeMasked<T> = arg;\n      return maybeMasked;\n    }).types([1, \"instantiations\"]);\n\n    bench(prefix + \"Result generic - functionality\", () => {\n      const maybeMasked: MaybeMasked<T> = arg;\n      // cannot use unresolved generic with `expectTypeOf` here so we just try an assignment the other way round\n      const test: T = maybeMasked;\n      return test;\n    });\n  }\n  withGenericResult({} as any);\n  withGenericDocument({} as any);\n});\n\ntest(\"Unmasked handles branded primitive types\", (prefix) => {\n  type Branded<T, Name extends string> = T & { __branded?: Name };\n  type UUID = Branded<string, \"UUID\">;\n  type Source = {\n    __typename: \"Foo\";\n    id: UUID;\n    name: string;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      FooFragment: FooFragment;\n    };\n  };\n  type FooFragment = {\n    __typename: \"Foo\";\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  bench(prefix + \"instantiations\", () => {\n    return {} as Unmasked<Source>;\n  }).types([6, \"instantiations\"]);\n\n  bench(prefix + \"functionality\", () => {\n    const x = {} as Unmasked<Source>;\n\n    expectTypeOf(x).branded.toEqualTypeOf<{\n      __typename: \"Foo\";\n      id: UUID;\n      name: string;\n      age: number;\n    }>();\n  });\n});\n\ntest(\"FragmentType\", () => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    id: number;\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" } & {\n    \" $fragmentRefs\"?: {\n      NameFieldsFragment: NameFieldsFragment;\n    };\n  };\n\n  type NameFieldsFragment = {\n    __typename: \"User\";\n    firstName: string;\n    lastName: string;\n  } & { \" $fragmentName\"?: \"NameFieldsFragment\" };\n\n  type Source = UserFieldsFragment;\n\n  const USER_FIELDS_FRAGMENT: TypedDocumentNode<UserFieldsFragment> = {} as any;\n\n  bench(\"normal usage\", () => {\n    expectTypeOf<FragmentType<Source>>().toEqualTypeOf<{\n      \" $fragmentRefs\"?: {\n        UserFieldsFragment: UserFieldsFragment;\n      };\n    }>();\n  });\n\n  bench(\"passing in the type of a `TypedDocumentNode`\", () => {\n    expectTypeOf<FragmentType<typeof USER_FIELDS_FRAGMENT>>().toEqualTypeOf<{\n      \" $fragmentRefs\"?: {\n        UserFieldsFragment: UserFieldsFragment;\n      };\n    }>();\n  });\n\n  bench(\"both usages yield the same result\", () => {\n    expectTypeOf<FragmentType<Source>>().toEqualTypeOf<\n      FragmentType<typeof USER_FIELDS_FRAGMENT>\n    >();\n  });\n});\n"
  },
  {
    "path": "src/masking/__tests__/maskFragment.test.ts",
    "content": "import { gql, InMemoryCache } from \"@apollo/client\";\nimport { maskFragment } from \"@apollo/client/masking\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { deepFreeze } from \"../../utilities/internal/deepFreeze.js\";\n\ntest(\"returns null when data is null\", () => {\n  const fragment = gql`\n    fragment Foo on Query {\n      foo\n      ...QueryFields\n    }\n\n    fragment QueryFields on Query {\n      bar\n    }\n  `;\n\n  const data = maskFragment(null, fragment, new InMemoryCache(), \"Foo\");\n\n  expect(data).toBe(null);\n});\n\ntest(\"returns undefined when data is undefined\", () => {\n  const fragment = gql`\n    fragment Foo on Query {\n      foo\n      ...QueryFields\n    }\n\n    fragment QueryFields on Query {\n      bar\n    }\n  `;\n\n  const data = maskFragment(undefined, fragment, new InMemoryCache(), \"Foo\");\n\n  expect(data).toBe(undefined);\n});\ntest(\"masks named fragments in fragment documents\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      ...UserProfile\n    }\n\n    fragment UserProfile on User {\n      age\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({ __typename: \"User\", id: 1, age: 30 }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(data).toEqual({ __typename: \"User\", id: 1 });\n});\n\ntest(\"masks named fragments in nested fragment objects\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      profile {\n        ...UserProfile\n      }\n    }\n\n    fragment UserProfile on User {\n      age\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"User\",\n      id: 1,\n      profile: { __typename: \"Profile\", age: 30 },\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"User\",\n    id: 1,\n    profile: { __typename: \"Profile\" },\n  });\n});\n\ntest(\"handles nulls in child selection sets\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      profile {\n        id\n      }\n      ...ProfileFields\n    }\n    fragment ProfileFields on User {\n      profile {\n        id\n        fullName\n      }\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({ __typename: \"User\", profile: null }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(data).toEqual({ __typename: \"User\", profile: null });\n});\n\ntest(\"handles nulls in arrays\", () => {\n  const fragment = gql`\n    fragment UserFields on Query {\n      users {\n        profile {\n          id\n        }\n        ...ProfileFields\n      }\n    }\n    fragment ProfileFields on User {\n      profile {\n        id\n        fullName\n      }\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      users: [\n        null,\n        { __typename: \"User\", profile: null },\n        {\n          __typename: \"User\",\n          profile: { __typename: \"Profile\", id: \"1\", fullName: \"Test User\" },\n        },\n      ],\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(data).toEqual({\n    users: [\n      null,\n      { __typename: \"User\", profile: null },\n      { __typename: \"User\", profile: { __typename: \"Profile\", id: \"1\" } },\n    ],\n  });\n});\n\ntest(\"deep freezes the masked result if the original data is frozen\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      profile {\n        ...UserProfile\n      }\n    }\n\n    fragment UserProfile on User {\n      age\n    }\n  `;\n\n  const frozenData = maskFragment(\n    deepFreeze({\n      __typename: \"User\",\n      id: 1,\n      profile: { __typename: \"Profile\", age: 30 },\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  const nonFrozenData = maskFragment(\n    {\n      __typename: \"User\",\n      id: 1,\n      profile: { __typename: \"Profile\", age: 30 },\n    },\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(Object.isFrozen(frozenData)).toBe(true);\n  expect(Object.isFrozen(nonFrozenData)).toBe(false);\n});\n\ntest(\"does not mask inline fragment in fragment documents\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      ... @defer {\n        age\n      }\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({ __typename: \"User\", id: 1, age: 30 }),\n    fragment,\n    new InMemoryCache(),\n    \"UserFields\"\n  );\n\n  expect(data).toEqual({ __typename: \"User\", id: 1, age: 30 });\n});\n\ntest(\"throws when document contains more than 1 fragment without a fragmentName\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      ...UserProfile\n    }\n\n    fragment UserProfile on User {\n      age\n    }\n  `;\n\n  expect(() =>\n    maskFragment(\n      deepFreeze({ __typename: \"User\", id: 1, age: 30 }),\n      fragment,\n      new InMemoryCache()\n    )\n  ).toThrow(\n    new InvariantError(\n      \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n    )\n  );\n});\n\ntest(\"throws when fragment cannot be found within document\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      ...UserProfile\n    }\n\n    fragment UserProfile on User {\n      age\n    }\n  `;\n\n  expect(() =>\n    maskFragment(\n      deepFreeze({ __typename: \"User\", id: 1, age: 30 }),\n      fragment,\n      new InMemoryCache(),\n      \"ProfileFields\"\n    )\n  ).toThrow(\n    new InvariantError('Could not find fragment with name \"ProfileFields\".')\n  );\n});\n\ntest(\"maintains referential equality on fragment subtrees that did not change\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      profile {\n        ...ProfileFields\n      }\n      post {\n        id\n        title\n      }\n      industries {\n        ... on TechIndustry {\n          languageRequirements\n        }\n        ... on FinanceIndustry {\n          ...FinanceIndustryFields\n        }\n        ... on TradeIndustry {\n          id\n          yearsInBusiness\n          ...TradeIndustryFields\n        }\n      }\n      drinks {\n        ... on SportsDrink {\n          ...SportsDrinkFields\n        }\n        ... on Espresso {\n          __typename\n        }\n      }\n    }\n\n    fragment ProfileFields on Profile {\n      age\n    }\n\n    fragment FinanceIndustryFields on FinanceIndustry {\n      yearsInBusiness\n    }\n\n    fragment TradeIndustryFields on TradeIndustry {\n      languageRequirements\n    }\n\n    fragment SportsDrinkFields on SportsDrink {\n      saltContent\n    }\n  `;\n\n  const profile = {\n    __typename: \"Profile\",\n    age: 30,\n  };\n  const post = { __typename: \"Post\", id: 1, title: \"Test Post\" };\n  const industries = [\n    { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n    { __typename: \"FinanceIndustry\", yearsInBusiness: 10 },\n    {\n      __typename: \"TradeIndustry\",\n      id: 10,\n      yearsInBusiness: 15,\n      languageRequirements: [\"English\", \"German\"],\n    },\n  ];\n  const drinks = [\n    { __typename: \"Espresso\" },\n    { __typename: \"SportsDrink\", saltContent: \"1000mg\" },\n  ];\n  const user = deepFreeze({\n    __typename: \"User\",\n    id: 1,\n    profile,\n    post,\n    industries,\n    drinks,\n  });\n\n  const data = maskFragment(user, fragment, new InMemoryCache(), \"UserFields\");\n\n  expect(data).toEqual({\n    __typename: \"User\",\n    id: 1,\n    profile: { __typename: \"Profile\" },\n    post: { __typename: \"Post\", id: 1, title: \"Test Post\" },\n    industries: [\n      { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n      { __typename: \"FinanceIndustry\" },\n      { __typename: \"TradeIndustry\", id: 10, yearsInBusiness: 15 },\n    ],\n    drinks: [{ __typename: \"Espresso\" }, { __typename: \"SportsDrink\" }],\n  });\n\n  expect(data).not.toBe(user);\n  expect(data.profile).not.toBe(profile);\n  expect(data.post).toBe(post);\n  expect(data.industries).not.toBe(industries);\n  expect(data.industries[0]).toBe(industries[0]);\n  expect(data.industries[1]).not.toBe(industries[1]);\n  expect(data.industries[2]).not.toBe(industries[2]);\n  expect(data.drinks).not.toBe(drinks);\n  expect(data.drinks[0]).toBe(drinks[0]);\n  expect(data.drinks[1]).not.toBe(drinks[1]);\n});\n\ntest(\"maintains referential equality on fragment when no data is masked\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      age\n    }\n  `;\n\n  const user = { __typename: \"User\", id: 1, age: 30 };\n\n  const data = maskFragment(deepFreeze(user), fragment, new InMemoryCache());\n\n  expect(data).toBe(user);\n});\n\ntest(\"does not mask named fragments and returns original object when using `@unmask` directive\", () => {\n  const fragment = gql`\n    fragment UnmaskedFragment on User {\n      id\n      name\n      ...UserFields @unmask\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const fragmentData = deepFreeze({\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    age: 30,\n  });\n\n  const data = maskFragment(\n    fragmentData,\n    fragment,\n    new InMemoryCache(),\n    \"UnmaskedFragment\"\n  );\n\n  expect(data).toBe(fragmentData);\n});\n\ntest(\"warns when accessing unmasked fields when using `@unmask` directive with mode 'migrate'\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const fragment = gql`\n    fragment UnmaskedFragment on User {\n      id\n      name\n      ...UserFields @unmask(mode: \"migrate\")\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UnmaskedFragment\"\n  );\n\n  data.__typename;\n  data.id;\n  data.name;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.age;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"fragment 'UnmaskedFragment'\",\n    \"age\"\n  );\n\n  data.age;\n\n  // Ensure we only warn once for each masked field\n  expect(console.warn).toHaveBeenCalledTimes(1);\n});\n\ntest(\"maintains referential equality on `@unmask` fragment subtrees\", () => {\n  const fragment = gql`\n    fragment UserFields on User {\n      id\n      profile {\n        ...ProfileFields @unmask\n      }\n      post {\n        id\n        title\n      }\n      industries {\n        ... on TechIndustry {\n          languageRequirements\n        }\n        ... on FinanceIndustry {\n          ...FinanceIndustryFields\n        }\n        ... on TradeIndustry {\n          id\n          yearsInBusiness\n          ...TradeIndustryFields\n        }\n      }\n      drinks {\n        ... on SportsDrink {\n          ...SportsDrinkFields @unmask\n        }\n        ... on Espresso {\n          __typename\n        }\n      }\n    }\n\n    fragment ProfileFields on Profile {\n      age\n      ...ProfileSubfields @unmask\n    }\n\n    fragment ProfileSubfields on Profile {\n      name\n    }\n\n    fragment FinanceIndustryFields on FinanceIndustry {\n      yearsInBusiness\n    }\n\n    fragment TradeIndustryFields on TradeIndustry {\n      languageRequirements\n    }\n\n    fragment SportsDrinkFields on SportsDrink {\n      saltContent\n    }\n  `;\n\n  const profile = {\n    __typename: \"Profile\",\n    age: 30,\n    name: \"Test User\",\n  };\n  const post = { __typename: \"Post\", id: 1, title: \"Test Post\" };\n  const industries = [\n    { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n    { __typename: \"FinanceIndustry\", yearsInBusiness: 10 },\n    {\n      __typename: \"TradeIndustry\",\n      id: 10,\n      yearsInBusiness: 15,\n      languageRequirements: [\"English\", \"German\"],\n    },\n  ];\n  const drinks = [\n    { __typename: \"Espresso\" },\n    { __typename: \"SportsDrink\", saltContent: \"1000mg\" },\n  ];\n  const user = deepFreeze({\n    __typename: \"User\",\n    id: 1,\n    profile,\n    post,\n    industries,\n    drinks,\n  });\n\n  const data = maskFragment(user, fragment, new InMemoryCache(), \"UserFields\");\n\n  expect(data).toEqual({\n    __typename: \"User\",\n    id: 1,\n    profile: { __typename: \"Profile\", age: 30, name: \"Test User\" },\n    post: { __typename: \"Post\", id: 1, title: \"Test Post\" },\n    industries: [\n      { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n      { __typename: \"FinanceIndustry\" },\n      { __typename: \"TradeIndustry\", id: 10, yearsInBusiness: 15 },\n    ],\n    drinks: [\n      { __typename: \"Espresso\" },\n      { __typename: \"SportsDrink\", saltContent: \"1000mg\" },\n    ],\n  });\n\n  expect(data).not.toBe(user);\n  expect(data.profile).toBe(profile);\n  expect(data.post).toBe(post);\n  expect(data.industries).not.toBe(industries);\n  expect(data.industries[0]).toBe(industries[0]);\n  expect(data.industries[1]).not.toBe(industries[1]);\n  expect(data.industries[2]).not.toBe(industries[2]);\n  expect(data.drinks).toBe(drinks);\n  expect(data.drinks[0]).toBe(drinks[0]);\n  expect(data.drinks[1]).toBe(drinks[1]);\n});\n\ntest(\"masks child fragments of @unmask(mode: 'migrate')\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const fragment = gql`\n    fragment UnmaskedUser on User {\n      id\n      name\n      ...UserFields @unmask(mode: \"migrate\")\n    }\n\n    fragment UserFields on User {\n      age\n      ...UserSubfields\n      ...UserSubfields2 @unmask\n    }\n\n    fragment UserSubfields on User {\n      username\n    }\n\n    fragment UserSubfields2 on User {\n      email\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n      username: \"testuser\",\n      email: \"test@example.com\",\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UnmaskedUser\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    age: 30,\n    email: \"test@example.com\",\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"fragment 'UnmaskedUser'\",\n    \"age\"\n  );\n});\n\ntest(\"masks child fragments of @unmask\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const fragment = gql`\n    fragment UnmaskedUser on User {\n      id\n      name\n      ...UserFields @unmask\n    }\n    fragment UserFields on User {\n      age\n      ...UserSubfields\n      ...UserSubfields2 @unmask\n    }\n    fragment UserSubfields on User {\n      username\n    }\n    fragment UserSubfields2 on User {\n      email\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n      username: \"testuser\",\n      email: \"test@example.com\",\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"UnmaskedUser\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    age: 30,\n    email: \"test@example.com\",\n  });\n});\n\ntest(\"masks partial data\", () => {\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ...AdditionalFields\n    }\n\n    fragment AdditionalFields on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"__Person\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n    });\n  }\n});\n\ntest(\"unmasks partial data with @unmask\", () => {\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ...AdditionalFields @unmask\n    }\n\n    fragment AdditionalFields on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      sentAt: \"2024-01-01\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"__Person\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      recipient: { __typename: \"__Person\" },\n    });\n  }\n});\n\ntest('unmasks partial data with warnings with @unmask(mode: \"migrate\")', () => {\n  using consoleSpy = spyOnConsole(\"warn\");\n\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ...AdditionalFields @unmask(mode: \"migrate\")\n    }\n\n    fragment AdditionalFields on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    data.message;\n    data.__typename;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    data.__typename;\n    data.message;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.sentAt;\n    expect(console.warn).toHaveBeenCalledTimes(1);\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      sentAt: \"2024-01-01\",\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"__Person\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    data.__typename;\n    data.message;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.recipient;\n    // We do not warn on access to __typename\n    data.recipient.__typename;\n    expect(console.warn).toHaveBeenCalledTimes(1);\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      recipient: { __typename: \"__Person\" },\n    });\n  }\n});\n\ntest(\"masks partial deferred data\", () => {\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ... @defer {\n        sentAt\n        ...AdditionalFields\n      }\n    }\n\n    fragment AdditionalFields on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"__Person\", name: \"Alice\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      sentAt: \"2024-01-01\",\n    });\n  }\n});\n\ntest(\"unmasks partial deferred data with @unmask\", () => {\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ... @defer {\n        sentAt\n        ...AdditionalFields @unmask\n      }\n    }\n\n    fragment AdditionalFields on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"__Person\", name: \"Alice\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      sentAt: \"2024-01-01\",\n      recipient: { __typename: \"__Person\", name: \"Alice\" },\n    });\n  }\n});\n\ntest('unmasks partial deferred data with warnings with @unmask(mode: \"migrate\")', () => {\n  using consoleSpy = spyOnConsole(\"warn\");\n\n  const fragment = gql`\n    fragment GreetingFields on Greeting {\n      message\n      ... @defer {\n        sentAt\n        ...AdditionalFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment AdditionalFields on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskFragment(\n      deepFreeze({ message: \"Hello world\", __typename: \"Greeting\" }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    expect(data).toEqual({\n      message: \"Hello world\",\n      __typename: \"Greeting\",\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskFragment(\n      deepFreeze({\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"__Person\", name: \"Alice\" },\n      }),\n      fragment,\n      new InMemoryCache(),\n      \"GreetingFields\"\n    );\n\n    data.message;\n    data.sentAt;\n    data.__typename;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.recipient;\n    data.recipient.name;\n    // We do not warn on access to __typename\n    data.recipient.__typename;\n    expect(console.warn).toHaveBeenCalledTimes(2);\n\n    expect(data).toEqual({\n      __typename: \"Greeting\",\n      message: \"Hello world\",\n      sentAt: \"2024-01-01\",\n      recipient: { __typename: \"__Person\", name: \"Alice\" },\n    });\n  }\n});\n\ntest(\"masks results with primitive arrays\", () => {\n  const fragment = gql`\n    fragment ListingFragment on Listing {\n      id\n      reviews\n      ...ListingFields\n    }\n\n    fragment ListingFields on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n      amenities: [\"pool\", \"hot tub\", \"backyard\"],\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"ListingFragment\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"Listing\",\n    id: \"1\",\n    reviews: [5, 5, 3, 4],\n  });\n});\n\ntest(\"unmasks results with primitive arrays with @unmask\", () => {\n  const fragment = gql`\n    fragment ListingFragment on Listing {\n      id\n      reviews\n      ...ListingFields @unmask\n    }\n\n    fragment ListingFields on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n      amenities: [\"pool\", \"hot tub\", \"backyard\"],\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"ListingFragment\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"Listing\",\n    id: \"1\",\n    reviews: [5, 5, 3, 4],\n    amenities: [\"pool\", \"hot tub\", \"backyard\"],\n  });\n});\n\ntest('unmasks results with warnings with primitive arrays with @unmask(mode: \"migrate\")', () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const fragment = gql`\n    fragment ListingFragment on Listing {\n      id\n      reviews\n      ...ListingFields @unmask(mode: \"migrate\")\n    }\n\n    fragment ListingFields on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskFragment(\n    deepFreeze({\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n      amenities: [\"pool\", \"hot tub\", \"backyard\"],\n    }),\n    fragment,\n    new InMemoryCache(),\n    \"ListingFragment\"\n  );\n\n  data.__typename;\n  data.id;\n  data.reviews;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.amenities;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"fragment 'ListingFragment'\",\n    \"amenities\"\n  );\n\n  expect(data).toEqual({\n    __typename: \"Listing\",\n    id: \"1\",\n    reviews: [5, 5, 3, 4],\n    amenities: [\"pool\", \"hot tub\", \"backyard\"],\n  });\n});\n"
  },
  {
    "path": "src/masking/__tests__/maskOperation.test.ts",
    "content": "import { gql, InMemoryCache } from \"@apollo/client\";\nimport { maskOperation } from \"@apollo/client/masking\";\nimport { spyOnConsole, withProdMode } from \"@apollo/client/testing/internal\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { deepFreeze } from \"../../utilities/internal/deepFreeze.js\";\n\ntest(\"throws when passing document with no operation to maskOperation\", () => {\n  const document = gql`\n    fragment Foo on Bar {\n      foo\n    }\n  `;\n\n  expect(() => maskOperation({}, document, new InMemoryCache())).toThrow(\n    new InvariantError(\n      \"Expected a parsed GraphQL document with a query, mutation, or subscription.\"\n    )\n  );\n});\n\ntest(\"throws when passing string query to maskOperation\", () => {\n  const document = `\n    query Foo {\n      foo\n    }\n  `;\n\n  expect(() =>\n    maskOperation(\n      {},\n      // @ts-expect-error\n      document,\n      new InMemoryCache()\n    )\n  ).toThrow(\n    new InvariantError(\n      'Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql'\n    )\n  );\n});\n\ntest(\"throws when passing multiple operations to maskOperation\", () => {\n  const document = gql`\n    query Foo {\n      foo\n    }\n\n    query Bar {\n      bar\n    }\n  `;\n\n  expect(() => maskOperation({}, document, new InMemoryCache())).toThrow(\n    new InvariantError(\"Ambiguous GraphQL document: contains 2 operations\")\n  );\n});\n\ntest(\"returns null when data is null\", () => {\n  const query = gql`\n    query {\n      foo\n      ...QueryFields\n    }\n\n    fragment QueryFields on Query {\n      bar\n    }\n  `;\n\n  const data = maskOperation(null, query, new InMemoryCache());\n\n  expect(data).toBe(null);\n});\n\ntest(\"returns undefined when data is undefined\", () => {\n  const query = gql`\n    query {\n      foo\n      ...QueryFields\n    }\n\n    fragment QueryFields on Query {\n      bar\n    }\n  `;\n\n  const data = maskOperation(undefined, query, new InMemoryCache());\n\n  expect(data).toBe(undefined);\n});\n\ntest(\"strips top-level fragment data from query\", () => {\n  const query = gql`\n    query {\n      foo\n      ...QueryFields\n    }\n\n    fragment QueryFields on Query {\n      bar\n    }\n  `;\n\n  const data = maskOperation(\n    { foo: true, bar: true },\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({ foo: true });\n});\n\ntest(\"strips fragment data from nested object\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({ user: { __typename: \"User\", id: 1, name: \"Test User\" } }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({ user: { __typename: \"User\", id: 1 } });\n});\n\ntest(\"retains __typename in the result\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        profile {\n          id\n        }\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on Query {\n      age\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        profile: { __typename: \"Profile\", id: 2 },\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      profile: { __typename: \"Profile\", id: 2 },\n    },\n  });\n});\n\ntest(\"masks fragments from nested objects when query gets fields from same object\", () => {\n  const query = gql`\n    query {\n      user {\n        profile {\n          __typename\n          id\n        }\n        ...UserFields\n      }\n    }\n    fragment UserFields on User {\n      profile {\n        id\n        fullName\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        profile: { __typename: \"Profile\", id: \"1\", fullName: \"Test User\" },\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      profile: { __typename: \"Profile\", id: \"1\" },\n    },\n  });\n});\n\ntest(\"masks fragments from nested objects when query gets fields from same object\", () => {\n  const query = gql`\n    query {\n      user {\n        ...FragmentA @unmask\n        ...FragmentB\n        ...FragmentC @unmask\n      }\n    }\n\n    fragment FragmentA on User {\n      this {\n        is {\n          very {\n            deeply {\n              nested {\n                a\n              }\n            }\n          }\n        }\n      }\n    }\n    fragment FragmentB on User {\n      this {\n        is {\n          very {\n            deeply {\n              nested {\n                b\n              }\n            }\n          }\n        }\n      }\n    }\n    fragment FragmentC on User {\n      this {\n        is {\n          very {\n            deeply {\n              nested {\n                c\n              }\n            }\n          }\n        }\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        this: {\n          is: [\n            {\n              very: {\n                deeply: [\n                  {\n                    nested: {\n                      a: 1,\n                      b: 2,\n                      c: 3,\n                    },\n                  },\n                ],\n              },\n            },\n          ],\n        },\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      this: {\n        is: [\n          {\n            very: {\n              deeply: [\n                {\n                  nested: {\n                    a: 1,\n                    c: 3,\n                  },\n                },\n              ],\n            },\n          },\n        ],\n      },\n    },\n  });\n});\n\ntest(\"handles nulls in child selection sets\", () => {\n  const query = gql`\n    query {\n      user {\n        profile {\n          id\n        }\n        ...UserFields\n      }\n    }\n    fragment UserFields on User {\n      profile {\n        id\n        fullName\n      }\n    }\n  `;\n\n  const nullUser = maskOperation(\n    deepFreeze({ user: null }),\n    query,\n    new InMemoryCache()\n  );\n  const nullProfile = maskOperation(\n    deepFreeze({ user: { __typename: \"User\", profile: null } }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(nullUser).toEqual({ user: null });\n  expect(nullProfile).toEqual({\n    user: { __typename: \"User\", profile: null },\n  });\n});\n\ntest(\"handles nulls in arrays\", () => {\n  const query = gql`\n    query {\n      users {\n        profile {\n          id\n        }\n        ...UserFields\n      }\n    }\n    fragment UserFields on User {\n      profile {\n        id\n        fullName\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      users: [\n        null,\n        { __typename: \"User\", profile: null },\n        {\n          __typename: \"User\",\n          profile: { __typename: \"Profile\", id: \"1\", fullName: \"Test User\" },\n        },\n      ],\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    users: [\n      null,\n      { __typename: \"User\", profile: null },\n      { __typename: \"User\", profile: { __typename: \"Profile\", id: \"1\" } },\n    ],\n  });\n});\n\ntest(\"deep freezes the masked result if the original data is frozen\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const frozenData = maskOperation(\n    deepFreeze({ user: { __typename: \"User\", id: 1, name: \"Test User\" } }),\n    query,\n    new InMemoryCache()\n  );\n\n  const nonFrozenData = maskOperation(\n    { user: { __typename: \"User\", id: 1, name: \"Test User\" } },\n    query,\n    new InMemoryCache()\n  );\n\n  expect(Object.isFrozen(frozenData)).toBe(true);\n  expect(Object.isFrozen(nonFrozenData)).toBe(false);\n});\n\ntest(\"strips fragment data from arrays\", () => {\n  const query = gql`\n    query {\n      users {\n        id\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      users: [\n        { __typename: \"User\", id: 1, name: \"Test User 1\" },\n        { __typename: \"User\", id: 2, name: \"Test User 2\" },\n      ],\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    users: [\n      { __typename: \"User\", id: 1 },\n      { __typename: \"User\", id: 2 },\n    ],\n  });\n});\n\ntest(\"strips multiple fragments in the same selection set\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ...UserProfileFields\n        ...UserAvatarFields\n      }\n    }\n\n    fragment UserProfileFields on User {\n      age\n    }\n\n    fragment UserAvatarFields on User {\n      avatarUrl\n    }\n  `;\n\n  const data = maskOperation(\n    {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        age: 30,\n        avatarUrl: \"https://example.com/avatar.jpg\",\n      },\n    },\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: { __typename: \"User\", id: 1 },\n  });\n});\n\ntest(\"strips multiple fragments across different selection sets\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ...UserFields\n      }\n      post {\n        id\n        ...PostFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n\n    fragment PostFields on Post {\n      title\n    }\n  `;\n\n  const data = maskOperation(\n    {\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"test user\",\n      },\n      post: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Test Post\",\n      },\n    },\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: { __typename: \"User\", id: 1 },\n    post: { __typename: \"Post\", id: 1 },\n  });\n});\n\ntest(\"leaves overlapping fields in query\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        birthdate\n        ...UserProfileFields\n      }\n    }\n\n    fragment UserProfileFields on User {\n      birthdate\n      name\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        birthdate: \"1990-01-01\",\n        name: \"Test User\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: { __typename: \"User\", id: 1, birthdate: \"1990-01-01\" },\n  });\n});\n\ntest(\"does not strip inline fragments\", () => {\n  const cache = new InMemoryCache({\n    possibleTypes: { Profile: [\"UserProfile\"] },\n  });\n\n  const query = gql`\n    query {\n      user {\n        id\n        ... @defer {\n          name\n        }\n      }\n      profile {\n        ... on UserProfile {\n          avatarUrl\n        }\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n      profile: {\n        __typename: \"UserProfile\",\n        avatarUrl: \"https://example.com/avatar.jpg\",\n      },\n    }),\n    query,\n    cache\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n    },\n    profile: {\n      __typename: \"UserProfile\",\n      avatarUrl: \"https://example.com/avatar.jpg\",\n    },\n  });\n});\n\ntest(\"strips named fragments inside inline fragments\", () => {\n  const cache = new InMemoryCache({\n    possibleTypes: { Industry: [\"TechIndustry\"], Profile: [\"UserProfile\"] },\n  });\n  const query = gql`\n    query {\n      user {\n        id\n        ... @defer {\n          name\n          ...UserFields\n        }\n      }\n      profile {\n        ... on UserProfile {\n          avatarUrl\n          ...UserProfileFields\n        }\n        industry {\n          ... on TechIndustry {\n            ...TechIndustryFields\n          }\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n\n    fragment UserProfileFields on UserProfile {\n      hometown\n    }\n\n    fragment TechIndustryFields on TechIndustry {\n      favoriteLanguage\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n      profile: {\n        __typename: \"UserProfile\",\n        avatarUrl: \"https://example.com/avatar.jpg\",\n        industry: {\n          __typename: \"TechIndustry\",\n          primaryLanguage: \"TypeScript\",\n        },\n      },\n    }),\n    query,\n    cache\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n    },\n    profile: {\n      __typename: \"UserProfile\",\n      avatarUrl: \"https://example.com/avatar.jpg\",\n      industry: { __typename: \"TechIndustry\" },\n    },\n  });\n});\n\ntest(\"handles objects with no matching inline fragment condition\", () => {\n  const cache = new InMemoryCache({\n    possibleTypes: {\n      Drink: [\"HotChocolate\", \"Juice\"],\n    },\n  });\n\n  const query = gql`\n    query {\n      drinks {\n        id\n        ... on Juice {\n          fruitBase\n        }\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      drinks: [\n        { __typename: \"HotChocolate\", id: 1 },\n        { __typename: \"Juice\", id: 2, fruitBase: \"Strawberry\" },\n      ],\n    }),\n    query,\n    cache\n  );\n\n  expect(data).toEqual({\n    drinks: [\n      { __typename: \"HotChocolate\", id: 1 },\n      { __typename: \"Juice\", id: 2, fruitBase: \"Strawberry\" },\n    ],\n  });\n});\n\ntest(\"can handle fragment spreads in inline fragments with mix masked and @unmask\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ... {\n          ...UserFields\n          ...ProfileFields @unmask\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n\n    fragment ProfileFields on User {\n      username\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        username: \"testuser\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      username: \"testuser\",\n    },\n  });\n});\n\ntest(\"can handle overlapping fragment spreads in inline fragments with mix masked and @unmask\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        ... {\n          ...UserFields\n          ...ProfileFields @unmask\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      username\n      name\n    }\n\n    fragment ProfileFields on User {\n      username\n      email\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        username: \"testuser\",\n        email: \"testuser@example.com\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      username: \"testuser\",\n      email: \"testuser@example.com\",\n    },\n  });\n});\n\ntest('can handle fragment spreads in inline fragments with mix masked and @unmask(mode: \"migrate\")', () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query GetUser {\n      user {\n        id\n        ... @defer {\n          ...UserFields\n          ...ProfileFields @unmask(mode: \"migrate\")\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n\n    fragment ProfileFields on User {\n      username\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        username: \"testuser\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.user.__typename;\n  data.user.id;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.user.username;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'GetUser'\",\n    \"user.username\"\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      username: \"testuser\",\n    },\n  });\n});\n\ntest('can handle overlapping fragment spreads in inline fragments with mix masked and @unmask(mode: \"migrate\")', () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query GetUser {\n      user {\n        id\n        ... {\n          ...UserFields\n          ...ProfileFields @unmask(mode: \"migrate\")\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      username\n      name\n    }\n\n    fragment ProfileFields on User {\n      username\n      email\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        username: \"testuser\",\n        email: \"testuser@example.com\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.user.__typename;\n  data.user.id;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.user.username;\n  data.user.email;\n\n  expect(console.warn).toHaveBeenCalledTimes(2);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'GetUser'\",\n    \"user.username\"\n  );\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'GetUser'\",\n    \"user.email\"\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      username: \"testuser\",\n      email: \"testuser@example.com\",\n    },\n  });\n});\n\ntest(\"handles field aliases\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        fullName: name\n        ... @defer {\n          userAddress: address\n        }\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      user: {\n        __typename: \"User\",\n        id: 1,\n        fullName: \"Test User\",\n        userAddress: \"1234 Main St\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      fullName: \"Test User\",\n      userAddress: \"1234 Main St\",\n    },\n  });\n});\n\ntest(\"handles overlapping fields inside multiple inline fragments\", () => {\n  const cache = new InMemoryCache({\n    possibleTypes: {\n      Drink: [\n        \"Espresso\",\n        \"Latte\",\n        \"Cappuccino\",\n        \"Cortado\",\n        \"Juice\",\n        \"HotChocolate\",\n      ],\n      Espresso: [\"Latte\", \"Cappuccino\", \"Cortado\"],\n    },\n  });\n  const query = gql`\n    query {\n      drinks {\n        id\n        ... @defer {\n          amount\n        }\n        ... on Espresso {\n          milkType\n          ... on Latte {\n            flavor {\n              name\n              ...FlavorFields\n            }\n          }\n          ... on Cappuccino {\n            roast\n          }\n          ... on Cortado {\n            ...CortadoFields\n          }\n        }\n        ... on Latte {\n          ... @defer {\n            shots\n          }\n        }\n        ... on Juice {\n          ...JuiceFields\n        }\n        ... on HotChocolate {\n          milkType\n          ...HotChocolateFields\n        }\n      }\n    }\n\n    fragment JuiceFields on Juice {\n      fruitBase\n    }\n\n    fragment HotChocolateFields on HotChocolate {\n      chocolateType\n    }\n\n    fragment FlavorFields on Flavor {\n      sweetness\n    }\n\n    fragment CortadoFields on Cortado {\n      temperature\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      drinks: [\n        {\n          __typename: \"Latte\",\n          id: 1,\n          amount: 12,\n          shots: 2,\n          milkType: \"Cow\",\n          flavor: {\n            __typename: \"Flavor\",\n            name: \"Cookie Butter\",\n            sweetness: \"high\",\n          },\n        },\n        {\n          __typename: \"Cappuccino\",\n          id: 2,\n          amount: 12,\n          milkType: \"Cow\",\n          roast: \"medium\",\n        },\n        {\n          __typename: \"Cortado\",\n          id: 3,\n          amount: 12,\n          milkType: \"Cow\",\n          temperature: 150,\n        },\n        { __typename: \"Juice\", id: 4, amount: 10, fruitBase: \"Apple\" },\n        {\n          __typename: \"HotChocolate\",\n          id: 5,\n          amount: 8,\n          milkType: \"Cow\",\n          chocolateType: \"dark\",\n        },\n      ],\n    }),\n    query,\n    cache\n  );\n\n  expect(data).toEqual({\n    drinks: [\n      {\n        __typename: \"Latte\",\n        id: 1,\n        amount: 12,\n        shots: 2,\n        milkType: \"Cow\",\n        flavor: {\n          __typename: \"Flavor\",\n          name: \"Cookie Butter\",\n        },\n      },\n      {\n        __typename: \"Cappuccino\",\n        id: 2,\n        amount: 12,\n        milkType: \"Cow\",\n        roast: \"medium\",\n      },\n      {\n        __typename: \"Cortado\",\n        id: 3,\n        amount: 12,\n        milkType: \"Cow\",\n      },\n      { __typename: \"Juice\", id: 4, amount: 10 },\n      {\n        __typename: \"HotChocolate\",\n        id: 5,\n        amount: 8,\n        milkType: \"Cow\",\n      },\n    ],\n  });\n});\n\ntest(\"does nothing if there are no fragments to mask\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        name\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({ user: { __typename: \"User\", id: 1, name: \"Test User\" } }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    user: { __typename: \"User\", id: 1, name: \"Test User\" },\n  });\n});\n\ntest(\"maintains referential equality on subtrees that did not change\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        profile {\n          avatarUrl\n        }\n        ...UserFields\n      }\n      post {\n        id\n        title\n      }\n      authors {\n        id\n        name\n      }\n      industries {\n        ... on TechIndustry {\n          languageRequirements\n        }\n        ... on FinanceIndustry {\n          ...FinanceIndustryFields\n        }\n        ... on TradeIndustry {\n          id\n          yearsInBusiness\n          ...TradeIndustryFields\n        }\n      }\n      drink {\n        ... on SportsDrink {\n          saltContent\n        }\n        ... on Espresso {\n          __typename\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n\n    fragment FinanceIndustryFields on FinanceIndustry {\n      yearsInBusiness\n    }\n\n    fragment TradeIndustryFields on TradeIndustry {\n      languageRequirements\n    }\n  `;\n\n  const profile = {\n    __typename: \"Profile\",\n    avatarUrl: \"https://example.com/avatar.jpg\",\n  };\n  const user = { __typename: \"User\", id: 1, name: \"Test User\", profile };\n  const post = { __typename: \"Post\", id: 1, title: \"Test Post\" };\n  const authors = [{ __typename: \"Author\", id: 1, name: \"A Author\" }];\n  const industries = [\n    { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n    { __typename: \"FinanceIndustry\", yearsInBusiness: 10 },\n    {\n      __typename: \"TradeIndustry\",\n      id: 10,\n      yearsInBusiness: 15,\n      languageRequirements: [\"English\", \"German\"],\n    },\n  ];\n  const drink = { __typename: \"Espresso\" };\n  const originalData = deepFreeze({ user, post, authors, industries, drink });\n\n  const data = maskOperation(originalData, query, new InMemoryCache());\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      profile: {\n        __typename: \"Profile\",\n        avatarUrl: \"https://example.com/avatar.jpg\",\n      },\n    },\n    post: { __typename: \"Post\", id: 1, title: \"Test Post\" },\n    authors: [{ __typename: \"Author\", id: 1, name: \"A Author\" }],\n    industries: [\n      { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n      { __typename: \"FinanceIndustry\" },\n      { __typename: \"TradeIndustry\", id: 10, yearsInBusiness: 15 },\n    ],\n    drink: { __typename: \"Espresso\" },\n  });\n\n  expect(data).not.toBe(originalData);\n  expect(data.user).not.toBe(user);\n  expect(data.user.profile).toBe(profile);\n  expect(data.post).toBe(post);\n  expect(data.authors).toBe(authors);\n  expect(data.industries).not.toBe(industries);\n  expect(data.industries[0]).toBe(industries[0]);\n  expect(data.industries[1]).not.toBe(industries[1]);\n  expect(data.industries[2]).not.toBe(industries[2]);\n  expect(data.drink).toBe(drink);\n});\n\ntest(\"maintains referential equality the entire result if there are no fragments\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        name\n      }\n    }\n  `;\n\n  const originalData = deepFreeze({\n    user: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n    },\n  });\n\n  const data = maskOperation(originalData, query, new InMemoryCache());\n\n  expect(data).toBe(originalData);\n});\n\ntest(\"does not mask named fragment fields and returns original object when using `@unmask` directive\", () => {\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const queryData = deepFreeze({\n    currentUser: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n    },\n  });\n\n  const data = maskOperation(queryData, query, new InMemoryCache());\n\n  expect(data).toBe(queryData);\n});\n\ntest(\"maintains referential equality on subtrees that contain @unmask\", () => {\n  const query = gql`\n    query {\n      user {\n        id\n        profile {\n          avatarUrl\n        }\n        ...UserFields @unmask\n      }\n      post {\n        id\n        title\n      }\n      authors {\n        id\n        name\n      }\n      industries {\n        ... on TechIndustry {\n          ...TechIndustryFields @unmask\n        }\n        ... on FinanceIndustry {\n          ...FinanceIndustryFields\n        }\n        ... on TradeIndustry {\n          id\n          yearsInBusiness\n          ...TradeIndustryFields @unmask\n        }\n      }\n    }\n\n    fragment UserFields on User {\n      name\n      ...UserSubfields @unmask\n    }\n\n    fragment UserSubfields on User {\n      age\n    }\n\n    fragment FinanceIndustryFields on FinanceIndustry {\n      yearsInBusiness\n    }\n\n    fragment TradeIndustryFields on TradeIndustry {\n      languageRequirements\n    }\n\n    fragment TechIndustryFields on TechIndustry {\n      languageRequirements\n      ...TechIndustrySubFields\n    }\n\n    fragment TechIndustrySubFields on TechIndustry {\n      focus\n    }\n  `;\n\n  const profile = {\n    __typename: \"Profile\",\n    avatarUrl: \"https://example.com/avatar.jpg\",\n  };\n  const user = {\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    profile,\n    age: 30,\n  };\n  const post = { __typename: \"Post\", id: 1, title: \"Test Post\" };\n  const authors = [{ __typename: \"Author\", id: 1, name: \"A Author\" }];\n  const industries = [\n    {\n      __typename: \"TechIndustry\",\n      languageRequirements: [\"TypeScript\"],\n      focus: \"innovation\",\n    },\n    { __typename: \"FinanceIndustry\", yearsInBusiness: 10 },\n    {\n      __typename: \"TradeIndustry\",\n      id: 10,\n      yearsInBusiness: 15,\n      languageRequirements: [\"English\", \"German\"],\n    },\n  ];\n  const originalData = deepFreeze({ user, post, authors, industries });\n\n  const data = maskOperation(originalData, query, new InMemoryCache());\n\n  expect(data).toEqual({\n    user: {\n      __typename: \"User\",\n      name: \"Test User\",\n      id: 1,\n      profile: {\n        __typename: \"Profile\",\n        avatarUrl: \"https://example.com/avatar.jpg\",\n      },\n      age: 30,\n    },\n    post: { __typename: \"Post\", id: 1, title: \"Test Post\" },\n    authors: [{ __typename: \"Author\", id: 1, name: \"A Author\" }],\n    industries: [\n      { __typename: \"TechIndustry\", languageRequirements: [\"TypeScript\"] },\n      { __typename: \"FinanceIndustry\" },\n      {\n        __typename: \"TradeIndustry\",\n        id: 10,\n        yearsInBusiness: 15,\n        languageRequirements: [\"English\", \"German\"],\n      },\n    ],\n  });\n\n  expect(data).not.toBe(originalData);\n  expect(data.user).toBe(user);\n  expect(data.user.profile).toBe(profile);\n  expect(data.post).toBe(post);\n  expect(data.authors).toBe(authors);\n  expect(data.industries).not.toBe(industries);\n  expect(data.industries[0]).not.toBe(industries[0]);\n  expect(data.industries[1]).not.toBe(industries[1]);\n  expect(data.industries[2]).toBe(industries[2]);\n});\n\ntest(\"warns when accessing unmasked fields when using `@unmask` directive with mode 'migrate'\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const anonymousQuery = gql`\n    query {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const currentUser = {\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    age: 30,\n  };\n\n  const cache = new InMemoryCache();\n\n  const data = maskOperation(deepFreeze({ currentUser }), query, cache);\n\n  const dataFromAnonymous = maskOperation(\n    { currentUser },\n    anonymousQuery,\n    cache\n  );\n\n  data.currentUser.age;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.age\"\n  );\n\n  dataFromAnonymous.currentUser.age;\n\n  expect(console.warn).toHaveBeenCalledTimes(2);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"anonymous query\",\n    \"currentUser.age\"\n  );\n\n  data.currentUser.age;\n  dataFromAnonymous.currentUser.age;\n\n  // Ensure we only warn once for each masked field\n  expect(console.warn).toHaveBeenCalledTimes(2);\n});\n\ntest(\"does not warn when accessing unmasked fields when using `@unmask` directive with mode 'migrate' in non-DEV mode\", () => {\n  using _ = withProdMode();\n  using __ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  const age = data.currentUser.age;\n\n  expect(age).toBe(30);\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"warns when accessing unmasked fields in arrays with mode: 'migrate'\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query UnmaskedQuery {\n      users {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      users: [\n        { __typename: \"User\", id: 1, name: \"John Doe\", age: 30 },\n        { __typename: \"User\", id: 2, name: \"Jane Doe\", age: 30 },\n      ],\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.users[0].age;\n  data.users[1].age;\n\n  expect(console.warn).toHaveBeenCalledTimes(2);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"users[0].age\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"users[1].age\"\n  );\n});\n\ntest(\"can mix and match masked vs unmasked fragment fields with proper warnings\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask\n      }\n    }\n\n    fragment UserFields on User {\n      age\n      profile {\n        email\n        ... @defer {\n          username\n        }\n        ...ProfileFields\n      }\n      skills {\n        name\n        ...SkillFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment ProfileFields on Profile {\n      settings {\n        darkMode\n      }\n    }\n\n    fragment SkillFields on Skill {\n      description\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n        profile: {\n          __typename: \"Profile\",\n          email: \"testuser@example.com\",\n          username: \"testuser\",\n          settings: {\n            __typename: \"Settings\",\n            darkMode: true,\n          },\n        },\n        skills: [\n          {\n            __typename: \"Skill\",\n            name: \"Skill 1\",\n            description: \"Skill 1 description\",\n          },\n          {\n            __typename: \"Skill\",\n            name: \"Skill 2\",\n            description: \"Skill 2 description\",\n          },\n        ],\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    currentUser: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n      profile: {\n        __typename: \"Profile\",\n        email: \"testuser@example.com\",\n        username: \"testuser\",\n      },\n      skills: [\n        {\n          __typename: \"Skill\",\n          name: \"Skill 1\",\n          description: \"Skill 1 description\",\n        },\n        {\n          __typename: \"Skill\",\n          name: \"Skill 2\",\n          description: \"Skill 2 description\",\n        },\n      ],\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(2);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.skills[0].description\"\n  );\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.skills[1].description\"\n  );\n});\n\ntest(\"masks child fragments of @unmask(mode: 'migrate')\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n      ...UserSubfields\n      ...UserSubfields2 @unmask\n    }\n\n    fragment UserSubfields on User {\n      username\n    }\n\n    fragment UserSubfields2 on User {\n      email\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n        username: \"testuser\",\n        email: \"test@example.com\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    currentUser: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n      email: \"test@example.com\",\n    },\n  });\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.age\"\n  );\n});\n\ntest(\"masks child fragments of @unmask\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask\n      }\n    }\n    fragment UserFields on User {\n      age\n      ...UserSubfields\n      ...UserSubfields2 @unmask\n    }\n    fragment UserSubfields on User {\n      username\n    }\n    fragment UserSubfields2 on User {\n      email\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n        username: \"testuser\",\n        email: \"test@example.com\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    currentUser: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 30,\n      email: \"test@example.com\",\n    },\n  });\n});\n\ntest(\"warns when accessing unmasked fields with complex selections with mode: 'migrate'\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      age\n      profile {\n        email\n        ... @defer {\n          username\n        }\n        ...ProfileFields @unmask(mode: \"migrate\")\n      }\n      skills {\n        name\n        ...SkillFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment ProfileFields on Profile {\n      settings {\n        dark: darkMode\n      }\n    }\n\n    fragment SkillFields on Skill {\n      description\n    }\n  `;\n\n  const currentUser = {\n    __typename: \"User\",\n    id: 1,\n    name: \"Test User\",\n    age: 30,\n    profile: {\n      __typename: \"Profile\",\n      email: \"testuser@example.com\",\n      username: \"testuser\",\n      settings: {\n        __typename: \"Settings\",\n        dark: true,\n      },\n    },\n    skills: [\n      {\n        __typename: \"Skill\",\n        name: \"Skill 1\",\n        description: \"Skill 1 description\",\n      },\n      {\n        __typename: \"Skill\",\n        name: \"Skill 2\",\n        description: \"Skill 2 description\",\n      },\n    ],\n  };\n\n  const data = maskOperation(\n    deepFreeze({ currentUser }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.currentUser.age;\n  data.currentUser.profile.email;\n  data.currentUser.profile.username;\n  data.currentUser.profile.settings;\n  data.currentUser.profile.settings.dark;\n  data.currentUser.skills[0].description;\n  data.currentUser.skills[1].description;\n\n  expect(console.warn).toHaveBeenCalledTimes(9);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.age\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.profile\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.profile.email\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.profile.username\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.profile.settings\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.profile.settings.dark\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.skills\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.skills[0].description\"\n  );\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'UnmaskedQuery'\",\n    \"currentUser.skills[1].description\"\n  );\n});\n\ntest(\"does not warn when accessing fields shared between the query and fragment with mode: 'migrate'\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        age\n        ...UserFields @unmask(mode: \"migrate\")\n        email\n      }\n    }\n\n    fragment UserFields on User {\n      age\n      email\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n        email: \"testuser@example.com\",\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.currentUser.age;\n  data.currentUser.email;\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"does not warn accessing fields with `@unmask` without mode argument\", () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query UnmaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields @unmask\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.currentUser.age;\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\n// https://github.com/apollographql/apollo-client/issues/12127\ntest('handles interface types when using @unmask(mode: \"migrate\")', async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query PlaybackStateSubscriberQuery {\n      playbackState {\n        __typename\n        ...PlaybackStateFragment @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment PlaybackStateFragment on PlaybackState {\n      item {\n        __typename\n        id\n\n        ... on Track {\n          album {\n            __typename\n            id\n          }\n        }\n\n        ... on Episode {\n          show {\n            __typename\n            id\n          }\n        }\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    {\n      playbackState: {\n        __typename: \"PlaybackState\",\n        item: {\n          __typename: \"Track\",\n          id: \"1\",\n          album: {\n            __typename: \"Album\",\n            id: \"2\",\n          },\n        },\n      },\n    },\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    playbackState: {\n      __typename: \"PlaybackState\",\n      item: {\n        __typename: \"Track\",\n        id: \"1\",\n        album: {\n          __typename: \"Album\",\n          id: \"2\",\n        },\n      },\n    },\n  });\n});\n\ntest('handles overlapping types when subtype has accessor warnings with @unmask(mode: \"migrate\")', async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query PlaylistQuery {\n      playlist {\n        ...PlaylistFragment @unmask(mode: \"migrate\")\n        id\n        name\n        album {\n          id\n          tracks {\n            id\n            __typename\n          }\n          __typename\n        }\n        artist {\n          id\n          topTracks {\n            id\n            __typename\n          }\n          __typename\n        }\n        __typename\n\n        ...PlaylistTitleCell @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment PlaylistFragment on Playlist {\n      album {\n        id\n        images {\n          url\n          __typename\n        }\n        tracks {\n          id\n          name\n          __typename\n        }\n        __typename\n      }\n    }\n\n    fragment PlaylistTitleCell on Playlist {\n      artist {\n        id\n        images {\n          url\n          __typename\n        }\n        topTracks {\n          id\n          name\n          __typename\n        }\n        __typename\n      }\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      playlist: {\n        id: \"1\",\n        name: \"Playlist\",\n        album: {\n          id: \"2RSIoPew2TOy41ASHpzOx3\",\n          __typename: \"Album\",\n          images: [{ url: \"https://i.scdn.co/image/1\", __typename: \"Image\" }],\n          tracks: [{ id: \"1\", name: \"Track 1\", __typename: \"Track\" }],\n        },\n        artist: {\n          id: \"2\",\n          __typename: \"Artist\",\n          images: [{ url: \"https://i.scdn.co/image/1\", __typename: \"Image\" }],\n          topTracks: [{ id: \"2\", name: \"Track 2\", __typename: \"Track\" }],\n        },\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.playlist.album;\n  data.playlist.album.id;\n  data.playlist.album.__typename;\n  data.playlist.album.tracks[0].id;\n  data.playlist.album.tracks[0].__typename;\n  data.playlist.artist;\n  data.playlist.artist.id;\n  data.playlist.artist.__typename;\n  data.playlist.artist.topTracks[0].id;\n  data.playlist.artist.topTracks[0].__typename;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.playlist.album.images;\n  data.playlist.album.tracks[0].name;\n  data.playlist.artist.images;\n  data.playlist.artist.topTracks[0].name;\n\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'PlaylistQuery'\",\n    \"playlist.album.images\"\n  );\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'PlaylistQuery'\",\n    \"playlist.album.tracks[0].name\"\n  );\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'PlaylistQuery'\",\n    \"playlist.artist.images\"\n  );\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'PlaylistQuery'\",\n    \"playlist.artist.topTracks[0].name\"\n  );\n  expect(console.warn).toHaveBeenCalledTimes(4);\n\n  expect(data).toEqual({\n    playlist: {\n      id: \"1\",\n      name: \"Playlist\",\n      album: {\n        id: \"2RSIoPew2TOy41ASHpzOx3\",\n        __typename: \"Album\",\n        images: [{ url: \"https://i.scdn.co/image/1\", __typename: \"Image\" }],\n        tracks: [{ id: \"1\", name: \"Track 1\", __typename: \"Track\" }],\n      },\n      artist: {\n        id: \"2\",\n        __typename: \"Artist\",\n        images: [{ url: \"https://i.scdn.co/image/1\", __typename: \"Image\" }],\n        topTracks: [{ id: \"2\", name: \"Track 2\", __typename: \"Track\" }],\n      },\n    },\n  });\n});\n\ntest(\"masks fragments in subscription documents\", () => {\n  const subscription = gql`\n    subscription {\n      onUserUpdated {\n        id\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      onUserUpdated: { __typename: \"User\", id: 1, name: \"Test User\" },\n    }),\n    subscription,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({ onUserUpdated: { __typename: \"User\", id: 1 } });\n});\n\ntest(\"honors @unmask used in subscription documents\", () => {\n  const subscription = gql`\n    subscription {\n      onUserUpdated {\n        id\n        ...UserFields @unmask\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const subscriptionData = deepFreeze({\n    onUserUpdated: { __typename: \"User\", id: 1, name: \"Test User\" },\n  });\n\n  const data = maskOperation(\n    subscriptionData,\n    subscription,\n    new InMemoryCache()\n  );\n\n  expect(data).toBe(subscriptionData);\n});\n\ntest(\"warns when accessing unmasked fields used in subscription documents with @unmask(mode: 'migrate')\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const subscription = gql`\n    subscription UserUpdatedSubscription {\n      onUserUpdated {\n        id\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const subscriptionData = deepFreeze({\n    onUserUpdated: { __typename: \"User\", id: 1, name: \"Test User\" },\n  });\n\n  const data = maskOperation(\n    subscriptionData,\n    subscription,\n    new InMemoryCache()\n  );\n\n  data.onUserUpdated.name;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"subscription 'UserUpdatedSubscription'\",\n    \"onUserUpdated.name\"\n  );\n});\n\ntest(\"masks fragments in mutation documents\", () => {\n  const mutation = gql`\n    mutation {\n      updateUser {\n        id\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      updateUser: { __typename: \"User\", id: 1, name: \"Test User\" },\n    }),\n    mutation,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({ updateUser: { __typename: \"User\", id: 1 } });\n});\n\ntest(\"honors @unmask used in mutation documents\", () => {\n  const mutation = gql`\n    mutation {\n      updateUser {\n        id\n        ...UserFields @unmask\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const mutationData = deepFreeze({\n    updateUser: { __typename: \"User\", id: 1, name: \"Test User\" },\n  });\n\n  const data = maskOperation(mutationData, mutation, new InMemoryCache());\n\n  expect(data).toBe(mutationData);\n});\n\ntest(\"warns when accessing unmasked fields used in mutation documents with @unmask(mode: 'migrate')\", () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const mutation = gql`\n    mutation UpdateUserMutation {\n      updateUser {\n        id\n        ...UserFields @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment UserFields on User {\n      name\n    }\n  `;\n\n  const mutationData = deepFreeze({\n    updateUser: { __typename: \"User\", id: 1, name: \"Test User\" },\n  });\n\n  const data = maskOperation(mutationData, mutation, new InMemoryCache());\n\n  data.updateUser.name;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"mutation 'UpdateUserMutation'\",\n    \"updateUser.name\"\n  );\n});\n\ntest(\"masks partial data\", () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ...GreetingFragment\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n      },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"__Person\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n      },\n    });\n  }\n});\n\ntest(\"unmasks partial data with @unmask\", () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ...GreetingFragment @unmask\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"__Person\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"__Person\" },\n      },\n    });\n  }\n});\n\ntest('unmasks partial data with warnings with @unmask(mode: \"migrate\")', () => {\n  using consoleSpy = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ...GreetingFragment @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      sentAt\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    data.greeting.__typename;\n    data.greeting.message;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    data.greeting.__typename;\n    data.greeting.message;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.greeting.sentAt;\n    expect(console.warn).toHaveBeenCalledTimes(1);\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      },\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"__Person\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    data.greeting.__typename;\n    data.greeting.message;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.greeting.recipient;\n    data.greeting.recipient.__typename;\n    expect(console.warn).toHaveBeenCalledTimes(1);\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"__Person\" },\n      },\n    });\n  }\n});\n\ntest(\"masks partial deferred data\", () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          sentAt\n          ...GreetingFragment\n        }\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n          recipient: { __typename: \"__Person\", name: \"Alice\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n      },\n    });\n  }\n});\n\ntest(\"unmasks partial deferred data with @unmask\", () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          sentAt\n          ...GreetingFragment @unmask\n        }\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n          recipient: { __typename: \"__Person\", name: \"Alice\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"__Person\", name: \"Alice\" },\n      },\n    });\n  }\n});\n\ntest('unmasks partial deferred data with warnings with @unmask(mode: \"migrate\")', () => {\n  using consoleSpy = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          sentAt\n          ...GreetingFragment @unmask(mode: \"migrate\")\n        }\n      }\n    }\n\n    fragment GreetingFragment on Greeting {\n      recipient {\n        name\n      }\n    }\n  `;\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    data.greeting.message;\n    data.greeting.__typename;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    expect(data).toEqual({\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    });\n  }\n\n  consoleSpy.warn.mockClear();\n\n  {\n    const data = maskOperation(\n      deepFreeze({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          sentAt: \"2024-01-01\",\n          recipient: { __typename: \"__Person\", name: \"Alice\" },\n        },\n      }),\n      query,\n      new InMemoryCache()\n    );\n\n    data.greeting.message;\n    data.greeting.sentAt;\n    data.greeting.__typename;\n\n    expect(console.warn).not.toHaveBeenCalled();\n\n    data.greeting.recipient;\n    data.greeting.recipient.name;\n    expect(console.warn).toHaveBeenCalledTimes(2);\n\n    expect(data).toEqual({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        sentAt: \"2024-01-01\",\n        recipient: { __typename: \"__Person\", name: \"Alice\" },\n      },\n    });\n  }\n});\n\ntest(\"masks results with primitive arrays\", () => {\n  const query = gql`\n    query {\n      listing {\n        id\n        reviews\n        ...ListingFragment\n      }\n    }\n\n    fragment ListingFragment on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      listing: {\n        __typename: \"Listing\",\n        id: \"1\",\n        reviews: [5, 5, 3, 4],\n        amenities: [\"pool\", \"hot tub\", \"backyard\"],\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    listing: {\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n    },\n  });\n});\n\ntest(\"unmasks results with primitive arrays with @unmask\", () => {\n  const query = gql`\n    query {\n      listing {\n        id\n        reviews\n        ...ListingFragment @unmask\n      }\n    }\n\n    fragment ListingFragment on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      listing: {\n        __typename: \"Listing\",\n        id: \"1\",\n        reviews: [5, 5, 3, 4],\n        amenities: [\"pool\", \"hot tub\", \"backyard\"],\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  expect(data).toEqual({\n    listing: {\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n      amenities: [\"pool\", \"hot tub\", \"backyard\"],\n    },\n  });\n});\n\ntest('unmasks results with warnings with primitive arrays with @unmask(mode: \"migrate\")', () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query GetListing {\n      listing {\n        id\n        reviews\n        ...ListingFragment @unmask(mode: \"migrate\")\n      }\n    }\n\n    fragment ListingFragment on Listing {\n      amenities\n    }\n  `;\n\n  const data = maskOperation(\n    deepFreeze({\n      listing: {\n        __typename: \"Listing\",\n        id: \"1\",\n        reviews: [5, 5, 3, 4],\n        amenities: [\"pool\", \"hot tub\", \"backyard\"],\n      },\n    }),\n    query,\n    new InMemoryCache()\n  );\n\n  data.listing.__typename;\n  data.listing.id;\n  data.listing.reviews;\n\n  expect(console.warn).not.toHaveBeenCalled();\n\n  data.listing.amenities;\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n    \"query 'GetListing'\",\n    \"listing.amenities\"\n  );\n\n  expect(data).toEqual({\n    listing: {\n      __typename: \"Listing\",\n      id: \"1\",\n      reviews: [5, 5, 3, 4],\n      amenities: [\"pool\", \"hot tub\", \"backyard\"],\n    },\n  });\n});\n"
  },
  {
    "path": "src/masking/__tests__/utils.test.ts",
    "content": "import { BREAK, type FragmentSpreadNode, visit } from \"graphql\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\n\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { getFragmentMaskMode } from \"../utils.js\";\n\ndescribe(\"getFragmentMaskMode\", () => {\n  it(\"returns 'unmask' when @unmask used on fragment node\", () => {\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @unmask\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(mode).toBe(\"unmask\");\n  });\n\n  it(\"returns 'mask' when no directives are present\", () => {\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(mode).toBe(\"mask\");\n  });\n\n  it(\"returns 'mask' when a different directive is used\", () => {\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @myDirective\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(mode).toBe(\"mask\");\n  });\n\n  it(\"returns 'unmask' when used with other directives\", () => {\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @myDirective @unmask\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(mode).toBe(\"unmask\");\n  });\n\n  it(\"returns 'migrate' when passing mode: 'migrate' as argument\", () => {\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @unmask(mode: \"migrate\")\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(mode).toBe(\"migrate\");\n  });\n\n  it(\"warns and returns 'unmask' when using variable for mode argument\", () => {\n    using _ = spyOnConsole(\"warn\");\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query ($mode: String!) {\n        ...MyFragment @unmask(mode: $mode)\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"@unmask 'mode' argument does not support variables.\"\n    );\n    expect(mode).toBe(\"unmask\");\n  });\n\n  it(\"warns and returns 'unmask' when passing a non-string argument to mode\", () => {\n    using _ = spyOnConsole(\"warn\");\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @unmask(mode: true)\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"@unmask 'mode' argument must be of type string.\"\n    );\n    expect(mode).toBe(\"unmask\");\n  });\n\n  it(\"warns and returns 'unmask' when passing a value other than 'migrate' to mode\", () => {\n    using _ = spyOnConsole(\"warn\");\n    const fragmentNode = getFragmentSpreadNode(gql`\n      query {\n        ...MyFragment @unmask(mode: \"invalid\")\n      }\n    `);\n\n    const mode = getFragmentMaskMode(fragmentNode);\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"@unmask 'mode' argument does not recognize value '%s'.\",\n      \"invalid\"\n    );\n    expect(mode).toBe(\"unmask\");\n  });\n});\n\nfunction getFragmentSpreadNode(document: DocumentNode): FragmentSpreadNode {\n  let fragmentSpreadNode: FragmentSpreadNode | undefined = undefined;\n\n  visit(document, {\n    FragmentSpread: (node) => {\n      fragmentSpreadNode = node;\n      return BREAK;\n    },\n  });\n\n  if (!fragmentSpreadNode) {\n    throw new Error(\"Must give a document with a fragment spread\");\n  }\n\n  return fragmentSpreadNode;\n}\n"
  },
  {
    "path": "src/masking/index.ts",
    "content": "export type { FragmentType, MaybeMasked, Unmasked } from \"./types.js\";\nexport type { GraphQLCodegenDataMasking } from \"./GraphQLCodegenDataMasking.js\";\nexport { disableWarningsSlot } from \"./utils.js\";\nexport { maskFragment } from \"./maskFragment.js\";\nexport { maskOperation } from \"./maskOperation.js\";\n"
  },
  {
    "path": "src/masking/internal/types.ts",
    "content": "import type {\n  IsAny,\n  Prettify,\n  Primitive,\n  RemoveIndexSignature,\n} from \"@apollo/client/utilities/internal\";\n\nexport type UnwrapFragmentRefs<TData> =\n  true extends IsAny<TData> ? TData\n  : TData extends any ?\n    // Ensure tagged/branded types are left alone (i.e. type UUID = string & { ... })\n    TData extends Primitive ? TData\n    : // Leave TData alone if it is Record<string, any> and not a specific shape\n    string extends keyof TData ? TData\n    : // short-circuit on empty object\n    keyof TData extends never ? TData\n    : TData extends { \" $fragmentRefs\"?: infer FragmentRefs } ?\n      UnwrapFragmentRefs<\n        CombineIntersection<\n          | Omit<TData, \" $fragmentRefs\">\n          | RemoveFragmentName<\n              NonNullable<\n                NonNullable<FragmentRefs>[keyof NonNullable<FragmentRefs>]\n              >\n            >\n        >\n      >\n    : TData extends object ?\n      {\n        [K in keyof TData]: UnwrapFragmentRefs<TData[K]>;\n      }\n    : TData\n  : never;\n\n/**\n * ```ts\n * CombineIntersection<\n *   | { foo: string }\n *   | { __typename: \"A\"; a: string }\n *   | { __typename: \"B\"; b1: number }\n *   | { __typename: \"B\"; b2: string }\n * > =>\n *   | { foo: string }\n *   | CombineByTypeName<\n *     | { __typename: \"A\"; a: string }\n *     | { __typename: \"B\"; b1: number }\n *     | { __typename: \"B\"; b2: string }\n *   >\n * ```\n */\ntype CombineIntersection<T> =\n  | Exclude<T, { __typename?: string }>\n  | CombineByTypeName<Extract<T, { __typename?: string }>>;\n/**\n * ```ts\n *   CombineByTypeName<\n *     | { __typename: \"A\"; a: string }\n *     | { __typename: \"B\"; b1: number }\n *     | { __typename: \"B\"; b2: string }\n *   > =>\n *   | CombineWithArrays<\n *     | { __typename: \"A\"; a: string }\n *   >\n *   | CombineWithArrays<\n *     | { __typename: \"B\"; b1: number }\n *     | { __typename: \"B\"; b2: number }\n *   >\n * ```\n */\ntype CombineByTypeName<T extends { __typename?: string }> = {\n  [TypeName in NonNullable<T[\"__typename\"]>]: Prettify<\n    MergeUnions<ExtractByMatchingTypeNames<T, TypeName>>\n  >;\n}[NonNullable<T[\"__typename\"]>];\n\n/**\n * ```ts\n * CombineByTypeName<\n *   | {\n *       __typename: \"Person\" | \"Animatronic\" | \"CartoonCharacter\";\n *       id: number;\n *       name: string;\n *     }\n *   | {\n *       __typename: \"Person\";\n *       birthdate: string;\n *     }\n *   | {\n *       __typename: \"Animatronic\";\n *       manufacturer: string;\n *       warrantyEndDate: string;\n *     }\n *   | {\n *       __typename: \"CartoonCharacter\";\n *       animator: string;\n *       voiceActor: string;\n *     }\n * >\n *     =>\n * {\n *     id: number;\n *     name: string;\n *     __typename: \"Person\";\n *     birthdate: string;\n * } | {\n *     id: number;\n *     name: string;\n *     __typename: \"Animatronic\";\n *     manufacturer: string;\n *     warrantyEndDate: string;\n * } | {\n *     id: number;\n *     name: string;\n *     __typename: \"CartoonCharacter\";\n *     animator: string;\n *     voiceActor: string;\n * }\n * ```\n */\ntype ExtractByMatchingTypeNames<\n  Union extends { __typename?: string },\n  TypeName extends string,\n> = Union extends any ?\n  TypeName extends NonNullable<Union[\"__typename\"]> ?\n    Omit<Union, \"__typename\"> & {\n      // preserve `?`, which `& { __typename: TypeName }` would not do\n      [K in keyof Union as K extends \"__typename\" ? K : never]: TypeName;\n    }\n  : never\n: never;\n\ntype MergeUnions<TUnion> = MergeUnionsAcc<\n  TUnion,\n  takeOneFromUnion<TUnion>,\n  never\n>;\n\ntype DistributedRequiredExclude<T, U> =\n  T extends any ?\n    Required<T> extends Required<U> ?\n      Required<U> extends Required<T> ?\n        never\n      : T\n    : T\n  : T;\n\ntype MergeUnionsAcc<TUnion, Curr, Merged> =\n  [Curr] extends [never] ? Merged\n  : MergeUnionsAcc<\n      DistributedRequiredExclude<TUnion, Curr>,\n      takeOneFromUnion<DistributedRequiredExclude<TUnion, Curr>>,\n      [Merged] extends [never] ? Curr : MergeObjects<Curr, Merged>\n    >;\ntype unionToIntersection<T> =\n  (T extends unknown ? (x: T) => unknown : never) extends (\n    (x: infer U) => unknown\n  ) ?\n    U\n  : never;\n\ntype takeOneFromUnion<T> =\n  unionToIntersection<T extends T ? (x: T) => 0 : never> extends (\n    (x: infer U) => 0\n  ) ?\n    U\n  : never;\n\ntype MergeObjects<T, U> = Prettify<\n  {\n    [k in keyof T]: k extends keyof U ?\n      [NonNullable<T[k]>, NonNullable<U[k]>] extends (\n        [infer TK extends object, infer UK extends object]\n      ) ?\n        TK extends unknown[] ?\n          UK extends unknown[] ?\n            | CombineIntersection<TK[number] | UK[number]>[]\n            | Extract<T[k] | U[k], undefined | null>\n          : T[k]\n        : CombineIntersection<TK | UK> | Extract<T[k] | U[k], undefined | null>\n      : T[k]\n    : T[k];\n  } & Pick<U, Exclude<keyof U, keyof T>>\n>;\n\n// force distribution when T is a union with | undefined\nexport type RemoveFragmentName<T> =\n  T extends any ? Omit<T, \" $fragmentName\"> : T;\n\ntype Exact<in out T> = (x: T) => T;\nexport type ContainsFragmentsRefs<TData, Seen = never> = true extends (\n  IsAny<TData>\n) ?\n  false\n: TData extends object ?\n  Exact<TData> extends Seen ? false\n  : \" $fragmentRefs\" extends keyof RemoveIndexSignature<TData> ? true\n  : ContainsFragmentsRefs<TData[keyof TData], Seen | Exact<TData>>\n: false;\n"
  },
  {
    "path": "src/masking/maskDefinition.ts",
    "content": "import type { FragmentDefinitionNode, SelectionSetNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport type { ApolloCache } from \"@apollo/client/cache\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type { FragmentMap } from \"@apollo/client/utilities/internal\";\nimport {\n  maybeDeepFreeze,\n  resultKeyNameFromField,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { disableWarningsSlot, getFragmentMaskMode } from \"./utils.js\";\n\ninterface MaskingContext {\n  operationType: \"query\" | \"mutation\" | \"subscription\" | \"fragment\";\n  operationName: string | undefined;\n  fragmentMap: FragmentMap;\n  cache: ApolloCache;\n  mutableTargets: WeakMap<any, any>;\n  knownChanged: WeakSet<any>;\n}\n\nexport function maskDefinition(\n  data: Record<string, any>,\n  selectionSet: SelectionSetNode,\n  context: MaskingContext\n) {\n  return disableWarningsSlot.withValue(true, () => {\n    const masked = maskSelectionSet(data, selectionSet, context, false);\n\n    if (Object.isFrozen(data)) {\n      maybeDeepFreeze(masked);\n    }\n    return masked;\n  });\n}\n\nfunction getMutableTarget(\n  data: Record<string, any>,\n  mutableTargets: WeakMap<any, any>\n): typeof data {\n  if (mutableTargets.has(data)) {\n    return mutableTargets.get(data);\n  }\n\n  const mutableTarget = Array.isArray(data) ? [] : {};\n  mutableTargets.set(data, mutableTarget);\n  return mutableTarget;\n}\n\nfunction maskSelectionSet(\n  data: any,\n  selectionSet: SelectionSetNode,\n  context: MaskingContext,\n  migration: boolean,\n  path?: string | undefined\n): typeof data {\n  const { knownChanged } = context;\n  const memo = getMutableTarget(data, context.mutableTargets);\n\n  if (Array.isArray(data)) {\n    for (const [index, item] of Array.from(data.entries())) {\n      if (item === null) {\n        memo[index] = null;\n        continue;\n      }\n\n      const masked = maskSelectionSet(\n        item,\n        selectionSet,\n        context,\n        migration,\n        __DEV__ ? `${path || \"\"}[${index}]` : void 0\n      );\n      if (knownChanged.has(masked)) {\n        knownChanged.add(memo);\n      }\n\n      memo[index] = masked;\n    }\n\n    return knownChanged.has(memo) ? memo : data;\n  }\n\n  for (const selection of selectionSet.selections) {\n    let value: any;\n\n    // we later want to add accessor warnings to the final result\n    // so we need a new object to add the accessor warning to\n    if (migration) {\n      knownChanged.add(memo);\n    }\n\n    if (selection.kind === Kind.FIELD) {\n      const keyName = resultKeyNameFromField(selection);\n      const childSelectionSet = selection.selectionSet;\n\n      value = memo[keyName] || data[keyName];\n\n      if (value === void 0) {\n        continue;\n      }\n\n      if (childSelectionSet && value !== null) {\n        const masked = maskSelectionSet(\n          data[keyName],\n          childSelectionSet,\n          context,\n          migration,\n          __DEV__ ? `${path || \"\"}.${keyName}` : void 0\n        );\n\n        if (knownChanged.has(masked)) {\n          value = masked;\n        }\n      }\n\n      if (!__DEV__) {\n        memo[keyName] = value;\n      }\n      if (__DEV__) {\n        if (\n          migration &&\n          keyName !== \"__typename\" &&\n          // either the field is not present in the memo object\n          // or it has a `get` descriptor, not a `value` descriptor\n          // => it is a warning accessor and we can overwrite it\n          // with another accessor\n          !Object.getOwnPropertyDescriptor(memo, keyName)?.value\n        ) {\n          Object.defineProperty(\n            memo,\n            keyName,\n            getAccessorWarningDescriptor(\n              keyName,\n              value,\n              path || \"\",\n              context.operationName,\n              context.operationType\n            )\n          );\n        } else {\n          delete memo[keyName];\n          memo[keyName] = value;\n        }\n      }\n    }\n\n    if (\n      selection.kind === Kind.INLINE_FRAGMENT &&\n      (!selection.typeCondition ||\n        context.cache.fragmentMatches(selection, data.__typename))\n    ) {\n      value = maskSelectionSet(\n        data,\n        selection.selectionSet,\n        context,\n        migration,\n        path\n      );\n    }\n\n    if (selection.kind === Kind.FRAGMENT_SPREAD) {\n      const fragmentName = selection.name.value;\n      const fragment: FragmentDefinitionNode | null =\n        context.fragmentMap[fragmentName] ||\n        (context.fragmentMap[fragmentName] =\n          context.cache.lookupFragment(fragmentName)!);\n      invariant(\n        fragment,\n        \"Could not find fragment with name '%s'.\",\n        fragmentName\n      );\n\n      const mode = getFragmentMaskMode(selection);\n\n      if (mode !== \"mask\") {\n        value = maskSelectionSet(\n          data,\n          fragment.selectionSet,\n          context,\n          mode === \"migrate\",\n          path\n        );\n      }\n    }\n\n    if (knownChanged.has(value)) {\n      knownChanged.add(memo);\n    }\n  }\n\n  if (\"__typename\" in data && !(\"__typename\" in memo)) {\n    memo.__typename = data.__typename;\n  }\n\n  // This check prevents cases where masked fields may accidentally be\n  // returned as part of this object when the fragment also selects\n  // additional fields from the same child selection.\n  if (Object.keys(memo).length !== Object.keys(data).length) {\n    knownChanged.add(memo);\n  }\n\n  return knownChanged.has(memo) ? memo : data;\n}\n\nfunction getAccessorWarningDescriptor(\n  fieldName: string,\n  value: any,\n  path: string,\n  operationName: string | undefined,\n  operationType: string\n): PropertyDescriptor {\n  let getValue = () => {\n    if (disableWarningsSlot.getValue()) {\n      return value;\n    }\n\n    invariant.warn(\n      \"Accessing unmasked field on %s at path '%s'. This field will not be available when masking is enabled. Please read the field from the fragment instead.\",\n      operationName ?\n        `${operationType} '${operationName}'`\n      : `anonymous ${operationType}`,\n      `${path}.${fieldName}`.replace(/^\\./, \"\")\n    );\n\n    getValue = () => value;\n\n    return value;\n  };\n\n  return {\n    get() {\n      return getValue();\n    },\n    set(newValue) {\n      getValue = () => newValue;\n    },\n    enumerable: true,\n    configurable: true,\n  };\n}\n"
  },
  {
    "path": "src/masking/maskFragment.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { FragmentDefinitionNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport type {\n  ApolloCache,\n  DocumentNode,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  createFragmentMap,\n  getFragmentDefinitions,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { maskDefinition } from \"./maskDefinition.js\";\n\n/** @internal */\nexport function maskFragment<TData = unknown>(\n  data: TData,\n  document: TypedDocumentNode<TData> | DocumentNode,\n  cache: ApolloCache,\n  fragmentName?: string\n): TData {\n  const fragments = document.definitions.filter(\n    (node): node is FragmentDefinitionNode =>\n      node.kind === Kind.FRAGMENT_DEFINITION\n  );\n\n  if (typeof fragmentName === \"undefined\") {\n    invariant(\n      fragments.length === 1,\n      `Found %s fragments. \\`fragmentName\\` must be provided when there is not exactly 1 fragment.`,\n      fragments.length\n    );\n    fragmentName = fragments[0].name.value;\n  }\n\n  const fragment = fragments.find(\n    (fragment) => fragment.name.value === fragmentName\n  );\n\n  invariant(\n    !!fragment,\n    `Could not find fragment with name \"%s\".`,\n    fragmentName\n  );\n\n  if (data == null) {\n    // Maintain the original `null` or `undefined` value\n    return data;\n  }\n\n  if (equal(data, {})) {\n    // Return early and skip the masking algorithm if we don't have any data\n    // yet. This can happen when cache.diff returns an empty object which is\n    // used from watchFragment.\n    return data;\n  }\n\n  return maskDefinition(data, fragment.selectionSet, {\n    operationType: \"fragment\",\n    operationName: fragment.name.value,\n    fragmentMap: createFragmentMap(getFragmentDefinitions(document)),\n    cache,\n    mutableTargets: new WeakMap(),\n    knownChanged: new WeakSet(),\n  });\n}\n"
  },
  {
    "path": "src/masking/maskOperation.ts",
    "content": "import type {\n  ApolloCache,\n  DocumentNode,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  createFragmentMap,\n  getFragmentDefinitions,\n  getOperationDefinition,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { maskDefinition } from \"./maskDefinition.js\";\n\n/** @internal */\nexport function maskOperation<TData = unknown>(\n  data: TData,\n  document: DocumentNode | TypedDocumentNode<TData>,\n  cache: ApolloCache\n): TData {\n  const definition = getOperationDefinition(document);\n\n  invariant(\n    definition,\n    \"Expected a parsed GraphQL document with a query, mutation, or subscription.\"\n  );\n\n  if (data == null) {\n    // Maintain the original `null` or `undefined` value\n    return data;\n  }\n\n  return maskDefinition(data, definition.selectionSet, {\n    operationType: definition.operation,\n    operationName: definition.name?.value,\n    fragmentMap: createFragmentMap(getFragmentDefinitions(document)),\n    cache,\n    mutableTargets: new WeakMap(),\n    knownChanged: new WeakSet(),\n  });\n}\n"
  },
  {
    "path": "src/masking/types.ts",
    "content": "import type { DocumentTypeDecoration } from \"@graphql-typed-document-node/core\";\n\nimport type { TypeOverrides } from \"@apollo/client\";\nimport type { ApplyHKTImplementationWithDefault } from \"@apollo/client/utilities/internal\";\n\nimport type { PreserveTypes } from \"./PreserveTypes.js\";\n\n/**\n * Type used with [fragments](https://apollographql.com/docs/react/data/fragments#using-with-fragments) to ensure parent objects contain the fragment spread from the type.\n */\nexport type FragmentType<TFragmentDataOrTypedDocumentNode> =\n  ApplyHKTImplementationWithDefault<\n    TypeOverrides,\n    \"FragmentType\",\n    PreserveTypes.TypeOverrides,\n    TFragmentDataOrTypedDocumentNode extends (\n      DocumentTypeDecoration<infer TFragmentData, any>\n    ) ?\n      TFragmentData\n    : TFragmentDataOrTypedDocumentNode\n  >;\n\n/** Unwraps `TData` into its unmasked type. */\nexport type Unmasked<TData> = ApplyHKTImplementationWithDefault<\n  TypeOverrides,\n  \"Unmasked\",\n  PreserveTypes.TypeOverrides,\n  TData\n>;\n\n/**\n * Returns TData as either masked or unmasked depending on whether masking is\n * enabled.\n */\nexport type MaybeMasked<TData> = ApplyHKTImplementationWithDefault<\n  TypeOverrides,\n  \"MaybeMasked\",\n  PreserveTypes.TypeOverrides,\n  TData\n>;\n"
  },
  {
    "path": "src/masking/utils.ts",
    "content": "import type { FragmentSpreadNode } from \"graphql\";\nimport { Kind } from \"graphql\";\nimport { Slot } from \"optimism\";\n\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\n// Contextual slot that allows us to disable accessor warnings on fields when in\n// migrate mode.\n/** @internal */\nexport const disableWarningsSlot = new Slot<boolean>();\n\nexport function getFragmentMaskMode(\n  fragment: FragmentSpreadNode\n): \"mask\" | \"migrate\" | \"unmask\" {\n  const directive = fragment.directives?.find(\n    ({ name }) => name.value === \"unmask\"\n  );\n\n  if (!directive) {\n    return \"mask\";\n  }\n\n  const modeArg = directive.arguments?.find(\n    ({ name }) => name.value === \"mode\"\n  );\n\n  if (__DEV__) {\n    if (modeArg) {\n      if (modeArg.value.kind === Kind.VARIABLE) {\n        invariant.warn(\"@unmask 'mode' argument does not support variables.\");\n      } else if (modeArg.value.kind !== Kind.STRING) {\n        invariant.warn(\"@unmask 'mode' argument must be of type string.\");\n      } else if (modeArg.value.value !== \"migrate\") {\n        invariant.warn(\n          \"@unmask 'mode' argument does not recognize value '%s'.\",\n          modeArg.value.value\n        );\n      }\n    }\n  }\n\n  if (\n    modeArg &&\n    \"value\" in modeArg.value &&\n    modeArg.value.value === \"migrate\"\n  ) {\n    return \"migrate\";\n  }\n\n  return \"unmask\";\n}\n"
  },
  {
    "path": "src/react/context/ApolloContext.ts",
    "content": "import type * as ReactTypes from \"react\";\nimport * as React from \"react\";\n\nimport type { ApolloClient } from \"@apollo/client\";\nimport type {\n  HookWrappers,\n  wrapperSymbol,\n} from \"@apollo/client/react/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nexport interface ApolloContextValue {\n  client?: ApolloClient;\n  [wrapperSymbol]?: HookWrappers;\n}\n\n// To make sure Apollo Client doesn't create more than one React context\n// (which can lead to problems like having an Apollo Client instance added\n// in one context, then attempting to retrieve it from another different\n// context), a single Apollo context is created and tracked in global state.\nconst contextKey = Symbol.for(\"__APOLLO_CONTEXT__\");\n\nexport function getApolloContext(): ReactTypes.Context<ApolloContextValue> {\n  invariant(\n    \"createContext\" in React,\n    \"Invoking `getApolloContext` in an environment where `React.createContext` is not available.\\n\" +\n      \"The Apollo Client functionality you are trying to use is only available in React Client Components.\\n\" +\n      'Please make sure to add \"use client\" at the top of your file.\\n' +\n      // TODO: change to React documentation once React documentation contains information about Client Components\n      \"For more information, see https://nextjs.org/docs/getting-started/react-essentials#client-components\"\n  );\n\n  let context = (React.createContext as any)[\n    contextKey\n  ] as React.Context<ApolloContextValue>;\n  if (!context) {\n    Object.defineProperty(React.createContext, contextKey, {\n      value: (context = React.createContext<ApolloContextValue>({})),\n      enumerable: false,\n      writable: false,\n      configurable: true,\n    });\n    context.displayName = \"ApolloContext\";\n  }\n  return context;\n}\n"
  },
  {
    "path": "src/react/context/ApolloProvider.tsx",
    "content": "import type * as ReactTypes from \"react\";\nimport * as React from \"react\";\n\nimport type { ApolloClient } from \"@apollo/client\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { getApolloContext } from \"./ApolloContext.js\";\n\nexport declare namespace ApolloProvider {\n  interface Props {\n    client: ApolloClient;\n    children: ReactTypes.ReactNode | ReactTypes.ReactNode[] | null;\n  }\n}\n\nexport const ApolloProvider: ReactTypes.FC<ApolloProvider.Props> = ({\n  client,\n  children,\n}) => {\n  const ApolloContext = getApolloContext();\n  const parentContext = React.useContext(ApolloContext);\n\n  const context = React.useMemo(() => {\n    return {\n      ...parentContext,\n      client: client || parentContext.client,\n    };\n  }, [parentContext, client]);\n\n  invariant(\n    context.client,\n    \"ApolloProvider was not passed a client instance. Make \" +\n      'sure you pass in your client via the \"client\" prop.'\n  );\n\n  return (\n    <ApolloContext.Provider value={context}>{children}</ApolloContext.Provider>\n  );\n};\n"
  },
  {
    "path": "src/react/context/__tests__/ApolloProvider.test.tsx",
    "content": "import { render, screen } from \"@testing-library/react\";\nimport React, { useContext } from \"react\";\nimport { EMPTY } from \"rxjs\";\n\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { ApolloProvider, getApolloContext } from \"@apollo/client/react\";\n\nimport type { ApolloContextValue } from \"../ApolloContext.js\";\n\ndescribe(\"<ApolloProvider /> Component\", () => {\n  const client = new ApolloClient({\n    cache: new Cache(),\n    link: new ApolloLink((o, f) => (f ? f(o) : EMPTY)),\n  });\n\n  const anotherClient = new ApolloClient({\n    cache: new Cache(),\n    link: new ApolloLink((o, f) => (f ? f(o) : EMPTY)),\n  });\n\n  it(\"should render children components\", () => {\n    render(\n      <ApolloProvider client={client}>\n        <div className=\"unique\">Test</div>\n      </ApolloProvider>\n    );\n\n    expect(screen.getByText(\"Test\")).toBeTruthy();\n  });\n\n  it(\"should support the 2.0\", () => {\n    render(\n      <ApolloProvider client={{} as ApolloClient}>\n        <div className=\"unique\">Test</div>\n      </ApolloProvider>\n    );\n\n    expect(screen.getByText(\"Test\")).toBeTruthy();\n  });\n\n  it(\"should require a client\", () => {\n    const originalConsoleError = console.error;\n    console.error = () => {\n      /* noop */\n    };\n    expect(() => {\n      // Before testing `ApolloProvider`, we first fully reset the\n      // existing context using `ApolloContext.Provider` directly.\n      const ApolloContext = getApolloContext();\n      render(\n        <ApolloContext.Provider value={{}}>\n          <ApolloProvider client={undefined as any}>\n            <div className=\"unique\" />\n          </ApolloProvider>\n        </ApolloContext.Provider>\n      );\n    }).toThrow(\n      \"ApolloProvider was not passed a client instance. Make \" +\n        'sure you pass in your client via the \"client\" prop.'\n    );\n    console.error = originalConsoleError;\n  });\n\n  it(\"should not require a store\", () => {\n    render(\n      <ApolloProvider client={client}>\n        <div className=\"unique\">Test</div>\n      </ApolloProvider>\n    );\n    expect(screen.getByText(\"Test\")).toBeTruthy();\n  });\n\n  it(\"should add the client to the children context\", () => {\n    const TestChild = () => {\n      const context = useContext(getApolloContext());\n      expect(context.client).toEqual(client);\n      return null;\n    };\n    render(\n      <ApolloProvider client={client}>\n        <TestChild />\n        <TestChild />\n      </ApolloProvider>\n    );\n  });\n\n  it(\"should update props when the client changes\", () => {\n    let clientToCheck = client;\n\n    const TestChild = () => {\n      const context = useContext(getApolloContext());\n      expect(context.client).toEqual(clientToCheck);\n      return null;\n    };\n    const { rerender } = render(\n      <ApolloProvider client={clientToCheck}>\n        <TestChild />\n      </ApolloProvider>\n    );\n\n    const newClient = new ApolloClient({\n      cache: new Cache(),\n      link: new ApolloLink((o, f) => (f ? f(o) : EMPTY)),\n    });\n    clientToCheck = newClient;\n    rerender(\n      <ApolloProvider client={clientToCheck}>\n        <TestChild />\n      </ApolloProvider>\n    );\n  });\n\n  describe.each<\n    [\n      string,\n      Omit<ApolloProvider.Props, \"children\">,\n      Omit<ApolloProvider.Props, \"children\">,\n    ]\n  >([[\"client\", { client }, { client: anotherClient }]])(\n    \"context value stability, %s prop\",\n    (prop, value, childValue) => {\n      it(`should not recreate the context value if the ${prop} prop didn't change`, () => {\n        let lastContext: ApolloContextValue | undefined;\n\n        const TestChild = () => {\n          lastContext = useContext(getApolloContext());\n          return null;\n        };\n\n        const { rerender } = render(\n          <ApolloProvider {...value}>\n            <TestChild />\n          </ApolloProvider>\n        );\n\n        const firstContextValue = lastContext;\n\n        rerender(\n          <ApolloProvider {...value}>\n            <TestChild />\n          </ApolloProvider>\n        );\n\n        expect(lastContext).toBe(firstContextValue);\n      });\n\n      it(`should not recreate the context if the parent context value differs, but the ${prop} prop didn't change`, () => {\n        let lastContext: ApolloContextValue | undefined;\n\n        const TestChild = () => {\n          lastContext = useContext(getApolloContext());\n          return null;\n        };\n\n        const { rerender } = render(\n          <ApolloProvider {...value}>\n            <ApolloProvider {...childValue}>\n              <TestChild />\n            </ApolloProvider>\n          </ApolloProvider>\n        );\n\n        const firstContextValue = lastContext;\n\n        rerender(\n          <ApolloProvider {...value}>\n            <ApolloProvider {...childValue}>\n              <TestChild />\n            </ApolloProvider>\n          </ApolloProvider>\n        );\n\n        expect(lastContext).toBe(firstContextValue);\n      });\n    }\n  );\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/bundle.test.tsx",
    "content": "import { build } from \"@apollo/client\";\nimport { reactCompilerVersion } from \"@apollo/client/react\";\n\nconst isCI = process.env.TEST_ENV === \"ci\";\n\ntest(\"test is running against source or ESM (in CI) build\", () => {\n  // We want to ensure that in CI, these tests run against the\n  // React Compiler-compiled ESM build\n  expect(build).toBe(isCI ? \"esm\" : \"source\");\n});\n\ntest(\"test is running against uncompiled or compiled (in CI)\", () => {\n  if (isCI) {\n    expect(reactCompilerVersion).toMatchInlineSnapshot(`\"1.0.0\"`);\n  } else {\n    expect(reactCompilerVersion).toBe(\"uncompiled\");\n  }\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useApolloClient.test.tsx",
    "content": "import { render } from \"@testing-library/react\";\nimport React from \"react\";\n\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { ApolloProvider, useApolloClient } from \"@apollo/client/react\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"useApolloClient Hook\", () => {\n  it(\"should return a client instance from the context if available\", () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    function App() {\n      expect(useApolloClient()).toEqual(client);\n      return null;\n    }\n\n    render(\n      <ApolloProvider client={client}>\n        <App />\n      </ApolloProvider>\n    );\n  });\n\n  it(\"should error if a client instance can't be found in the context\", () => {\n    function App() {\n      expect(() => useApolloClient()).toThrow(InvariantError);\n      return null;\n    }\n\n    render(<App />);\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/defer20220824.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useBackgroundQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDefer20220824,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  TQueryRef extends QueryRef<any, any, any>,\n  TStates extends DataState<TData>[\"dataState\"] = TQueryRef extends (\n    QueryRef<any, any, infer States>\n  ) ?\n    States\n  : never,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => [TQueryRef, useBackgroundQuery.Result<TData, TVariables>],\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({ queryRef }: { queryRef: QueryRef }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    replaceSnapshot(useReadQuery(queryRef) as any);\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useBackgroundQuery\" });\n    const [queryRef] = renderHook(props as any);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseReadQuery queryRef={queryRef} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useReadQuery.Result<TData, TStates> | { error: ErrorLike }\n  >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  interface Data {\n    greeting: {\n      __typename: string;\n      message: string;\n      recipient: { name: string; __typename: string };\n    };\n  }\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const cache = new InMemoryCache();\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useBackgroundQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello cached\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  interface QueryData {\n    greeting: {\n      __typename: string;\n      message?: string;\n      recipient?: {\n        __typename: string;\n        name: string;\n      };\n    };\n  }\n\n  const query: TypedDocumentNode<QueryData> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const cache = new InMemoryCache();\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useBackgroundQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/deferGraphQL17Alpha9.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useBackgroundQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDeferStreamGraphQL17Alpha9,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  TQueryRef extends QueryRef<any, any, any>,\n  TStates extends DataState<TData>[\"dataState\"] = TQueryRef extends (\n    QueryRef<any, any, infer States>\n  ) ?\n    States\n  : never,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => [TQueryRef, useBackgroundQuery.Result<TData, TVariables>],\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({ queryRef }: { queryRef: QueryRef }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    replaceSnapshot(useReadQuery(queryRef) as any);\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useBackgroundQuery\" });\n    const [queryRef] = renderHook(props as any);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseReadQuery queryRef={queryRef} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useReadQuery.Result<TData, TStates> | { error: ErrorLike }\n  >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  interface Data {\n    greeting: {\n      __typename: string;\n      message: string;\n      recipient: { name: string; __typename: string };\n    };\n  }\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const cache = new InMemoryCache();\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useBackgroundQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello cached\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  interface QueryData {\n    greeting: {\n      __typename: string;\n      message?: string;\n      recipient?: {\n        __typename: string;\n        name: string;\n      };\n    };\n  }\n\n  const query: TypedDocumentNode<QueryData> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const cache = new InMemoryCache();\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useBackgroundQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/skipToken.test.tsx",
    "content": "import { disableActEnvironment } from \"@testing-library/react-render-stream\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\nimport { delay, of, Subject } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { skipToken, useBackgroundQuery } from \"@apollo/client/react\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  createClientWrapper,\n  createMockWrapper,\n  ObservableStream,\n  setupVariablesCase,\n} from \"@apollo/client/testing/internal\";\n\nimport { renderUseBackgroundQuery } from \"./testUtils.js\";\n\n// https://github.com/apollographql/apollo-client/issues/12989\ntest(\"maintains variables when switching to `skipToken` and calling `refetchQueries` while skipped after initial request\", async () => {\n  const { query } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    link: new ApolloLink((operation) => {\n      return of(\n        operation.variables.id === \"1\" ?\n          {\n            data: {\n              character: {\n                __typename: \"Character\",\n                id: \"1\",\n                name: \"Spider-Man\",\n              },\n            },\n          }\n        : {\n            data: null,\n            errors: [\n              { message: `Fetched wrong id: ${operation.variables.id}` },\n            ],\n          }\n      ).pipe(delay(10));\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender, takeRender } = await renderUseBackgroundQuery(\n    ({ id }) =>\n      useBackgroundQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"<Suspense />\",\n    ]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n\n  await expect(\n    client.refetchQueries({ include: [query] })\n  ).resolves.toStrictEqualTyped([\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    },\n  ]);\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends and fetches when changing variables when no longer using skipToken\", async () => {\n  const { query, mocks } = setupVariablesCase({\n    delay: React.version.startsWith(\"18\") ? 200 : 20,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender, takeRender } = await renderUseBackgroundQuery(\n    ({ id }) =>\n      useBackgroundQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createMockWrapper({ mocks }),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"<Suspense />\",\n    ]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: \"2\" });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"<Suspense />\",\n    ]);\n  }\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend for data in the cache when changing variables when no longer using skipToken\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender, takeRender } = await renderUseBackgroundQuery(\n    ({ id }) =>\n      useBackgroundQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createMockWrapper({ cache, mocks }),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"<Suspense />\",\n    ]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: \"2\" });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"client.refetchQueries should not refetch queries that start with skipToken until they have been executed\", async () => {\n  const query = gql`\n    query getAuthor($id: ID!) {\n      author(id: $id) {\n        firstName\n        lastName\n      }\n    }\n  `;\n  const data = {\n    author: {\n      firstName: \"John\",\n      lastName: \"Smith\",\n    },\n  };\n  const secondReqData = {\n    author: {\n      firstName: \"Jane\",\n      lastName: \"Johnson\",\n    },\n  };\n\n  const operationSubject = new Subject<ApolloLink.Operation>();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation, forward) => {\n      operationSubject.next(operation);\n      return forward(operation);\n    }).concat(link),\n  });\n\n  const operationStream = new ObservableStream(operationSubject);\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender, takeRender } = await renderUseBackgroundQuery(\n    (options) => useBackgroundQuery(query, options),\n    {\n      initialProps: skipToken as\n        | typeof skipToken\n        | useBackgroundQuery.Options<{ id: string }>,\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(operationStream).not.toEmitAnything();\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useBackgroundQuery\"]);\n  }\n\n  void client.refetchQueries({ include: [query] });\n  await expect(operationStream).not.toEmitAnything();\n  await expect(takeRender).not.toRerender();\n\n  await rerender({ variables: { id: \"1234\" } });\n  await expect(operationStream).toEmitNext();\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"<Suspense />\",\n    ]);\n  }\n\n  link.simulateResult({ result: { data } }, true);\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data,\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  void client.refetchQueries({ include: [query] });\n  await expect(operationStream).toEmitNext();\n  link.simulateResult({ result: { data: secondReqData } }, true);\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: secondReqData,\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/streamDefer20220824.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { from } from \"rxjs\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useBackgroundQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha2,\n  friendListSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  TQueryRef extends QueryRef<any, any, any>,\n  TStates extends DataState<TData>[\"dataState\"] = TQueryRef extends (\n    QueryRef<any, any, infer States>\n  ) ?\n    States\n  : never,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => [TQueryRef, useBackgroundQuery.Result<TData, TVariables>],\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({ queryRef }: { queryRef: QueryRef }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    replaceSnapshot(useReadQuery(queryRef) as any);\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useBackgroundQuery\" });\n    const [queryRef] = renderHook(props as any);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseReadQuery queryRef={queryRef} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useReadQuery.Result<TData, TStates> | { error: ErrorLike }\n  >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha2(\n        friendListSchemaGraphQL17Alpha2,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  interface Data {\n    friendList: Array<{ __typename: \"Friend\"; id: string; name: string }>;\n  }\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: (_, incoming) => {\n              return incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n  cache.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useBackgroundQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  interface QueryData {\n    friendList: Array<{ __typename: \"Friend\"; id: string; name: string }>;\n  }\n\n  const query: TypedDocumentNode<QueryData> = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => {\n                return incoming;\n              },\n            },\n          },\n        },\n      },\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    client.writeQuery({\n      query,\n      data: {\n        friendList: [\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"1\" },\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"2\" },\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useBackgroundQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\" },\n          { __typename: \"Friend\", id: \"2\" },\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/streamGraphQL17Alpha9.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { from } from \"rxjs\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useBackgroundQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha9,\n  friendListSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  TQueryRef extends QueryRef<any, any, any>,\n  TStates extends DataState<TData>[\"dataState\"] = TQueryRef extends (\n    QueryRef<any, any, infer States>\n  ) ?\n    States\n  : never,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => [TQueryRef, useBackgroundQuery.Result<TData, TVariables>],\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({ queryRef }: { queryRef: QueryRef }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    replaceSnapshot(useReadQuery(queryRef) as any);\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useBackgroundQuery\" });\n    const [queryRef] = renderHook(props as any);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseReadQuery queryRef={queryRef} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useReadQuery.Result<TData, TStates> | { error: ErrorLike }\n  >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha9(\n        friendListSchemaGraphQL17Alpha9,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  interface Data {\n    friendList: Array<{ __typename: \"Friend\"; id: string; name: string }>;\n  }\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: (_, incoming) => {\n              return incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n  cache.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useBackgroundQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  interface QueryData {\n    friendList: Array<{ __typename: \"Friend\"; id: string; name: string }>;\n  }\n\n  const query: TypedDocumentNode<QueryData> = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => {\n                return incoming;\n              },\n            },\n          },\n        },\n      },\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    client.writeQuery({\n      query,\n      data: {\n        friendList: [\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"1\" },\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"2\" },\n          // @ts-expect-error\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useBackgroundQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useBackgroundQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\" },\n          { __typename: \"Friend\", id: \"2\" },\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery/testUtils.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type { DataState, ErrorLike, OperationVariables } from \"@apollo/client\";\nimport type { QueryRef, useBackgroundQuery } from \"@apollo/client/react\";\nimport { useReadQuery } from \"@apollo/client/react\";\n\nexport async function renderUseBackgroundQuery<\n  TData,\n  TVariables extends OperationVariables,\n  TQueryRef extends QueryRef<any, any, any>,\n  TStates extends DataState<TData>[\"dataState\"] = TQueryRef extends (\n    QueryRef<any, any, infer States>\n  ) ?\n    States\n  : never,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => [TQueryRef | undefined, useBackgroundQuery.Result<TData, TVariables>],\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({ queryRef }: { queryRef: QueryRef }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    replaceSnapshot(useReadQuery(queryRef) as any);\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"<Suspense />\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"<ErrorBoundary />\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useBackgroundQuery\" });\n    const [queryRef] = renderHook(props as any);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          {queryRef && <UseReadQuery queryRef={queryRef} />}\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useReadQuery.Result<TData, TStates> | { error: ErrorLike }\n  >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n"
  },
  {
    "path": "src/react/hooks/__tests__/useBackgroundQuery.test.tsx",
    "content": "import { act, renderHook, screen } from \"@testing-library/react\";\nimport type { RenderStream } from \"@testing-library/react-render-stream\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { equal } from \"@wry/equality\";\nimport { expectTypeOf } from \"expect-type\";\nimport { GraphQLError } from \"graphql\";\nimport React, { Suspense } from \"react\";\nimport type { FallbackProps } from \"react-error-boundary\";\nimport { ErrorBoundary as ReactErrorBoundary } from \"react-error-boundary\";\nimport { Observable, of } from \"rxjs\";\n\nimport type {\n  DataState,\n  DataValue,\n  ErrorPolicy,\n  ObservableQuery,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  skipToken,\n  useBackgroundQuery,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  PaginatedCaseData,\n  SimpleCaseData,\n  VariablesCaseData,\n  VariablesCaseVariables,\n} from \"@apollo/client/testing/internal\";\nimport {\n  addDelayToMocks,\n  createClientWrapper,\n  createMockWrapper,\n  setupMaskedVariablesCase,\n  setupPaginatedCase,\n  setupSimpleCase,\n  setupVariablesCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  concatPagination,\n  offsetLimitPagination,\n} from \"@apollo/client/utilities\";\nimport { getMainDefinition } from \"@apollo/client/utilities/internal\";\n\nimport type {\n  RefetchWritePolicy,\n  SubscribeToMoreFunction,\n} from \"../../../core/watchQueryOptions.js\";\nimport type {\n  MaskedVariablesCaseData,\n  UnmaskedVariablesCaseData,\n} from \"../../../testing/internal/scenarios/index.js\";\n\nafterEach(() => {\n  jest.useRealTimers();\n});\n\nfunction createDefaultTrackedComponents<\n  Snapshot extends {\n    result: useReadQuery.Result<any> | null;\n  },\n  TData = Snapshot[\"result\"] extends useReadQuery.Result<infer TData> | null ?\n    TData\n  : unknown,\n  TStates extends DataState<TData>[\"dataState\"] = Snapshot[\"result\"] extends (\n    useReadQuery.Result<any, infer TStates> | null\n  ) ?\n    TStates\n  : \"complete\" | \"streaming\",\n>(renderStream: RenderStream<Snapshot>) {\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function ReadQueryHook({\n    queryRef,\n  }: {\n    queryRef: QueryRef<TData, any, TStates>;\n  }) {\n    useTrackRenders();\n    renderStream.mergeSnapshot({\n      result: useReadQuery(queryRef),\n    } as unknown as Partial<Snapshot>);\n\n    return null;\n  }\n\n  return { SuspenseFallback, ReadQueryHook };\n}\n\nfunction createTrackedErrorComponents<Snapshot extends { error: Error | null }>(\n  renderStream: RenderStream<Snapshot>\n) {\n  function ErrorFallback({ error }: FallbackProps) {\n    useTrackRenders({ name: \"ErrorFallback\" });\n    renderStream.mergeSnapshot({ error } as Partial<Snapshot>);\n\n    return <div>Error</div>;\n  }\n\n  function ErrorBoundary({ children }: { children: React.ReactNode }) {\n    return (\n      <ReactErrorBoundary FallbackComponent={ErrorFallback}>\n        {children}\n      </ReactErrorBoundary>\n    );\n  }\n\n  return { ErrorBoundary };\n}\n\nfunction createErrorProfiler<TData = unknown>() {\n  return createRenderStream({\n    initialSnapshot: {\n      error: null as Error | null,\n      result: null as useReadQuery.Result<TData> | null,\n    },\n  });\n}\n\nfunction createDefaultProfiler<TData = unknown>() {\n  return createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<TData> | null,\n    },\n  });\n}\n\nit(\"fetches a simple query with minimal config\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"tears down the query on unmount\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { unmount } = await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  // initial suspended render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  unmount();\n\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"auto disposes of the queryRef if not used within timeout\", async () => {\n  jest.useFakeTimers();\n  const { query } = setupSimpleCase();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  const { result } = renderHook(() => useBackgroundQuery(query, { client }));\n\n  const [queryRef] = result.current;\n\n  expect(queryRef).not.toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await act(() => {\n    link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n    // Ensure simulateResult will deliver the result since its wrapped with\n    // setTimeout\n    jest.advanceTimersByTime(10);\n  });\n\n  jest.advanceTimersByTime(30_000);\n\n  expect(queryRef).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"auto disposes of the queryRef if not used within configured timeout\", async () => {\n  jest.useFakeTimers();\n  const { query } = setupSimpleCase();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      react: {\n        suspense: {\n          autoDisposeTimeoutMs: 5000,\n        },\n      },\n    },\n  });\n\n  const { result } = renderHook(() => useBackgroundQuery(query, { client }));\n\n  const [queryRef] = result.current;\n\n  expect(queryRef).not.toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await act(() => {\n    link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n    // Ensure simulateResult will deliver the result since its wrapped with\n    // setTimeout\n    jest.advanceTimersByTime(10);\n  });\n\n  jest.advanceTimersByTime(5000);\n\n  expect(queryRef).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"will resubscribe after disposed when mounting useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      react: {\n        suspense: {\n          // Set this to something really low to avoid fake timers\n          autoDisposeTimeoutMs: 20,\n        },\n      },\n    },\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(false);\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  // Wait long enough for auto dispose to kick in\n  await wait(80);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  await user.click(screen.getByText(\"Toggle\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello again\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"auto resubscribes when mounting useReadQuery after naturally disposed by useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  // We retain the cache entry in useBackgroundQuery to avoid recreating the\n  // queryRef if useBackgroundQuery rerenders before useReadQuery is mounted\n  // again.\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await user.click(toggleButton);\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello again\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"does not recreate queryRef and execute a network request when rerendering useBackgroundQuery after queryRef is disposed\", async () => {\n  const { query } = setupSimpleCase();\n  const user = userEvent.setup();\n  let fetchCount = 0;\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      fetchCount++;\n\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({ data: { greeting: \"Hello\" } });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n    // Use a fetchPolicy of no-cache to ensure we can more easily track if\n    // another network request was made\n    const [queryRef] = useBackgroundQuery(query, { fetchPolicy: \"no-cache\" });\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  await rerender(<App />);\n  await renderStream.takeRender();\n\n  expect(fetchCount).toBe(1);\n\n  await user.click(toggleButton);\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\n// https://github.com/apollographql/apollo-client/issues/11815\nit(\"does not recreate queryRef or execute a network request when rerendering useBackgroundQuery in strict mode\", async () => {\n  const { query } = setupSimpleCase();\n  const user = userEvent.setup();\n  let fetchCount = 0;\n  const client = new ApolloClient({\n    link: new ApolloLink(() => {\n      fetchCount++;\n\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({ data: { greeting: \"Hello\" } });\n          observer.complete();\n        }, 20);\n      });\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      queryRef: null as QueryRef<SimpleCaseData> | null,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [, setCount] = React.useState(0);\n    // Use a fetchPolicy of no-cache to ensure we can more easily track if\n    // another network request was made\n    const [queryRef] = useBackgroundQuery(query, { fetchPolicy: \"no-cache\" });\n\n    renderStream.mergeSnapshot({ queryRef });\n\n    return (\n      <>\n        <button onClick={() => setCount((count) => count + 1)}>\n          Increment\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client, React.StrictMode),\n  });\n\n  const incrementButton = screen.getByText(\"Increment\");\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  // eslint-disable-next-line testing-library/render-result-naming-convention\n  const firstRender = await renderStream.takeRender();\n  const initialQueryRef = firstRender.snapshot.queryRef;\n\n  await user.click(incrementButton);\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.queryRef).toBe(initialQueryRef);\n    expect(fetchCount).toBe(1);\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"disposes of the queryRef when unmounting before it is used by useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  function App() {\n    useTrackRenders();\n    useBackgroundQuery(query);\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { unmount } = await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  unmount();\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"disposes of old queryRefs when changing variables before the queryRef is used by useReadQuery\", async () => {\n  const { query, mocks } = setupVariablesCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  function App({ id }: { id: string }) {\n    useTrackRenders();\n    useBackgroundQuery(query, { variables: { id } });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App id=\"1\" />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query, {\n    variables: { id: \"1\" },\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await rerender(<App id=\"2\" />);\n\n  await wait(10);\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query, {\n    variables: { id: \"2\" },\n  });\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query, {\n    variables: { id: \"1\" },\n  });\n});\n\nit(\"does not prematurely dispose of the queryRef when using strict mode\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  function App() {\n    useTrackRenders();\n    useBackgroundQuery(query);\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client, React.StrictMode),\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await wait(10);\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"disposes of the queryRef when unmounting before it is used by useReadQuery even if it has been rerendered\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n  const user = userEvent.setup();\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  function App() {\n    useTrackRenders();\n    useBackgroundQuery(query);\n\n    const [a, setA] = React.useState(0);\n\n    return (\n      <>\n        <button onClick={() => setA(a + 1)}>Increment</button>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { unmount } = await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n  const button = screen.getByText(\"Increment\");\n\n  await user.click(button);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await wait(0);\n\n  unmount();\n  await wait(0);\n  expect(client.getObservableQueries().size).toBe(0);\n});\n\nit(\"allows the client to be overridden\", async () => {\n  const { query } = setupSimpleCase();\n\n  const globalClient = new ApolloClient({\n    link: new ApolloLink(() => of({ data: { greeting: \"global hello\" } })),\n    cache: new InMemoryCache(),\n  });\n\n  const localClient = new ApolloClient({\n    link: new ApolloLink(() => of({ data: { greeting: \"local hello\" } })),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { client: localClient });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(globalClient),\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"local hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"passes context to the link\", async () => {\n  const query = gql`\n    query ContextQuery {\n      context\n    }\n  `;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      const { valueA, valueB } = operation.getContext();\n\n      observer.next({ data: { context: { valueA, valueB } } });\n      observer.complete();\n    });\n  });\n\n  const renderStream = createDefaultProfiler();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      context: { valueA: \"A\", valueB: \"B\" },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ link }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { context: { valueA: \"A\", valueB: \"B\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"returns initial cache data followed by network data when the fetch policy is `cache-and-network`\", async () => {\n  const { query } = setupSimpleCase();\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { greeting: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { greeting: \"from cache\" } });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"from cache\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"all data is present in the cache, no network request is made\", async () => {\n  const { query } = setupSimpleCase();\n  const cache = new InMemoryCache();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    fetchCount++;\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { greeting: \"from link\" } });\n        observer.complete();\n      }, 20);\n    });\n  });\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { greeting: \"from cache\" } });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-first\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n  expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { greeting: \"from cache\" },\n    dataState: \"complete\",\n    error: undefined,\n    networkStatus: NetworkStatus.ready,\n  });\n\n  expect(fetchCount).toBe(0);\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"partial data is present in the cache so it is ignored and network request is made\", async () => {\n  const query = gql`\n    {\n      hello\n      foo\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\", foo: \"bar\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  {\n    // we expect a \"Missing field 'foo' while writing result...\" error\n    // when writing hello to the cache, so we'll silence the console.error\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({ query, data: { hello: \"from cache\" } });\n  }\n\n  const renderStream = createDefaultProfiler();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-first\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { foo: \"bar\", hello: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"existing data in the cache is ignored when fetchPolicy is 'network-only'\", async () => {\n  const { query } = setupSimpleCase();\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { greeting: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { greeting: \"from cache\" } });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"network-only\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(client.cache.extract()).toEqual({\n    ROOT_QUERY: { __typename: \"Query\", greeting: \"from link\" },\n  });\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"fetches data from the network but does not update the cache when fetchPolicy is 'no-cache'\", async () => {\n  const { query } = setupSimpleCase();\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { greeting: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { greeting: \"from cache\" } });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { fetchPolicy: \"no-cache\" });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(client.cache.extract()).toEqual({\n    ROOT_QUERY: { __typename: \"Query\", greeting: \"from cache\" },\n  });\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"works with startTransition to change variables\", async () => {\n  type Variables = {\n    id: string;\n  };\n\n  interface Data {\n    todo: {\n      id: string;\n      name: string;\n      completed: boolean;\n    };\n  }\n\n  const user = userEvent.setup();\n\n  const query: TypedDocumentNode<Data, Variables> = gql`\n    query TodoItemQuery($id: ID!) {\n      todo(id: $id) {\n        id\n        name\n        completed\n      }\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"2\" } },\n      result: {\n        data: {\n          todo: { id: \"2\", name: \"Take out trash\", completed: true },\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      isPending: false,\n      result: null as useReadQuery.Result<Data> | null,\n    },\n  });\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [id, setId] = React.useState(\"1\");\n    const [isPending, startTransition] = React.useTransition();\n    const [queryRef] = useBackgroundQuery(query, {\n      variables: { id },\n    });\n\n    renderStream.mergeSnapshot({ isPending });\n\n    return (\n      <>\n        <button\n          onClick={() => {\n            startTransition(() => {\n              setId(\"2\");\n            });\n          }}\n        >\n          Change todo\n        </button>\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </ApolloProvider>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Change todo\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: true,\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    // Eventually we should see the updated todo content once its done\n    // suspending.\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { todo: { id: \"2\", name: \"Take out trash\", completed: true } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n});\n\nit(\"reacts to cache updates\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello again\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"You again?\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"You again?\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"reacts to variables updates\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App({ id }: { id: string }) {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { variables: { id } });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App id=\"1\" />, {\n    wrapper: createMockWrapper({\n      mocks: addDelayToMocks(mocks, 150, true),\n    }),\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender(<App id=\"2\" />);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"does not suspend when `skip` is true\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { skip: true });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        {queryRef && <ReadQueryHook queryRef={queryRef} />}\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  const { renderedComponents } = await renderStream.takeRender();\n\n  expect(renderedComponents).toStrictEqual([App]);\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"does not suspend when using `skipToken` in options\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, skipToken);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        {queryRef && <ReadQueryHook queryRef={queryRef} />}\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  const { renderedComponents } = await renderStream.takeRender();\n\n  expect(renderedComponents).toStrictEqual([App]);\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"suspends when `skip` becomes `false` after it was `true`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, { skip });\n\n    return (\n      <>\n        <button onClick={() => setSkip(false)}>Run query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await user.click(screen.getByText(\"Run query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"suspends when switching away from `skipToken` in options\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, skip ? skipToken : undefined);\n\n    return (\n      <>\n        <button onClick={() => setSkip(false)}>Run query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await user.click(screen.getByText(\"Run query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"renders skip result, does not suspend, and maintains `data` when `skip` becomes `true` after it was `false`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(false);\n    const [queryRef] = useBackgroundQuery(query, { skip });\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"renders skip result, does not suspend, and maintains `data` when switching back to `skipToken`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(false);\n    const [queryRef] = useBackgroundQuery(query, skip ? skipToken : undefined);\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"does not make network requests when `skip` is `true`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n\n  let fetchCount = 0;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      fetchCount++;\n\n      const mock = mocks.find(({ request }) =>\n        equal(request.query, operation.query)\n      );\n\n      if (!mock) {\n        throw new Error(\"Could not find mock for operation\");\n      }\n\n      observer.next((mock as any).result);\n      observer.complete();\n    });\n  });\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, { skip });\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial skipped result\n  await renderStream.takeRender();\n  expect(fetchCount).toBe(0);\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  expect(fetchCount).toBe(1);\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // Toggle skip to `true`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  expect(fetchCount).toBe(1);\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"does not make network requests when `skipToken` is used\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n  const user = userEvent.setup();\n\n  let fetchCount = 0;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      fetchCount++;\n\n      const mock = mocks.find(({ request }) =>\n        equal(request.query, operation.query)\n      );\n\n      if (!mock) {\n        throw new Error(\"Could not find mock for operation\");\n      }\n\n      observer.next((mock as any).result);\n      observer.complete();\n    });\n  });\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, skip ? skipToken : undefined);\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial skipped result\n  await renderStream.takeRender();\n  expect(fetchCount).toBe(0);\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  expect(fetchCount).toBe(1);\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // Toggle skip to `true`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  expect(fetchCount).toBe(1);\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"does not make network requests when `skipToken` is used in strict mode\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n  const user = userEvent.setup();\n\n  let fetchCount = 0;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      fetchCount++;\n\n      const mock = mocks.find(({ request }) =>\n        equal(request.query, operation.query)\n      );\n\n      if (!mock) {\n        throw new Error(\"Could not find mock for operation\");\n      }\n\n      observer.next((mock as any).result);\n      observer.complete();\n    });\n  });\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, skip ? skipToken : undefined);\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client, React.StrictMode),\n  });\n\n  // initial skipped result\n  await renderStream.takeRender();\n  expect(fetchCount).toBe(0);\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // Toggle skip to `true`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"does not make network requests when using `skip` option in strict mode\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n  const user = userEvent.setup();\n\n  let fetchCount = 0;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      fetchCount++;\n\n      const mock = mocks.find(({ request }) =>\n        equal(request.query, operation.query)\n      );\n\n      if (!mock) {\n        throw new Error(\"Could not find mock for operation\");\n      }\n\n      observer.next((mock as any).result);\n      observer.complete();\n    });\n  });\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [queryRef] = useBackgroundQuery(query, { skip });\n\n    return (\n      <>\n        <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client, React.StrictMode),\n  });\n\n  // initial skipped result\n  await renderStream.takeRender();\n  expect(fetchCount).toBe(0);\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // Toggle skip to `true`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"result is referentially stable\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  let result: useReadQuery.Result<SimpleCaseData> | null = null;\n\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App />, {\n    wrapper: createMockWrapper({ mocks }),\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    result = snapshot.result;\n  }\n\n  await rerender(<App />);\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toBe(result);\n  }\n});\n\nit(\"`skip` option works with `startTransition`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      isPending: false,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [isPending, startTransition] = React.useTransition();\n    const [queryRef] = useBackgroundQuery(query, { skip });\n\n    renderStream.mergeSnapshot({ isPending });\n\n    return (\n      <>\n        <button\n          disabled={isPending}\n          onClick={() =>\n            startTransition(() => {\n              setSkip((skip) => !skip);\n            })\n          }\n        >\n          Toggle skip\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: true,\n      result: null,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"`skipToken` works with `startTransition`\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      isPending: false,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [skip, setSkip] = React.useState(true);\n    const [isPending, startTransition] = React.useTransition();\n    const [queryRef] = useBackgroundQuery(query, skip ? skipToken : undefined);\n\n    renderStream.mergeSnapshot({ isPending });\n\n    return (\n      <>\n        <button\n          disabled={isPending}\n          onClick={() =>\n            startTransition(() => {\n              setSkip((skip) => !skip);\n            })\n          }\n        >\n          Toggle skip\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  // Toggle skip to `false`\n  await user.click(screen.getByText(\"Toggle skip\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: true,\n      result: null,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"applies `errorPolicy` on next fetch when it changes between renders\", async () => {\n  const { query } = setupSimpleCase();\n  const user = userEvent.setup();\n\n  const mocks = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: 10,\n    },\n    {\n      request: { query },\n      result: {\n        errors: [new GraphQLError(\"oops\")],\n      },\n      delay: 10,\n    },\n  ];\n\n  const renderStream = createErrorProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n  const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [errorPolicy, setErrorPolicy] = React.useState<ErrorPolicy>(\"none\");\n    const [queryRef, { refetch }] = useBackgroundQuery(query, {\n      errorPolicy,\n    });\n\n    return (\n      <>\n        <button onClick={() => setErrorPolicy(\"all\")}>\n          Change error policy\n        </button>\n        <button onClick={() => refetch()}>Refetch greeting</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            <ReadQueryHook queryRef={queryRef} />\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createMockWrapper({ mocks }) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Change error policy\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch greeting\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      error: null,\n      result: {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"oops\" }] }),\n        networkStatus: NetworkStatus.error,\n      },\n    });\n  }\n});\n\nit(\"applies `context` on next fetch when it changes between renders\", async () => {\n  interface Data {\n    context: Record<string, any>;\n  }\n\n  const user = userEvent.setup();\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      context\n    }\n  `;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((observer) => {\n      setTimeout(() => {\n        const { phase } = operation.getContext();\n        observer.next({ data: { context: { phase } } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  const renderStream = createDefaultProfiler<Data>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [phase, setPhase] = React.useState(\"initial\");\n    const [queryRef, { refetch }] = useBackgroundQuery(query, {\n      context: { phase },\n    });\n\n    return (\n      <>\n        <button onClick={() => setPhase(\"rerender\")}>Update context</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { context: { phase: \"initial\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Update context\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { context: { phase: \"rerender\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"applies changed `refetchWritePolicy` to next fetch when changing between renders\", async () => {\n  interface Data {\n    primes: number[];\n  }\n\n  const user = userEvent.setup();\n\n  const query: TypedDocumentNode<Data, { min: number; max: number }> = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 30, max: 50 } },\n      result: { data: { primes: [31, 37, 41, 43, 47] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<Data>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [refetchWritePolicy, setRefetchWritePolicy] =\n      React.useState<RefetchWritePolicy>(\"merge\");\n\n    const [queryRef, { refetch }] = useBackgroundQuery(query, {\n      refetchWritePolicy,\n      variables: { min: 0, max: 12 },\n    });\n\n    return (\n      <>\n        <button onClick={() => setRefetchWritePolicy(\"overwrite\")}>\n          Change refetch write policy\n        </button>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>\n          Refetch next\n        </button>\n        <button onClick={() => refetch({ min: 30, max: 50 })}>\n          Refetch last\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial suspended render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch next\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n  }\n\n  await user.click(screen.getByText(\"Change refetch write policy\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch last\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [31, 37, 41, 43, 47] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n      [undefined, [31, 37, 41, 43, 47]],\n    ]);\n  }\n});\n\nit(\"applies `returnPartialData` on next fetch when it changes between renders\", async () => {\n  const query: TypedDocumentNode<\n    VariablesCaseData,\n    Record<string, never>\n  > = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  interface PartialData {\n    character: {\n      __typename: \"Character\";\n      id: string;\n    };\n  }\n\n  const user = userEvent.setup();\n\n  const partialQuery: TypedDocumentNode<PartialData> = gql`\n    query {\n      character {\n        __typename\n        id\n      }\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange\",\n          },\n        },\n      },\n      delay: 10,\n    },\n    {\n      request: { query },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange (refetched)\",\n          },\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [returnPartialData, setReturnPartialData] = React.useState(false);\n    const [queryRef] = useBackgroundQuery(query, { returnPartialData });\n\n    return (\n      <>\n        <button onClick={() => setReturnPartialData(true)}>\n          Update partial data\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial suspended render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Update partial data\"));\n  await renderStream.takeRender();\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Character\", id: \"1\" }),\n    fields: {\n      name: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strange (refetched)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"applies updated `fetchPolicy` on next fetch when it changes between renders\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const user = userEvent.setup();\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    variables: { id: \"1\" },\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Spider-Cacheman\",\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    const [fetchPolicy, setFetchPolicy] =\n      React.useState<useBackgroundQuery.FetchPolicy>(\"cache-first\");\n\n    const [queryRef, { refetch }] = useBackgroundQuery(query, {\n      fetchPolicy,\n      variables: { id: \"1\" },\n    });\n\n    return (\n      <>\n        <button onClick={() => setFetchPolicy(\"no-cache\")}>\n          Change fetch policy\n        </button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Spider-Cacheman\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Change fetch policy\"));\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    // ensure we haven't changed the result yet just by changing the fetch policy\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Spider-Cacheman\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // Because we switched to a `no-cache` fetch policy, we should not see the\n  // newly fetched data in the cache after the fetch occurred.\n  expect(cache.readQuery({ query, variables: { id: \"1\" } })).toStrictEqualTyped(\n    {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Spider-Cacheman\",\n      },\n    }\n  );\n});\n\nit(\"properly handles changing options along with changing `variables`\", async () => {\n  const { query } = setupVariablesCase();\n  const user = userEvent.setup();\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        errors: [new GraphQLError(\"oops\")],\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"2\" } },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"2\",\n            name: \"Hulk\",\n          },\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    variables: {\n      id: \"1\",\n    },\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Doctor Strangecache\",\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createErrorProfiler<VariablesCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n  const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [id, setId] = React.useState(\"1\");\n\n    const [queryRef, { refetch }] = useBackgroundQuery(query, {\n      errorPolicy: id === \"1\" ? \"all\" : \"none\",\n      variables: { id },\n    });\n\n    return (\n      <>\n        <button onClick={() => setId(\"1\")}>Get first character</button>\n        <button onClick={() => setId(\"2\")}>Get second character</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <ErrorBoundary>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </ErrorBoundary>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      error: null,\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strangecache\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Get second character\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      error: null,\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"2\",\n            name: \"Hulk\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Get first character\"));\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      error: null,\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strangecache\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    // Ensure we render the inline error instead of the error boundary, which\n    // tells us the error policy was properly applied.\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      error: null,\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strangecache\",\n          },\n        },\n        dataState: \"complete\",\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"oops\" }] }),\n        networkStatus: NetworkStatus.error,\n      },\n    });\n  }\n});\n\nit('does not suspend when partial data is in the cache and using a \"cache-first\" fetch policy with returnPartialData', async () => {\n  const { query, mocks } = setupVariablesCase();\n  const cache = new InMemoryCache();\n\n  {\n    // Disable missing field warning\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      // @ts-expect-error writing partial query data\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      variables: { id: \"1\" },\n    });\n  }\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-first\",\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit('suspends and does not use partial data from other variables in the cache when changing variables and using a \"cache-first\" fetch policy with returnPartialData: true', async () => {\n  const { query, mocks } = setupVariablesCase();\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App({ id }: { id: string }) {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-first\",\n      returnPartialData: true,\n      variables: { id },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App id=\"1\" />, {\n    wrapper: createMockWrapper({\n      cache,\n      mocks: addDelayToMocks(mocks, 150, true),\n    }),\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender(<App id=\"2\" />);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit('suspends when partial data is in the cache and using a \"network-only\" fetch policy with returnPartialData', async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const partialQuery = gql`\n    query ($id: String!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    variables: { id: \"1\" },\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"network-only\",\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit('suspends when partial data is in the cache and using a \"no-cache\" fetch policy with returnPartialData', async () => {\n  using _consoleSpy = spyOnConsole(\"warn\");\n  const { query, mocks } = setupVariablesCase();\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"no-cache\",\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit('warns when using returnPartialData with a \"no-cache\" fetch policy', async () => {\n  using _consoleSpy = spyOnConsole(\"warn\");\n\n  const query: TypedDocumentNode<SimpleCaseData> = gql`\n    query UserQuery {\n      greeting\n    }\n  `;\n  const mocks = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n    },\n  ];\n\n  renderHook(\n    () =>\n      useBackgroundQuery(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: ({ children }) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      ),\n    }\n  );\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n  );\n});\n\nit('does not suspend when partial data is in the cache and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit('suspends and does not use partial data when changing variables and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n  const { query, mocks } = setupVariablesCase();\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App({ id }: { id: string }) {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n      returnPartialData: true,\n      variables: { id },\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await renderStream.render(<App id=\"1\" />, {\n    wrapper: createMockWrapper({\n      cache,\n      mocks: addDelayToMocks(mocks, 150, true),\n    }),\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender(<App id=\"2\" />);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit.each<useBackgroundQuery.FetchPolicy>([\n  \"cache-first\",\n  \"network-only\",\n  \"cache-and-network\",\n])(\n  'responds to cache updates in strict mode while using a \"%s\" fetch policy',\n  async (fetchPolicy) => {\n    const { query, mocks } = setupSimpleCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createDefaultProfiler<SimpleCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef] = useBackgroundQuery(query, { fetchPolicy });\n\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client, React.StrictMode),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    client.writeQuery({\n      query,\n      data: { greeting: \"Updated hello\" },\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { greeting: \"Updated hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  }\n);\n\nit(\"masks queries when dataMasking is `true`\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  // loading\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"does not mask query when dataMasking is `false`\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n      age: number;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: false,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // loading\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    },\n    dataState: \"complete\",\n    error: undefined,\n    networkStatus: NetworkStatus.ready,\n  });\n});\n\nit(\"does not mask query by default\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n      age: number;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // loading\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    },\n    dataState: \"complete\",\n    error: undefined,\n    networkStatus: NetworkStatus.ready,\n  });\n});\n\nit(\"masks queries updated by the cache\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // loading\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User (updated)\",\n        // @ts-ignore TODO: Determine how to handle cache writes with masked\n        // query type\n        age: 35,\n      },\n    },\n  });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (updated)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"does not rerender when updating field in named fragment\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n\n  // loading\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        // @ts-ignore TODO: Determine how to handle cache writes with masked\n        // query type\n        age: 35,\n      },\n    },\n  });\n\n  await expect(renderStream).not.toRerender();\n\n  expect(client.readQuery({ query })).toStrictEqualTyped({\n    currentUser: {\n      __typename: \"User\",\n      id: 1,\n      name: \"Test User\",\n      age: 35,\n    },\n  });\n});\n\nit(\"masks result from cache when using with cache-first fetch policy\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    },\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-first\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    },\n    dataState: \"complete\",\n    error: undefined,\n    networkStatus: NetworkStatus.ready,\n  });\n});\n\nit(\"masks cache and network result when using cache-and-network fetch policy\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User (server)\",\n            age: 35,\n          },\n        },\n      },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 34,\n      },\n    },\n  });\n\n  const renderStream = createDefaultProfiler<Query>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n    });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"masks partial cache data when returnPartialData is `true`\", async () => {\n  type UserFieldsFragment = {\n    __typename: \"User\";\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User (server)\",\n            age: 35,\n          },\n        },\n      },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  {\n    using _ = spyOnConsole(\"error\");\n    client.writeQuery({\n      query,\n      data: {\n        // @ts-expect-error writing partial cache data\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          age: 34,\n        },\n      },\n    });\n  }\n\n  const renderStream = createDefaultProfiler<DeepPartial<Query>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { returnPartialData: true });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n        },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"masks partial data returned from data on errors with errorPolicy `all`\", async () => {\n  type UserFieldsFragment = {\n    age: number;\n  } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n  interface Query {\n    currentUser: {\n      __typename: \"User\";\n      id: number;\n      name: string | null;\n    } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n  }\n\n  const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n    query MaskedQuery {\n      currentUser {\n        id\n        name\n        ...UserFields\n      }\n    }\n\n    fragment UserFields on User {\n      age\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: null,\n            age: 34,\n          },\n        },\n        errors: [new GraphQLError(\"Couldn't get name\")],\n      },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const renderStream = createDefaultProfiler<Query | undefined>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultTrackedComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query, { errorPolicy: \"all\" });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // loading\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: null,\n        },\n      },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: null,\n            age: 34,\n          },\n        },\n        errors: [{ message: \"Couldn't get name\" }],\n      }),\n      networkStatus: NetworkStatus.error,\n    });\n  }\n});\n\ndescribe(\"refetch\", () => {\n  it(\"re-suspends when calling `refetch`\", async () => {\n    const { query, mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<VariablesCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetched)\",\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Spider-Man\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      // parent component re-suspends\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Spider-Man (refetched)\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"re-suspends when calling `refetch` with new variables\", async () => {\n    const { query, mocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<VariablesCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch({ id: \"2\" })}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Spider-Man\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"2\",\n            name: \"Black Widow\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"re-suspends multiple times when calling `refetch` multiple times\", async () => {\n    const { query, mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<VariablesCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetched)\",\n            },\n          },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetched again)\",\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    const button = screen.getByText(\"Refetch\");\n\n    await user.click(button);\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Spider-Man (refetched)\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(button);\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Spider-Man (refetched again)\",\n          },\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"throws errors when errors are returned after calling `refetch`\", async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n    const { query, mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<VariablesCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n    const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ErrorBoundary>\n              <ReadQueryHook queryRef={queryRef} />\n            </ErrorBoundary>\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"ErrorFallback\"]);\n      expect(snapshot.error).toEqual(\n        new CombinedGraphQLErrors({\n          errors: [{ message: \"Something went wrong\" }],\n        })\n      );\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it('ignores errors returned after calling `refetch` when errorPolicy is set to \"ignore\"', async () => {\n    const { query, mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const mocks = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<VariablesCaseData | undefined>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n    const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n        errorPolicy: \"ignore\",\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ErrorBoundary>\n              <ReadQueryHook queryRef={queryRef} />\n            </ErrorBoundary>\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it('returns errors after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n    const { query, mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const mocks = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<VariablesCaseData | undefined>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n    const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n        errorPolicy: \"all\",\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ErrorBoundary>\n              <ReadQueryHook queryRef={queryRef} />\n            </ErrorBoundary>\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"Something went wrong\" }],\n          }),\n          networkStatus: NetworkStatus.error,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it('handles partial data results after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n    type VariablesCaseData = {\n      character: {\n        __typename: \"Character\";\n        id: string;\n        name: string | null;\n      };\n    };\n    const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n      gql`\n        query CharacterQuery($id: ID!) {\n          character(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n    const { mocks: defaultMocks } = setupVariablesCase();\n    const user = userEvent.setup();\n    const mocks = [\n      ...defaultMocks,\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { character: { __typename: \"Character\", id: \"1\", name: null } },\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<VariablesCaseData | undefined>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n    const { ErrorBoundary } = createTrackedErrorComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n        errorPolicy: \"all\",\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch()}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ErrorBoundary>\n              <ReadQueryHook queryRef={queryRef} />\n            </ErrorBoundary>\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man\",\n            },\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        error: null,\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: null,\n            },\n          },\n          dataState: \"complete\",\n          error: new CombinedGraphQLErrors({\n            data: {\n              character: {\n                __typename: \"Character\",\n                id: \"1\",\n                name: null,\n              },\n            },\n            errors: [{ message: \"Something went wrong\" }],\n          }),\n          networkStatus: NetworkStatus.error,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"can refetch after error is encountered\", async () => {\n    type Variables = {\n      id: string;\n    };\n\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: null,\n          errors: [new GraphQLError(\"Oops couldn't fetch\")],\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<Data>();\n    const { SuspenseFallback } = createDefaultTrackedComponents(renderStream);\n\n    function ErrorFallback({ error, resetErrorBoundary }: FallbackProps) {\n      useTrackRenders();\n      renderStream.mergeSnapshot({ error });\n\n      return <button onClick={resetErrorBoundary}>Retry</button>;\n    }\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReactErrorBoundary\n            onReset={() => refetch()}\n            FallbackComponent={ErrorFallback}\n          >\n            <Todo queryRef={queryRef} />\n          </ReactErrorBoundary>\n        </Suspense>\n      );\n    }\n\n    function Todo({ queryRef }: { queryRef: QueryRef<Data> }) {\n      useTrackRenders();\n      renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      // Disable error message shown in the console due to an uncaught error.\n      using _consoleSpy = spyOnConsole(\"error\");\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ErrorFallback]);\n      expect(snapshot).toStrictEqualTyped({\n        error: new CombinedGraphQLErrors({\n          data: null,\n          errors: [{ message: \"Oops couldn't fetch\" }],\n        }),\n        result: null,\n      });\n    }\n\n    await user.click(screen.getByText(\"Retry\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([Todo]);\n      expect(snapshot).toStrictEqualTyped({\n        // TODO: We should reset the snapshot between renders to better capture\n        // the actual result. This makes it seem like the error is rendered, but\n        // in this is just leftover from the previous snapshot.\n        error: new CombinedGraphQLErrors({\n          data: null,\n          errors: [{ message: \"Oops couldn't fetch\" }],\n        }),\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n  });\n\n  it(\"throws errors on refetch after error is encountered after first fetch with error\", async () => {\n    // Disable error message shown in the console due to an uncaught error.\n    using _consoleSpy = spyOnConsole(\"error\");\n    type Variables = {\n      id: string;\n    };\n\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n\n    const user = userEvent.setup();\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: null,\n          errors: [new GraphQLError(\"Oops couldn't fetch\")],\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: null,\n          errors: [new GraphQLError(\"Oops couldn't fetch again\")],\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createErrorProfiler<Data>();\n    const { SuspenseFallback } = createDefaultTrackedComponents(renderStream);\n\n    function ErrorFallback({ error, resetErrorBoundary }: FallbackProps) {\n      useTrackRenders();\n      renderStream.mergeSnapshot({ error });\n\n      return <button onClick={resetErrorBoundary}>Retry</button>;\n    }\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReactErrorBoundary\n            onReset={() => refetch()}\n            FallbackComponent={ErrorFallback}\n          >\n            <Todo queryRef={queryRef} />\n          </ReactErrorBoundary>\n        </Suspense>\n      );\n    }\n\n    function Todo({ queryRef }: { queryRef: QueryRef<Data> }) {\n      useTrackRenders();\n      renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ErrorFallback]);\n      expect(snapshot).toStrictEqualTyped({\n        error: new CombinedGraphQLErrors({\n          data: null,\n          errors: [{ message: \"Oops couldn't fetch\" }],\n        }),\n        result: null,\n      });\n    }\n\n    await user.click(screen.getByText(\"Retry\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ErrorFallback]);\n      expect(snapshot).toStrictEqualTyped({\n        error: new CombinedGraphQLErrors({\n          data: null,\n          errors: [{ message: \"Oops couldn't fetch again\" }],\n        }),\n        result: null,\n      });\n    }\n  });\n\n  it(\"`refetch` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n    type Variables = {\n      id: string;\n    };\n\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        isPending: false,\n        result: null as useReadQuery.Result<Data> | null,\n      },\n    });\n\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [isPending, startTransition] = React.useTransition();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      renderStream.mergeSnapshot({ isPending });\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                void refetch();\n              });\n            }}\n          >\n            Refetch\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ mocks }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      // startTransition will avoid rendering the suspense fallback for already\n      // revealed content if the state update inside the transition causes the\n      // component to suspend.\n      //\n      // Here we should not see the suspense fallback while the component\n      // suspends until the todo is finished loading. Seeing the suspense\n      // fallback is an indication that we are suspending the component too late\n      // in the process.\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: true,\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      // Eventually we should see the updated todo content once its done\n      // suspending.\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n  });\n\n  it('honors refetchWritePolicy set to \"merge\"', async () => {\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<QueryData, { min: number; max: number }> =\n      gql`\n        query GetPrimes($min: number, $max: number) {\n          primes(min: $min, max: $max)\n        }\n      `;\n\n    interface QueryData {\n      primes: number[];\n    }\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const renderStream = createDefaultProfiler<QueryData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache,\n    });\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { min: 0, max: 12 },\n        refetchWritePolicy: \"merge\",\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { primes: [2, 3, 5, 7, 11] },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n      expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n      expect(mergeParams).toEqual([\n        [undefined, [2, 3, 5, 7, 11]],\n        [\n          [2, 3, 5, 7, 11],\n          [13, 17, 19, 23, 29],\n        ],\n      ]);\n    }\n  });\n\n  it('defaults refetchWritePolicy to \"overwrite\"', async () => {\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<QueryData, { min: number; max: number }> =\n      gql`\n        query GetPrimes($min: number, $max: number) {\n          primes(min: $min, max: $max)\n        }\n      `;\n\n    interface QueryData {\n      primes: number[];\n    }\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache,\n    });\n\n    const renderStream = createDefaultProfiler<QueryData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { refetch }] = useBackgroundQuery(query, {\n        variables: { min: 0, max: 12 },\n      });\n\n      return (\n        <>\n          <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { primes: [2, 3, 5, 7, 11] },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n      expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n    }\n\n    await user.click(screen.getByText(\"Refetch\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { primes: [13, 17, 19, 23, 29] },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n      expect(mergeParams).toEqual([\n        [undefined, [2, 3, 5, 7, 11]],\n        [undefined, [13, 17, 19, 23, 29]],\n      ]);\n    }\n  });\n});\n\ndescribe(\"fetchMore\", () => {\n  it(\"re-suspends when calling `fetchMore` with different variables\", async () => {\n    const { query, link } = setupPaginatedCase();\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    });\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<PaginatedCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { fetchMore }] = useBackgroundQuery(query);\n\n      return (\n        <>\n          <button\n            onClick={() => fetchMore({ variables: { offset: 2, limit: 2 } })}\n          >\n            Fetch more\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ cache, link }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 1, letter: \"A\" },\n            { __typename: \"Letter\", position: 2, letter: \"B\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch more\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 3, letter: \"C\" },\n            { __typename: \"Letter\", position: 4, letter: \"D\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"properly uses `updateQuery` when calling `fetchMore`\", async () => {\n    const { query, link } = setupPaginatedCase();\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<PaginatedCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { fetchMore }] = useBackgroundQuery(query);\n\n      return (\n        <>\n          <button\n            onClick={() =>\n              fetchMore({\n                variables: { offset: 2, limit: 2 },\n                updateQuery: (prev, { fetchMoreResult }) => ({\n                  letters: prev.letters.concat(fetchMoreResult.letters),\n                }),\n              })\n            }\n          >\n            Fetch more\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createMockWrapper({ link }),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 1, letter: \"A\" },\n            { __typename: \"Letter\", position: 2, letter: \"B\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch more\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 1, letter: \"A\" },\n            { __typename: \"Letter\", position: 2, letter: \"B\" },\n            { __typename: \"Letter\", position: 3, letter: \"C\" },\n            { __typename: \"Letter\", position: 4, letter: \"D\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"properly uses cache field policies when calling `fetchMore` without `updateQuery`\", async () => {\n    const { query, link } = setupPaginatedCase();\n    const user = userEvent.setup();\n    const renderStream = createDefaultProfiler<PaginatedCaseData>();\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              letters: concatPagination(),\n            },\n          },\n        },\n      }),\n    });\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { fetchMore }] = useBackgroundQuery(query);\n\n      return (\n        <>\n          <button\n            onClick={() => fetchMore({ variables: { offset: 2, limit: 2 } })}\n          >\n            Fetch more\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 1, letter: \"A\" },\n            { __typename: \"Letter\", position: 2, letter: \"B\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch more\"));\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result).toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", position: 1, letter: \"A\" },\n            { __typename: \"Letter\", position: 2, letter: \"B\" },\n            { __typename: \"Letter\", position: 3, letter: \"C\" },\n            { __typename: \"Letter\", position: 4, letter: \"D\" },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    await expect(renderStream).not.toRerender({ timeout: 50 });\n  });\n\n  it(\"`fetchMore` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n    type Variables = {\n      offset: number;\n    };\n\n    interface Todo {\n      __typename: \"Todo\";\n      id: string;\n      name: string;\n      completed: boolean;\n    }\n\n    interface Data {\n      todos: Todo[];\n    }\n\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodosQuery($offset: Int!) {\n        todos(offset: $offset) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { offset: 0 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { offset: 1 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        isPending: false,\n        result: null as useReadQuery.Result<Data> | null,\n      },\n    });\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              todos: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n    });\n\n    function App() {\n      useTrackRenders();\n      const [isPending, startTransition] = React.useTransition();\n      const [queryRef, { fetchMore }] = useBackgroundQuery(query, {\n        variables: { offset: 0 },\n      });\n\n      renderStream.mergeSnapshot({ isPending });\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                void fetchMore({ variables: { offset: 1 } });\n              });\n            }}\n          >\n            Load more\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Load more\"));\n\n    {\n      // startTransition will avoid rendering the suspense fallback for already\n      // revealed content if the state update inside the transition causes the\n      // component to suspend.\n      //\n      // Here we should not see the suspense fallback while the component suspends\n      // until the todo is finished loading. Seeing the suspense fallback is an\n      // indication that we are suspending the component too late in the process.\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: true,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    {\n      // Eventually we should see the updated todos content once its done\n      // suspending.\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11708\n  it(\"`fetchMore` works with startTransition when setting errorPolicy as default option in ApolloClient constructor\", async () => {\n    type Variables = {\n      offset: number;\n    };\n\n    interface Todo {\n      __typename: \"Todo\";\n      id: string;\n      name: string;\n      completed: boolean;\n    }\n    interface Data {\n      todos: Todo[];\n    }\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodosQuery($offset: Int!) {\n        todos(offset: $offset) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { offset: 0 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { offset: 1 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        isPending: false,\n        result: null as useReadQuery.Result<Data> | null,\n      },\n    });\n\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              todos: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n      defaultOptions: {\n        watchQuery: {\n          errorPolicy: \"all\",\n        },\n      },\n    });\n\n    function App() {\n      useTrackRenders();\n      const [isPending, startTransition] = React.useTransition();\n      const [queryRef, { fetchMore }] = useBackgroundQuery(query, {\n        variables: { offset: 0 },\n      });\n\n      renderStream.mergeSnapshot({ isPending });\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                void fetchMore({ variables: { offset: 1 } });\n              });\n            }}\n          >\n            Load more\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <ReadQueryHook queryRef={queryRef} />\n          </Suspense>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Load more\"));\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: true,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n      expect(snapshot).toStrictEqualTyped({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n          dataState: \"complete\",\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"can subscribe to subscriptions and react to cache updates via `subscribeToMore`\", async () => {\n    interface SubscriptionData {\n      greetingUpdated: string;\n    }\n\n    type UpdateQueryFn = NonNullable<\n      ObservableQuery.SubscribeToMoreOptions<\n        SimpleCaseData,\n        Record<string, never>,\n        SubscriptionData\n      >[\"updateQuery\"]\n    >;\n\n    const subscription: TypedDocumentNode<\n      SubscriptionData,\n      Record<string, never>\n    > = gql`\n      subscription {\n        greetingUpdated\n      }\n    `;\n\n    const { mocks, query } = setupSimpleCase();\n\n    const wsLink = new MockSubscriptionLink();\n    const mockLink = new MockLink(mocks);\n\n    const link = ApolloLink.split(\n      ({ query }) => {\n        const definition = getMainDefinition(query);\n\n        return (\n          definition.kind === \"OperationDefinition\" &&\n          definition.operation === \"subscription\"\n        );\n      },\n      wsLink,\n      mockLink\n    );\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        subscribeToMore: null as SubscribeToMoreFunction<\n          SimpleCaseData,\n          Record<string, never>\n        > | null,\n        result: null as useReadQuery.Result<SimpleCaseData> | null,\n      },\n    });\n\n    const { SuspenseFallback, ReadQueryHook } =\n      createDefaultTrackedComponents(renderStream);\n\n    function App() {\n      useTrackRenders();\n      const [queryRef, { subscribeToMore }] = useBackgroundQuery(query);\n\n      renderStream.mergeSnapshot({ subscribeToMore });\n\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    const updateQuery = jest.fn<\n      ReturnType<UpdateQueryFn>,\n      Parameters<UpdateQueryFn>\n    >((_, { subscriptionData: { data } }) => {\n      return { greeting: data.greetingUpdated };\n    });\n\n    const { snapshot } = renderStream.getCurrentRender();\n\n    snapshot.subscribeToMore!({ document: subscription, updateQuery });\n\n    wsLink.simulateResult({\n      result: {\n        data: {\n          greetingUpdated: \"Subscription hello\",\n        },\n      },\n    });\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n      expect(snapshot.result).toStrictEqualTyped({\n        data: { greeting: \"Subscription hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      });\n    }\n\n    expect(updateQuery).toHaveBeenCalledTimes(1);\n    expect(updateQuery).toHaveBeenCalledWith(\n      { greeting: \"Hello\" },\n      {\n        complete: true,\n        previousData: { greeting: \"Hello\" },\n        subscriptionData: {\n          data: { greetingUpdated: \"Subscription hello\" },\n        },\n        variables: {},\n      }\n    );\n  });\n});\n\ndescribe.skip(\"type tests\", () => {\n  it(\"returns unknown when TData cannot be inferred\", () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n\n    const [queryRef] = useBackgroundQuery(query);\n    const { data, dataState } = useReadQuery(queryRef);\n\n    expectTypeOf(queryRef).toEqualTypeOf<\n      QueryRef<unknown, OperationVariables, \"complete\" | \"streaming\">\n    >;\n    expectTypeOf(data).toEqualTypeOf<unknown>();\n    expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n  });\n\n  it(\"disallows wider variables type than specified\", () => {\n    const { query } = setupVariablesCase();\n\n    useBackgroundQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  it(\"returns TData in default case\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, { variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it('returns TData | undefined with errorPolicy: \"ignore\"', () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | undefined | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { errorPolicy: \"ignore\", variables: { id: \"1\" } });\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | undefined | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"ignore\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"ignore\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  it('returns TData | undefined with errorPolicy: \"all\"', () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        errorPolicy: \"all\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | undefined | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        errorPolicy: \"all\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | undefined | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        errorPolicy: \"all\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"all\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"all\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | undefined\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  it('returns TData with errorPolicy: \"none\"', () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"none\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { errorPolicy: \"none\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns DeepPartial<TData> with returnPartialData: true\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        returnPartialData: true,\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: true, variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        returnPartialData: true,\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { returnPartialData: true, variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { returnPartialData: true, variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns TData with returnPartialData: false\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        returnPartialData: false,\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: false, variables: { id: \"1\" } });\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        returnPartialData: false,\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { returnPartialData: false, variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { returnPartialData: false, variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns DeepPartial<TData> with returnPartialData: boolean\", () => {\n    const { query } = setupVariablesCase();\n\n    const options = {\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    };\n\n    {\n      const [queryRef] = useBackgroundQuery(query, options);\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, options);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n  });\n\n  it(\"returns TData with returnPartialData: true and fetchPolicy: no-cache\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        returnPartialData: true,\n        fetchPolicy: \"no-cache\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, {\n        returnPartialData: true,\n        fetchPolicy: \"no-cache\",\n        variables: { id: \"1\" },\n      });\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns TData when passing an option that does not affect TData\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        fetchPolicy: \"no-cache\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { fetchPolicy: \"no-cache\", variables: { id: \"1\" } });\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        fetchPolicy: \"no-cache\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { fetchPolicy: \"no-cache\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { fetchPolicy: \"no-cache\", variables: { id: \"1\" } });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"handles combinations of options\", () => {\n    const { query } = setupVariablesCase();\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | undefined\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | MaskedVariablesCaseData\n        | DeepPartial<MaskedVariablesCaseData>\n        | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DeepPartial<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns correct TData type when combined options that do not affect TData\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n        variables: { id: \"1\" },\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns QueryRef<TData> | undefined when `skip` is present\", () => {\n    const { query } = setupVariablesCase();\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        skip: true,\n        variables: { id: \"1\" },\n      });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >;\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { skip: true, variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        skip: true,\n        variables: { id: \"1\" },\n      });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { skip: true, variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { skip: true, variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    // TypeScript is too smart and using a `const` or `let` boolean variable\n    // for the `skip` option results in a false positive. Using an options\n    // object allows us to properly check for a dynamic case.\n    const options = {\n      skip: true,\n    };\n\n    {\n      const [queryRef] = useBackgroundQuery(query, {\n        skip: options.skip,\n        variables: { id: \"1\" },\n      });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, {\n        skip: options.skip,\n        variables: { id: \"1\" },\n      });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { skip: options.skip, variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, { skip: options.skip, variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n  });\n\n  it(\"returns `undefined` when using `skipToken` unconditionally\", () => {\n    const { query } = setupVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(query, skipToken);\n\n      expectTypeOf(queryRef).toEqualTypeOf<undefined>();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, skipToken);\n\n      expectTypeOf(queryRef).toEqualTypeOf<undefined>();\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(maskedQuery, skipToken);\n\n      expectTypeOf(queryRef).toEqualTypeOf<undefined>();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, skipToken);\n\n      expectTypeOf(queryRef).toEqualTypeOf<undefined>();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, skipToken);\n\n      expectTypeOf(queryRef).toEqualTypeOf<undefined>();\n    }\n  });\n\n  it(\"returns QueryRef<TData> | undefined when using conditional `skipToken`\", () => {\n    const { query } = setupVariablesCase();\n    const options = {\n      skip: true,\n    };\n\n    {\n      const [queryRef] = useBackgroundQuery(\n        query,\n        options.skip ? skipToken : { variables: { id: \"1\" } }\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(\n        maskedQuery,\n        options.skip ? skipToken : { variables: { id: \"1\" } }\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(maskedQuery, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\"\n          >\n        | undefined\n      >();\n    }\n  });\n\n  it(\"returns QueryRef<DeepPartial<TData>> | undefined when using `skipToken` with `returnPartialData`\", () => {\n    const { query } = setupVariablesCase();\n    const options = {\n      skip: true,\n    };\n\n    {\n      const [queryRef] = useBackgroundQuery(\n        query,\n        options.skip ? skipToken : (\n          { returnPartialData: true, variables: { id: \"1\" } }\n        )\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(\n        query,\n        options.skip ? skipToken : (\n          { returnPartialData: true, variables: { id: \"1\" } }\n        )\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            VariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n        | undefined\n      >();\n    }\n\n    const { query: maskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [queryRef] = useBackgroundQuery(\n        maskedQuery,\n        options.skip ? skipToken : (\n          { returnPartialData: true, variables: { id: \"1\" } }\n        )\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(\n        maskedQuery,\n        options.skip ? skipToken : (\n          { returnPartialData: true, variables: { id: \"1\" } }\n        )\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n        | undefined\n      >();\n    }\n\n    {\n      const [queryRef] = useBackgroundQuery<\n        MaskedVariablesCaseData,\n        VariablesCaseVariables\n      >(\n        maskedQuery,\n        options.skip ? skipToken : (\n          { returnPartialData: true, variables: { id: \"1\" } }\n        )\n      );\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        | QueryRef<\n            MaskedVariablesCaseData,\n            VariablesCaseVariables,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n        | undefined\n      >();\n    }\n  });\n\n  it(\"uses proper masked types for refetch\", async () => {\n    const { query, unmaskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [, { refetch }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n      const { data } = await refetch();\n\n      expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n    }\n\n    {\n      const [, { refetch }] = useBackgroundQuery(unmaskedQuery, {\n        variables: { id: \"1\" },\n      });\n      const { data } = await refetch();\n\n      expectTypeOf(data).toEqualTypeOf<UnmaskedVariablesCaseData | undefined>();\n    }\n  });\n\n  it(\"uses proper masked types for fetchMore\", async () => {\n    const { query, unmaskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [, { fetchMore }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      const { data } = await fetchMore({\n        updateQuery: (queryData, { fetchMoreResult }) => {\n          expectTypeOf(queryData).toEqualTypeOf<UnmaskedVariablesCaseData>();\n\n          expectTypeOf(\n            fetchMoreResult\n          ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n\n          return {} as UnmaskedVariablesCaseData;\n        },\n      });\n\n      expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n    }\n\n    {\n      const [, { fetchMore }] = useBackgroundQuery(unmaskedQuery, {\n        variables: { id: \"1\" },\n      });\n\n      const { data } = await fetchMore({\n        updateQuery: (queryData, { fetchMoreResult }) => {\n          expectTypeOf(queryData).toEqualTypeOf<UnmaskedVariablesCaseData>();\n          expectTypeOf(queryData).not.toEqualTypeOf<MaskedVariablesCaseData>();\n\n          expectTypeOf(\n            fetchMoreResult\n          ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n          expectTypeOf(\n            fetchMoreResult\n          ).not.toEqualTypeOf<MaskedVariablesCaseData>();\n\n          return {} as UnmaskedVariablesCaseData;\n        },\n      });\n\n      expectTypeOf(data).toEqualTypeOf<UnmaskedVariablesCaseData | undefined>();\n    }\n  });\n\n  it(\"uses proper masked types for subscribeToMore\", async () => {\n    type CharacterFragment = {\n      __typename: \"Character\";\n      name: string;\n    } & { \" $fragmentName\": \"CharacterFragment\" };\n\n    type Subscription = {\n      pushLetter: {\n        __typename: \"Character\";\n        id: number;\n      } & { \" $fragmentRefs\": { CharacterFragment: CharacterFragment } };\n    };\n\n    type UnmaskedSubscription = {\n      pushLetter: {\n        __typename: \"Character\";\n        id: number;\n        name: string;\n      };\n    };\n\n    const { query, unmaskedQuery } = setupMaskedVariablesCase();\n\n    {\n      const [, { subscribeToMore }] = useBackgroundQuery(query, {\n        variables: { id: \"1\" },\n      });\n\n      const subscription: TypedDocumentNode<\n        Subscription,\n        { letterId: string }\n      > = gql`\n        subscription LetterPushed($letterId: ID!) {\n          pushLetter(letterId: $letterId) {\n            id\n            ...CharacterFragment\n          }\n        }\n\n        fragment CharacterFragment on Character {\n          name\n        }\n      `;\n\n      subscribeToMore({\n        document: subscription,\n        updateQuery: (\n          queryData,\n          { subscriptionData, variables, complete, previousData }\n        ) => {\n          expectTypeOf(queryData).toEqualTypeOf<\n            DeepPartial<UnmaskedVariablesCaseData>\n          >();\n          expectTypeOf(queryData).not.toEqualTypeOf<MaskedVariablesCaseData>();\n          expectTypeOf(previousData).toEqualTypeOf<\n            | UnmaskedVariablesCaseData\n            | DeepPartial<UnmaskedVariablesCaseData>\n            | undefined\n          >();\n\n          if (complete) {\n            // Should narrow the type\n            expectTypeOf(\n              previousData\n            ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n            expectTypeOf(\n              previousData\n            ).not.toEqualTypeOf<MaskedVariablesCaseData>();\n          } else {\n            expectTypeOf(previousData).toEqualTypeOf<\n              DeepPartial<UnmaskedVariablesCaseData> | undefined\n            >();\n          }\n\n          expectTypeOf(\n            subscriptionData.data\n          ).toEqualTypeOf<UnmaskedSubscription>();\n          expectTypeOf(subscriptionData.data).not.toEqualTypeOf<Subscription>();\n\n          expectTypeOf(variables).toEqualTypeOf<\n            VariablesCaseVariables | undefined\n          >();\n\n          return {} as UnmaskedVariablesCaseData;\n        },\n      });\n    }\n\n    {\n      const [, { subscribeToMore }] = useBackgroundQuery(unmaskedQuery, {\n        variables: { id: \"1\" },\n      });\n\n      const subscription: TypedDocumentNode<Subscription, never> = gql`\n        subscription {\n          pushLetter {\n            id\n            ...CharacterFragment\n          }\n        }\n\n        fragment CharacterFragment on Character {\n          name\n        }\n      `;\n\n      subscribeToMore({\n        document: subscription,\n        updateQuery: (\n          queryData,\n          { subscriptionData, variables, complete, previousData }\n        ) => {\n          expectTypeOf(queryData).toEqualTypeOf<\n            DeepPartial<UnmaskedVariablesCaseData>\n          >();\n          expectTypeOf(queryData).not.toEqualTypeOf<MaskedVariablesCaseData>();\n\n          expectTypeOf(previousData).toEqualTypeOf<\n            | UnmaskedVariablesCaseData\n            | DeepPartial<UnmaskedVariablesCaseData>\n            | undefined\n          >();\n\n          if (complete) {\n            // Should narrow the type\n            expectTypeOf(\n              previousData\n            ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n            expectTypeOf(\n              previousData\n            ).not.toEqualTypeOf<MaskedVariablesCaseData>();\n          } else {\n            expectTypeOf(previousData).toEqualTypeOf<\n              DeepPartial<UnmaskedVariablesCaseData> | undefined\n            >();\n          }\n\n          expectTypeOf(\n            subscriptionData.data\n          ).toEqualTypeOf<UnmaskedSubscription>();\n          expectTypeOf(subscriptionData.data).not.toEqualTypeOf<Subscription>();\n\n          expectTypeOf(variables).toEqualTypeOf<\n            VariablesCaseVariables | undefined\n          >();\n\n          return queryData as UnmaskedVariablesCaseData;\n        },\n      });\n    }\n  });\n\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const query = gql``;\n\n    useBackgroundQuery(query);\n    useBackgroundQuery(query, {});\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, { variables: { foo: \"bar\" } });\n    useBackgroundQuery(query, { variables: { bar: \"baz\" } });\n\n    let skip!: boolean;\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(query, skip ? skipToken : {});\n    useBackgroundQuery(query, skip ? skipToken : { variables: {} });\n    useBackgroundQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n    useBackgroundQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    useBackgroundQuery(query);\n    useBackgroundQuery(query, {});\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, { variables: { foo: \"bar\" } });\n    useBackgroundQuery(query, { variables: { bar: \"baz\" } });\n\n    let skip!: boolean;\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(query, skip ? skipToken : {});\n    useBackgroundQuery(query, skip ? skipToken : { variables: {} });\n    useBackgroundQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n    useBackgroundQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    useBackgroundQuery(query);\n    useBackgroundQuery(query, {});\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(query, skip ? skipToken : {});\n    useBackgroundQuery(query, skip ? skipToken : { variables: {} });\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error unknown variables\n      skip ? skipToken : { variables: { foo: \"bar\" } }\n    );\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    // @ts-expect-error\n    useBackgroundQuery(query);\n    // @ts-expect-error\n    useBackgroundQuery(query, {});\n    useBackgroundQuery(query, {\n      // @ts-expect-error\n      variables: {},\n    });\n    useBackgroundQuery(query, {\n      // @ts-expect-error\n      variables: undefined,\n    });\n    useBackgroundQuery(query, {\n      // @ts-expect-error\n      variables: {\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : {}\n    );\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : { variables: {} }\n    );\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : { variables: undefined }\n    );\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error unknown variables\n      skip ? skipToken : { variables: { foo: \"bar\" } }\n    );\n  });\n\n  test(\"optional variables are optional\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    useBackgroundQuery(query);\n    useBackgroundQuery(query, {});\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, { variables: { limit: 10 } });\n    useBackgroundQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useBackgroundQuery(query, {\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(query, skip ? skipToken : {});\n    useBackgroundQuery(query, skip ? skipToken : { variables: {} });\n    useBackgroundQuery(query, skip ? skipToken : { variables: { limit: 10 } });\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            limit: 10,\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n\n  test(\"enforces required variables when TVariables includes required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query);\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query, {});\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, { variables: { id: \"1\" } });\n    useBackgroundQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useBackgroundQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error missing variables option\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error missing variables option\n      skip ? skipToken : {}\n    );\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error missing required variables\n      skip ? skipToken : { variables: {} }\n    );\n    useBackgroundQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query);\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query, {});\n    // @ts-expect-error empty variables\n    useBackgroundQuery(query, { variables: {} });\n    useBackgroundQuery(query, { variables: { id: \"1\" } });\n    useBackgroundQuery(query, {\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    useBackgroundQuery(query, { variables: { id: \"1\", language: \"en\" } });\n    useBackgroundQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useBackgroundQuery(query, {\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error missing variables option\n    useBackgroundQuery(query, skip ? skipToken : undefined);\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error missing variables option\n      skip ? skipToken : {}\n    );\n    useBackgroundQuery(\n      query,\n      // @ts-expect-error missing required variables\n      skip ? skipToken : { variables: {} }\n    );\n    useBackgroundQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : { variables: { id: \"1\", language: \"en\" } }\n    );\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useBackgroundQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            language: \"en\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useFragment/arrays.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport { useFragment } from \"@apollo/client/react\";\nimport { createClientWrapper } from \"@apollo/client/testing/internal\";\n\ntest(\"can use array for `from` to get array of items\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"returns result as complete for null array item `from` value\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [null, null, null],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [null, null, null],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"returns as partial if some `from` items are incomplete mixed with null\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [null, null, { __typename: \"Item\", id: 5 }],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [null, null, null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"allows mix of array identifiers\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [{ __typename: \"Item\", id: 1 }, \"Item:2\", null],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"returns empty array with empty from\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useFragment({ fragment, from: [] }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [],\n    dataState: \"complete\",\n    complete: true,\n  });\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"returns incomplete results when cache is empty\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [null, null, null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: \"Dangling reference to missing Item:1 object\",\n      1: \"Dangling reference to missing Item:2 object\",\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"can use static arrays with useFragment with partially fulfilled items\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 2; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"handles changing array size\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n    ({ from }) => useFragment({ fragment, from }),\n    {\n      initialProps: {\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n        ],\n      },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await rerender({\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await rerender({\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await rerender({\n    from: [],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await rerender({\n    from: [{ __typename: \"Item\", id: 6 }],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [null],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: \"Dangling reference to missing Item:6 object\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"updates items in the array with cache writes\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const { cache } = client;\n\n  for (let i = 1; i <= 2; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 2,\n      text: \"Item #2 updated\",\n    },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      null,\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      2: \"Dangling reference to missing Item:5 object\",\n    },\n  });\n\n  client.cache.batch({\n    update: (cache) => {\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 1,\n          text: \"Item #1 from batch\",\n        },\n      });\n\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 from batch\",\n        },\n      });\n    },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1 from batch\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5 from batch\" },\n    ],\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Item\", id: 1 }),\n    fields: {\n      text: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5 from batch\" },\n    ],\n    dataState: \"partial\",\n    complete: false,\n    missing: {\n      0: {\n        text: \"Can't find field 'text' on Item:1 object\",\n      },\n    },\n  });\n\n  // should not cause rerender since its an item not watched\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 6,\n      text: \"Item #6 ignored\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useFragment.test.tsx",
    "content": "import assert from \"assert\";\n\nimport {\n  act,\n  render,\n  renderHook,\n  screen,\n  waitFor,\n  within,\n} from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport * as React from \"react\";\nimport type { Observer } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nimport type {\n  DocumentNode,\n  OperationVariables,\n  Reference,\n  StoreObject,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  DocumentTransform,\n  gql,\n  InMemoryCache,\n} from \"@apollo/client\";\nimport type { FragmentType } from \"@apollo/client/masking\";\nimport { ApolloProvider, useFragment, useQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport { concatPagination } from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\n\ndescribe(\"useFragment\", () => {\n  it(\"is importable and callable\", () => {\n    expect(typeof useFragment).toBe(\"function\");\n  });\n\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const ListFragment: TypedDocumentNode<QueryDataWithExtra> = gql`\n    fragment ListFragment on Query {\n      list {\n        id\n      }\n      # Used to make sure ListFragment got used, even if the id field of the\n      # nested list items is provided by other means.\n      extra\n    }\n  `;\n\n  const ItemFragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      text\n    }\n  `;\n\n  interface QueryData {\n    __typename?: \"Query\";\n    list: Item[];\n  }\n\n  interface QueryDataWithExtra extends QueryData {\n    extra: string;\n  }\n\n  it(\"can rerender individual list elements\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Item: {\n          fields: {\n            text(existing, { readField }) {\n              return existing || `Item #${readField(\"id\")}`;\n            },\n          },\n        },\n      },\n    });\n\n    const listQuery: TypedDocumentNode<QueryData> = gql`\n      query {\n        list {\n          id\n        }\n      }\n    `;\n\n    cache.writeQuery({\n      query: listQuery,\n      data: {\n        list: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      },\n    });\n\n    const renders: string[] = [];\n\n    function List() {\n      renders.push(\"list\");\n      const { loading, data } = useQuery(listQuery);\n      expect(loading).toBe(false);\n      return (\n        <ol>{data?.list.map((item) => <Item key={item.id} id={item.id} />)}</ol>\n      );\n    }\n\n    function Item(props: { id: number }) {\n      renders.push(\"item \" + props.id);\n      const { complete, data } = useFragment({\n        fragment: ItemFragment,\n        fragmentName: \"ItemFragment\",\n        from: {\n          __typename: \"Item\",\n          id: props.id,\n        },\n      });\n      return <li>{complete ? data.text : \"incomplete\"}</li>;\n    }\n\n    render(\n      <MockedProvider cache={cache}>\n        <List />\n      </MockedProvider>\n    );\n\n    function getItemTexts() {\n      return screen.getAllByText(/^Item/).map(\n        // eslint-disable-next-line testing-library/no-node-access\n        (li) => li.firstChild!.textContent\n      );\n    }\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\"list\", \"item 1\", \"item 2\", \"item 5\"]);\n\n    await act(async () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 2,\n          text: \"Item #2 updated\",\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      // Only the second item should have re-rendered.\n      \"item 2\",\n    ]);\n\n    await act(async () => {\n      cache.modify({\n        fields: {\n          list(list: readonly Reference[], { readField }) {\n            return [\n              ...list,\n              cache.writeFragment({\n                fragment: ItemFragment,\n                data: {\n                  __typename: \"Item\",\n                  id: 3,\n                  text: \"Item #3 from cache.modify\",\n                },\n              })!,\n              cache.writeFragment({\n                fragment: ItemFragment,\n                data: {\n                  __typename: \"Item\",\n                  id: 4,\n                  text: \"Item #4 from cache.modify\",\n                },\n              })!,\n            ].sort(\n              (ref1, ref2) =>\n                readField<Item[\"id\"]>(\"id\", ref1)! -\n                readField<Item[\"id\"]>(\"id\", ref2)!\n            );\n          },\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #3 from cache.modify\",\n        \"Item #4 from cache.modify\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      \"item 2\",\n      // This is what's new:\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 3\",\n      \"item 4\",\n      \"item 5\",\n    ]);\n\n    await act(async () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 4,\n          text: \"Item #4 updated\",\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #3 from cache.modify\",\n        \"Item #4 updated\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      \"item 2\",\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 3\",\n      \"item 4\",\n      \"item 5\",\n      // Only the fourth item should have re-rendered.\n      \"item 4\",\n    ]);\n\n    // set Item #2 back to its original value\n    await act(async () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 2,\n          text: \"Item #2\",\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2\",\n        \"Item #3 from cache.modify\",\n        \"Item #4 updated\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      \"item 2\",\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 3\",\n      \"item 4\",\n      \"item 5\",\n      \"item 4\",\n      // Only the second item should have re-rendered.\n      \"item 2\",\n    ]);\n\n    expect(cache.extract()).toStrictEqualTyped({\n      \"Item:1\": {\n        __typename: \"Item\",\n        id: 1,\n      },\n      \"Item:2\": {\n        __typename: \"Item\",\n        id: 2,\n        text: \"Item #2\",\n      },\n      \"Item:3\": {\n        __typename: \"Item\",\n        id: 3,\n        text: \"Item #3 from cache.modify\",\n      },\n      \"Item:4\": {\n        __typename: \"Item\",\n        id: 4,\n        text: \"Item #4 updated\",\n      },\n      \"Item:5\": {\n        __typename: \"Item\",\n        id: 5,\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        list: [\n          { __ref: \"Item:1\" },\n          { __ref: \"Item:2\" },\n          { __ref: \"Item:3\" },\n          { __ref: \"Item:4\" },\n          { __ref: \"Item:5\" },\n        ],\n      },\n      __META: {\n        extraRootIds: [\"Item:2\", \"Item:3\", \"Item:4\"],\n      },\n    });\n  });\n\n  it(\"returns data on first render\", () => {\n    const ItemFragment: TypedDocumentNode<Item> = gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `;\n    const cache = new InMemoryCache();\n    const item = { __typename: \"Item\", id: 1, text: \"Item #1\" };\n    cache.writeFragment({\n      fragment: ItemFragment,\n      data: item,\n    });\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n    });\n    function Component() {\n      const { data } = useFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 1 },\n      });\n      return <>{data.text}</>;\n    }\n    render(\n      <ApolloProvider client={client}>\n        <Component />\n      </ApolloProvider>\n    );\n\n    // would throw if not present synchronously\n    screen.getByText(/Item #1/);\n  });\n\n  it(\"allows the client to be overridden\", () => {\n    const ItemFragment: TypedDocumentNode<Item> = gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `;\n    const cache = new InMemoryCache();\n    const item = { __typename: \"Item\", id: 1, text: \"Item #1\" };\n    cache.writeFragment({\n      fragment: ItemFragment,\n      data: item,\n    });\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n    });\n    function Component() {\n      const { data } = useFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 1 },\n        client,\n      });\n      return <>{data.text}</>;\n    }\n\n    // Without a MockedProvider supplying the client via context,\n    // the client must be passed directly to the hook or an error is thrown\n    expect(() => render(<Component />)).not.toThrow(/pass an ApolloClient/);\n\n    // Item #1 is rendered\n    screen.getByText(/Item #1/);\n  });\n\n  it(\"throws if no client is provided\", () => {\n    function Component() {\n      const { data } = useFragment({\n        fragment: ItemFragment,\n        from: { __typename: \"Item\", id: 1 },\n      });\n      return <>{data.text}</>;\n    }\n\n    // silence the console error\n    {\n      using _spy = spyOnConsole(\"error\");\n      expect(() => render(<Component />)).toThrow(/pass an ApolloClient/);\n    }\n  });\n\n  it.each<TypedDocumentNode<{ list: Item[] }>>([\n    // This query uses a basic field-level @nonreactive directive.\n    gql`\n      query GetItems {\n        list {\n          id\n          text @nonreactive\n        }\n      }\n    `,\n    // This query uses @nonreactive on an anonymous/inline ...spread directive.\n    gql`\n      query GetItems {\n        list {\n          id\n          ... @nonreactive {\n            text\n          }\n        }\n      }\n    `,\n    // This query uses @nonreactive on a ...spread with a type condition.\n    gql`\n      query GetItems {\n        list {\n          id\n          ... on Item @nonreactive {\n            text\n          }\n        }\n      }\n    `,\n    // This query uses @nonreactive directive on a named fragment ...spread.\n    gql`\n      query GetItems {\n        list {\n          id\n          ...ItemText @nonreactive\n        }\n      }\n      fragment ItemText on Item {\n        text\n      }\n    `,\n  ])(\n    \"Parent list component can use @nonreactive to avoid rerendering\",\n    async (query) => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              list: concatPagination(),\n            },\n          },\n          Item: {\n            keyFields: [\"id\"],\n            // Configuring keyArgs:false for Item.text is one way to prevent field\n            // keys like text@nonreactive, but it's not the only way. Since\n            // @nonreactive is now in the KNOWN_DIRECTIVES array defined in\n            // utilities/graphql/storeUtils.ts, the '@nonreactive' suffix won't be\n            // automatically appended to field keys by default.\n            // fields: {\n            //   text: {\n            //     keyArgs: false,\n            //   },\n            // },\n          },\n        },\n      });\n\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n\n      const renders: string[] = [];\n\n      function List() {\n        const { data } = useQuery(query);\n\n        renders.push(\"list\");\n\n        return (\n          <ul>\n            {data?.list.map((item) => <Item key={item.id} item={item} />)}\n          </ul>\n        );\n      }\n\n      function Item({ item }: { item: Item }) {\n        const { data } = useFragment({\n          fragment: ItemFragment,\n          fragmentName: \"ItemFragment\",\n          from: item,\n        });\n\n        renders.push(`item ${item.id}`);\n\n        if (!data) return null;\n\n        return <li>{`Item #${item.id}: ${data.text}`}</li>;\n      }\n\n      act(() => {\n        cache.writeQuery({\n          query,\n          data: {\n            list: [\n              { __typename: \"Item\", id: 1, text: \"first\" },\n              { __typename: \"Item\", id: 2, text: \"second\" },\n              { __typename: \"Item\", id: 3, text: \"third\" },\n            ],\n          },\n        });\n      });\n\n      expect(cache.extract()).toStrictEqualTyped({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          list: [\n            { __ref: 'Item:{\"id\":1}' },\n            { __ref: 'Item:{\"id\":2}' },\n            { __ref: 'Item:{\"id\":3}' },\n          ],\n        },\n        'Item:{\"id\":1}': {\n          __typename: \"Item\",\n          id: 1,\n          text: \"first\",\n        },\n        'Item:{\"id\":2}': {\n          __typename: \"Item\",\n          id: 2,\n          text: \"second\",\n        },\n        'Item:{\"id\":3}': {\n          __typename: \"Item\",\n          id: 3,\n          text: \"third\",\n        },\n      });\n\n      render(\n        <ApolloProvider client={client}>\n          <List />\n        </ApolloProvider>\n      );\n\n      function getItemTexts() {\n        return screen.getAllByText(/Item #\\d+/).map((el) => el.textContent);\n      }\n\n      await waitFor(() => {\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: first\",\n          \"Item #2: second\",\n          \"Item #3: third\",\n        ]);\n      });\n\n      expect(renders).toStrictEqualTyped([\n        \"list\",\n        \"item 1\",\n        \"item 2\",\n        \"item 3\",\n      ]);\n\n      function appendLyToText(id: number) {\n        act(() => {\n          cache.modify({\n            id: cache.identify({ __typename: \"Item\", id })!,\n            fields: {\n              text(existing) {\n                return existing + \"ly\";\n              },\n            },\n          });\n        });\n      }\n\n      appendLyToText(2);\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: first\",\n          \"Item #2: secondly\",\n          \"Item #3: third\",\n        ]);\n      });\n\n      appendLyToText(1);\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n          \"item 1\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: firstly\",\n          \"Item #2: secondly\",\n          \"Item #3: third\",\n        ]);\n      });\n\n      appendLyToText(3);\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n          \"item 1\",\n          \"item 3\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: firstly\",\n          \"Item #2: secondly\",\n          \"Item #3: thirdly\",\n        ]);\n      });\n\n      act(() => {\n        cache.writeQuery({\n          query,\n          data: {\n            list: [\n              { __typename: \"Item\", id: 4, text: \"fourth\" },\n              { __typename: \"Item\", id: 5, text: \"fifth\" },\n            ],\n          },\n        });\n      });\n\n      expect(cache.extract()).toStrictEqualTyped({\n        ROOT_QUERY: {\n          __typename: \"Query\",\n          list: [\n            { __ref: 'Item:{\"id\":1}' },\n            { __ref: 'Item:{\"id\":2}' },\n            { __ref: 'Item:{\"id\":3}' },\n            { __ref: 'Item:{\"id\":4}' },\n            { __ref: 'Item:{\"id\":5}' },\n          ],\n        },\n        'Item:{\"id\":1}': {\n          __typename: \"Item\",\n          id: 1,\n          text: \"firstly\",\n        },\n        'Item:{\"id\":2}': {\n          __typename: \"Item\",\n          id: 2,\n          text: \"secondly\",\n        },\n        'Item:{\"id\":3}': {\n          __typename: \"Item\",\n          id: 3,\n          text: \"thirdly\",\n        },\n        'Item:{\"id\":4}': {\n          __typename: \"Item\",\n          id: 4,\n          text: \"fourth\",\n        },\n        'Item:{\"id\":5}': {\n          __typename: \"Item\",\n          id: 5,\n          text: \"fifth\",\n        },\n      });\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n          \"item 1\",\n          \"item 3\",\n          // The whole list had to be rendered again to append 4 and 5\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 4\",\n          \"item 5\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: firstly\",\n          \"Item #2: secondly\",\n          \"Item #3: thirdly\",\n          \"Item #4: fourth\",\n          \"Item #5: fifth\",\n        ]);\n      });\n\n      appendLyToText(5);\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n          \"item 1\",\n          \"item 3\",\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 4\",\n          \"item 5\",\n          // A single new render:\n          \"item 5\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: firstly\",\n          \"Item #2: secondly\",\n          \"Item #3: thirdly\",\n          \"Item #4: fourth\",\n          \"Item #5: fifthly\",\n        ]);\n      });\n\n      appendLyToText(4);\n\n      await waitFor(() => {\n        expect(renders).toStrictEqualTyped([\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 2\",\n          \"item 1\",\n          \"item 3\",\n          \"list\",\n          \"item 1\",\n          \"item 2\",\n          \"item 3\",\n          \"item 4\",\n          \"item 5\",\n          \"item 5\",\n          // A single new render:\n          \"item 4\",\n        ]);\n\n        expect(getItemTexts()).toStrictEqualTyped([\n          \"Item #1: firstly\",\n          \"Item #2: secondly\",\n          \"Item #3: thirdly\",\n          \"Item #4: fourthly\",\n          \"Item #5: fifthly\",\n        ]);\n      });\n    }\n  );\n\n  it(\"List can use useFragment with ListFragment\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Item: {\n          fields: {\n            text(existing, { readField }) {\n              return existing || `Item #${readField(\"id\")}`;\n            },\n          },\n        },\n      },\n    });\n\n    const listQuery: TypedDocumentNode<QueryDataWithExtra> = gql`\n      query {\n        ...ListFragment\n        list {\n          ...ItemFragment\n        }\n      }\n      ${ListFragment}\n      ${ItemFragment}\n    `;\n\n    cache.writeQuery({\n      query: listQuery,\n      data: {\n        list: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n        extra: \"from ListFragment\",\n      },\n    });\n\n    const renders: string[] = [];\n\n    function List() {\n      renders.push(\"list\");\n      const { complete, data } = useFragment({\n        fragment: ListFragment,\n        from: { __typename: \"Query\" },\n      });\n      expect(complete).toBe(true);\n      assert(!!complete);\n      return (\n        <ol>\n          {data.list.map((item) => (\n            <Item key={item.id} id={item.id} />\n          ))}\n        </ol>\n      );\n    }\n\n    function Item(props: { id: number }) {\n      renders.push(\"item \" + props.id);\n      const { complete, data } = useFragment({\n        fragment: ItemFragment,\n        from: {\n          __typename: \"Item\",\n          id: props.id,\n        },\n      });\n      return <li>{complete ? data.text : \"incomplete\"}</li>;\n    }\n\n    render(\n      <MockedProvider cache={cache}>\n        <List />\n      </MockedProvider>\n    );\n\n    function getItemTexts() {\n      return screen.getAllByText(/^Item/).map(\n        // eslint-disable-next-line testing-library/no-node-access\n        (li) => li.firstChild!.textContent\n      );\n    }\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\"list\", \"item 1\", \"item 2\", \"item 5\"]);\n\n    await act(async () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 2,\n          text: \"Item #2 updated\",\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      // Only the second item should have re-rendered.\n      \"item 2\",\n    ]);\n\n    await act(async () => {\n      cache.modify({\n        fields: {\n          list(list: readonly Reference[], { readField }) {\n            return [\n              ...list,\n              cache.writeFragment({\n                fragment: ItemFragment,\n                data: {\n                  __typename: \"Item\",\n                  id: 3,\n                },\n              })!,\n              cache.writeFragment({\n                fragment: ItemFragment,\n                data: {\n                  __typename: \"Item\",\n                  id: 4,\n                },\n              })!,\n            ].sort(\n              (ref1, ref2) =>\n                readField<Item[\"id\"]>(\"id\", ref1)! -\n                readField<Item[\"id\"]>(\"id\", ref2)!\n            );\n          },\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #3\",\n        \"Item #4\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      \"item 2\",\n      // This is what's new:\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 3\",\n      \"item 4\",\n      \"item 5\",\n    ]);\n\n    await act(async () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 4,\n          text: \"Item #4 updated\",\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        \"Item #1\",\n        \"Item #2 updated\",\n        \"Item #3\",\n        \"Item #4 updated\",\n        \"Item #5\",\n      ]);\n    });\n\n    expect(renders).toStrictEqualTyped([\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 5\",\n      \"item 2\",\n      \"list\",\n      \"item 1\",\n      \"item 2\",\n      \"item 3\",\n      \"item 4\",\n      \"item 5\",\n      // Only the fourth item should have re-rendered.\n      \"item 4\",\n    ]);\n\n    expect(cache.extract()).toStrictEqualTyped({\n      \"Item:1\": {\n        __typename: \"Item\",\n        id: 1,\n      },\n      \"Item:2\": {\n        __typename: \"Item\",\n        id: 2,\n        text: \"Item #2 updated\",\n      },\n      \"Item:3\": {\n        __typename: \"Item\",\n        id: 3,\n      },\n      \"Item:4\": {\n        __typename: \"Item\",\n        id: 4,\n        text: \"Item #4 updated\",\n      },\n      \"Item:5\": {\n        __typename: \"Item\",\n        id: 5,\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        list: [\n          { __ref: \"Item:1\" },\n          { __ref: \"Item:2\" },\n          { __ref: \"Item:3\" },\n          { __ref: \"Item:4\" },\n          { __ref: \"Item:5\" },\n        ],\n        extra: \"from ListFragment\",\n      },\n      __META: {\n        extraRootIds: [\"Item:2\", \"Item:3\", \"Item:4\"],\n      },\n    });\n  });\n\n  it(\"useFragment(...).missing is a tree describing missing fields\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            list(items: Reference[] | undefined, { canRead }) {\n              // This filtering happens by default currently in the StoreReader\n              // execSubSelectedArrayImpl method, but I am beginning to question\n              // the wisdom of that automatic filtering. In case we end up\n              // changing the default behavior in the future, I've encoded the\n              // filtering explicitly here, so this test won't be broken.\n              return items && items.filter(canRead);\n            },\n          },\n        },\n      },\n    });\n\n    const wrapper = ({ children }: any) => (\n      <MockedProvider cache={cache}>{children}</MockedProvider>\n    );\n\n    const ListAndItemFragments: TypedDocumentNode<QueryData> = gql`\n      fragment ListFragment on Query {\n        list {\n          id\n          ...ItemFragment\n        }\n      }\n      ${ItemFragment}\n    `;\n\n    const ListQuery: TypedDocumentNode<QueryData> = gql`\n      query ListQuery {\n        list {\n          id\n        }\n      }\n    `;\n\n    const ListQueryWithText: TypedDocumentNode<QueryData> = gql`\n      query ListQuery {\n        list {\n          id\n          text\n        }\n      }\n    `;\n\n    const { result: renderResult } = renderHook(\n      () =>\n        useFragment({\n          fragment: ListAndItemFragments,\n          fragmentName: \"ListFragment\",\n          from: { __typename: \"Query\" },\n        }),\n      { wrapper }\n    );\n\n    function checkHistory(expectedResultCount: number) {\n      // Temporarily disabling this check until we can come up with a better\n      // (more opt-in) system than result.previousResult.previousResult...\n      // function historyToArray(\n      //   result: UseFragmentResult<QueryData>,\n      // ): UseFragmentResult<QueryData>[] {\n      //   const array = result.previousResult\n      //     ? historyToArray(result.previousResult)\n      //     : [];\n      //   array.push(result);\n      //   return array;\n      // }\n      // const all = historyToArray(renderResult.current);\n      // expect(all.length).toBe(expectedResultCount);\n      // expect(all).toStrictEqualTyped(renderResult.all);\n      // if (renderResult.current.complete) {\n      //   expect(renderResult.current).toBe(\n      //     renderResult.current.lastCompleteResult\n      //   );\n      // } else {\n      //   expect(renderResult.current).not.toBe(\n      //     renderResult.current.lastCompleteResult\n      //   );\n      // }\n    }\n\n    expect(renderResult.current.complete).toBe(false);\n    expect(renderResult.current.data).toStrictEqualTyped({\n      __typename: \"Query\",\n    });\n    expect(renderResult.current.missing).toStrictEqualTyped({\n      list: \"Can't find field 'list' on ROOT_QUERY object\",\n    });\n\n    checkHistory(1);\n\n    const data125 = {\n      __typename: \"Query\" as const,\n      list: [\n        { __typename: \"Item\", id: 1 },\n        { __typename: \"Item\", id: 2 },\n        { __typename: \"Item\", id: 5 },\n      ],\n    };\n\n    await act(async () => {\n      cache.writeQuery({\n        query: ListQuery,\n        data: data125,\n      });\n    });\n\n    await waitFor(() =>\n      expect(renderResult.current.data).toStrictEqualTyped(data125)\n    );\n    expect(renderResult.current.complete).toBe(false);\n    expect(renderResult.current.missing).toStrictEqualTyped({\n      list: {\n        // Even though Query.list is actually an array in the data, data paths\n        // through this array leading to missing fields potentially involve only\n        // a small/sparse subset of the array's indexes, so we use objects for\n        // the entire MissingTree, to avoid having to worry about sparse arrays.\n        // This also means there's no missing.list.length property, which is\n        // good because \"length\" could be a name of an actual field that's\n        // missing, and it's somewhat unclear what the length of a sparse array\n        // should be, whereas object keys have a less ambiguous interpretation.\n        0: { text: \"Can't find field 'text' on Item:1 object\" },\n        1: { text: \"Can't find field 'text' on Item:2 object\" },\n        2: { text: \"Can't find field 'text' on Item:5 object\" },\n      },\n    });\n\n    checkHistory(2);\n\n    const data182WithText = {\n      __typename: \"Query\" as const,\n      list: [\n        { __typename: \"Item\", id: 1, text: \"oyez1\" },\n        { __typename: \"Item\", id: 8, text: \"oyez8\" },\n        { __typename: \"Item\", id: 2, text: \"oyez2\" },\n      ],\n    };\n\n    await act(async () => {\n      cache.writeQuery({\n        query: ListQueryWithText,\n        data: data182WithText,\n      });\n    });\n\n    await waitFor(() =>\n      expect(renderResult.current.data).toStrictEqualTyped(data182WithText)\n    );\n    expect(renderResult.current.complete).toBe(true);\n    expect(renderResult.current.missing).toBeUndefined();\n\n    checkHistory(3);\n\n    await act(async () =>\n      cache.batch({\n        update(cache) {\n          cache.evict({\n            id: cache.identify({\n              __typename: \"Item\",\n              id: 8,\n            }),\n          });\n\n          cache.evict({\n            id: cache.identify({\n              __typename: \"Item\",\n              id: 2,\n            }),\n            fieldName: \"text\",\n          });\n        },\n      })\n    );\n\n    await waitFor(() =>\n      expect(renderResult.current.data).toStrictEqualTyped({\n        __typename: \"Query\",\n        list: [\n          { __typename: \"Item\", id: 1, text: \"oyez1\" },\n          { __typename: \"Item\", id: 2 },\n        ],\n      })\n    );\n    expect(renderResult.current.complete).toBe(false);\n    expect(renderResult.current.missing).toStrictEqualTyped({\n      // TODO Figure out why Item:8 is not represented here. Likely because of\n      // auto-filtering of dangling references from arrays, but that should\n      // still be reflected here, if possible.\n      list: {\n        1: {\n          text: \"Can't find field 'text' on Item:2 object\",\n        },\n      },\n    });\n\n    checkHistory(4);\n\n    expect(cache.extract()).toStrictEqualTyped({\n      \"Item:1\": {\n        __typename: \"Item\",\n        id: 1,\n        text: \"oyez1\",\n      },\n      \"Item:2\": {\n        __typename: \"Item\",\n        id: 2,\n      },\n      \"Item:5\": {\n        __typename: \"Item\",\n        id: 5,\n      },\n      ROOT_QUERY: {\n        __typename: \"Query\",\n        list: [{ __ref: \"Item:1\" }, { __ref: \"Item:8\" }, { __ref: \"Item:2\" }],\n      },\n    });\n\n    expect(cache.gc().sort()).toStrictEqualTyped([\"Item:5\"]);\n  });\n\n  it(\"returns new diff when UseFragmentOptions change\", async () => {\n    const ListFragment: TypedDocumentNode<QueryData> = gql`\n      fragment ListFragment on Query {\n        list {\n          id\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Item: {\n          fields: {\n            text(existing, { readField }) {\n              return existing || `Item #${readField(\"id\")}`;\n            },\n          },\n        },\n      },\n    });\n\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            if (operation.operationName === \"ListQueryWithItemFragment\") {\n              setTimeout(() => {\n                observer.next({\n                  data: {\n                    list: [\n                      { __typename: \"Item\", id: 1 },\n                      { __typename: \"Item\", id: 2 },\n                      { __typename: \"Item\", id: 5 },\n                    ],\n                  },\n                });\n                observer.complete();\n              }, 10);\n            } else {\n              observer.error(\n                `unexpected query ${operation.operationName || operation.query}`\n              );\n            }\n          })\n      ),\n    });\n\n    const listQuery: TypedDocumentNode<QueryData> = gql`\n      query ListQueryWithItemFragment {\n        list {\n          id\n          ...ItemFragment\n        }\n      }\n      ${ItemFragment}\n    `;\n\n    function List() {\n      const [currentItem, setCurrentItem] = React.useState(1);\n      useQuery(listQuery);\n\n      const { complete, data } = useFragment({\n        fragment: ListFragment,\n        from: { __typename: \"Query\" },\n      });\n\n      return complete ?\n          <>\n            <select\n              onChange={(e) => {\n                setCurrentItem(parseInt(e.currentTarget.value));\n              }}\n            >\n              {data.list.map((item) => (\n                <option key={item.id} value={item.id}>\n                  Select item {item.id}\n                </option>\n              ))}\n            </select>\n            <div>\n              <Item id={currentItem} />\n            </div>\n            <ol>\n              {data.list.map((item) => (\n                <Item key={item.id} id={item.id} />\n              ))}\n            </ol>\n          </>\n        : null;\n    }\n\n    function Item({ id }: { id: number }) {\n      const { complete, data } = useFragment({\n        fragment: ItemFragment,\n        from: {\n          __typename: \"Item\",\n          id,\n        },\n      });\n      return <li>{complete ? data.text : \"incomplete\"}</li>;\n    }\n\n    render(\n      <ApolloProvider client={client}>\n        <List />\n      </ApolloProvider>\n    );\n\n    function getItemTexts() {\n      return screen.getAllByText(/^Item/).map(\n        // eslint-disable-next-line testing-library/no-node-access\n        (li) => li.firstChild!.textContent\n      );\n    }\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        // On initial render, Item #1 is selected\n        // and renders above the list\n        \"Item #1\",\n        \"Item #1\",\n        \"Item #2\",\n        \"Item #5\",\n      ]);\n    });\n\n    // Select \"Item #2\" via <select />\n    const user = userEvent.setup();\n    await user.selectOptions(\n      screen.getByRole(\"combobox\"),\n      screen.getByRole(\"option\", { name: \"Select item 2\" })\n    );\n\n    await waitFor(() => {\n      expect(getItemTexts()).toStrictEqualTyped([\n        // Now the selected item at the top should render\n        // \"Item #2\" + the list of items below\n        \"Item #2\",\n        \"Item #1\",\n        \"Item #2\",\n        \"Item #5\",\n      ]);\n    });\n  });\n\n  it(\"returns correct data when from changes\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    type User = { __typename: \"User\"; id: number; name: string };\n    const fragment: TypedDocumentNode<User> = gql`\n      fragment UserFragment on User {\n        id\n        name\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"User\", id: 1, name: \"Alice\" },\n    });\n\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"User\", id: 2, name: \"Charlie\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ id }) => useFragment({ fragment, from: { __typename: \"User\", id } }),\n      {\n        initialProps: { id: 1 },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: { __typename: \"User\", id: 1, name: \"Alice\" },\n        dataState: \"complete\",\n      });\n    }\n\n    await rerender({ id: 2 });\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: { __typename: \"User\", id: 2, name: \"Charlie\" },\n        dataState: \"complete\",\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"returns correct data when options change\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n    type User = { __typename: \"User\"; id: number; name: string };\n    const fragment: TypedDocumentNode<User> = gql`\n      fragment UserFragment on User {\n        id\n        name(casing: $casing)\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"User\", id: 1, name: \"ALICE\" },\n      variables: { casing: \"upper\" },\n    });\n\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"User\", id: 1, name: \"alice\" },\n      variables: { casing: \"lower\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ casing }) =>\n        useFragment({\n          fragment,\n          from: { __typename: \"User\", id: 1 },\n          variables: { casing },\n        }),\n      {\n        initialProps: { casing: \"upper\" },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: { __typename: \"User\", id: 1, name: \"ALICE\" },\n        dataState: \"complete\",\n      });\n    }\n\n    await rerender({ casing: \"lower\" });\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: { __typename: \"User\", id: 1, name: \"alice\" },\n        dataState: \"complete\",\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"does not rerender when fields with @nonreactive change\", async () => {\n    type Post = {\n      __typename: \"Post\";\n      id: number;\n      title: string;\n      updatedAt: string;\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const fragment: TypedDocumentNode<Post> = gql`\n      fragment PostFragment on Post {\n        id\n        title\n        updatedAt @nonreactive\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        updatedAt: \"2024-01-01\",\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useFragment({ fragment, from: { __typename: \"Post\", id: 1 } }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n          updatedAt: \"2024-01-01\",\n        },\n        dataState: \"complete\",\n      });\n    }\n\n    client.writeFragment({\n      fragment,\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        updatedAt: \"2024-02-01\",\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"does not rerender when fields with @nonreactive on nested fragment change\", async () => {\n    type Post = {\n      __typename: \"Post\";\n      id: number;\n      title: string;\n      updatedAt: string;\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const fragment: TypedDocumentNode<Post> = gql`\n      fragment PostFragment on Post {\n        id\n        title\n        ...PostFields @nonreactive\n      }\n\n      fragment PostFields on Post {\n        updatedAt\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        updatedAt: \"2024-01-01\",\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          fragmentName: \"PostFragment\",\n          from: { __typename: \"Post\", id: 1 },\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n          updatedAt: \"2024-01-01\",\n        },\n        dataState: \"complete\",\n      });\n    }\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        updatedAt: \"2024-02-01\",\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"warns when passing parent object to `from` when key fields are missing\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    interface Fragment {\n      age: number;\n    }\n\n    const fragment: TypedDocumentNode<Fragment, never> = gql`\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useFragment({ fragment, from: { __typename: \"User\" } }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { data, complete } = await takeSnapshot();\n\n      expect(data).toStrictEqualTyped({});\n      // TODO: Update when https://github.com/apollographql/apollo-client/issues/12003 is fixed\n      expect(complete).toBe(true);\n    }\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n      \"UserFields\"\n    );\n  });\n\n  it(\"allows `null` as valid `from` value without warning\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    interface Fragment {\n      age: number;\n    }\n\n    const fragment: TypedDocumentNode<Fragment, never> = gql`\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useFragment({ fragment, from: null }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { data, complete } = await takeSnapshot();\n\n      expect(data).toStrictEqualTyped({});\n      expect(complete).toBe(false);\n    }\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  it(\"properly handles changing from null to valid from value\", async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    interface Fragment {\n      __typename: \"User\";\n      id: string;\n      age: number;\n    }\n\n    const fragment: TypedDocumentNode<Fragment, Record<string, never>> = gql`\n      fragment UserFields on User {\n        __typename\n        id\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeFragment({\n      fragment,\n      data: {\n        __typename: \"User\",\n        id: \"1\",\n        age: 30,\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ from }) => useFragment({ fragment, from }),\n      {\n        initialProps: { from: null as useFragment.Options<any, never>[\"from\"] },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {},\n      dataState: \"partial\",\n      complete: false,\n    });\n\n    await rerender({ from: { __typename: \"User\", id: \"1\" } });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { __typename: \"User\", id: \"1\", age: 30 },\n      dataState: \"complete\",\n      complete: true,\n    });\n  });\n\n  describe(\"tests with incomplete data\", () => {\n    let cache: InMemoryCache, wrapper: React.FunctionComponent;\n    const ItemFragment = gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `;\n\n    beforeEach(() => {\n      cache = new InMemoryCache();\n      wrapper = ({ children }: any) => (\n        <MockedProvider cache={cache}>{children}</MockedProvider>\n      );\n\n      // silence the console for the incomplete fragment write\n      {\n        using _spy = spyOnConsole(\"error\");\n        cache.writeFragment({\n          fragment: ItemFragment,\n          data: {\n            __typename: \"Item\",\n            id: 5,\n          },\n        });\n      }\n    });\n\n    it(\"assumes `returnPartialData: true` per default\", () => {\n      const { result } = renderHook(\n        () =>\n          useFragment({\n            fragment: ItemFragment,\n            from: { __typename: \"Item\", id: 5 },\n          }),\n        { wrapper }\n      );\n\n      expect(result.current.data).toStrictEqualTyped({\n        __typename: \"Item\",\n        id: 5,\n      });\n      expect(result.current.complete).toBe(false);\n    });\n  });\n\n  describe(\"return value `complete` property\", () => {\n    let cache: InMemoryCache, wrapper: React.FunctionComponent;\n    const ItemFragment: TypedDocumentNode<{\n      __typename: \"Item\";\n      id: number;\n      text: string;\n    }> = gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `;\n\n    beforeEach(() => {\n      cache = new InMemoryCache();\n      wrapper = ({ children }: any) => (\n        <MockedProvider cache={cache}>{children}</MockedProvider>\n      );\n    });\n\n    test(\"if all data is available, `complete` is `true`\", () => {\n      cache.writeFragment({\n        fragment: ItemFragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5\",\n        },\n      });\n\n      const { result } = renderHook(\n        () =>\n          useFragment({\n            fragment: ItemFragment,\n            from: { __typename: \"Item\", id: 5 },\n          }),\n        { wrapper }\n      );\n\n      expect(result.current).toStrictEqualTyped({\n        data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n        complete: true,\n        dataState: \"complete\",\n      });\n    });\n\n    test(\"if only partial data is available, `complete` is `false`\", () => {\n      {\n        using _ = spyOnConsole(\"error\");\n        cache.writeFragment({\n          fragment: ItemFragment,\n          // @ts-expect-error purposefully omitting text\n          data: {\n            __typename: \"Item\",\n            id: 5,\n          },\n        });\n      }\n\n      const { result } = renderHook(\n        () =>\n          useFragment({\n            fragment: ItemFragment,\n            from: { __typename: \"Item\", id: 5 },\n          }),\n        { wrapper }\n      );\n\n      expect(result.current).toStrictEqualTyped({\n        data: { __typename: \"Item\", id: 5 },\n        complete: false,\n        missing: {\n          text: \"Can't find field 'text' on Item:5 object\",\n        },\n        dataState: \"partial\",\n      });\n    });\n\n    test(\"if no data is available, `complete` is `false`\", () => {\n      const { result } = renderHook(\n        () =>\n          useFragment({\n            fragment: ItemFragment,\n            from: { __typename: \"Item\", id: 5 },\n          }),\n        { wrapper }\n      );\n\n      expect(result.current).toStrictEqualTyped({\n        data: {},\n        complete: false,\n        missing: \"Dangling reference to missing Item:5 object\",\n        dataState: \"partial\",\n      });\n    });\n  });\n});\n\ndescribe(\"data masking\", () => {\n  it(\"returns masked fragment when data masking is enabled\", async () => {\n    type Post = {\n      __typename: \"Post\";\n      id: number;\n      title: string;\n    };\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const fragment: TypedDocumentNode<Post> = gql`\n      fragment PostFragment on Post {\n        id\n        title\n        ...PostFields\n      }\n\n      fragment PostFields on Post {\n        updatedAt\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        // @ts-expect-error Need to determine how to work with masked types\n        updatedAt: \"2024-01-01\",\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          fragmentName: \"PostFragment\",\n          from: { __typename: \"Post\", id: 1 },\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n        },\n        dataState: \"complete\",\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"does not rerender for cache writes to masked fields\", async () => {\n    type Post = {\n      __typename: \"Post\";\n      id: number;\n      title: string;\n    };\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const fragment: TypedDocumentNode<Post> = gql`\n      fragment PostFragment on Post {\n        id\n        title\n        ...PostFields\n      }\n\n      fragment PostFields on Post {\n        updatedAt\n      }\n    `;\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        // @ts-expect-error Need to determine how to work with masked types\n        updatedAt: \"2024-01-01\",\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          fragmentName: \"PostFragment\",\n          from: { __typename: \"Post\", id: 1 },\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const snapshot = await takeSnapshot();\n\n      expect(snapshot).toStrictEqualTyped({\n        complete: true,\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n        },\n        dataState: \"complete\",\n      });\n    }\n\n    client.writeFragment({\n      fragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        // @ts-expect-error Need to determine how to work with masked types\n        updatedAt: \"2024-02-01\",\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"updates child fragments for cache updates to masked fields\", async () => {\n    type ParentFragment = {\n      __typename: \"Post\";\n      id: number;\n      title: string;\n    };\n\n    type ChildFragment = {\n      __typename: \"Post\";\n      updatedAt: string;\n    };\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const childFragment: TypedDocumentNode<ChildFragment> = gql`\n      fragment PostFields on Post {\n        updatedAt\n      }\n    `;\n\n    const parentFragment: TypedDocumentNode<ParentFragment> = gql`\n      fragment PostFragment on Post {\n        id\n        title\n        ...PostFields\n      }\n\n      ${childFragment}\n    `;\n\n    client.writeFragment({\n      fragment: parentFragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        // @ts-expect-error Need to determine how to work with masked types\n        updatedAt: \"2024-01-01\",\n      },\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        parent: null as useFragment.Result<ParentFragment> | null,\n        child: null as useFragment.Result<ChildFragment> | null,\n      },\n    });\n\n    function Parent() {\n      useTrackRenders();\n      const parent = useFragment({\n        fragment: parentFragment,\n        fragmentName: \"PostFragment\",\n        from: { __typename: \"Post\", id: 1 },\n      });\n\n      renderStream.mergeSnapshot({ parent });\n\n      return parent.complete ? <Child parent={parent.data} /> : null;\n    }\n\n    function Child({ parent }: { parent: ParentFragment }) {\n      useTrackRenders();\n      const child = useFragment({ fragment: childFragment, from: parent });\n\n      renderStream.mergeSnapshot({ child });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<Parent />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([Parent, Child]);\n      expect(snapshot).toStrictEqualTyped({\n        parent: {\n          complete: true,\n          data: {\n            __typename: \"Post\",\n            id: 1,\n            title: \"Blog post\",\n          },\n          dataState: \"complete\",\n        },\n        child: {\n          complete: true,\n          data: {\n            __typename: \"Post\",\n            updatedAt: \"2024-01-01\",\n          },\n          dataState: \"complete\",\n        },\n      });\n    }\n\n    client.writeFragment({\n      fragment: parentFragment,\n      fragmentName: \"PostFragment\",\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n        // @ts-expect-error Need to determine how to work with masked types\n        updatedAt: \"2024-02-01\",\n      },\n    });\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([Child]);\n      expect(snapshot).toStrictEqualTyped({\n        parent: {\n          complete: true,\n          data: {\n            __typename: \"Post\",\n            id: 1,\n            title: \"Blog post\",\n          },\n          dataState: \"complete\",\n        },\n        child: {\n          complete: true,\n          data: {\n            __typename: \"Post\",\n            updatedAt: \"2024-02-01\",\n          },\n          dataState: \"complete\",\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n});\n\ndescribe(\"has the same timing as `useQuery`\", () => {\n  const itemFragment = gql`\n    fragment ItemFragment on Item {\n      id\n      title\n    }\n  `;\n\n  it(\"both in same component\", async () => {\n    const initialItem = { __typename: \"Item\", id: 1, title: \"Item #initial\" };\n    const updatedItem = { __typename: \"Item\", id: 1, title: \"Item #updated\" };\n\n    const query = gql`\n      query {\n        item {\n          ...ItemFragment\n        }\n      }\n      ${itemFragment}\n    `;\n    let observer: Observer<ApolloLink.Result>;\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: new ApolloLink(\n        (operation) => new Observable((o) => void (observer = o))\n      ),\n    });\n\n    function Component() {\n      const { data: queryData } = useQuery(query, { returnPartialData: true });\n      const { data: fragmentData, complete } = useFragment({\n        fragment: itemFragment,\n        from: initialItem,\n      });\n\n      renderStream.replaceSnapshot({ queryData, fragmentData });\n\n      return complete ? JSON.stringify(fragmentData) : \"loading\";\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        queryData: undefined as any,\n        fragmentData: undefined as any,\n      },\n    });\n    await renderStream.render(<Component />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.queryData).toBe(undefined);\n      expect(snapshot.fragmentData).toStrictEqualTyped({});\n    }\n\n    assert(observer!);\n    observer.next({ data: { item: initialItem } });\n    observer.complete();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.queryData).toStrictEqualTyped({ item: initialItem });\n      expect(snapshot.fragmentData).toStrictEqualTyped(initialItem);\n    }\n\n    cache.writeQuery({ query, data: { item: updatedItem } });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      expect(snapshot.queryData).toStrictEqualTyped({ item: updatedItem });\n      expect(snapshot.fragmentData).toStrictEqualTyped(updatedItem);\n    }\n  });\n\n  it(\"`useQuery` in parent, `useFragment` in child\", async () => {\n    const item1 = { __typename: \"Item\", id: 1, title: \"Item #1\" };\n    const item2 = { __typename: \"Item\", id: 2, title: \"Item #2\" };\n    const query: TypedDocumentNode<{ items: Array<typeof item1> }> = gql`\n      query {\n        items {\n          ...ItemFragment\n        }\n      }\n      ${itemFragment}\n    `;\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n    });\n    cache.writeQuery({ query, data: { items: [item1, item2] } });\n\n    function Parent() {\n      const { data } = useQuery(query);\n      if (!data) throw new Error(\"should never happen\");\n      return (\n        <>\n          <div data-testid=\"parent\">\n            <p>{JSON.stringify(data)}</p>\n          </div>\n          <div data-testid=\"children\">\n            {data.items.map((item, i) => (\n              <p key={i}>\n                <Child id={item.id} />\n              </p>\n            ))}\n          </div>\n        </>\n      );\n    }\n    function Child({ id }: { id: number }) {\n      const { data } = useFragment({\n        fragment: itemFragment,\n        from: { __typename: \"Item\", id },\n      });\n      return <>{JSON.stringify({ item: data })}</>;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      snapshotDOM: true,\n    });\n    await renderStream.render(<Parent />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { withinDOM } = await renderStream.takeRender();\n      const parent = withinDOM().getByTestId(\"parent\");\n      const children = withinDOM().getByTestId(\"children\");\n\n      expect(within(parent).queryAllByText(/Item #1/).length).toBe(1);\n      expect(within(children).queryAllByText(/Item #1/).length).toBe(1);\n\n      expect(within(parent).queryAllByText(/Item #2/).length).toBe(1);\n      expect(within(children).queryAllByText(/Item #2/).length).toBe(1);\n    }\n\n    cache.evict({\n      id: cache.identify(item2),\n    });\n\n    {\n      const { withinDOM } = await renderStream.takeRender();\n      const parent = withinDOM().getByTestId(\"parent\");\n      const children = withinDOM().getByTestId(\"children\");\n\n      expect(within(parent).queryAllByText(/Item #1/).length).toBe(1);\n      expect(within(children).queryAllByText(/Item #1/).length).toBe(1);\n\n      expect(within(parent).queryAllByText(/Item #2/).length).toBe(0);\n      expect(within(children).queryAllByText(/Item #2/).length).toBe(0);\n    }\n\n    // currently will fail because of the extra render\n    // await expect(renderStream).toRenderExactlyTimes(2);\n  });\n\n  /**\n   * This would be optimal, but would only work if `useFragment` and\n   * `useQuery` had exactly the same timing, which is not the case with\n   * the current implementation.\n   * The best we can do is to make sure that `useFragment` is not\n   * faster than `useQuery` in reasonable cases (of course, `useQuery`\n   * could trigger a network request on cache update, which would be slower\n   * than `useFragment`, no matter how much we delay it).\n   * If we change the core implementation into a more synchronous one,\n   * we should try to get this test to work, too.\n   */\n  it.failing(\"`useFragment` in parent, `useQuery` in child\", async () => {\n    const item1 = { __typename: \"Item\", id: 1, title: \"Item #1\" };\n    const item2 = { __typename: \"Item\", id: 2, title: \"Item #2\" };\n    const query: TypedDocumentNode<{ items: Array<typeof item1> }> = gql`\n      query {\n        items {\n          ...ItemFragment\n        }\n      }\n      ${itemFragment}\n    `;\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: ApolloLink.empty(),\n    });\n    cache.writeQuery({ query, data: { items: [item1, item2] } });\n\n    function Parent() {\n      const { data: data1 } = useFragment({\n        fragment: itemFragment,\n        from: { __typename: \"Item\", id: 1 },\n      });\n      const { data: data2 } = useFragment({\n        fragment: itemFragment,\n        from: { __typename: \"Item\", id: 2 },\n      });\n      return (\n        <>\n          <div data-testid=\"parent\">\n            <p>{JSON.stringify(data1)}</p>\n            <p>{JSON.stringify(data2)}</p>\n          </div>\n          <div data-testid=\"children\">\n            <p>\n              <Child />\n            </p>\n          </div>\n        </>\n      );\n    }\n    function Child() {\n      const { data } = useQuery(query);\n      if (!data) throw new Error(\"should never happen\");\n      return <>{JSON.stringify(data)}</>;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      onRender() {\n        const parent = screen.getByTestId(\"parent\");\n        const children = screen.getByTestId(\"children\");\n        expect(within(parent).queryAllByText(/Item #1/).length).toBe(\n          within(children).queryAllByText(/Item #1/).length\n        );\n        expect(within(parent).queryAllByText(/Item #2/).length).toBe(\n          within(children).queryAllByText(/Item #2/).length\n        );\n      },\n    });\n    await renderStream.render(<Parent />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { withinDOM } = await renderStream.takeRender();\n      expect(withinDOM().queryAllByText(/Item #2/).length).toBe(2);\n    }\n\n    cache.evict({\n      id: cache.identify(item2),\n    });\n\n    {\n      const { withinDOM } = await renderStream.takeRender();\n      expect(withinDOM().queryAllByText(/Item #2/).length).toBe(0);\n    }\n\n    await expect(renderStream).toRenderExactlyTimes(3);\n  });\n});\n\ntest(\"runs custom document transforms\", async () => {\n  const fragment = gql`\n    fragment TestFragment on Dog {\n      id\n      name\n      breed @custom\n    }\n  `;\n\n  const documentTransform = new DocumentTransform((document) => {\n    return removeDirectivesFromDocument(\n      [{ name: \"custom\", remove: true }],\n      document\n    )!;\n  });\n\n  const client = new ApolloClient({\n    link: ApolloLink.empty(),\n    cache: new InMemoryCache(),\n    documentTransform,\n  });\n\n  client.writeFragment({\n    fragment: gql`\n      fragment TestFragment on Dog {\n        id\n        name\n      }\n    `,\n    data: {\n      __typename: \"Dog\",\n      id: 1,\n      name: \"Buddy\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useFragment({ fragment, from: { __typename: \"Dog\", id: 1 } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { __typename: \"Dog\", id: 1, name: \"Buddy\" },\n    dataState: \"complete\",\n    complete: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ndescribe(\"works with skip/non-include of all fields, even if the cache doesn't add a `__typename` field\", () => {\n  const fragment: TypedDocumentNode<\n    { __typename?: string; id?: number; name?: string },\n    { shouldSkip: boolean; shouldInclude: boolean }\n  > = gql`\n    fragment TestFragment on Dog {\n      id @skip(if: $shouldSkip)\n      name @include(if: $shouldInclude)\n    }\n  `;\n\n  const cache = new InMemoryCache({});\n  const client = new ApolloClient({\n    link: ApolloLink.empty(),\n    cache,\n  });\n  cache.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Dog\",\n      id: 1,\n      name: \"Buddy\",\n    },\n    id: \"Dog:1\",\n    variables: { shouldSkip: true, shouldInclude: false },\n  });\n  // we have no good way to prevent `InMemoryCache` from adding __typename\n  // but we want to simulate a 3rd party cache that doesn't add `__typename`\n  // without building an entire mock cache in this test. Instead we\n  // override the diff method to strip it out again\n  cache.diff = (options) => {\n    const diff = (InMemoryCache.prototype.diff<any>).call(cache, options);\n    if (diff.result) {\n      const { __typename: _, ...rest } = diff.result;\n      diff.result = rest;\n    }\n    return diff;\n  };\n\n  test(\"single from\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          from: { __typename: \"Dog\", id: 1 },\n          variables: { shouldSkip: true, shouldInclude: false },\n        }),\n      { wrapper: createClientWrapper(client) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {},\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"single from in array\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          from: [{ __typename: \"Dog\", id: 1 }],\n          variables: { shouldSkip: true, shouldInclude: false },\n        }),\n      { wrapper: createClientWrapper(client) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: [{}],\n      dataState: \"complete\",\n      complete: true,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"multiple from, mixed presence\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useFragment({\n          fragment,\n          from: [\n            { __typename: \"Dog\", id: 1 },\n            { __typename: \"Dog\", id: 2 },\n          ],\n          variables: { shouldSkip: true, shouldInclude: false },\n        }),\n      { wrapper: createClientWrapper(client) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: [{}, null],\n      dataState: \"partial\",\n      complete: false,\n      missing: {\n        1: \"Dangling reference to missing Dog:2 object\",\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n});\n\ndescribe.skip(\"Type Tests\", () => {\n  test(\"NoInfer prevents adding arbitrary additional variables\", () => {\n    const typedNode = {} as TypedDocumentNode<{ foo: string }, { bar: number }>;\n    useFragment({\n      fragment: typedNode,\n      from: { __typename: \"Query\" },\n      variables: {\n        bar: 4,\n        // @ts-expect-error\n        nonExistingVariable: \"string\",\n      },\n    });\n  });\n\n  test(\"UseFragmentOptions interface shape\", <TData, TVariables extends\n    OperationVariables>() => {\n    expectTypeOf<\n      useFragment.Options<TData, TVariables>\n    >().branded.toEqualTypeOf<{\n      from:\n        | string\n        | StoreObject\n        | Reference\n        | FragmentType<TData>\n        | null\n        | Array<string | StoreObject | Reference | FragmentType<TData> | null>;\n      fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n      fragmentName?: string;\n      optimistic?: boolean;\n      variables?: TVariables;\n      client?: ApolloClient;\n    }>();\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useLazyQuery.test.tsx",
    "content": "import { act, renderHook, screen, waitFor } from \"@testing-library/react\";\nimport {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { Observable, Subject } from \"rxjs\";\n\nimport type {\n  DataValue,\n  ErrorPolicy,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport { ApolloProvider, useLazyQuery } from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  SimpleCaseData,\n  VariablesCaseVariables,\n} from \"@apollo/client/testing/internal\";\nimport {\n  ObservableStream,\n  renderAsync,\n  setupSimpleCase,\n  setupVariablesCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ndescribe(\"useLazyQuery Hook\", () => {\n  const helloQuery: TypedDocumentNode<{\n    hello: string;\n  }> = gql`\n    query {\n      hello\n    }\n  `;\n\n  it(\"should hold query execution until manually triggered\", async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world\" } },\n        delay: 50,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(helloQuery), {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n    const result = await execute();\n\n    expect(result).toStrictEqualTyped({\n      data: { hello: \"world\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should use variables passed to execute function when running the lazy execution function\", async () => {\n    const query = gql`\n      query ($id: number) {\n        hello(id: $id)\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: 1 } },\n        result: { data: { hello: \"world 1\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(query), {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n    const result = await execute({ variables: { id: 1 } });\n\n    expect(result).toStrictEqualTyped({\n      data: { hello: \"world 1\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not emit loading state when notifyOnNetworkStatusChange is false\", async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world\" } },\n        delay: 50,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useLazyQuery(helloQuery, { notifyOnNetworkStatusChange: false }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n    const result = await execute();\n\n    expect(result).toStrictEqualTyped({\n      data: { hello: \"world\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"changing queries\", async () => {\n    const query1 = gql`\n      query {\n        hello\n      }\n    `;\n    const query2 = gql`\n      query {\n        name\n      }\n    `;\n    const mocks = [\n      {\n        request: { query: query1 },\n        result: { data: { hello: \"world\" } },\n        delay: 20,\n      },\n      {\n        request: { query: query2 },\n        result: { data: { name: \"changed\" } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(({ query }) => useLazyQuery(query), {\n        initialProps: { query: query1 },\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks} cache={cache}>\n            {children}\n          </MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await rerender({ query: query2 });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { name: \"changed\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: { hello: \"world\" },\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { name: \"changed\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"applies changed query to next refetch after execute\", async () => {\n    const query1 = gql`\n      query {\n        hello\n      }\n    `;\n    const query2 = gql`\n      query {\n        name\n      }\n    `;\n    const mocks = [\n      {\n        request: { query: query1 },\n        result: { data: { hello: \"world\" } },\n        delay: 20,\n      },\n      {\n        request: { query: query2 },\n        result: { data: { name: \"changed\" } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(({ query }) => useLazyQuery(query), {\n        initialProps: { query: query1 },\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks} cache={cache}>\n            {children}\n          </MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await rerender({ query: query2 });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [, { refetch }] = getCurrentSnapshot();\n\n    await expect(refetch()).resolves.toStrictEqualTyped({\n      data: { name: \"changed\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: { hello: \"world\" },\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { name: \"changed\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not render loading states when changing queries with notifyOnNetworkStatusChange: false\", async () => {\n    const query1 = gql`\n      query {\n        hello\n      }\n    `;\n    const query2 = gql`\n      query {\n        name\n      }\n    `;\n    const mocks = [\n      {\n        request: { query: query1 },\n        result: { data: { hello: \"world\" } },\n        delay: 20,\n      },\n      {\n        request: { query: query2 },\n        result: { data: { name: \"changed\" } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(\n        ({ query }) =>\n          useLazyQuery(query, { notifyOnNetworkStatusChange: false }),\n        {\n          initialProps: { query: query1 },\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks} cache={cache}>\n              {children}\n            </MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await rerender({ query: query2 });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { name: \"changed\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { name: \"changed\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it('should fetch data each time the execution function is called, when using a \"network-only\" fetch policy', async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 1\" } },\n        delay: 20,\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 2\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useLazyQuery(helloQuery, {\n            fetchPolicy: \"network-only\",\n          }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 1\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 2\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it('does not render loading states when the execution function is called when using a \"network-only\" fetch policy with notifyOnNetworkStatusChange: false', async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 1\" } },\n        delay: 20,\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 2\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useLazyQuery(helloQuery, {\n            notifyOnNetworkStatusChange: false,\n            fetchPolicy: \"network-only\",\n          }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 1\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 2\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should persist previous data when a query is refetched\", async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 1\" } },\n        delay: 20,\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 2\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(helloQuery), {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 1\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [, { refetch }] = getCurrentSnapshot();\n\n    await expect(refetch()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 2\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  // TODO: Determine if this hook makes sense for polling or if that should be\n  // reserved for useQuery. At the very least, we need to figure out if you can\n  // start polling a query before it has been executed\n  it(\"should allow for the query to start with polling\", async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 1\" } },\n        delay: 10,\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 2\" } },\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"world 3\" } },\n      },\n    ];\n\n    const wrapper = ({ children }: any) => (\n      <MockedProvider mocks={mocks}>{children}</MockedProvider>\n    );\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(helloQuery), {\n        wrapper,\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"world 1\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    getCurrentSnapshot()[1].startPolling(10);\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.poll,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.poll,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"world 3\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 2\" },\n        variables: {},\n      });\n    }\n\n    getCurrentSnapshot()[1].stopPolling();\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should persist previous data when a query is re-run and variable changes\", async () => {\n    const CAR_QUERY_BY_ID = gql`\n      query ($id: Int) {\n        car(id: $id) {\n          make\n          model\n        }\n      }\n    `;\n\n    const data1 = {\n      car: {\n        make: \"Audi\",\n        model: \"A4\",\n        __typename: \"Car\",\n      },\n    };\n\n    const data2 = {\n      car: {\n        make: \"Audi\",\n        model: \"RS8\",\n        __typename: \"Car\",\n      },\n    };\n\n    const mocks = [\n      {\n        request: { query: CAR_QUERY_BY_ID, variables: { id: 1 } },\n        result: { data: data1 },\n        delay: 20,\n      },\n      {\n        request: { query: CAR_QUERY_BY_ID, variables: { id: 2 } },\n        result: { data: data2 },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(CAR_QUERY_BY_ID), {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute({ variables: { id: 1 } })).resolves.toStrictEqualTyped(\n      { data: data1 }\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(execute({ variables: { id: 2 } })).resolves.toStrictEqualTyped(\n      { data: data2 }\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: data1,\n        variables: { id: 2 },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data2,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data1,\n        variables: { id: 2 },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not render loading states when a query is re-run and variables changes with notifyOnNetworkStatusChange: false\", async () => {\n    const CAR_QUERY_BY_ID = gql`\n      query ($id: Int) {\n        car(id: $id) {\n          make\n          model\n        }\n      }\n    `;\n\n    const data1 = {\n      car: {\n        make: \"Audi\",\n        model: \"A4\",\n        __typename: \"Car\",\n      },\n    };\n\n    const data2 = {\n      car: {\n        make: \"Audi\",\n        model: \"RS8\",\n        __typename: \"Car\",\n      },\n    };\n\n    const mocks = [\n      {\n        request: { query: CAR_QUERY_BY_ID, variables: { id: 1 } },\n        result: { data: data1 },\n        delay: 20,\n      },\n      {\n        request: { query: CAR_QUERY_BY_ID, variables: { id: 2 } },\n        result: { data: data2 },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useLazyQuery(CAR_QUERY_BY_ID, { notifyOnNetworkStatusChange: false }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute({ variables: { id: 1 } })).resolves.toStrictEqualTyped(\n      { data: data1 }\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(execute({ variables: { id: 2 } })).resolves.toStrictEqualTyped(\n      { data: data2 }\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data2,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data1,\n        variables: { id: 2 },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should work with cache-and-network fetch policy\", async () => {\n    const cache = new InMemoryCache();\n    const link = new MockLink([\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"from link\" } },\n        delay: 20,\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache,\n    });\n\n    cache.writeQuery({ query: helloQuery, data: { hello: \"from cache\" } });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useLazyQuery(helloQuery, { fetchPolicy: \"cache-and-network\" }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"from link\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from cache\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from link\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"from cache\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"executes on the network multiple times with a cache-and-network fetch policy\", async () => {\n    const cache = new InMemoryCache();\n    const link = new MockLink([\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"from link\" } },\n        delay: 20,\n      },\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"from link 2\" } },\n        delay: 20,\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache,\n    });\n\n    cache.writeQuery({ query: helloQuery, data: { hello: \"from cache\" } });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useLazyQuery(helloQuery, { fetchPolicy: \"cache-and-network\" }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"from link\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from cache\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from link\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"from cache\" },\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"from link 2\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from link\" },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: { hello: \"from cache\" },\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from link 2\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"from link\" },\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"executes on the network multiple times with a cache-and-network fetch policy when changing variables\", async () => {\n    const { query, mocks } = setupVariablesCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n      },\n      variables: { id: \"1\" },\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n      },\n      variables: { id: \"2\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useLazyQuery(query, { fetchPolicy: \"cache-and-network\" }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(\n      execute({ variables: { id: \"1\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n        },\n        variables: { id: \"1\" },\n      });\n    }\n\n    await expect(\n      execute({ variables: { id: \"2\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        variables: { id: \"2\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n        },\n        variables: { id: \"2\" },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"renders loading states with a cache-and-network fetch policy when changing variables with notifyOnNetworkStatusChange: false when there is cached data\", async () => {\n    const { query, mocks } = setupVariablesCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n      },\n      variables: { id: \"1\" },\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n      },\n      variables: { id: \"2\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useLazyQuery(query, {\n            fetchPolicy: \"cache-and-network\",\n            notifyOnNetworkStatusChange: false,\n          }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(\n      execute({ variables: { id: \"1\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Cache 1\" },\n        },\n        variables: { id: \"1\" },\n      });\n    }\n\n    await expect(\n      execute({ variables: { id: \"2\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        variables: { id: \"2\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Cache 2\" },\n        },\n        variables: { id: \"2\" },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not render loading states with a cache-and-network fetch policy when changing variables with notifyOnNetworkStatusChange: false with no cached data\", async () => {\n    const { query, mocks } = setupVariablesCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useLazyQuery(query, {\n            fetchPolicy: \"cache-and-network\",\n            notifyOnNetworkStatusChange: false,\n          }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(\n      execute({ variables: { id: \"1\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    await expect(\n      execute({ variables: { id: \"2\" } })\n    ).resolves.toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n        variables: { id: \"2\" },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"the promise returned from execute rejects when GraphQL errors are returned and errorPolicy is `none`\", async () => {\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: {\n          errors: [{ message: \"error 1\" }],\n        },\n        delay: 20,\n      },\n      {\n        request: { query: helloQuery },\n        result: {\n          errors: [{ message: \"error 2\" }],\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, peekSnapshot } = await renderHookToSnapshotStream(\n      () => useLazyQuery(helloQuery),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    const [execute] = await peekSnapshot();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"error 1\" }] })\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"error 1\" }] }),\n        variables: {},\n      });\n    }\n\n    await expect(execute()).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"error 2\" }] })\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"error 2\" }] }),\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"the promise returned from execute resolves when GraphQL errors are returned and errorPolicy is `all`\", async () => {\n    const query: TypedDocumentNode<{\n      currentUser: { __typename: \"User\"; id: string } | null;\n    }> = gql`\n      query currentUser {\n        id\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in\" }],\n        },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: {\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in 2\" }],\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, peekSnapshot } = await renderHookToSnapshotStream(\n      () => useLazyQuery(query, { errorPolicy: \"all\" }),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    const [execute] = await peekSnapshot();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { currentUser: null },\n      error: new CombinedGraphQLErrors({\n        data: { currentUser: null },\n        errors: [{ message: \"Not logged in\" }],\n      }),\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { currentUser: null },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        error: new CombinedGraphQLErrors({\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in\" }],\n        }),\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { currentUser: null },\n      error: new CombinedGraphQLErrors({\n        data: { currentUser: null },\n        errors: [{ message: \"Not logged in 2\" }],\n      }),\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          currentUser: null,\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { currentUser: null },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        error: new CombinedGraphQLErrors({\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in 2\" }],\n        }),\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"the promise returned from execute resolves when GraphQL errors are returned and errorPolicy is `ignore`\", async () => {\n    const query: TypedDocumentNode<{\n      currentUser: { __typename: \"User\"; id: string } | null;\n    }> = gql`\n      query currentUser {\n        id\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in\" }],\n        },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: {\n          data: { currentUser: null },\n          errors: [{ message: \"Not logged in 2\" }],\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, peekSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useLazyQuery(query, {\n          errorPolicy: \"ignore\",\n          notifyOnNetworkStatusChange: false,\n        }),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    const [execute] = await peekSnapshot();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { currentUser: null },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { currentUser: null },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { currentUser: null },\n    });\n\n    // We don't see an extra render here since the result is deeply equal to the\n    // previous result.\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"in-flight request promises reject with an `AbortError` when a new request is started before it could finish`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result } = renderHook(() => useLazyQuery(helloQuery), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    const [execute] = result.current;\n\n    let promise1: ReturnType<typeof execute>;\n    act(() => {\n      promise1 = execute();\n    });\n    let promise2: ReturnType<typeof execute>;\n    act(() => {\n      promise2 = execute();\n    });\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n\n    await expect(promise1!).rejects.toStrictEqual(\n      new DOMException(\"The operation was aborted.\", \"AbortError\")\n    );\n    await expect(promise2!).resolves.toStrictEqual({\n      data: { hello: \"Greetings\" },\n    });\n  });\n\n  it(\"in-flight request promises reject with an `AbortError` when component unmounts`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result, unmount } = renderHook(() => useLazyQuery(helloQuery), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    const [execute] = result.current;\n\n    let promise: ReturnType<typeof execute>;\n    act(() => {\n      promise = execute();\n    });\n\n    unmount();\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n\n    await expect(promise!).rejects.toStrictEqual(\n      new DOMException(\"The operation was aborted.\", \"AbortError\")\n    );\n  });\n\n  it(\"allows in-flight requests to resolve when component unmounts when used with `.retain()`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result, unmount } = renderHook(() => useLazyQuery(helloQuery), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    const [execute] = result.current;\n\n    let promise: ReturnType<typeof execute>;\n    act(() => {\n      promise = execute().retain();\n    });\n\n    unmount();\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n\n    await expect(promise!).resolves.toStrictEqualTyped({\n      data: { hello: \"Greetings\" },\n    });\n  });\n\n  it(\"handles resolving multiple in-flight requests when component unmounts with `.retain()`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result, unmount } = renderHook(() => useLazyQuery(helloQuery), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    const [execute] = result.current;\n\n    let promise1: Promise<ApolloClient.QueryResult<{ hello: string }>>;\n    let promise2: Promise<ApolloClient.QueryResult<{ hello: string }>>;\n    act(() => {\n      promise1 = execute().retain();\n      promise2 = execute().retain();\n    });\n\n    unmount();\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n\n    const expectedResult: ApolloClient.QueryResult<{ hello: string }> = {\n      data: { hello: \"Greetings\" },\n    };\n\n    await expect(promise1!).resolves.toStrictEqualTyped(expectedResult);\n    await expect(promise2!).resolves.toStrictEqualTyped(expectedResult);\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/9755\n  it(\"resolves each execution of the query with the appropriate result and renders with the result from the latest execution\", async () => {\n    interface Data {\n      user: { id: string; name: string };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query UserQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: { data: { user: { id: \"1\", name: \"John Doe\" } } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: { data: { user: { id: \"2\", name: \"Jane Doe\" } } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, peekSnapshot } = await renderHookToSnapshotStream(\n      // This test is too complicated between the react versions when testing\n      // the loading state\n      () => useLazyQuery(query, { notifyOnNetworkStatusChange: false }),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    const [execute] = await peekSnapshot();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const promise1 = execute({ variables: { id: \"1\" } }).retain();\n    const promise2 = execute({ variables: { id: \"2\" } });\n\n    await expect(promise1).resolves.toStrictEqualTyped({\n      data: mocks[0].result.data,\n    });\n\n    await expect(promise2).resolves.toStrictEqualTyped({\n      data: mocks[1].result.data,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: mocks[1].result.data,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"2\" },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"aborts early execution of previous query if a subsequent query is started\", async () => {\n    interface Data {\n      user: { id: string; name: string };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query UserQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: { data: { user: { id: \"1\", name: \"John Doe\" } } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: { data: { user: { id: \"2\", name: \"Jane Doe\" } } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, peekSnapshot } = await renderHookToSnapshotStream(\n      // This test is too complicated between the react versions when testing\n      // the loading state\n      () => useLazyQuery(query, { notifyOnNetworkStatusChange: false }),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    const [execute] = await peekSnapshot();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const promise1 = execute({ variables: { id: \"1\" } });\n    const promise2 = execute({ variables: { id: \"2\" } });\n\n    await expect(promise1).rejects.toStrictEqual(\n      new DOMException(\"The operation was aborted.\", \"AbortError\")\n    );\n\n    await expect(promise2).resolves.toStrictEqualTyped({\n      data: mocks[1].result.data,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: mocks[1].result.data,\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"2\" },\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/10198\n  it(\"uses the most recent query document when the hook rerenders before execution\", async () => {\n    const query = gql`\n      query DummyQuery {\n        shouldNotBeUsed\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: helloQuery },\n        result: { data: { hello: \"Greetings\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(({ query }) => useLazyQuery(query), {\n        initialProps: { query },\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await rerender({ query: helloQuery });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [execute] = getCurrentSnapshot();\n\n    await expect(execute()).resolves.toStrictEqualTyped({\n      data: { hello: \"Greetings\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"Greetings\" },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"does not refetch when rerendering after executing query\", async () => {\n    interface Data {\n      user: { id: string; name: string };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query UserQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    let fetchCount = 0;\n\n    const link = new ApolloLink((operation) => {\n      fetchCount++;\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { user: { id: operation.variables.id, name: \"John Doe\" } },\n          });\n          observer.complete();\n        }, 20);\n      });\n    });\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result, rerender } = renderHook(() => useLazyQuery(query), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    const [execute] = result.current;\n\n    await act(() => execute({ variables: { id: \"2\" } }));\n\n    expect(fetchCount).toBe(1);\n\n    rerender();\n\n    await wait(10);\n\n    expect(fetchCount).toBe(1);\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/9448\n  it.each([\"network-only\", \"no-cache\", \"cache-and-network\"] as const)(\n    \"does not issue multiple network calls when calling execute again without variables with a %s fetch policy\",\n    async (fetchPolicy) => {\n      interface Data {\n        user: { id: string | null; name: string };\n      }\n\n      interface Variables {\n        id?: string;\n      }\n\n      const query: TypedDocumentNode<Data, Variables> = gql`\n        query UserQuery($id: ID) {\n          user(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n      let fetchCount = 0;\n\n      const link = new ApolloLink((operation) => {\n        fetchCount++;\n        return new Observable((observer) => {\n          const { id } = operation.variables;\n\n          setTimeout(() => {\n            observer.next({\n              data: {\n                user:\n                  id ?\n                    { id, name: \"John Doe\" }\n                  : { id: null, name: \"John Default\" },\n              },\n            });\n            observer.complete();\n          }, 20);\n        });\n      });\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const { result } = renderHook(\n        () => useLazyQuery(query, { fetchPolicy }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await act(() => result.current[0]({ variables: { id: \"2\" } }));\n\n      expect(fetchCount).toBe(1);\n\n      await waitFor(() => {\n        expect(result.current[1]).toStrictEqualTyped({\n          data: { user: { id: \"2\", name: \"John Doe\" } },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: \"2\" },\n        });\n      });\n\n      expect(fetchCount).toBe(1);\n\n      await act(() => result.current[0]());\n\n      await waitFor(() => {\n        expect(result.current[1]).toStrictEqualTyped({\n          data: { user: { id: null, name: \"John Default\" } },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { user: { id: \"2\", name: \"John Doe\" } },\n          variables: {},\n        });\n      });\n\n      expect(fetchCount).toBe(2);\n    }\n  );\n\n  it(\"maintains stable execute function when passing in dynamic function options\", async () => {\n    interface Data {\n      user: { id: string; name: string };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query UserQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const link = new MockLink([\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: { data: { user: { id: \"1\", name: \"John Doe\" } } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: { errors: [{ message: \"Oops\" }] },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"3\" } },\n        result: { data: { user: { id: \"3\", name: \"Johnny Three\" } } },\n        delay: 20,\n        maxUsageCount: Number.POSITIVE_INFINITY,\n      },\n    ]);\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    let countRef = { current: 0 };\n\n    const trackClosureValue = jest.fn();\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(\n        () => {\n          let count = countRef.current;\n\n          return useLazyQuery(query, {\n            fetchPolicy: \"cache-first\",\n            skipPollAttempt: () => {\n              trackClosureValue(\"skipPollAttempt\", count);\n              return false;\n            },\n            nextFetchPolicy: (currentFetchPolicy) => {\n              trackClosureValue(\"nextFetchPolicy\", count);\n              return currentFetchPolicy;\n            },\n          });\n        },\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const [originalExecute] = getCurrentSnapshot();\n\n    countRef.current++;\n    await rerender();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    let [execute] = getCurrentSnapshot();\n    expect(execute).toBe(originalExecute);\n\n    await execute({ variables: { id: \"1\" } });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { user: { id: \"1\", name: \"John Doe\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    // after fetch\n    expect(trackClosureValue).toHaveBeenNthCalledWith(1, \"nextFetchPolicy\", 1);\n    trackClosureValue.mockClear();\n\n    countRef.current++;\n\n    await rerender();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { user: { id: \"1\", name: \"John Doe\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"1\" },\n      });\n    }\n\n    [execute] = getCurrentSnapshot();\n    expect(execute).toBe(originalExecute);\n\n    await expect(execute({ variables: { id: \"2\" } })).rejects.toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: { user: { id: \"1\", name: \"John Doe\" } },\n        variables: { id: \"2\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] }),\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: { user: { id: \"1\", name: \"John Doe\" } },\n        variables: { id: \"2\" },\n      });\n    }\n\n    // variables changed\n    expect(trackClosureValue).toHaveBeenNthCalledWith(1, \"nextFetchPolicy\", 2);\n    // after fetch\n    expect(trackClosureValue).toHaveBeenNthCalledWith(2, \"nextFetchPolicy\", 2);\n    trackClosureValue.mockClear();\n\n    countRef.current++;\n    await rerender();\n\n    [execute] = getCurrentSnapshot();\n    expect(execute).toBe(originalExecute);\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] }),\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: { user: { id: \"1\", name: \"John Doe\" } },\n        variables: { id: \"2\" },\n      });\n    }\n\n    await execute({ variables: { id: \"3\" } });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: { user: { id: \"1\", name: \"John Doe\" } },\n        variables: { id: \"3\" },\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { user: { id: \"3\", name: \"Johnny Three\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { user: { id: \"1\", name: \"John Doe\" } },\n        variables: { id: \"3\" },\n      });\n    }\n\n    // variables changed\n    expect(trackClosureValue).toHaveBeenNthCalledWith(1, \"nextFetchPolicy\", 3);\n    // after fetch\n    expect(trackClosureValue).toHaveBeenNthCalledWith(2, \"nextFetchPolicy\", 3);\n    trackClosureValue.mockClear();\n\n    // Test for stale closures for skipPollAttempt\n    getCurrentSnapshot()[1].startPolling(20);\n    await wait(50);\n    getCurrentSnapshot()[1].stopPolling();\n\n    expect(trackClosureValue).toHaveBeenCalledWith(\"skipPollAttempt\", 3);\n  });\n\n  it(\"maintains stable execute function identity when changing non-callback options\", async () => {\n    interface Data {\n      user: { id: string; name: string };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query UserQuery($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { user: { id: operation.variables.id, name: \"John Doe\" } },\n          });\n          observer.complete();\n        }, 20);\n      });\n    });\n\n    const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n    const { result, rerender } = renderHook(\n      ({ notifyOnNetworkStatusChange }) =>\n        useLazyQuery(query, { notifyOnNetworkStatusChange }),\n      {\n        initialProps: { notifyOnNetworkStatusChange: false },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    const [execute] = result.current;\n\n    rerender({ notifyOnNetworkStatusChange: true });\n\n    expect(result.current[0]).toBe(execute);\n  });\n\n  describe(\"network errors\", () => {\n    // For errorPolicy:\"none\", we expect result.error to be defined and\n    // result.data to be undefined\n    it('handles errorPolicy:\"none\" appropriately', async () => {\n      const networkError = new Error(\"from the network\");\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (request) =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                observer.error(networkError);\n              }, 20);\n            })\n        ),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useLazyQuery(helloQuery, {\n              errorPolicy: \"none\",\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: false,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      const [execute] = getCurrentSnapshot();\n\n      await expect(execute()).rejects.toEqual(networkError);\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: networkError,\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('handles errorPolicy:\"all\" appropriately', async () => {\n      const networkError = new Error(\"from the network\");\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (request) =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                observer.error(networkError);\n              }, 20);\n            })\n        ),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useLazyQuery(helloQuery, {\n              errorPolicy: \"all\",\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: false,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      const [execute] = getCurrentSnapshot();\n\n      await expect(execute()).resolves.toStrictEqualTyped({\n        data: undefined,\n        error: networkError,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: networkError,\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('handles errorPolicy:\"ignore\" appropriately', async () => {\n      const networkError = new Error(\"from the network\");\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (request) =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                observer.error(networkError);\n              }, 20);\n            })\n        ),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useLazyQuery(helloQuery, {\n              errorPolicy: \"ignore\",\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: false,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      const [execute] = getCurrentSnapshot();\n\n      await expect(execute()).resolves.toStrictEqualTyped({ data: undefined });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  // regression for https://github.com/apollographql/apollo-client/issues/11988\n  test(\"calling `clearStore` while a lazy query is running puts the hook into an error state and resolves the promise with an error result\", async () => {\n    const link = new MockSubscriptionLink();\n    let requests = 0;\n    link.onSetup(() => requests++);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useLazyQuery(helloQuery), {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    const execute = getCurrentSnapshot()[0];\n\n    const promise = execute();\n    expect(requests).toBe(1);\n\n    await wait(10);\n    await client.clearStore();\n\n    await expect(promise).rejects.toEqual(\n      new InvariantError(\n        \"Store reset while query was in flight (not completed in link chain)\"\n      )\n    );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new InvariantError(\n          \"Store reset while query was in flight (not completed in link chain)\"\n        ),\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n    await expect(takeSnapshot).not.toRerender({ timeout: 50 });\n    expect(requests).toBe(1);\n  });\n\n  describe(\"data masking\", () => {\n    it(\"masks queries when dataMasking is `true`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n          delay: 10,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useLazyQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      // initial render\n      await takeSnapshot();\n\n      const [execute] = getCurrentSnapshot();\n      const result = await execute();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n          },\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"does not mask queries when dataMasking is `false`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<\n        Unmasked<Query>,\n        Record<string, never>\n      > = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n          delay: 10,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: false,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useLazyQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      // initial render\n      await takeSnapshot();\n\n      const [execute] = getCurrentSnapshot();\n      const result = await execute();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"does not mask queries by default\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<\n        Unmasked<Query>,\n        Record<string, never>\n      > = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n          delay: 10,\n        },\n      ];\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useLazyQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      // initial render\n      await takeSnapshot();\n\n      const [execute] = getCurrentSnapshot();\n      const result = await execute();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"masks queries updated by the cache\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n          delay: 10,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useLazyQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      // initial render\n      await takeSnapshot();\n\n      const [execute] = getCurrentSnapshot();\n      await execute();\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User (updated)\",\n            age: 35,\n          },\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (updated)\",\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            currentUser: { __typename: \"User\", id: 1, name: \"Test User\" },\n          },\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"does not rerender when updating field in named fragment\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useLazyQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      // initial render\n      await takeSnapshot();\n\n      const [execute] = getCurrentSnapshot();\n      await execute();\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          called: true,\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          called: true,\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 35,\n          },\n        },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(client.readQuery({ query })).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 35,\n        },\n      });\n    });\n  });\n});\n\ntest(\"throws when calling `refetch` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { refetch }] = await takeSnapshot();\n\n  expect(() => {\n    void refetch();\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'refetch' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling `fetchMore` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { fetchMore }] = await takeSnapshot();\n\n  expect(() => {\n    void fetchMore({});\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'fetchMore' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling `subscribeToMore` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { subscribeToMore }] = await takeSnapshot();\n\n  expect(() => {\n    subscribeToMore({\n      document: gql`\n        subscription {\n          foo\n        }\n      `,\n    });\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'subscribeToMore' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling `updateQuery` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { updateQuery }] = await takeSnapshot();\n\n  expect(() => {\n    updateQuery(() => ({ greeting: \"foo\" }));\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'updateQuery' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling `startPolling` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { startPolling }] = await takeSnapshot();\n\n  expect(() => {\n    startPolling(10);\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'startPolling' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling `stopPolling` before execute function is called\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const [, { stopPolling }] = await takeSnapshot();\n\n  expect(() => {\n    stopPolling();\n  }).toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'stopPolling' cannot be called before executing the query.\"\n    )\n  );\n});\n\ntest(\"throws when calling execute function during first render\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query, mocks } = setupSimpleCase();\n\n  function App() {\n    const [execute] = useLazyQuery(query);\n\n    void execute();\n\n    return null;\n  }\n\n  // We need to use the `async` function here to prevent console errors from\n  // showing up\n  await expect(async () =>\n    renderAsync(<App />, {\n      wrapper: ({ children }) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      ),\n    })\n  ).rejects.toThrow(\n    new InvariantError(\n      \"useLazyQuery: 'execute' should not be called during render. To start a query during render, use the 'useQuery' hook.\"\n    )\n  );\n});\n\ntest(\"throws when calling execute function during subsequent render\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query, mocks } = setupSimpleCase();\n  const user = userEvent.setup();\n\n  function App() {\n    const [count, setCount] = React.useState(0);\n    const [execute] = useLazyQuery(query);\n\n    if (count === 1) {\n      void execute();\n    }\n\n    return <button onClick={() => setCount(1)}>Load</button>;\n  }\n\n  let error!: Error;\n\n  await renderAsync(<App />, {\n    wrapper: ({ children }) => (\n      <ErrorBoundary onError={(e) => (error = e)} fallback={<div>Oops</div>}>\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      </ErrorBoundary>\n    ),\n  });\n\n  await act(() => user.click(screen.getByText(\"Load\")));\n\n  expect(error).toEqual(\n    new InvariantError(\n      \"useLazyQuery: 'execute' should not be called during render. To start a query during render, use the 'useQuery' hook.\"\n    )\n  );\n});\n\ntest(\"uses the updated client when executing the function after changing clients\", async () => {\n  const { query } = setupSimpleCase();\n\n  const client1 = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello client 1\" } },\n        delay: 20,\n      },\n    ]),\n  });\n\n  const client2 = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello client 2\" } },\n        delay: 20,\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ client }) => useLazyQuery(query, { client }),\n      { initialProps: { client: client1 } }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello client 1\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello client 1\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  await rerender({ client: client2 });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello client 1\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello client 2\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: { greeting: \"Hello client 1\" },\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello client 2\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello client 1\" },\n      variables: {},\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"responds to cache updates after executing query\", async () => {\n  const { query } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello\" } },\n        delay: 20,\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: {\n      greeting: \"Hello (updated)\",\n    },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello (updated)\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        greeting: \"Hello\",\n      },\n      variables: {},\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"responds to cache updates after changing variables\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  client.writeQuery({\n    query,\n    variables: { id: \"2\" },\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"2\",\n        name: \"Black Widow (updated)\",\n      },\n    },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Black Widow (updated)\",\n        },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  // Ensure that writing data to a different set of variables does not rerender\n  // the hook\n  client.writeQuery({\n    query,\n    variables: { id: \"1\" },\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Spider-Man (updated)\",\n      },\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"uses cached result when switching to variables already written to the cache\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    variables: { id: \"2\" },\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Character\" },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Cached Character\",\n        },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Cached Character\",\n        },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"does not render loading states when switching to variables maybe written to the cache with notifyOnNetworkStatusChange: false\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    variables: { id: \"2\" },\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Character\" },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query, { notifyOnNetworkStatusChange: false }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Cached Character\",\n        },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Cached Character\",\n        },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"3\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"3\",\n          name: \"Iron Man\",\n        },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"3\",\n          name: \"Iron Man\",\n        },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: {\n          __typename: \"Character\",\n          id: \"2\",\n          name: \"Cached Character\",\n        },\n      },\n      variables: { id: \"3\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `errorPolicy` on next fetch when it changes between renders\", async () => {\n  const query: TypedDocumentNode<\n    {\n      character: { __typename: \"Character\"; id: string; name: string } | null;\n    },\n    VariablesCaseVariables\n  > = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: {\n          character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n        },\n      },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: {\n          character: null,\n        },\n        errors: [new GraphQLError(\"Could not find character 1\")],\n      },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ errorPolicy }: { errorPolicy: ErrorPolicy }) =>\n        useLazyQuery(query, { errorPolicy }),\n      {\n        initialProps: { errorPolicy: \"none\" },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await rerender({ errorPolicy: \"all\" });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  const [, { refetch }] = getCurrentSnapshot();\n  void refetch();\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: null,\n      },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({\n        data: { character: null },\n        errors: [{ message: \"Could not find character 1\" }],\n      }),\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `context` for each fetch\", async () => {\n  const query = gql`\n    query {\n      context\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      const context = operation.getContext();\n\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { context: { source: context.source ?? null } },\n          });\n          observer.complete();\n        }, 20);\n      });\n    }),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query, { fetchPolicy: \"network-only\" }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(\n    execute({ context: { source: \"firstExecuteValue\" } })\n  ).resolves.toStrictEqualTyped({\n    data: { context: { source: \"firstExecuteValue\" } },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"firstExecuteValue\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  await expect(\n    execute({ context: { source: \"reexecute\" } })\n  ).resolves.toStrictEqualTyped({\n    data: { context: { source: \"reexecute\" } },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"firstExecuteValue\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"reexecute\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { context: { source: \"firstExecuteValue\" } },\n      variables: {},\n    });\n  }\n\n  // Ensure context isn't just applied to execute function\n  void getCurrentSnapshot()[1].refetch();\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"reexecute\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: { context: { source: \"firstExecuteValue\" } },\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"reexecute\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { context: { source: \"firstExecuteValue\" } },\n      variables: {},\n    });\n  }\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { context: { source: null } },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: \"reexecute\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: { context: { source: \"firstExecuteValue\" } },\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { context: { source: null } },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { context: { source: \"reexecute\" } },\n      variables: {},\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `refetchWritePolicy` on next fetch when it changes between renders\", async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 30, max: 50 } },\n      result: { data: { primes: [31, 37, 41, 43, 47] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ refetchWritePolicy }) => useLazyQuery(query, { refetchWritePolicy }),\n      {\n        initialProps: { refetchWritePolicy: \"merge\" as RefetchWritePolicy },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(\n    execute({ variables: { min: 0, max: 12 } })\n  ).resolves.toStrictEqualTyped({ data: mocks[0].result.data });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { min: 0, max: 12 },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: mocks[0].result.data,\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { min: 0, max: 12 },\n    });\n  }\n\n  expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n  const [, { refetch }] = getCurrentSnapshot();\n\n  void refetch({ min: 12, max: 30 });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: mocks[0].result.data,\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables: { min: 12, max: 30 },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: mocks[0].result.data,\n      variables: { min: 12, max: 30 },\n    });\n  }\n\n  expect(mergeParams).toEqual([\n    [undefined, [2, 3, 5, 7, 11]],\n    [\n      [2, 3, 5, 7, 11],\n      [13, 17, 19, 23, 29],\n    ],\n  ]);\n\n  await rerender({ refetchWritePolicy: \"overwrite\" });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: mocks[0].result.data,\n      variables: { min: 12, max: 30 },\n    });\n  }\n\n  void refetch({ min: 30, max: 50 });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: mocks[0].result.data,\n      variables: { min: 30, max: 50 },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: mocks[2].result.data,\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      variables: { min: 30, max: 50 },\n    });\n  }\n\n  expect(mergeParams).toEqual([\n    [undefined, [2, 3, 5, 7, 11]],\n    [\n      [2, 3, 5, 7, 11],\n      [13, 17, 19, 23, 29],\n    ],\n    [undefined, [31, 37, 41, 43, 47]],\n  ]);\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `returnPartialData` on next fetch when it changes between renders\", async () => {\n  const fullQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query: fullQuery, variables: { id: \"1\" } },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange\",\n          },\n        },\n      },\n      delay: 20,\n    },\n    {\n      request: { query: fullQuery, variables: { id: \"2\" } },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"2\",\n            name: \"Hulk\",\n          },\n        },\n      },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  client.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"2\" } },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ returnPartialData }) => useLazyQuery(fullQuery, { returnPartialData }),\n      {\n        initialProps: { returnPartialData: false },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await rerender({ returnPartialData: true });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Hulk\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"2\" } },\n      dataState: \"partial\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"2\", name: \"Hulk\" } },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"2\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies updated `fetchPolicy` on next fetch when it changes between renders\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n    },\n    variables: { id: \"1\" },\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ fetchPolicy }) => useLazyQuery(query, { fetchPolicy }),\n      {\n        initialProps: { fetchPolicy: \"cache-first\" as WatchQueryFetchPolicy },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await rerender({ fetchPolicy: \"cache-and-network\" });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"renders loading states at appropriate times on next fetch after updating `notifyOnNetworkStatusChange`\", async () => {\n  const { query } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      { request: { query }, result: { data: { greeting: \"Hello 1\" } } },\n      { request: { query }, result: { data: { greeting: \"Hello 2\" } } },\n      { request: { query }, result: { data: { greeting: \"Hello 3\" } } },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot, rerender } =\n    await renderHookToSnapshotStream(\n      ({ notifyOnNetworkStatusChange }) =>\n        useLazyQuery(query, {\n          notifyOnNetworkStatusChange,\n          fetchPolicy: \"network-only\",\n        }),\n      {\n        initialProps: { notifyOnNetworkStatusChange: false },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 1\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  await rerender({ notifyOnNetworkStatusChange: true });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 2\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 2\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello 1\" },\n      variables: {},\n    });\n  }\n\n  await rerender({ notifyOnNetworkStatusChange: false });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 2\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello 1\" },\n      variables: {},\n    });\n  }\n\n  await expect(execute()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 3\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello 3\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello 2\" },\n      variables: {},\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"uses default variables in query\", async () => {\n  const query: TypedDocumentNode<\n    { letters: string[] },\n    { limit?: number; offset: number }\n  > = gql`\n    query DefaultsQuery($limit: Int! = 2, $offset: Int!) {\n      letters\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query, variables: { limit: 2, offset: 0 } },\n        result: { data: { letters: [\"a\", \"b\"] } },\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { limit: 2 },\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(\n    execute({ variables: { offset: 0 } })\n  ).resolves.toStrictEqualTyped({ data: { letters: [\"a\", \"b\"] } });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { limit: 2, offset: 0 },\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { letters: [\"a\", \"b\"] },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { limit: 2, offset: 0 },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"rerenders with data: undefined when changing variables and an error is returned with notifyOnNetworkStatusChange: false\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      mocks[0],\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: { errors: [{ message: \"Something went wrong\" }] },\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query, { notifyOnNetworkStatusChange: false }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute({ variables: { id: \"1\" } })).resolves.toStrictEqualTyped(\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1\" },\n    });\n  }\n\n  await expect(execute({ variables: { id: \"2\" } })).rejects.toEqual(\n    new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    })\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      variables: { id: \"2\" },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"executes network request when calling `refetch` on a cache-only query\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useLazyQuery(query, { fetchPolicy: \"cache-only\" }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await expect(execute()).resolves.toStrictEqualTyped({ data: undefined });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  const [, { refetch }] = getCurrentSnapshot();\n\n  await expect(refetch()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello\" },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n});\n\ntest(\"client.refetchQueries should not refetch queries that have not been executed yet\", async () => {\n  const query = gql`\n    query getAuthor($id: ID!) {\n      author(id: $id) {\n        firstName\n        lastName\n      }\n    }\n  `;\n  const data = {\n    author: {\n      firstName: \"John\",\n      lastName: \"Smith\",\n    },\n  };\n  const secondReqData = {\n    author: {\n      firstName: \"Jane\",\n      lastName: \"Johnson\",\n    },\n  };\n\n  const operationSubject = new Subject<ApolloLink.Operation>();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation, forward) => {\n      operationSubject.next(operation);\n      return forward(operation);\n    }).concat(link),\n  });\n\n  const operationStream = new ObservableStream(operationSubject);\n\n  const wrapper = ({ children }: any) => (\n    <ApolloProvider client={client}>{children}</ApolloProvider>\n  );\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    () => useLazyQuery(query),\n    { wrapper }\n  );\n\n  {\n    const [, result] = await renderStream.takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: false,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  }\n  await expect(operationStream).not.toEmitAnything();\n\n  await client.refetchQueries({ include: [query] });\n  await expect(renderStream).not.toRerender();\n  await expect(operationStream).not.toEmitAnything();\n\n  {\n    const [execute] = renderStream.getCurrentSnapshot();\n    execute({ variables: { id: \"1234\" } });\n  }\n\n  {\n    const [, result] = await renderStream.takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      called: true,\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: undefined,\n      variables: { id: \"1234\" },\n    });\n  }\n  await expect(operationStream).toEmitNext();\n\n  link.simulateResult({ result: { data } }, true);\n\n  {\n    const [, result] = await renderStream.takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data,\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: \"1234\" },\n    });\n  }\n\n  void client.refetchQueries({ include: [query] });\n  await expect(operationStream).toEmitNext();\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot({\n    expected: (previous) => [\n      previous[0],\n      {\n        ...previous[1],\n        previousData: undefined,\n        networkStatus: NetworkStatus.refetch,\n        loading: true,\n      },\n    ],\n  });\n\n  link.simulateResult({ result: { data: secondReqData } }, true);\n  {\n    const [, result] = await renderStream.takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: secondReqData,\n      dataState: \"complete\",\n      called: true,\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: data,\n      variables: { id: \"1234\" },\n    });\n  }\n});\n\ndescribe.skip(\"Type Tests\", () => {\n  test(\"returns narrowed TData in default case\", () => {\n    const { query } = setupSimpleCase();\n\n    const [, { data, dataState, called }] = useLazyQuery(query);\n\n    if (!called) {\n      expectTypeOf(dataState).toEqualTypeOf<\"empty\">();\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n\n    if (dataState === \"complete\") {\n      expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n    }\n\n    if (dataState === \"streaming\") {\n      expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n    }\n\n    if (dataState === \"empty\") {\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n  });\n\n  test(\"returns DeepPartial<TData> with returnPartialData: true\", () => {\n    const { query } = setupSimpleCase();\n\n    const [, { data, dataState, called }] = useLazyQuery(query, {\n      returnPartialData: true,\n    });\n\n    if (!called) {\n      expectTypeOf(dataState).toEqualTypeOf<\"empty\">();\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n\n    expectTypeOf(dataState).toEqualTypeOf<\n      \"empty\" | \"streaming\" | \"complete\" | \"partial\"\n    >;\n\n    if (dataState === \"complete\") {\n      expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n    }\n\n    if (dataState === \"partial\") {\n      expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n    }\n\n    if (dataState === \"streaming\") {\n      expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n    }\n\n    if (dataState === \"empty\") {\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n  });\n  test(\"NoInfer prevents adding arbitrary additional variables\", () => {\n    const typedNode = {} as TypedDocumentNode<{ foo: string }, { bar: number }>;\n    const [execute, { variables }] = useLazyQuery(typedNode);\n\n    void execute({\n      variables: {\n        bar: 4,\n        // @ts-expect-error\n        nonExistingVariable: \"string\",\n      },\n    });\n\n    variables?.bar;\n    // @ts-expect-error\n    variables?.nonExistingVariable;\n  });\n\n  test(\"uses masked types when using masked document\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface UnmaskedQuery {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    interface Subscription {\n      updatedUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface UnmaskedSubscription {\n      updatedUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    const query: TypedDocumentNode<Query> = gql``;\n\n    const [\n      execute,\n      { data, previousData, subscribeToMore, fetchMore, refetch, updateQuery },\n    ] = useLazyQuery(query);\n\n    expectTypeOf(data).toEqualTypeOf<\n      Query | DataValue.Streaming<Query> | undefined\n    >();\n    expectTypeOf(previousData).toEqualTypeOf<Query | undefined>();\n\n    subscribeToMore({\n      document: gql`` as TypedDocumentNode<Subscription, never>,\n      updateQuery(queryData, { subscriptionData, complete, previousData }) {\n        expectTypeOf(queryData).toEqualTypeOf<DeepPartial<UnmaskedQuery>>();\n        expectTypeOf(complete).toEqualTypeOf<boolean>();\n        expectTypeOf(previousData).toEqualTypeOf<\n          UnmaskedQuery | DeepPartial<UnmaskedQuery> | undefined\n        >();\n\n        if (complete) {\n          expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n        } else {\n          expectTypeOf(previousData).toEqualTypeOf<\n            DeepPartial<UnmaskedQuery> | undefined\n          >();\n        }\n        expectTypeOf(\n          subscriptionData.data\n        ).toEqualTypeOf<UnmaskedSubscription>();\n\n        return {} as UnmaskedQuery;\n      },\n    });\n\n    updateQuery((_previousData, { complete, previousData }) => {\n      expectTypeOf(_previousData).toEqualTypeOf<DeepPartial<UnmaskedQuery>>();\n      expectTypeOf(complete).toEqualTypeOf<boolean>();\n      expectTypeOf(previousData).toEqualTypeOf<\n        UnmaskedQuery | DeepPartial<UnmaskedQuery> | undefined\n      >();\n\n      return {} as UnmaskedQuery;\n    });\n\n    {\n      const { data } = await execute();\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n\n    {\n      const { data } = await fetchMore({\n        variables: {},\n        updateQuery: (queryData, { fetchMoreResult }) => {\n          expectTypeOf(queryData).toEqualTypeOf<UnmaskedQuery>();\n          expectTypeOf(fetchMoreResult).toEqualTypeOf<UnmaskedQuery>();\n\n          return {} as UnmaskedQuery;\n        },\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n\n    {\n      const { data } = await refetch();\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n  });\n\n  test(\"uses unmodified types when using TypedDocumentNode\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface UnmaskedQuery {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    interface Subscription {\n      updatedUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    interface UnmaskedSubscription {\n      updatedUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    const query: TypedDocumentNode<Query> = gql``;\n\n    const [\n      execute,\n      { data, previousData, fetchMore, refetch, subscribeToMore, updateQuery },\n    ] = useLazyQuery(query);\n\n    expectTypeOf(data).toEqualTypeOf<\n      Query | DataValue.Streaming<Query> | undefined\n    >();\n    expectTypeOf(previousData).toEqualTypeOf<Query | undefined>();\n\n    subscribeToMore({\n      document: gql`` as TypedDocumentNode<Subscription, never>,\n      updateQuery(queryData, { subscriptionData, complete, previousData }) {\n        expectTypeOf(queryData).toEqualTypeOf<DeepPartial<UnmaskedQuery>>();\n        expectTypeOf(previousData).toEqualTypeOf<\n          UnmaskedQuery | DeepPartial<UnmaskedQuery> | undefined\n        >();\n        expectTypeOf(\n          subscriptionData.data\n        ).toEqualTypeOf<UnmaskedSubscription>();\n\n        if (complete) {\n          expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n        } else {\n          expectTypeOf(previousData).toEqualTypeOf<\n            DeepPartial<UnmaskedQuery> | undefined\n          >();\n        }\n\n        return {} as UnmaskedQuery;\n      },\n    });\n\n    updateQuery((_previousData, { complete, previousData }) => {\n      expectTypeOf(_previousData).toEqualTypeOf<DeepPartial<UnmaskedQuery>>();\n      expectTypeOf(complete).toEqualTypeOf<boolean>();\n      expectTypeOf(previousData).toEqualTypeOf<\n        UnmaskedQuery | DeepPartial<UnmaskedQuery> | undefined\n      >();\n\n      if (complete) {\n        expectTypeOf(previousData).toEqualTypeOf<UnmaskedQuery>();\n      } else {\n        expectTypeOf(previousData).toEqualTypeOf<\n          DeepPartial<UnmaskedQuery> | undefined\n        >();\n      }\n    });\n\n    {\n      const { data } = await execute();\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n\n    {\n      const { data } = await fetchMore({\n        variables: {},\n        updateQuery: (queryData, { fetchMoreResult }) => {\n          expectTypeOf(queryData).toEqualTypeOf<UnmaskedQuery>();\n          expectTypeOf(fetchMoreResult).toEqualTypeOf<UnmaskedQuery>();\n\n          return {} as UnmaskedQuery;\n        },\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n\n    {\n      const { data } = await refetch();\n\n      expectTypeOf(data).toEqualTypeOf<Query | undefined>();\n    }\n  });\n\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const query = gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    void execute();\n    void execute({});\n    void execute({ variables: {} });\n    void execute({ variables: { foo: \"bar\" } });\n    void execute({ variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    void execute();\n    void execute({});\n    void execute({ variables: {} });\n    void execute({ variables: { foo: \"bar\" } });\n    void execute({ variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    void execute();\n    void execute({});\n    void execute({ variables: {} });\n    void execute({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    // @ts-expect-error\n    void execute();\n    // @ts-expect-error expecting variables key\n    void execute({});\n    // @ts-expect-error variables is never\n    void execute({ variables: {} });\n    // @ts-expect-error variables is never\n    void execute({ variables: undefined });\n    // @ts-expect-error unknown variables\n    void execute({ variables: { foo: \"bar\" } });\n  });\n\n  test(\"optional variables are optional\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    void execute();\n    void execute({});\n    void execute({ variables: {} });\n    void execute({ variables: { limit: 10 } });\n    void execute({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void execute({\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"enforces required variables when TVariables includes required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    // @ts-expect-error empty variables\n    void execute();\n    // @ts-expect-error empty variables\n    void execute({});\n    // @ts-expect-error empty variables\n    void execute({ variables: {} });\n    void execute({ variables: { id: \"1\" } });\n    void execute({\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void execute({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    const [execute] = useLazyQuery(query);\n\n    // @ts-expect-error empty variables\n    void execute();\n    // @ts-expect-error empty variables\n    void execute({});\n    // @ts-expect-error empty variables\n    void execute({ variables: {} });\n    void execute({ variables: { id: \"1\" } });\n    void execute({\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    void execute({ variables: { id: \"1\", language: \"en\" } });\n    void execute({\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    void execute({\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"execution result has `.retain` method\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql`\n      query Greeting {\n        greeting\n      }\n    `;\n\n    const [execute] = useLazyQuery(query);\n    const result = execute();\n\n    // test assignability to a normal promise\n    expectTypeOf(result).toMatchTypeOf<\n      Promise<\n        ApolloClient.QueryResult<{\n          greeting: string;\n        }>\n      >\n    >();\n\n    // retain should return the same type as the original result\n    expectTypeOf(result.retain()).toEqualTypeOf(result);\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useLoadableQuery/defer20220824.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useLoadableQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDefer20220824,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderHook<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useLoadableQuery.Result<TData, TVariables, TStates>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({\n    queryRef,\n  }: {\n    queryRef: QueryRef<TData, TVariables, TStates>;\n  }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useLoadableQuery\" });\n    const [loadQuery, queryRef] = renderHook(props as any);\n\n    mergeSnapshot({ loadQuery });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          {queryRef && <UseReadQuery queryRef={queryRef} />}\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const {\n    render,\n    getCurrentRender,\n    takeRender,\n    mergeSnapshot,\n    replaceSnapshot,\n  } = createRenderStream<\n    | {\n        loadQuery: useLoadableQuery.LoadQueryFunction<TVariables>;\n        result?: useReadQuery.Result<TData, TStates>;\n      }\n    | { error: ErrorLike }\n  >({ initialSnapshot: { loadQuery: null as any } });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n    invariant(\n      \"loadQuery\" in snapshot,\n      \"Expected rendered hook instead of error boundary\"\n    );\n\n    return snapshot;\n  }\n\n  return { takeRender, rerender, getCurrentSnapshot };\n}\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  interface Data {\n    greeting: {\n      __typename: string;\n      message: string;\n      recipient: { name: string; __typename: string };\n    };\n  }\n\n  const query: TypedDocumentNode<Data, Record<string, never>> = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const cache = new InMemoryCache();\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderHook(\n    () => useLoadableQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useLoadableQuery\"]);\n  }\n\n  getCurrentSnapshot().loadQuery();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\n      \"useLoadableQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello cached\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  interface QueryData {\n    greeting: {\n      __typename: string;\n      message?: string;\n      recipient?: {\n        __typename: string;\n        name: string;\n      };\n    };\n  }\n\n  const query: TypedDocumentNode<QueryData, Record<string, never>> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const cache = new InMemoryCache();\n\n  {\n    // We are intentionally writing partial data to the cache. Supress console\n    // warnings to avoid unnecessary noise in the test.\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderHook(\n    () =>\n      useLoadableQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useLoadableQuery\"]);\n  }\n\n  getCurrentSnapshot().loadQuery();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\n      \"useLoadableQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useLoadableQuery/deferGraphQL17Alpha9.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type {\n  DataState,\n  ErrorLike,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport { useLoadableQuery, useReadQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDeferStreamGraphQL17Alpha9,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderHook<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useLoadableQuery.Result<TData, TVariables, TStates>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseReadQuery({\n    queryRef,\n  }: {\n    queryRef: QueryRef<TData, TVariables, TStates>;\n  }) {\n    useTrackRenders({ name: \"useReadQuery\" });\n    mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useLoadableQuery\" });\n    const [loadQuery, queryRef] = renderHook(props as any);\n\n    mergeSnapshot({ loadQuery });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          {queryRef && <UseReadQuery queryRef={queryRef} />}\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const {\n    render,\n    getCurrentRender,\n    takeRender,\n    mergeSnapshot,\n    replaceSnapshot,\n  } = createRenderStream<\n    | {\n        loadQuery: useLoadableQuery.LoadQueryFunction<TVariables>;\n        result?: useReadQuery.Result<TData, TStates>;\n      }\n    | { error: ErrorLike }\n  >({ initialSnapshot: { loadQuery: null as any } });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n    invariant(\n      \"loadQuery\" in snapshot,\n      \"Expected rendered hook instead of error boundary\"\n    );\n\n    return snapshot;\n  }\n\n  return { takeRender, rerender, getCurrentSnapshot };\n}\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  interface Data {\n    greeting: {\n      __typename: string;\n      message: string;\n      recipient: { name: string; __typename: string };\n    };\n  }\n\n  const query: TypedDocumentNode<Data, Record<string, never>> = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const cache = new InMemoryCache();\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderHook(\n    () => useLoadableQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useLoadableQuery\"]);\n  }\n\n  getCurrentSnapshot().loadQuery();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\n      \"useLoadableQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello cached\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  interface QueryData {\n    greeting: {\n      __typename: string;\n      message?: string;\n      recipient?: {\n        __typename: string;\n        name: string;\n      };\n    };\n  }\n\n  const query: TypedDocumentNode<QueryData, Record<string, never>> = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const cache = new InMemoryCache();\n\n  {\n    // We are intentionally writing partial data to the cache. Supress console\n    // warnings to avoid unnecessary noise in the test.\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderHook(\n    () =>\n      useLoadableQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useLoadableQuery\"]);\n  }\n\n  getCurrentSnapshot().loadQuery();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\n      \"useLoadableQuery\",\n      \"useReadQuery\",\n    ]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    invariant(\"result\" in snapshot);\n    expect(renderedComponents).toStrictEqual([\"useReadQuery\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useLoadableQuery.test.tsx",
    "content": "import { act, renderHook, screen, waitFor } from \"@testing-library/react\";\nimport type {\n  AsyncRenderFn,\n  RenderStream,\n} from \"@testing-library/react-render-stream\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport { GraphQLError } from \"graphql\";\nimport React, { Suspense, useState } from \"react\";\nimport { ErrorBoundary as ReactErrorBoundary } from \"react-error-boundary\";\nimport { Observable } from \"rxjs\";\n\nimport type {\n  DataState,\n  DataValue,\n  ErrorPolicy,\n  ObservableQuery,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  useLoadableQuery,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  PaginatedCaseData,\n  SimpleCaseData,\n} from \"@apollo/client/testing/internal\";\nimport {\n  renderAsync,\n  setupPaginatedCase,\n  setupSimpleCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport type { MockedProviderProps } from \"@apollo/client/testing/react\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  concatPagination,\n  offsetLimitPagination,\n} from \"@apollo/client/utilities\";\nimport { getMainDefinition } from \"@apollo/client/utilities/internal\";\nimport { invariant, InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport type { SubscribeToMoreFunction } from \"../../../core/watchQueryOptions.js\";\nimport type {\n  FetchMoreFunction,\n  RefetchFunction,\n} from \"../../internal/types.js\";\n\nconst IS_REACT_19 = React.version.startsWith(\"19\");\n\nafterEach(() => {\n  jest.useRealTimers();\n});\n\ninterface SimpleQueryData {\n  greeting: string;\n}\n\nfunction useSimpleQueryCase() {\n  const query: TypedDocumentNode<SimpleQueryData, Record<string, never>> = gql`\n    query GreetingQuery {\n      greeting\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<SimpleQueryData>[] = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: 10,\n    },\n  ];\n\n  return { query, mocks };\n}\n\ninterface VariablesCaseData {\n  character: {\n    id: string;\n    name: string;\n  };\n}\n\ninterface VariablesCaseVariables {\n  id: string;\n}\n\nfunction useVariablesQueryCase() {\n  const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n    gql`\n      query CharacterQuery($id: ID!) {\n        character(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n  const CHARACTERS = [\"Spider-Man\", \"Black Widow\", \"Iron Man\", \"Hulk\"];\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    ...CHARACTERS,\n  ].map((name, index) => ({\n    request: { query, variables: { id: String(index + 1) } },\n    result: { data: { character: { id: String(index + 1), name } } },\n    delay: 20,\n  }));\n\n  return { mocks, query };\n}\n\ninterface PaginatedQueryData {\n  letters: {\n    letter: string;\n    position: number;\n  }[];\n}\n\ninterface PaginatedQueryVariables {\n  limit?: number;\n  offset?: number;\n}\n\nfunction usePaginatedQueryCase() {\n  const query: TypedDocumentNode<PaginatedQueryData, PaginatedQueryVariables> =\n    gql`\n      query letters($limit: Int, $offset: Int) {\n        letters(limit: $limit) {\n          letter\n          position\n        }\n      }\n    `;\n\n  const data = \"ABCDEFG\"\n    .split(\"\")\n    .map((letter, index) => ({ letter, position: index + 1 }));\n\n  const link = new ApolloLink((operation) => {\n    const { offset = 0, limit = 2 } = operation.variables;\n    const letters = data.slice(offset, offset + limit);\n\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { letters } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n  return { query, link, client };\n}\n\nfunction createDefaultProfiler<TData>() {\n  return createRenderStream({\n    initialSnapshot: {\n      error: null as Error | null,\n      result: null as useReadQuery.Result<TData> | null,\n    },\n    skipNonTrackingRenders: true,\n  });\n}\n\nfunction createDefaultProfiledComponents<\n  Snapshot extends {\n    result: useReadQuery.Result<any> | null;\n    error?: Error | null;\n  },\n  TData = Snapshot[\"result\"] extends useReadQuery.Result<infer TData> | null ?\n    TData\n  : unknown,\n  TStates extends DataState<TData>[\"dataState\"] = Snapshot[\"result\"] extends (\n    useReadQuery.Result<any, infer TStates> | null\n  ) ?\n    TStates\n  : \"complete\" | \"streaming\",\n>(profiler: RenderStream<Snapshot>) {\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({\n    queryRef,\n  }: {\n    queryRef: QueryRef<TData, any, TStates>;\n  }) {\n    useTrackRenders();\n    profiler.mergeSnapshot({\n      result: useReadQuery(queryRef),\n    } as unknown as Partial<Snapshot>);\n\n    return null;\n  }\n\n  function ErrorFallback({ error }: { error: Error }) {\n    useTrackRenders();\n    profiler.mergeSnapshot({ error } as Partial<Snapshot>);\n\n    return <div>Oops</div>;\n  }\n\n  function ErrorBoundary({ children }: { children: React.ReactNode }) {\n    return (\n      <ReactErrorBoundary FallbackComponent={ErrorFallback}>\n        {children}\n      </ReactErrorBoundary>\n    );\n  }\n\n  return {\n    SuspenseFallback,\n    ReadQueryHook,\n    ErrorFallback,\n    ErrorBoundary,\n  };\n}\n\nasync function renderWithMocks(\n  ui: React.ReactElement,\n  props: MockedProviderProps,\n  { render: doRender }: { render: AsyncRenderFn | typeof renderAsync }\n) {\n  const user = userEvent.setup();\n\n  const utils = await doRender(ui, {\n    wrapper: ({ children }) => (\n      <MockedProvider {...props}>{children}</MockedProvider>\n    ),\n  });\n\n  return { ...utils, user };\n}\n\nasync function renderWithClient(\n  ui: React.ReactElement,\n  options: { client: ApolloClient },\n  { render: doRender }: { render: AsyncRenderFn | typeof renderAsync }\n) {\n  const { client } = options;\n  const user = userEvent.setup();\n\n  const utils = await doRender(ui, {\n    wrapper: ({ children }: { children: React.ReactNode }) => (\n      <ApolloProvider client={client}>{children}</ApolloProvider>\n    ),\n  });\n\n  return { ...utils, user };\n}\n\nit(\"loads a query and suspends when the load query function is called\", async () => {\n  const { query, mocks } = useSimpleQueryCase();\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleQueryData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n  }\n});\n\nit(\"loads a query with variables and suspends by passing variables to the loadQuery function\", async () => {\n  const { query, mocks } = useVariablesQueryCase();\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"tears down the query on unmount\", async () => {\n  const { query, mocks } = useSimpleQueryCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleQueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user, unmount } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { greeting: \"Hello\" },\n    dataState: \"complete\",\n    error: undefined,\n    networkStatus: NetworkStatus.ready,\n  });\n\n  unmount();\n\n  // We need to wait a tick since the cleanup is run in a setTimeout to\n  // prevent strict mode bugs.\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"auto disposes of the queryRef if not used within timeout\", async () => {\n  jest.useFakeTimers();\n  const { query } = setupSimpleCase();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  const { result } = renderHook(() => useLoadableQuery(query, { client }));\n  const [loadQuery] = result.current;\n\n  void act(() => loadQuery());\n  const [, queryRef] = result.current;\n\n  expect(queryRef!).not.toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await act(async () => {\n    link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n    // Ensure simulateResult will deliver the result since its wrapped with\n    // setTimeout\n    await jest.advanceTimersByTimeAsync(10);\n  });\n\n  jest.advanceTimersByTime(30_000);\n\n  expect(queryRef!).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"auto disposes of the queryRef if not used within configured timeout\", async () => {\n  jest.useFakeTimers();\n  const { query } = setupSimpleCase();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      react: {\n        suspense: {\n          autoDisposeTimeoutMs: 5000,\n        },\n      },\n    },\n  });\n\n  const { result } = renderHook(() => useLoadableQuery(query, { client }));\n  const [loadQuery] = result.current;\n\n  void act(() => loadQuery());\n  const [, queryRef] = result.current;\n\n  expect(queryRef!).not.toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  await act(async () => {\n    link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n    // Ensure simulateResult will deliver the result since its wrapped with\n    // setTimeout\n    await jest.advanceTimersByTimeAsync(10);\n  });\n\n  jest.advanceTimersByTime(5000);\n\n  expect(queryRef!).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\nit(\"will resubscribe after disposed when mounting useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n    defaultOptions: {\n      react: {\n        suspense: {\n          // Set this to something really low to avoid fake timers\n          autoDisposeTimeoutMs: 20,\n        },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(false);\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n  await user.click(screen.getByText(\"Load query\"));\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  // Wait long enough for auto dispose to kick in\n  await wait(50);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  await user.click(screen.getByText(\"Toggle\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello again\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"auto resubscribes when mounting useReadQuery after naturally disposed by useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n  await user.click(screen.getByText(\"Load query\"));\n\n  expect(client.getObservableQueries().size).toBe(1);\n  expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  await user.click(toggleButton);\n\n  expect(client.getObservableQueries().size).toBe(1);\n  // Here we don't expect a suspense cache entry because we previously disposed\n  // of it and did not call `loadQuery` again, which would normally add it to\n  // the suspense cache\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello again\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender({ timeout: 50 });\n});\n\nit(\"changes variables on a query and resuspends when passing new variables to the loadQuery function\", async () => {\n  const { query, mocks } = useVariablesQueryCase();\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const App = () => {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>\n          Load 1st character\n        </button>\n        <button onClick={() => loadQuery({ id: \"2\" })}>\n          Load 2nd character\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  };\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n  }\n\n  await user.click(screen.getByText(\"Load 1st character\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load 2nd character\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"2\", name: \"Black Widow\" } },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"resets the `queryRef` to null and disposes of it when calling the `reset` function\", async () => {\n  const { query, mocks } = useSimpleQueryCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleQueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { reset }] = useLoadableQuery(query);\n\n    // Resetting the result allows us to detect when ReadQueryHook is unmounted\n    // since it won't render and overwrite the `null`\n    renderStream.mergeSnapshot({ result: null });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button onClick={() => reset()}>Reset query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Reset query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toBeNull();\n  }\n\n  // Since dispose is called in a setTimeout, we need to wait a tick before\n  // checking to see if the query ref was properly disposed\n  await wait(0);\n\n  expect(client.getObservableQueries().size).toBe(0);\n});\n\nit(\"allows the client to be overridden\", async () => {\n  const { query } = useSimpleQueryCase();\n\n  const globalClient = new ApolloClient({\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"global hello\" } },\n        delay: 10,\n      },\n    ]),\n    cache: new InMemoryCache(),\n  });\n\n  const localClient = new ApolloClient({\n    link: new MockLink([\n      {\n        request: { query },\n        result: { data: { greeting: \"local hello\" } },\n        delay: 10,\n      },\n    ]),\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleQueryData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      client: localClient,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client: globalClient,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { greeting: \"local hello\" },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n});\n\nit(\"passes context to the link\", async () => {\n  interface QueryData {\n    context: Record<string, any>;\n  }\n\n  const query: TypedDocumentNode<QueryData, Record<string, never>> = gql`\n    query ContextQuery {\n      context\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        const { valueA, valueB } = operation.getContext();\n        setTimeout(() => {\n          observer.next({ data: { context: { valueA, valueB } } });\n          observer.complete();\n        }, 10);\n      });\n    }),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<QueryData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      context: { valueA: \"A\", valueB: \"B\" },\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { context: { valueA: \"A\", valueB: \"B\" } },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n});\n\nit(\"returns initial cache data followed by network data when the fetch policy is `cache-and-network`\", async () => {\n  type QueryData = { hello: string };\n  const query: TypedDocumentNode<QueryData, Record<string, never>> = gql`\n    query {\n      hello\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { hello: \"from cache\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<QueryData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { hello: \"from cache\" },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { hello: \"from link\" },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n});\n\nit(\"all data is present in the cache, no network request is made\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache,\n  });\n\n  cache.writeQuery({ query, data: { hello: \"from cache\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n  expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { hello: \"from cache\" },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"partial data is present in the cache so it is ignored and network request is made\", async () => {\n  const query = gql`\n    {\n      hello\n      foo\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\", foo: \"bar\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache,\n  });\n\n  {\n    // we expect a \"Missing field 'foo' while writing result...\" error\n    // when writing hello to the cache, so we'll silence the console.error\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({ query, data: { hello: \"from cache\" } });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { foo: \"bar\", hello: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"existing data in the cache is ignored when `fetchPolicy` is 'network-only'\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache,\n  });\n\n  cache.writeQuery({ query, data: { hello: \"from cache\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      fetchPolicy: \"network-only\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { hello: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"fetches data from the network but does not update the cache when `fetchPolicy` is 'no-cache'\", async () => {\n  const query = gql`\n    query {\n      hello\n    }\n  `;\n  const cache = new InMemoryCache();\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { hello: \"from link\" } },\n      delay: 20,\n    },\n  ]);\n\n  const client = new ApolloClient({ link, cache });\n\n  cache.writeQuery({ query, data: { hello: \"from cache\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      fetchPolicy: \"no-cache\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { hello: \"from link\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(client.extract()).toEqual({\n    ROOT_QUERY: { __typename: \"Query\", hello: \"from cache\" },\n  });\n});\n\nit(\"works with startTransition to change variables\", async () => {\n  type Variables = {\n    id: string;\n  };\n\n  interface Data {\n    todo: {\n      id: string;\n      name: string;\n      completed: boolean;\n    };\n  }\n\n  const query: TypedDocumentNode<Data, Variables> = gql`\n    query TodoItemQuery($id: ID!) {\n      todo(id: $id) {\n        id\n        name\n        completed\n      }\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"2\" } },\n      result: {\n        data: {\n          todo: { id: \"2\", name: \"Take out trash\", completed: true },\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  function SuspenseFallback() {\n    return <p>Loading</p>;\n  }\n\n  function App() {\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <div>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load first todo</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && (\n            <Todo queryRef={queryRef} onChange={(id) => loadQuery({ id })} />\n          )}\n        </Suspense>\n      </div>\n    );\n  }\n\n  function Todo({\n    queryRef,\n    onChange,\n  }: {\n    queryRef: QueryRef<Data, Variables>;\n    onChange: (id: string) => void;\n  }) {\n    const { data } = useReadQuery(queryRef);\n    const [isPending, startTransition] = React.useTransition();\n    const { todo } = data;\n\n    return (\n      <>\n        <button\n          onClick={() => {\n            startTransition(() => {\n              onChange(\"2\");\n            });\n          }}\n        >\n          Refresh\n        </button>\n        <div data-testid=\"todo\" aria-busy={isPending}>\n          {todo.name}\n          {todo.completed && \" (completed)\"}\n        </div>\n      </>\n    );\n  }\n\n  await renderWithClient(<App />, { client }, { render: renderAsync });\n  const user = userEvent.setup();\n\n  await act(() => user.click(screen.getByText(\"Load first todo\")));\n\n  expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n  expect(await screen.findByTestId(\"todo\")).toBeInTheDocument();\n\n  const todo = screen.getByTestId(\"todo\");\n  const button = screen.getByText(\"Refresh\");\n\n  expect(todo).toHaveTextContent(\"Clean room\");\n\n  await act(() => user.click(button));\n\n  // startTransition will avoid rendering the suspense fallback for already\n  // revealed content if the state update inside the transition causes the\n  // component to suspend.\n  //\n  // Here we should not see the suspense fallback while the component suspends\n  // until the todo is finished loading. Seeing the suspense fallback is an\n  // indication that we are suspending the component too late in the process.\n  expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n\n  // We can ensure this works with isPending from useTransition in the process\n  expect(todo).toHaveAttribute(\"aria-busy\", \"true\");\n\n  // Ensure we are showing the stale UI until the new todo has loaded\n  expect(todo).toHaveTextContent(\"Clean room\");\n\n  // Eventually we should see the updated todo content once its done\n  // suspending.\n  await waitFor(() => {\n    expect(todo).toHaveTextContent(\"Take out trash (completed)\");\n  });\n});\n\nit(\"reacts to cache updates\", async () => {\n  const { query, mocks } = useSimpleQueryCase();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleQueryData> | null,\n    },\n  });\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Updated Hello\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Updated Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"applies `errorPolicy` on next fetch when it changes between renders\", async () => {\n  const { query } = useSimpleQueryCase();\n\n  const mocks: MockLink.MockedResponse<SimpleQueryData>[] = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: 10,\n    },\n    {\n      request: { query },\n      result: {\n        errors: [new GraphQLError(\"oops\")],\n      },\n      delay: 10,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<SimpleQueryData>();\n  const { SuspenseFallback, ReadQueryHook, ErrorBoundary, ErrorFallback } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [errorPolicy, setErrorPolicy] = useState<ErrorPolicy>(\"none\");\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      errorPolicy,\n    });\n\n    return (\n      <>\n        <button onClick={() => setErrorPolicy(\"all\")}>\n          Change error policy\n        </button>\n        <button onClick={() => refetch()}>Refetch greeting</button>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            {queryRef && <ReadQueryHook queryRef={queryRef} />}\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Change error policy\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch greeting\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    // Ensure we aren't rendering the error boundary and instead rendering the\n    // error message in the hook component.\n    expect(renderedComponents).not.toContain(ErrorFallback);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({ errors: [{ message: \"oops\" }] }),\n      networkStatus: NetworkStatus.error,\n    });\n  }\n});\n\nit(\"applies `context` on next fetch when it changes between renders\", async () => {\n  interface Data {\n    phase: string;\n  }\n\n  const query: TypedDocumentNode<Data, Record<string, never>> = gql`\n    query {\n      phase\n    }\n  `;\n\n  const link = new ApolloLink((operation) => {\n    return new Observable((subscriber) => {\n      setTimeout(() => {\n        subscriber.next({\n          data: {\n            phase: operation.getContext().phase,\n          },\n        });\n        subscriber.complete();\n      }, 10);\n    });\n  });\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<Data>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [phase, setPhase] = React.useState(\"initial\");\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      context: { phase },\n    });\n\n    return (\n      <>\n        <button onClick={() => setPhase(\"rerender\")}>Update context</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { phase: \"initial\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Update context\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { phase: \"rerender\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"applies changed `refetchWritePolicy` to next fetch when changing between renders\", async () => {\n  interface Data {\n    primes: number[];\n  }\n\n  const query: TypedDocumentNode<Data, { min: number; max: number }> = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 30, max: 50 } },\n      result: { data: { primes: [31, 37, 41, 43, 47] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<Data>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [refetchWritePolicy, setRefetchWritePolicy] =\n      React.useState<RefetchWritePolicy>(\"merge\");\n\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      refetchWritePolicy,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ min: 0, max: 12 })}>\n          Load query\n        </button>\n        <button onClick={() => setRefetchWritePolicy(\"overwrite\")}>\n          Change refetch write policy\n        </button>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>\n          Refetch next\n        </button>\n        <button onClick={() => refetch({ min: 30, max: 50 })}>\n          Refetch last\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch next\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n  }\n\n  await user.click(screen.getByText(\"Change refetch write policy\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch last\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [31, 37, 41, 43, 47] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n      [undefined, [31, 37, 41, 43, 47]],\n    ]);\n  }\n});\n\nit(\"applies `returnPartialData` on next fetch when it changes between renders\", async () => {\n  interface Data {\n    character: {\n      __typename: \"Character\";\n      id: string;\n      name: string;\n    };\n  }\n\n  interface PartialData {\n    character: {\n      __typename: \"Character\";\n      id: string;\n    };\n  }\n\n  const fullQuery: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        __typename\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery: TypedDocumentNode<PartialData> = gql`\n    query {\n      character {\n        __typename\n        id\n      }\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query: fullQuery },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange\",\n          },\n        },\n      },\n      delay: 10,\n    },\n    {\n      request: { query: fullQuery },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange (refetched)\",\n          },\n        },\n      },\n      delay: 100,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<Data | DeepPartial<Data>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [returnPartialData, setReturnPartialData] = React.useState(false);\n\n    const [loadQuery, queryRef] = useLoadableQuery(fullQuery, {\n      returnPartialData,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button onClick={() => setReturnPartialData(true)}>\n          Update partial data\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Update partial data\"));\n  await renderStream.takeRender();\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Character\", id: \"1\" }),\n    fields: {\n      name: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\" },\n      },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strange (refetched)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"applies updated `fetchPolicy` on next fetch when it changes between renders\", async () => {\n  interface Data {\n    character: {\n      __typename: \"Character\";\n      id: string;\n      name: string;\n    };\n  }\n\n  const query: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        __typename\n        id\n        name\n      }\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strange\",\n          },\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Doctor Strangecache\",\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<Data>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [fetchPolicy, setFetchPolicy] =\n      React.useState<useLoadableQuery.FetchPolicy>(\"cache-first\");\n\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      fetchPolicy,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button onClick={() => setFetchPolicy(\"no-cache\")}>\n          Change fetch policy\n        </button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strangecache\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Change fetch policy\"));\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strange\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // Because we switched to a `no-cache` fetch policy, we should not see the\n  // newly fetched data in the cache after the fetch occurred.\n  expect(cache.readQuery({ query })).toStrictEqualTyped({\n    character: {\n      __typename: \"Character\",\n      id: \"1\",\n      name: \"Doctor Strangecache\",\n    },\n  });\n});\n\nit(\"re-suspends when calling `refetch`\", async () => {\n  const { query } = useVariablesQueryCase();\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      },\n      delay: 20,\n    },\n    // refetch\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Spider-Man (updated)\" } },\n      },\n      delay: 20,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man (updated)\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"re-suspends when calling `refetch` with new variables\", async () => {\n  const { query } = useVariablesQueryCase();\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"2\" } },\n      result: {\n        data: { character: { id: \"2\", name: \"Captain America\" } },\n      },\n      delay: 10,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch({ id: \"2\" })}>Refetch with ID 2</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch with ID 2\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"2\", name: \"Captain America\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"re-suspends multiple times when calling `refetch` multiple times\", async () => {\n  const { query } = useVariablesQueryCase();\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      },\n      maxUsageCount: 3,\n      delay: 10,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  const button = screen.getByText(\"Refetch\");\n\n  await user.click(button);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(button);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"throws errors when errors are returned after calling `refetch`\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const { query } = useVariablesQueryCase();\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        errors: [new GraphQLError(\"Something went wrong\")],\n      },\n      delay: 20,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook, ErrorBoundary, ErrorFallback } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            {queryRef && <ReadQueryHook queryRef={queryRef} />}\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ErrorFallback]);\n    expect(snapshot.error).toEqual(\n      new CombinedGraphQLErrors({\n        errors: [{ message: \"Something went wrong\" }],\n      })\n    );\n  }\n});\n\nit('ignores errors returned after calling `refetch` when errorPolicy is set to \"ignore\"', async () => {\n  const { query } = useVariablesQueryCase();\n\n  const mocks = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        errors: [new GraphQLError(\"Something went wrong\")],\n      },\n      delay: 10,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData | undefined>();\n\n  const { SuspenseFallback, ReadQueryHook, ErrorBoundary, ErrorFallback } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      errorPolicy: \"ignore\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            {queryRef && <ReadQueryHook queryRef={queryRef} />}\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.error).toBeNull();\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    expect(renderedComponents).not.toContain(ErrorFallback);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('returns errors after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n  const { query } = useVariablesQueryCase();\n\n  const mocks: MockLink.MockedResponse<VariablesCaseData>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        errors: [new GraphQLError(\"Something went wrong\")],\n      },\n      delay: 20,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData | undefined>();\n\n  const { SuspenseFallback, ReadQueryHook, ErrorBoundary, ErrorFallback } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      errorPolicy: \"all\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            {queryRef && <ReadQueryHook queryRef={queryRef} />}\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).not.toContain(ErrorFallback);\n    expect(snapshot.error).toBeNull();\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Captain Marvel\" } },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n      networkStatus: NetworkStatus.error,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('handles partial data results after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n  type VariablesCaseData = {\n    character: {\n      __typename: \"Character\";\n      id: string;\n      name: string | null;\n    };\n  };\n  const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n    gql`\n      query CharacterQuery($id: ID!) {\n        character(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n  const mocks = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Captain Marvel\",\n          },\n        },\n      },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { character: { __typename: \"Character\", id: \"1\", name: null } },\n        errors: [new GraphQLError(\"Something went wrong\")],\n      },\n      delay: 20,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<VariablesCaseData>();\n\n  const { SuspenseFallback, ReadQueryHook, ErrorBoundary, ErrorFallback } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      errorPolicy: \"all\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary>\n            {queryRef && <ReadQueryHook queryRef={queryRef} />}\n          </ErrorBoundary>\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Captain Marvel\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).not.toContain(ErrorFallback);\n    expect(snapshot.error).toBeNull();\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\", name: null } },\n      dataState: \"complete\",\n      error: new CombinedGraphQLErrors({\n        data: { character: { __typename: \"Character\", id: \"1\", name: null } },\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n      networkStatus: NetworkStatus.error,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"`refetch` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n  type Variables = {\n    id: string;\n  };\n\n  interface Data {\n    todo: {\n      id: string;\n      name: string;\n      completed: boolean;\n    };\n  }\n\n  const query: TypedDocumentNode<Data, Variables> = gql`\n    query TodoItemQuery($id: ID!) {\n      todo(id: $id) {\n        id\n        name\n        completed\n      }\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<Data>[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n      },\n      delay: 10,\n    },\n  ];\n\n  function SuspenseFallback() {\n    return <p>Loading</p>;\n  }\n\n  function App() {\n    const [id, setId] = React.useState(\"1\");\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id })}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && (\n            <Todo refetch={refetch} queryRef={queryRef} onChange={setId} />\n          )}\n        </Suspense>\n      </>\n    );\n  }\n\n  function Todo({\n    queryRef,\n    refetch,\n  }: {\n    refetch: RefetchFunction<Data, OperationVariables>;\n    queryRef: QueryRef<Data>;\n    onChange: (id: string) => void;\n  }) {\n    const { data } = useReadQuery(queryRef);\n    const [isPending, startTransition] = React.useTransition();\n    const { todo } = data;\n\n    return (\n      <>\n        <button\n          onClick={() => {\n            startTransition(() => {\n              void refetch();\n            });\n          }}\n        >\n          Refresh\n        </button>\n        <div data-testid=\"todo\" aria-busy={isPending}>\n          {todo.name}\n          {todo.completed && \" (completed)\"}\n        </div>\n      </>\n    );\n  }\n\n  await renderWithMocks(<App />, { mocks }, { render: renderAsync });\n  const user = userEvent.setup();\n\n  await act(() => user.click(screen.getByText(\"Load query\")));\n\n  expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n  expect(await screen.findByTestId(\"todo\")).toBeInTheDocument();\n\n  const todo = screen.getByTestId(\"todo\");\n  const button = screen.getByText(\"Refresh\");\n\n  expect(todo).toHaveTextContent(\"Clean room\");\n\n  await act(() => user.click(button));\n\n  // startTransition will avoid rendering the suspense fallback for already\n  // revealed content if the state update inside the transition causes the\n  // component to suspend.\n  //\n  // Here we should not see the suspense fallback while the component suspends\n  // until the todo is finished loading. Seeing the suspense fallback is an\n  // indication that we are suspending the component too late in the process.\n  expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n\n  // We can ensure this works with isPending from useTransition in the process\n  expect(todo).toHaveAttribute(\"aria-busy\", \"true\");\n\n  // Ensure we are showing the stale UI until the new todo has loaded\n  expect(todo).toHaveTextContent(\"Clean room\");\n\n  // Eventually we should see the updated todo content once its done\n  // suspending.\n  await waitFor(() => {\n    expect(todo).toHaveTextContent(\"Clean room (completed)\");\n  });\n});\n\nit(\"re-suspends when calling `fetchMore` with different variables\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: {\n              keyArgs: false,\n            },\n          },\n        },\n      },\n    }),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<PaginatedCaseData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { fetchMore }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button\n          onClick={() => fetchMore({ variables: { offset: 2, limit: 2 } })}\n        >\n          Fetch more\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Fetch more\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"properly uses `updateQuery` when calling `fetchMore`\", async () => {\n  const { query, client } = usePaginatedQueryCase();\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<PaginatedQueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { fetchMore }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button\n          onClick={() =>\n            fetchMore({\n              variables: { offset: 2, limit: 2 },\n              updateQuery: (prev, { fetchMoreResult }) => ({\n                letters: prev.letters.concat(fetchMoreResult.letters),\n              }),\n            })\n          }\n        >\n          Fetch more\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { letter: \"A\", position: 1 },\n          { letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Fetch more\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { letter: \"A\", position: 1 },\n          { letter: \"B\", position: 2 },\n          { letter: \"C\", position: 3 },\n          { letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // TODO investigate: this test highlights a React render\n  // that actually doesn't rerender any user-provided components\n  // so we need to use `skipNonTrackingRenders`\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"properly uses cache field policies when calling `fetchMore` without `updateQuery`\", async () => {\n  const { query, link } = usePaginatedQueryCase();\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<PaginatedQueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: concatPagination(),\n          },\n        },\n      },\n    }),\n  });\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { fetchMore }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <button\n          onClick={() => fetchMore({ variables: { offset: 2, limit: 2 } })}\n        >\n          Fetch more\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { letter: \"A\", position: 1 },\n          { letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Fetch more\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { letter: \"A\", position: 1 },\n          { letter: \"B\", position: 2 },\n          { letter: \"C\", position: 3 },\n          { letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // TODO investigate: this test highlights a React render\n  // that actually doesn't rerender any user-provided components\n  // so we need to use `skipNonTrackingRenders`\n  await expect(renderStream).not.toRerender();\n});\n\nit(\"`fetchMore` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n  type Variables = {\n    offset: number;\n  };\n\n  interface Todo {\n    __typename: \"Todo\";\n    id: string;\n    name: string;\n    completed: boolean;\n  }\n  interface Data {\n    todos: Todo[];\n  }\n\n  const query: TypedDocumentNode<Data, Variables> = gql`\n    query TodosQuery($offset: Int!) {\n      todos(offset: $offset) {\n        id\n        name\n        completed\n      }\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<Data>[] = [\n    {\n      request: { query, variables: { offset: 0 } },\n      result: {\n        data: {\n          todos: [\n            {\n              __typename: \"Todo\",\n              id: \"1\",\n              name: \"Clean room\",\n              completed: false,\n            },\n          ],\n        },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { offset: 1 } },\n      result: {\n        data: {\n          todos: [\n            {\n              __typename: \"Todo\",\n              id: \"2\",\n              name: \"Take out trash\",\n              completed: true,\n            },\n          ],\n        },\n      },\n      delay: 10,\n    },\n  ];\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            todos: offsetLimitPagination(),\n          },\n        },\n      },\n    }),\n  });\n\n  function SuspenseFallback() {\n    return <p>Loading</p>;\n  }\n\n  function App() {\n    const [loadQuery, queryRef, { fetchMore }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ offset: 0 })}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <Todo fetchMore={fetchMore} queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function Todo({\n    queryRef,\n    fetchMore,\n  }: {\n    fetchMore: FetchMoreFunction<Data, OperationVariables>;\n    queryRef: QueryRef<Data>;\n  }) {\n    const { data } = useReadQuery(queryRef);\n    const [isPending, startTransition] = React.useTransition();\n    const { todos } = data;\n\n    return (\n      <>\n        <button\n          onClick={() => {\n            startTransition(() => {\n              void fetchMore({ variables: { offset: 1 } });\n            });\n          }}\n        >\n          Load more\n        </button>\n        <div data-testid=\"todos\" aria-busy={isPending}>\n          {todos.map((todo) => (\n            <div data-testid={`todo:${todo.id}`} key={todo.id}>\n              {todo.name}\n              {todo.completed && \" (completed)\"}\n            </div>\n          ))}\n        </div>\n      </>\n    );\n  }\n\n  await renderWithClient(<App />, { client }, { render: renderAsync });\n  const user = userEvent.setup();\n\n  await act(() => user.click(screen.getByText(\"Load query\")));\n\n  expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n  expect(await screen.findByTestId(\"todos\")).toBeInTheDocument();\n\n  const todos = screen.getByTestId(\"todos\");\n  const todo1 = screen.getByTestId(\"todo:1\");\n  const button = screen.getByText(\"Load more\");\n\n  expect(todo1).toBeInTheDocument();\n\n  await act(() => user.click(button));\n\n  // startTransition will avoid rendering the suspense fallback for already\n  // revealed content if the state update inside the transition causes the\n  // component to suspend.\n  //\n  // Here we should not see the suspense fallback while the component suspends\n  // until the todo is finished loading. Seeing the suspense fallback is an\n  // indication that we are suspending the component too late in the process.\n  expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n\n  // We can ensure this works with isPending from useTransition in the process\n  expect(todos).toHaveAttribute(\"aria-busy\", \"true\");\n\n  // Ensure we are showing the stale UI until the new todo has loaded\n  expect(todo1).toHaveTextContent(\"Clean room\");\n\n  // Eventually we should see the updated todos content once its done\n  // suspending.\n  await waitFor(() => {\n    expect(screen.getByTestId(\"todo:2\")).toHaveTextContent(\n      \"Take out trash (completed)\"\n    );\n    expect(todo1).toHaveTextContent(\"Clean room\");\n  });\n});\n\nit('honors refetchWritePolicy set to \"merge\"', async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  interface QueryData {\n    primes: number[];\n  }\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<QueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query, {\n      refetchWritePolicy: \"merge\",\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ min: 0, max: 12 })}>\n          Load query\n        </button>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('defaults refetchWritePolicy to \"overwrite\"', async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  interface QueryData {\n    primes: number[];\n  }\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<QueryData>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { refetch }] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ min: 0, max: 12 })}>\n          Load query\n        </button>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial load\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [undefined, [13, 17, 19, 23, 29]],\n    ]);\n  }\n});\n\nit('does not suspend when partial data is in the cache and using a \"cache-first\" fetch policy with returnPartialData', async () => {\n  interface Data {\n    character: {\n      id: string;\n      name: string;\n    };\n  }\n\n  const fullQuery: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query {\n      character {\n        id\n      }\n    }\n  `;\n  const mocks = [\n    {\n      request: { query: fullQuery },\n      result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n      delay: 20,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<Data>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n  });\n\n  const client = new ApolloClient({ link: new MockLink(mocks), cache });\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(fullQuery, {\n      fetchPolicy: \"cache-first\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n\n  // initial load\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Doctor Strange\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('suspends and does not use partial data from other variables in the cache when changing variables and using a \"cache-first\" fetch policy with returnPartialData: true', async () => {\n  const { query, mocks } = useVariablesQueryCase();\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      fetchPolicy: \"cache-first\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => loadQuery({ id: \"2\" })}>Change variables</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n      cache,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n  }\n\n  await user.click(screen.getByText(\"Change variables\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"2\", name: \"Black Widow\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('suspends when partial data is in the cache and using a \"network-only\" fetch policy with returnPartialData', async () => {\n  interface Data {\n    character: {\n      id: string;\n      name: string;\n    };\n  }\n\n  const fullQuery: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query {\n      character {\n        id\n      }\n    }\n  `;\n  const mocks = [\n    {\n      request: { query: fullQuery },\n      result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n      delay: 10,\n    },\n  ];\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<Data>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n  });\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(fullQuery, {\n      fetchPolicy: \"network-only\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n      cache,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Doctor Strange\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\nit('suspends when partial data is in the cache and using a \"no-cache\" fetch policy with returnPartialData', async () => {\n  using _consoleSpy = spyOnConsole(\"warn\");\n\n  interface Data {\n    character: {\n      id: string;\n      name: string;\n    };\n  }\n\n  const fullQuery: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query {\n      character {\n        id\n      }\n    }\n  `;\n  const mocks = [\n    {\n      request: { query: fullQuery },\n      result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n      delay: 10,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<Data>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(fullQuery, {\n      fetchPolicy: \"no-cache\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n      cache,\n    },\n    renderStream\n  );\n\n  // initial load\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Doctor Strange\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit('warns when using returnPartialData with a \"no-cache\" fetch policy', async () => {\n  using _consoleSpy = spyOnConsole(\"warn\");\n\n  const query: TypedDocumentNode<SimpleQueryData> = gql`\n    query UserQuery {\n      greeting\n    }\n  `;\n\n  renderHook(\n    () =>\n      useLoadableQuery(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: ({ children }) => (\n        <MockedProvider mocks={[]}>{children}</MockedProvider>\n      ),\n    }\n  );\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n  );\n});\n\nit('does not suspend when partial data is in the cache and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n  interface Data {\n    character: {\n      id: string;\n      name: string;\n    };\n  }\n\n  const fullQuery: TypedDocumentNode<Data> = gql`\n    query {\n      character {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query {\n      character {\n        id\n      }\n    }\n  `;\n  const mocks = [\n    {\n      request: { query: fullQuery },\n      result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n      delay: 20,\n    },\n  ];\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<Data>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(fullQuery, {\n      fetchPolicy: \"cache-and-network\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n      cache,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Doctor Strange\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit('suspends and does not use partial data when changing variables and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n  const { query, mocks } = useVariablesQueryCase();\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query: partialQuery,\n    data: { character: { id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createDefaultProfiler<DeepPartial<VariablesCaseData>>();\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query, {\n      fetchPolicy: \"cache-and-network\",\n      returnPartialData: true,\n    });\n\n    return (\n      <>\n        <button onClick={() => loadQuery({ id: \"1\" })}>Load query</button>\n        <button onClick={() => loadQuery({ id: \"2\" })}>Change variables</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  const { user } = await renderWithMocks(\n    <App />,\n    {\n      mocks,\n      cache,\n    },\n    renderStream\n  );\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"1\", name: \"Spider-Man\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Change variables\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { id: \"2\", name: \"Black Widow\" } },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\nit(\"throws when calling loadQuery on first render\", async () => {\n  // We don't provide this functionality with React 19 anymore since it requires internals access\n  if (IS_REACT_19) return;\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query, mocks } = useSimpleQueryCase();\n\n  function App() {\n    const [loadQuery] = useLoadableQuery(query);\n\n    loadQuery();\n\n    return null;\n  }\n\n  await expect(\n    renderWithMocks(\n      <App />,\n      { mocks },\n      {\n        render: renderAsync,\n      }\n    )\n  ).rejects.toThrow(\n    new InvariantError(\n      \"useLoadableQuery: 'loadQuery' should not be called during render. To start a query during render, use the 'useBackgroundQuery' hook.\"\n    )\n  );\n});\n\nit(\"throws when calling loadQuery on subsequent render\", async () => {\n  // We don't provide this functionality with React 19 anymore since it requires internals access\n  if (React.version.startsWith(\"19\")) return;\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query, mocks } = useSimpleQueryCase();\n\n  let error!: Error;\n\n  function App() {\n    const [count, setCount] = useState(0);\n    const [loadQuery] = useLoadableQuery(query);\n\n    if (count === 1) {\n      loadQuery();\n    }\n\n    return <button onClick={() => setCount(1)}>Load query in render</button>;\n  }\n\n  await renderWithMocks(\n    <ReactErrorBoundary onError={(e) => (error = e)} fallback={<div>Oops</div>}>\n      <App />\n    </ReactErrorBoundary>,\n    { mocks },\n    { render: renderAsync }\n  );\n  const user = userEvent.setup();\n\n  await act(() => user.click(screen.getByText(\"Load query in render\")));\n\n  expect(error).toEqual(\n    new InvariantError(\n      \"useLoadableQuery: 'loadQuery' should not be called during render. To start a query during render, use the 'useBackgroundQuery' hook.\"\n    )\n  );\n});\n\nit(\"allows loadQuery to be called in useEffect on first render\", async () => {\n  const { query, mocks } = useSimpleQueryCase();\n\n  function App() {\n    const [loadQuery] = useLoadableQuery(query);\n\n    React.useEffect(() => {\n      loadQuery();\n    }, []);\n\n    return null;\n  }\n\n  await expect(\n    renderWithMocks(<App />, { mocks }, { render: renderAsync })\n  ).resolves.not.toThrow();\n});\n\nit(\"can subscribe to subscriptions and react to cache updates via `subscribeToMore`\", async () => {\n  interface SubscriptionData {\n    greetingUpdated: string;\n  }\n\n  type UpdateQueryFn = NonNullable<\n    ObservableQuery.SubscribeToMoreOptions<\n      SimpleCaseData,\n      Record<string, never>,\n      SubscriptionData\n    >[\"updateQuery\"]\n  >;\n\n  const subscription: TypedDocumentNode<\n    SubscriptionData,\n    Record<string, never>\n  > = gql`\n    subscription {\n      greetingUpdated\n    }\n  `;\n\n  const { mocks, query } = setupSimpleCase();\n\n  const wsLink = new MockSubscriptionLink();\n  const mockLink = new MockLink(mocks);\n\n  const link = ApolloLink.split(\n    ({ query }) => {\n      const definition = getMainDefinition(query);\n\n      return (\n        definition.kind === \"OperationDefinition\" &&\n        definition.operation === \"subscription\"\n      );\n    },\n    wsLink,\n    mockLink\n  );\n\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      subscribeToMore: null as SubscribeToMoreFunction<\n        SimpleCaseData,\n        Record<string, never>\n      > | null,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { subscribeToMore }] = useLoadableQuery(query);\n\n    renderStream.mergeSnapshot({ subscribeToMore });\n\n    return (\n      <div>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </div>\n    );\n  }\n\n  const { user } = await renderWithClient(\n    <App />,\n    {\n      client,\n    },\n    renderStream\n  );\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  const updateQuery = jest.fn<\n    ReturnType<UpdateQueryFn>,\n    Parameters<UpdateQueryFn>\n  >((_, { subscriptionData: { data } }) => {\n    return { greeting: data.greetingUpdated };\n  });\n\n  const { snapshot } = renderStream.getCurrentRender();\n\n  snapshot.subscribeToMore!({ document: subscription, updateQuery });\n\n  wsLink.simulateResult({\n    result: {\n      data: {\n        greetingUpdated: \"Subscription hello\",\n      },\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Subscription hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(updateQuery).toHaveBeenCalledTimes(1);\n  expect(updateQuery).toHaveBeenCalledWith(\n    { greeting: \"Hello\" },\n    {\n      complete: true,\n      previousData: { greeting: \"Hello\" },\n      subscriptionData: {\n        data: { greetingUpdated: \"Subscription hello\" },\n      },\n      variables: {},\n    }\n  );\n});\n\nit(\"throws when calling `subscribeToMore` before loading the query\", async () => {\n  interface SubscriptionData {\n    greetingUpdated: string;\n  }\n\n  const subscription: TypedDocumentNode<\n    SubscriptionData,\n    Record<string, never>\n  > = gql`\n    subscription {\n      greetingUpdated\n    }\n  `;\n\n  const { mocks, query } = setupSimpleCase();\n\n  const wsLink = new MockSubscriptionLink();\n  const mockLink = new MockLink(mocks);\n\n  const link = ApolloLink.split(\n    ({ query }) => {\n      const definition = getMainDefinition(query);\n\n      return (\n        definition.kind === \"OperationDefinition\" &&\n        definition.operation === \"subscription\"\n      );\n    },\n    wsLink,\n    mockLink\n  );\n\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      subscribeToMore: null as SubscribeToMoreFunction<\n        SimpleCaseData,\n        Record<string, never>\n      > | null,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  const { SuspenseFallback, ReadQueryHook } =\n    createDefaultProfiledComponents(renderStream);\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef, { subscribeToMore }] = useLoadableQuery(query);\n\n    renderStream.mergeSnapshot({ subscribeToMore });\n\n    return (\n      <div>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </div>\n    );\n  }\n\n  await renderWithClient(<App />, { client }, renderStream);\n  // initial render\n  await renderStream.takeRender();\n\n  const { snapshot } = renderStream.getCurrentRender();\n\n  expect(() => {\n    snapshot.subscribeToMore!({ document: subscription });\n  }).toThrow(\n    new InvariantError(\"The query has not been loaded. Please load the query.\")\n  );\n});\n\ndescribe.skip(\"type tests\", () => {\n  it(\"returns unknown when TData cannot be inferred\", () => {\n    const query = gql``;\n\n    const [, queryRef] = useLoadableQuery(query);\n\n    invariant(queryRef);\n\n    const { data } = useReadQuery(queryRef);\n\n    expectTypeOf(data).toEqualTypeOf<unknown>();\n    expectTypeOf(queryRef).toEqualTypeOf<\n      QueryRef<unknown, OperationVariables, \"complete\" | \"streaming\">\n    >;\n  });\n\n  it(\"variables are optional and can be anything with an untyped DocumentNode\", () => {\n    const query = gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    loadQuery();\n    loadQuery({});\n    loadQuery({ foo: \"bar\" });\n    loadQuery({ bar: \"baz\" });\n  });\n\n  it(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    loadQuery();\n    loadQuery({});\n    loadQuery({ foo: \"bar\" });\n    loadQuery({ bar: \"baz\" });\n  });\n\n  it(\"variables are optional when TVariables are empty\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    loadQuery();\n    loadQuery({});\n    // @ts-expect-error unknown variable\n    loadQuery({ foo: \"bar\" });\n  });\n\n  it(\"is not valid when TVariables is `never`\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    // @ts-expect-error\n    loadQuery();\n    // @ts-expect-error no variables argument allowed\n    loadQuery({});\n    // @ts-expect-error no variables argument allowed\n    loadQuery({ foo: \"bar\" });\n  });\n\n  it(\"optional variables are optional to loadQuery\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    loadQuery();\n    loadQuery({});\n    loadQuery({ limit: 10 });\n    loadQuery({\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n    loadQuery({\n      limit: 10,\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n  });\n\n  it(\"enforces required variables when TVariables includes required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    // @ts-expect-error missing variables argument\n    loadQuery();\n    // @ts-expect-error empty variables\n    loadQuery({});\n    loadQuery({ id: \"1\" });\n    loadQuery({\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n    loadQuery({\n      id: \"1\",\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n  });\n\n  it(\"requires variables with mixed TVariables\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    const [loadQuery] = useLoadableQuery(query);\n\n    // @ts-expect-error missing variables argument\n    loadQuery();\n    // @ts-expect-error empty variables\n    loadQuery({});\n    loadQuery({ id: \"1\" });\n    // @ts-expect-error missing required variable\n    loadQuery({ language: \"en\" });\n    loadQuery({ id: \"1\", language: \"en\" });\n    loadQuery({\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n    loadQuery({\n      id: \"1\",\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n    loadQuery({\n      id: \"1\",\n      language: \"en\",\n      // @ts-expect-error unknown variable\n      foo: \"bar\",\n    });\n  });\n\n  it(\"returns TData in default case\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query);\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query);\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it('returns TData | undefined with errorPolicy: \"ignore\"', () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        errorPolicy: \"ignore\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { errorPolicy: \"ignore\" });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  it('returns TData | undefined with errorPolicy: \"all\"', () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        errorPolicy: \"all\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { errorPolicy: \"all\" });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  it('returns TData with errorPolicy: \"none\"', () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        errorPolicy: \"none\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { errorPolicy: \"none\" });\n\n      invariant(queryRef);\n\n      const { data } = useReadQuery(queryRef);\n\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n    }\n  });\n\n  it(\"returns DeepPartial<TData> with returnPartialData: true\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        returnPartialData: true,\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: true });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n  });\n\n  it(\"returns TData with returnPartialData: false\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        returnPartialData: false,\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: false });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"returns TData when passing an option that does not affect TData\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        fetchPolicy: \"no-cache\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { fetchPolicy: \"no-cache\" });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n    }\n  });\n\n  it(\"handles combinations of options\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: true, errorPolicy: \"ignore\" });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, { returnPartialData: true, errorPolicy: \"none\" });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n  });\n\n  it(\"returns correct TData type when combined options that do not affect TData\", () => {\n    const { query } = useVariablesQueryCase();\n\n    {\n      const [, queryRef] = useLoadableQuery(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n\n    {\n      const [, queryRef] = useLoadableQuery<\n        VariablesCaseData,\n        VariablesCaseVariables\n      >(query, {\n        fetchPolicy: \"no-cache\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n\n      invariant(queryRef);\n\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        QueryRef<\n          VariablesCaseData,\n          VariablesCaseVariables,\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >;\n      expectTypeOf(data).toEqualTypeOf<\n        | VariablesCaseData\n        | DeepPartial<VariablesCaseData>\n        | DataValue.Streaming<VariablesCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<\n          DataValue.Streaming<VariablesCaseData>\n        >();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n      }\n    }\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useMutation/context.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport React from \"react\";\nimport { delay, of } from \"rxjs\";\n\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport { ApolloProvider, useMutation } from \"@apollo/client/react\";\n\nconst echoContextLink = new ApolloLink((operation) => {\n  // filter out internal client set context values\n  const { queryDeduplication, optimisticResponse, ...context } =\n    operation.getContext();\n  return of({\n    data: { echo: { context } },\n  }).pipe(delay(20));\n});\n\ntest(\"context is provided from hook\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { context: { foo: true } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await execute();\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { echo: { context: { foo: true } } },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"context provided to execute function overrides hook context\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { context: { foo: true } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await execute({ context: { bar: true } });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: { echo: { context: { bar: true } } },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"allows context as callback called with context from hook\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { context: { foo: true } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  const contextFn = jest.fn((ctx) => ({ ...ctx, bar: true }));\n  await execute({ context: contextFn });\n\n  expect(contextFn).toHaveBeenCalledTimes(1);\n  expect(contextFn).toHaveBeenCalledWith({ foo: true });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        echo: { context: { foo: true, bar: true } },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"provides undefined to context callback if context is not provided to hook\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  const contextFn = jest.fn((ctx) => ({ ...ctx, bar: true }));\n  await execute({ context: contextFn });\n\n  expect(contextFn).toHaveBeenCalledTimes(1);\n  expect(contextFn).toHaveBeenCalledWith(undefined);\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        echo: { context: { bar: true } },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"does not merge returned context from context callback with hook\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { context: { foo: true } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  const contextFn = jest.fn(() => ({ baz: true }));\n  await execute({ context: contextFn });\n\n  expect(contextFn).toHaveBeenCalledTimes(1);\n  expect(contextFn).toHaveBeenCalledWith({ foo: true });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        echo: { context: { baz: true } },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"provides full context returned from callback to update function\", async () => {\n  const mutation = gql`\n    mutation {\n      echo {\n        context\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: echoContextLink,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const update = jest.fn();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { context: { foo: true }, update }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [execute] = getCurrentSnapshot();\n\n  await execute({ context: (ctx) => ({ ...ctx, bar: true }) });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        echo: { context: { foo: true, bar: true } },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(update).toHaveBeenCalledTimes(1);\n  expect(update).toHaveBeenCalledWith(\n    client.cache,\n    {\n      data: {\n        echo: { context: { foo: true, bar: true } },\n      },\n    },\n    { context: { foo: true, bar: true }, variables: {} }\n  );\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useMutation/defer20220824.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { gql } from \"graphql-tag\";\n\nimport { ApolloClient, CombinedGraphQLErrors } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { useMutation } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDefer20220824,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nconst CREATE_TODO_ERROR = \"Failed to create item\";\n\ntest(\"resolves a deferred mutation with the full result\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [mutate] = getCurrentSnapshot();\n\n  const promise = mutate({ variables });\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n        path: [\"createTodo\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(promise).resolves.toStrictEqualTyped({\n    data: {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    },\n  });\n\n  expect(console.error).not.toHaveBeenCalled();\n});\n\ntest(\"resolves with resulting errors and calls onError callback\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const onError = jest.fn();\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { onError }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [createTodo] = getCurrentSnapshot();\n\n  const promise = createTodo({ variables });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: null,\n        errors: [{ message: CREATE_TODO_ERROR }],\n        path: [\"createTodo\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(promise).rejects.toThrow(\n    new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] })\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: { createTodo: { __typename: \"Todo\", id: 1 } },\n        errors: [{ message: CREATE_TODO_ERROR }],\n      }),\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(onError).toHaveBeenCalledTimes(1);\n  expect(onError).toHaveBeenLastCalledWith(\n    new CombinedGraphQLErrors({\n      data: { createTodo: { __typename: \"Todo\", id: 1 } },\n      errors: [{ message: CREATE_TODO_ERROR }],\n    }),\n    expect.anything()\n  );\n  expect(console.error).not.toHaveBeenCalled();\n});\n\ntest(\"calls the update function with the final merged result data\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n  const update = jest.fn();\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation<any>(mutation, { update }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [createTodo] = getCurrentSnapshot();\n\n  const promiseReturnedByMutate = createTodo({ variables });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n        path: [\"createTodo\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(promiseReturnedByMutate).resolves.toStrictEqualTyped({\n    data: {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(update).toHaveBeenCalledTimes(1);\n  expect(update).toHaveBeenCalledWith(\n    // the first item is the cache, which we don't need to make any\n    // assertions against in this test\n    expect.anything(),\n    // second argument is the result\n    expect.objectContaining({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n    }),\n    // third argument is an object containing context and variables\n    // but we only care about variables here\n    expect.objectContaining({ variables })\n  );\n\n  expect(console.error).not.toHaveBeenCalled();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useMutation/deferGraphQL17Alpha9.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { gql } from \"graphql-tag\";\n\nimport { ApolloClient, CombinedGraphQLErrors } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { useMutation } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  mockDeferStreamGraphQL17Alpha9,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nconst CREATE_TODO_ERROR = \"Failed to create item\";\n\ntest(\"resolves a deferred mutation with the full result\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [mutate] = getCurrentSnapshot();\n\n  const promise = mutate({ variables });\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"createTodo\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const [, mutation] = await takeSnapshot();\n\n    expect(mutation).toStrictEqualTyped({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(promise).resolves.toStrictEqualTyped({\n    data: {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    },\n  });\n\n  expect(console.error).not.toHaveBeenCalled();\n});\n\ntest(\"resolves with resulting errors and calls onError callback\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const onError = jest.fn();\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation(mutation, { onError }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [createTodo] = getCurrentSnapshot();\n\n  const promise = createTodo({ variables });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"createTodo\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    completed: [{ id: \"0\", errors: [{ message: CREATE_TODO_ERROR }] }],\n    hasNext: false,\n  });\n\n  await expect(promise).rejects.toThrow(\n    new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] })\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: { createTodo: { __typename: \"Todo\", id: 1 } },\n        errors: [{ message: CREATE_TODO_ERROR }],\n      }),\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(onError).toHaveBeenCalledTimes(1);\n  expect(onError).toHaveBeenLastCalledWith(\n    new CombinedGraphQLErrors({\n      data: { createTodo: { __typename: \"Todo\", id: 1 } },\n      errors: [{ message: CREATE_TODO_ERROR }],\n    }),\n    expect.anything()\n  );\n  expect(console.error).not.toHaveBeenCalled();\n});\n\ntest(\"calls the update function with the final merged result data\", async () => {\n  using _ = spyOnConsole(\"error\");\n  const mutation = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        ... @defer {\n          description\n          priority\n        }\n      }\n    }\n  `;\n  const variables = {\n    description: \"Get milk!\",\n  };\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n  const update = jest.fn();\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, getCurrentSnapshot } = await renderHookToSnapshotStream(\n    () => useMutation<any>(mutation, { update }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n      called: false,\n    });\n  }\n\n  const [createTodo] = getCurrentSnapshot();\n\n  const promiseReturnedByMutate = createTodo({ variables });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n      called: true,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: {\n      createTodo: {\n        id: 1,\n        __typename: \"Todo\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"createTodo\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(promiseReturnedByMutate).resolves.toStrictEqualTyped({\n    data: {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    },\n  });\n\n  {\n    const [, result] = await takeSnapshot();\n\n    expect(result).toStrictEqualTyped({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n      error: undefined,\n      loading: false,\n      called: true,\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(update).toHaveBeenCalledTimes(1);\n  expect(update).toHaveBeenCalledWith(\n    // the first item is the cache, which we don't need to make any\n    // assertions against in this test\n    expect.anything(),\n    // second argument is the result\n    expect.objectContaining({\n      data: {\n        createTodo: {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      },\n    }),\n    // third argument is an object containing context and variables\n    // but we only care about variables here\n    expect.objectContaining({ variables })\n  );\n\n  expect(console.error).not.toHaveBeenCalled();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useMutation.test.tsx",
    "content": "import {\n  act,\n  render,\n  renderHook,\n  screen,\n  waitFor,\n} from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport fetchMock from \"fetch-mock\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport React, { useEffect } from \"react\";\nimport { Observable } from \"rxjs\";\n\nimport type { Cache, ObservableQuery, TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { BatchHttpLink } from \"@apollo/client/link/batch-http\";\nimport { ApolloProvider, useMutation, useQuery } from \"@apollo/client/react\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport { spyOnConsole, wait } from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nconst IS_REACT_17 = React.version.startsWith(\"17\");\nconst IS_REACT_18 = React.version.startsWith(\"18\");\nconst IS_REACT_19 = React.version.startsWith(\"19\");\n\ndescribe(\"useMutation Hook\", () => {\n  interface Todo {\n    id: number;\n    description: string;\n    priority: string;\n  }\n\n  const CREATE_TODO_MUTATION = gql`\n    mutation createTodo($description: String!, $priority: String) {\n      createTodo(description: $description, priority: $priority) {\n        id\n        description\n        priority\n      }\n    }\n  `;\n\n  const CREATE_TODO_RESULT = {\n    createTodo: {\n      id: 1,\n      description: \"Get milk!\",\n      priority: \"High\",\n      __typename: \"Todo\",\n    },\n  };\n\n  const CREATE_TODO_ERROR = \"Failed to create item\";\n\n  it(\"should handle a simple mutation properly\", async () => {\n    const variables = {\n      description: \"Get milk!\",\n    };\n\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables,\n        },\n        result: { data: CREATE_TODO_RESULT },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useMutation(CREATE_TODO_MUTATION),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [createTodo] = getCurrentSnapshot();\n\n    await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_RESULT,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        // TODO: Remove error field when there is no error\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: CREATE_TODO_RESULT,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should be able to call mutations as an effect\", async () => {\n    const variables = {\n      description: \"Get milk!\",\n    };\n\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables,\n        },\n        result: { data: CREATE_TODO_RESULT },\n        delay: 20,\n      },\n    ];\n\n    const useCreateTodo = () => {\n      const [createTodo, { loading, data }] = useMutation(CREATE_TODO_MUTATION);\n      useEffect(() => {\n        void createTodo({ variables });\n      }, [variables]);\n\n      return { loading, data };\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useCreateTodo(),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      loading: true,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_RESULT,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should ensure the mutation callback function has a stable identity no matter what\", async () => {\n    const variables1 = {\n      description: \"Get milk\",\n    };\n\n    const data1 = {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    };\n\n    const variables2 = {\n      description: \"Write blog post\",\n    };\n\n    const data2 = {\n      createTodo: {\n        id: 1,\n        description: \"Write blog post\",\n        priority: \"High\",\n        __typename: \"Todo\",\n      },\n    };\n\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables: variables1,\n        },\n        result: { data: data1 },\n        delay: 20,\n      },\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables: variables2,\n        },\n        result: { data: data2 },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        ({ variables }) => useMutation(CREATE_TODO_MUTATION, { variables }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n          initialProps: {\n            variables: variables1,\n          },\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [createTodo] = getCurrentSnapshot();\n\n    await expect(createTodo()).resolves.toStrictEqualTyped({\n      data: data1,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    expect(getCurrentSnapshot()[0]).toBe(createTodo);\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data1,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    expect(getCurrentSnapshot()[0]).toBe(createTodo);\n\n    await rerender({ variables: variables2 });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data1,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    expect(getCurrentSnapshot()[0]).toBe(createTodo);\n\n    await expect(createTodo()).resolves.toStrictEqualTyped({\n      data: data2,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    expect(getCurrentSnapshot()[0]).toBe(createTodo);\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: data2,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    expect(getCurrentSnapshot()[0]).toBe(createTodo);\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should not call setResult on an unmounted component\", async () => {\n    using consoleSpies = spyOnConsole(\"error\");\n    const variables = {\n      description: \"Get milk!\",\n    };\n\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables,\n        },\n        result: { data: CREATE_TODO_RESULT },\n      },\n    ];\n\n    const useCreateTodo = () => {\n      const [createTodo, { reset }] = useMutation(CREATE_TODO_MUTATION);\n      return { reset, createTodo };\n    };\n\n    const { result, unmount } = renderHook(() => useCreateTodo(), {\n      wrapper: ({ children }) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      ),\n    });\n\n    unmount();\n\n    await act(async () => {\n      await result.current.createTodo({ variables });\n      result.current.reset();\n    });\n\n    expect(consoleSpies.error).not.toHaveBeenCalled();\n  });\n\n  describe(\"mutate function upon error\", () => {\n    it(\"resolves with the resulting data and errors\", async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      const onError = jest.fn();\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { onError }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).rejects.toThrow(\n        new CombinedGraphQLErrors({\n          data: CREATE_TODO_RESULT,\n          errors: [{ message: CREATE_TODO_ERROR }],\n        })\n      );\n\n      expect(onError).toHaveBeenCalledTimes(1);\n      expect(onError).toHaveBeenLastCalledWith(\n        new CombinedGraphQLErrors({\n          data: CREATE_TODO_RESULT,\n          errors: [{ message: CREATE_TODO_ERROR }],\n        }),\n        expect.anything()\n      );\n    });\n\n    it(\"should reject when there’s an error and no error policy is set\", async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] })\n      );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: CREATE_TODO_ERROR }],\n          }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"does not cause unhandled rejections\", async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 10,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { variables }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      await takeSnapshot();\n\n      const [createTodo] = getCurrentSnapshot();\n\n      // Intentionally don't await this to ensure we don't get unhandled rejections\n      createTodo();\n      await wait(15);\n\n      // No assertions needed. This test fails if the promise throws an\n      // unhandled rection\n    });\n\n    it(`should reject when errorPolicy is 'none'`, async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { errorPolicy: \"none\" }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] })\n      );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: new CombinedGraphQLErrors({\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(`should resolve with 'data' and 'error' properties when errorPolicy is 'all'`, async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { errorPolicy: \"all\" }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_RESULT,\n        error: new CombinedGraphQLErrors({\n          data: CREATE_TODO_RESULT,\n          errors: [{ message: CREATE_TODO_ERROR }],\n        }),\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: new CombinedGraphQLErrors({\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(`should call onError when errorPolicy is 'all'`, async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      const onError = jest.fn();\n      const onCompleted = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation(CREATE_TODO_MUTATION, {\n              errorPolicy: \"all\",\n              onError,\n              onCompleted,\n            }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_RESULT,\n        error: new CombinedGraphQLErrors({\n          data: CREATE_TODO_RESULT,\n          errors: [{ message: CREATE_TODO_ERROR }],\n        }),\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: new CombinedGraphQLErrors({\n            data: CREATE_TODO_RESULT,\n            errors: [{ message: CREATE_TODO_ERROR }],\n          }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      expect(onError).toHaveBeenCalledTimes(1);\n      expect(onError).toHaveBeenLastCalledWith(\n        new CombinedGraphQLErrors({\n          data: CREATE_TODO_RESULT,\n          errors: [{ message: CREATE_TODO_ERROR }],\n        }),\n        expect.anything()\n      );\n      expect(onCompleted).not.toHaveBeenCalled();\n    });\n\n    it(`should ignore errors when errorPolicy is 'ignore'`, async () => {\n      using consoleSpy = spyOnConsole(\"error\");\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { errorPolicy: \"ignore\" }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: undefined,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(consoleSpy.error).toHaveBeenCalledTimes(1);\n      expect(consoleSpy.error.mock.calls[0][0]).toMatch(\"Missing field\");\n    });\n\n    it(`should not call onError when errorPolicy is 'ignore'`, async () => {\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      const onError = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation(CREATE_TODO_MUTATION, {\n              errorPolicy: \"ignore\",\n              onError,\n            }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: undefined,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      expect(onError).not.toHaveBeenCalled();\n    });\n  });\n\n  it(\"should return the current client instance in the result object\", async () => {\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const { result } = renderHook(() => useMutation(CREATE_TODO_MUTATION), {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n    expect(result.current[1].client).toBe(client);\n  });\n\n  it(\"should call client passed to execute function\", async () => {\n    using _disabledAct = disableActEnvironment();\n\n    const defaultClient = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query: CREATE_TODO_MUTATION },\n          result: { errors: [{ message: \"Oops wrong client\" }] },\n          delay: 20,\n        },\n      ]),\n    });\n\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useMutation(CREATE_TODO_MUTATION),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={defaultClient}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink([\n        {\n          request: { query: CREATE_TODO_MUTATION },\n          result: { data: CREATE_TODO_RESULT },\n          delay: 20,\n        },\n      ]),\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [createTodo] = getCurrentSnapshot();\n\n    await expect(createTodo({ client })).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_RESULT,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: CREATE_TODO_RESULT,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  // TODO: Do we want to keep this variable merge behavior?\n  it(\"should merge provided variables\", async () => {\n    const CREATE_TODO_DATA = {\n      createTodo: {\n        id: 1,\n        description: \"Get milk!\",\n        priority: \"Low\",\n        __typename: \"Todo\",\n      },\n    };\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables: {\n            priority: \"Low\",\n            description: \"Get milk.\",\n          },\n        },\n        result: {\n          data: CREATE_TODO_DATA,\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useMutation<\n            { createTodo: Todo },\n            { priority?: string; description?: string }\n          >(CREATE_TODO_MUTATION, {\n            variables: { priority: \"Low\" },\n          }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [createTodo] = getCurrentSnapshot();\n\n    await expect(\n      createTodo({ variables: { description: \"Get milk.\" } })\n    ).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_DATA,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: CREATE_TODO_DATA,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should be possible to reset the mutation\", async () => {\n    const CREATE_TODO_DATA = {\n      createTodo: {\n        id: 1,\n        priority: \"Low\",\n        description: \"Get milk!\",\n        __typename: \"Todo\",\n      },\n    };\n\n    const mocks = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables: {\n            priority: \"Low\",\n            description: \"Get milk.\",\n          },\n        },\n        result: {\n          data: CREATE_TODO_DATA,\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () =>\n          useMutation<\n            { createTodo: Todo },\n            { priority: string; description: string }\n          >(CREATE_TODO_MUTATION),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [createTodo] = getCurrentSnapshot();\n\n    await expect(\n      createTodo({ variables: { priority: \"Low\", description: \"Get milk.\" } })\n    ).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_DATA,\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: CREATE_TODO_DATA,\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    getCurrentSnapshot()[1].reset();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"resetting while a mutation is running: ensure that the result doesn't end up in the hook\", async () => {\n    const CREATE_TODO_DATA = {\n      createTodo: {\n        id: 1,\n        priority: \"Low\",\n        description: \"Get milk!\",\n        __typename: \"Todo\",\n      },\n    };\n\n    const mocks: MockLink.MockedResponse[] = [\n      {\n        request: {\n          query: CREATE_TODO_MUTATION,\n          variables: {\n            priority: \"Low\",\n            description: \"Get milk.\",\n          },\n        },\n        result: {\n          data: CREATE_TODO_DATA,\n        },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useMutation<\n          { createTodo: Todo },\n          { priority: string; description: string }\n        >(CREATE_TODO_MUTATION),\n      {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    let createTodo: Awaited<ReturnType<typeof takeSnapshot>>[0];\n    let reset: Awaited<ReturnType<typeof takeSnapshot>>[1][\"reset\"];\n\n    {\n      const [mutate, result] = await takeSnapshot();\n      createTodo = mutate;\n      reset = result.reset;\n      //initial value\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const fetchResult = createTodo({\n      variables: { priority: \"Low\", description: \"Get milk.\" },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      // started loading\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    reset();\n\n    {\n      const [, result] = await takeSnapshot();\n\n      // reset to initial value\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    await expect(fetchResult).resolves.toStrictEqualTyped({\n      data: CREATE_TODO_DATA,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  describe(\"Callbacks\", () => {\n    it(\"should allow passing an onCompleted handler to the execution function\", async () => {\n      const CREATE_TODO_DATA = {\n        createTodo: {\n          id: 1,\n          priority: \"Low\",\n          description: \"Get milk!\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk.\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_DATA,\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation<\n              { createTodo: Todo },\n              { priority: string; description: string }\n            >(CREATE_TODO_MUTATION),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      const onCompleted = jest.fn();\n      const onError = jest.fn();\n      await expect(\n        createTodo({ variables, onCompleted, onError })\n      ).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_DATA,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_DATA,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(onCompleted).toHaveBeenCalledTimes(1);\n      expect(onCompleted).toHaveBeenCalledWith(\n        CREATE_TODO_DATA,\n        expect.objectContaining({ variables })\n      );\n      expect(onError).toHaveBeenCalledTimes(0);\n    });\n\n    it(\"prefers the onCompleted handler passed to the execution function rather than the hook\", async () => {\n      const CREATE_TODO_DATA = {\n        createTodo: {\n          id: 1,\n          priority: \"Low\",\n          description: \"Get milk!\",\n          __typename: \"Todo\",\n        },\n      };\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk.\",\n      };\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_DATA,\n          },\n          delay: 20,\n        },\n      ];\n\n      const hookOnCompleted = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation(CREATE_TODO_MUTATION, { onCompleted: hookOnCompleted }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n      const onCompleted = jest.fn();\n\n      await expect(\n        createTodo({ variables, onCompleted })\n      ).resolves.toStrictEqualTyped({ data: CREATE_TODO_DATA });\n\n      expect(onCompleted).toHaveBeenCalledTimes(1);\n      expect(hookOnCompleted).not.toHaveBeenCalled();\n    });\n\n    it(\"should allow passing an onError handler to the execution function\", async () => {\n      const errors = [new GraphQLError(CREATE_TODO_ERROR)];\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk.\",\n      };\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors,\n          },\n          delay: 20,\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation<\n              { createTodo: Todo },\n              { priority: string; description: string }\n            >(CREATE_TODO_MUTATION),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      const onCompleted = jest.fn();\n      const onError = jest.fn();\n\n      await expect(\n        createTodo({ variables, onCompleted, onError })\n      ).rejects.toThrow(new CombinedGraphQLErrors({ errors }));\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: new CombinedGraphQLErrors({ errors }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(onCompleted).toHaveBeenCalledTimes(0);\n      expect(onError).toHaveBeenCalledTimes(1);\n      expect(onError).toHaveBeenCalledWith(\n        new CombinedGraphQLErrors({ errors }),\n        expect.objectContaining({ variables })\n      );\n    });\n\n    it(\"prefers the onError handler passed to the execution function instead of the hook\", async () => {\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk.\",\n      };\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors: [{ message: CREATE_TODO_ERROR }],\n          },\n          delay: 20,\n        },\n      ];\n\n      const hookOnError = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { onError: hookOnError }),\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n      const onError = jest.fn();\n      await expect(createTodo({ variables, onError })).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] })\n      );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: CREATE_TODO_ERROR }],\n          }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      expect(onError).toHaveBeenCalledTimes(1);\n      expect(onError).toHaveBeenCalledWith(\n        new CombinedGraphQLErrors({ errors: [{ message: CREATE_TODO_ERROR }] }),\n        expect.objectContaining({ variables })\n      );\n      expect(hookOnError).not.toHaveBeenCalled();\n    });\n\n    it(\"should allow updating onError while mutation is executing\", async () => {\n      const errors = [{ message: CREATE_TODO_ERROR }];\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk.\",\n      };\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            errors,\n          },\n          delay: 20,\n        },\n      ];\n\n      const onCompleted = jest.fn();\n      const onError = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ onCompleted, onError }) => {\n            return useMutation<\n              { createTodo: Todo },\n              { priority: string; description: string }\n            >(CREATE_TODO_MUTATION, { onCompleted, onError });\n          },\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n            initialProps: { onCompleted, onError },\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      const onError1 = jest.fn();\n      await rerender({ onCompleted, onError: onError1 });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      await expect(createTodo({ variables })).rejects.toThrow(\n        new CombinedGraphQLErrors({ errors })\n      );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: new CombinedGraphQLErrors({ errors }),\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(onCompleted).toHaveBeenCalledTimes(0);\n      expect(onError).toHaveBeenCalledTimes(0);\n      expect(onError1).toHaveBeenCalledTimes(1);\n      expect(onError1).toHaveBeenCalledWith(\n        new CombinedGraphQLErrors({ errors }),\n        expect.objectContaining({ variables })\n      );\n    });\n\n    it(\"should never allow onCompleted handler to be stale\", async () => {\n      const CREATE_TODO_DATA = {\n        createTodo: {\n          id: 1,\n          priority: \"Low\",\n          description: \"Get milk!\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk2.\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_DATA,\n          },\n          delay: 20,\n        },\n      ];\n\n      const onCompleted = jest.fn();\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ onCompleted }) => {\n            return useMutation<\n              { createTodo: Todo },\n              { priority: string; description: string }\n            >(CREATE_TODO_MUTATION, { onCompleted });\n          },\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n            initialProps: { onCompleted },\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const onCompleted1 = jest.fn();\n      await rerender({ onCompleted: onCompleted1 });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_DATA,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_DATA,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(onCompleted).toHaveBeenCalledTimes(0);\n      expect(onCompleted1).toHaveBeenCalledTimes(1);\n      expect(onCompleted1).toHaveBeenCalledWith(\n        CREATE_TODO_DATA,\n        expect.objectContaining({ variables })\n      );\n    });\n\n    it(\"should allow updating onCompleted while mutation is executing\", async () => {\n      const CREATE_TODO_DATA = {\n        createTodo: {\n          id: 1,\n          priority: \"Low\",\n          description: \"Get milk!\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk2.\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_DATA,\n          },\n          delay: 20,\n        },\n      ];\n\n      const onCompleted = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ onCompleted }) => {\n            return useMutation<\n              { createTodo: Todo },\n              { priority: string; description: string }\n            >(CREATE_TODO_MUTATION, { onCompleted });\n          },\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n            initialProps: { onCompleted },\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      const onCompleted1 = jest.fn();\n      await rerender({ onCompleted: onCompleted1 });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      await expect(createTodo({ variables })).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_DATA,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_DATA,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(onCompleted).toHaveBeenCalledTimes(0);\n      expect(onCompleted1).toHaveBeenCalledTimes(1);\n      expect(onCompleted1).toHaveBeenCalledWith(\n        CREATE_TODO_DATA,\n        expect.objectContaining({ variables })\n      );\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/12008\n    it(\"does not call onError if errors are thrown in the onCompleted callback\", async () => {\n      const CREATE_TODO_DATA = {\n        createTodo: {\n          id: 1,\n          priority: \"Low\",\n          description: \"Get milk!\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        priority: \"Low\",\n        description: \"Get milk2.\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_DATA,\n          },\n        },\n      ];\n\n      const onError = jest.fn();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () =>\n          useMutation(CREATE_TODO_MUTATION, {\n            onCompleted: () => {\n              throw new Error(\"Oops\");\n            },\n            onError,\n          }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n      const [createTodo] = await takeSnapshot();\n\n      await expect(createTodo({ variables })).rejects.toEqual(\n        new Error(\"Oops\")\n      );\n\n      expect(onError).not.toHaveBeenCalled();\n    });\n  });\n\n  describe(\"ROOT_MUTATION cache data\", () => {\n    const startTime = Date.now();\n    const link = new ApolloLink(\n      (operation) =>\n        new Observable((observer) => {\n          setTimeout(() => {\n            observer.next({\n              data: {\n                __typename: \"Mutation\",\n                doSomething: {\n                  __typename: \"MutationPayload\",\n                  time: startTime,\n                },\n              },\n            });\n            observer.complete();\n          }, 20);\n        })\n    );\n\n    const mutation: TypedDocumentNode<any> = gql`\n      mutation DoSomething {\n        doSomething {\n          time\n        }\n      }\n    `;\n\n    it(\"should be removed by default after the mutation\", async () => {\n      let timeReadCount = 0;\n      let timeMergeCount = 0;\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            MutationPayload: {\n              fields: {\n                time: {\n                  read(ms: number = Date.now()) {\n                    ++timeReadCount;\n                    return new Date(ms);\n                  },\n                  merge(existing, incoming: number) {\n                    ++timeMergeCount;\n                    expect(existing).toBeUndefined();\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useMutation(mutation), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [mutate] = getCurrentSnapshot();\n\n      await expect(\n        mutate({\n          update(cache, { data }) {\n            expect(data).toStrictEqualTyped({\n              doSomething: {\n                __typename: \"MutationPayload\",\n                time: new Date(startTime),\n              },\n            });\n\n            expect(timeReadCount).toBe(1);\n            expect(timeMergeCount).toBe(1);\n            // The contents of the ROOT_MUTATION object exist only briefly,\n            // for the duration of the mutation update, and are removed\n            // after the mutation write is finished.\n            expect(cache.extract()).toEqual({\n              ROOT_MUTATION: {\n                __typename: \"Mutation\",\n                doSomething: {\n                  __typename: \"MutationPayload\",\n                  time: startTime,\n                },\n              },\n            });\n          },\n        })\n      ).resolves.toStrictEqualTyped({\n        data: {\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: new Date(startTime),\n          },\n        },\n      });\n\n      expect(timeReadCount).toBe(1);\n      expect(timeMergeCount).toBe(1);\n      // The contents of the ROOT_MUTATION object exist only briefly,\n      // for the duration of the mutation update, and are removed after\n      // the mutation write is finished.\n      expect(client.cache.extract()).toEqual({\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            doSomething: {\n              __typename: \"MutationPayload\",\n              time: new Date(startTime),\n            },\n          },\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"can be preserved by passing keepRootFields: true\", async () => {\n      let timeReadCount = 0;\n      let timeMergeCount = 0;\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            MutationPayload: {\n              fields: {\n                time: {\n                  read(ms: number = Date.now()) {\n                    ++timeReadCount;\n                    return new Date(ms);\n                  },\n                  merge(existing, incoming: number) {\n                    ++timeMergeCount;\n                    expect(existing).toBeUndefined();\n                    return incoming;\n                  },\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useMutation(mutation, {\n              keepRootFields: true,\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [mutate] = getCurrentSnapshot();\n\n      await expect(\n        mutate({\n          update(cache, { data }) {\n            expect(data).toStrictEqualTyped({\n              doSomething: {\n                __typename: \"MutationPayload\",\n                time: new Date(startTime),\n              },\n            });\n            expect(timeReadCount).toBe(1);\n            expect(timeMergeCount).toBe(1);\n            expect(cache.extract()).toEqual({\n              ROOT_MUTATION: {\n                __typename: \"Mutation\",\n                doSomething: {\n                  __typename: \"MutationPayload\",\n                  time: startTime,\n                },\n              },\n            });\n          },\n        })\n      ).resolves.toStrictEqualTyped({\n        data: {\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: new Date(startTime),\n          },\n        },\n      });\n\n      expect(timeReadCount).toBe(1);\n      expect(timeMergeCount).toBe(1);\n      expect(client.cache.extract()).toEqual({\n        ROOT_MUTATION: {\n          __typename: \"Mutation\",\n          doSomething: {\n            __typename: \"MutationPayload\",\n            time: startTime,\n          },\n        },\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            doSomething: {\n              __typename: \"MutationPayload\",\n              time: new Date(startTime),\n            },\n          },\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"Update function\", () => {\n    it(\"should be called with the provided variables\", async () => {\n      const variables = { description: \"Get milk!\" };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: { data: CREATE_TODO_RESULT },\n        },\n      ];\n\n      let variablesMatched = false;\n      const Component = () => {\n        const [createTodo] = useMutation(CREATE_TODO_MUTATION, {\n          update(_, __, options) {\n            expect(options.variables).toEqual(variables);\n            variablesMatched = true;\n          },\n        });\n\n        useEffect(() => {\n          void createTodo({ variables });\n        }, []);\n\n        return null;\n      };\n\n      render(\n        <MockedProvider mocks={mocks}>\n          <Component />\n        </MockedProvider>\n      );\n\n      await waitFor(() => expect(variablesMatched).toBe(true));\n    });\n\n    it(\"should be called with the provided context\", async () => {\n      const context = { id: 3 };\n\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: { data: CREATE_TODO_RESULT },\n        },\n      ];\n\n      let foundContext = false;\n      const Component = () => {\n        const [createTodo] = useMutation<Todo, { description: string }>(\n          CREATE_TODO_MUTATION,\n          {\n            context,\n            update(_, __, options) {\n              expect(options.context).toEqual(context);\n              foundContext = true;\n            },\n          }\n        );\n\n        useEffect(() => {\n          void createTodo({ variables });\n        }, []);\n\n        return null;\n      };\n\n      render(\n        <MockedProvider mocks={mocks}>\n          <Component />\n        </MockedProvider>\n      );\n\n      await waitFor(() => {\n        expect(foundContext).toBe(true);\n      });\n    });\n\n    describe(\"If context is not provided\", () => {\n      it(\"should be undefined\", async () => {\n        const variables = {\n          description: \"Get milk!\",\n        };\n\n        const mocks = [\n          {\n            request: {\n              query: CREATE_TODO_MUTATION,\n              variables,\n            },\n            result: { data: CREATE_TODO_RESULT },\n          },\n        ];\n\n        let checkedContext = false;\n        const Component = () => {\n          const [createTodo] = useMutation(CREATE_TODO_MUTATION, {\n            update(_, __, options) {\n              expect(options.context).toBeUndefined();\n              checkedContext = true;\n            },\n          });\n\n          useEffect(() => {\n            void createTodo({ variables });\n          }, []);\n\n          return null;\n        };\n\n        render(\n          <MockedProvider mocks={mocks}>\n            <Component />\n          </MockedProvider>\n        );\n\n        await waitFor(() => {\n          expect(checkedContext).toBe(true);\n        });\n      });\n    });\n  });\n\n  describe(\"Optimistic response\", () => {\n    it(\"should support optimistic response handling\", async () => {\n      const optimisticResponse = {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: 1,\n          description: \"TEMPORARY\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: { data: CREATE_TODO_RESULT },\n          delay: 20,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({ cache, link: new MockLink(mocks) });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useMutation(CREATE_TODO_MUTATION, { optimisticResponse }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const [createTodo] = getCurrentSnapshot();\n\n      const promise = createTodo({ variables });\n\n      expect(cache.extract(true)[\"Todo:1\"]).toEqual(\n        optimisticResponse.createTodo\n      );\n\n      await expect(promise).resolves.toStrictEqualTyped({\n        data: CREATE_TODO_RESULT,\n      });\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const [, result] = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should be called with the provided context\", async () => {\n      const optimisticResponse = {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: 1,\n          description: \"TEMPORARY\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const context = { id: 3 };\n\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const mocks = [\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: { data: CREATE_TODO_RESULT },\n        },\n      ];\n\n      const contextFn = jest.fn();\n\n      const Component = () => {\n        const [createTodo] = useMutation(CREATE_TODO_MUTATION, {\n          optimisticResponse,\n          context,\n          update(_, __, options) {\n            contextFn(options.context);\n          },\n        });\n\n        useEffect(() => {\n          void createTodo({ variables });\n        }, []);\n\n        return null;\n      };\n\n      render(\n        <MockedProvider mocks={mocks}>\n          <Component />\n        </MockedProvider>\n      );\n\n      await waitFor(() => {\n        expect(contextFn).toHaveBeenCalledTimes(2);\n      });\n      expect(contextFn).toHaveBeenCalledWith(context);\n    });\n  });\n\n  describe(\"refetching queries\", () => {\n    const GET_TODOS_QUERY = gql`\n      query getTodos {\n        todos {\n          id\n          description\n          priority\n        }\n      }\n    `;\n\n    const GET_TODOS_RESULT_1 = {\n      todos: [\n        {\n          id: 2,\n          description: \"Walk the dog\",\n          priority: \"Medium\",\n          __typename: \"Todo\",\n        },\n        {\n          id: 3,\n          description: \"Call mom\",\n          priority: \"Low\",\n          __typename: \"Todo\",\n        },\n      ],\n    };\n\n    const GET_TODOS_RESULT_2 = {\n      todos: [\n        {\n          id: 1,\n          description: \"Get milk!\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n        {\n          id: 2,\n          description: \"Walk the dog\",\n          priority: \"Medium\",\n          __typename: \"Todo\",\n        },\n        {\n          id: 3,\n          description: \"Call mom\",\n          priority: \"Low\",\n          __typename: \"Todo\",\n        },\n      ],\n    };\n\n    it(\"can pass onQueryUpdated to useMutation\", async () => {\n      interface TData {\n        todoCount: number;\n      }\n      const countQuery: TypedDocumentNode<TData> = gql`\n        query Count {\n          todoCount @client\n        }\n      `;\n\n      const optimisticResponse = {\n        __typename: \"Mutation\",\n        createTodo: {\n          id: 1,\n          description: \"TEMPORARY\",\n          priority: \"High\",\n          __typename: \"Todo\",\n        },\n      };\n\n      const variables = {\n        description: \"Get milk!\",\n      };\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                todoCount(count = 0) {\n                  return count;\n                },\n              },\n            },\n          },\n        }),\n\n        link: new MockLink([\n          {\n            request: {\n              query: CREATE_TODO_MUTATION,\n              variables,\n            },\n            result: { data: CREATE_TODO_RESULT },\n            delay: 20,\n          },\n        ]),\n      });\n\n      // The goal of this test is to make sure onQueryUpdated gets called as\n      // part of the createTodo mutation, so we use this reobservePromise to\n      // await the calling of onQueryUpdated.\n      interface OnQueryUpdatedResults {\n        obsQuery: ObservableQuery;\n        diff: Cache.DiffResult<TData>;\n        result: ApolloClient.QueryResult<TData>;\n      }\n      let resolveOnUpdate: (results: OnQueryUpdatedResults) => any;\n      const onUpdatePromise = new Promise<OnQueryUpdatedResults>((resolve) => {\n        resolveOnUpdate = resolve;\n      }).then((onUpdateResult) => {\n        expect(onUpdateResult.diff).toEqual({\n          complete: true,\n          result: {\n            todoCount: 1,\n          },\n        });\n        expect(onUpdateResult.result).toStrictEqualTyped({\n          data: { todoCount: 1 },\n        });\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => ({\n            query: useQuery(countQuery),\n            mutation: useMutation(CREATE_TODO_MUTATION, {\n              optimisticResponse,\n              update(cache) {\n                const result = cache.readQuery({ query: countQuery });\n\n                cache.writeQuery({\n                  query: countQuery,\n                  data: {\n                    todoCount: (result ? result.todoCount : 0) + 1,\n                  },\n                });\n              },\n            }),\n          }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: { todoCount: 0 },\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          loading: false,\n          previousData: undefined,\n          variables: {},\n        });\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const {\n        mutation: [createTodo],\n      } = getCurrentSnapshot();\n\n      await expect(\n        createTodo({\n          variables,\n          async onQueryUpdated(obsQuery, diff) {\n            const result = await obsQuery.reobserve();\n            resolveOnUpdate({ obsQuery, diff, result });\n            return result;\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: CREATE_TODO_RESULT });\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        if (IS_REACT_17) {\n          expect(query).toStrictEqualTyped({\n            data: { todoCount: 0 },\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            loading: false,\n            previousData: undefined,\n            variables: {},\n          });\n\n          expect(mutation).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n            called: true,\n          });\n        } else {\n          expect(query).toStrictEqualTyped({\n            data: { todoCount: 1 },\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            loading: false,\n            previousData: { todoCount: 0 },\n            variables: {},\n          });\n        }\n\n        if (IS_REACT_18) {\n          expect(mutation).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: false,\n            called: false,\n          });\n        } else {\n          expect(mutation).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n            called: true,\n          });\n        }\n      }\n\n      if (IS_REACT_19) {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: { todoCount: 1 },\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          loading: false,\n          previousData: { todoCount: 0 },\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      } else {\n        {\n          const {\n            query,\n            mutation: [, mutation],\n          } = await takeSnapshot();\n\n          expect(query).toStrictEqualTyped({\n            data: { todoCount: 1 },\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            loading: false,\n            previousData: { todoCount: 0 },\n            variables: {},\n          });\n\n          expect(mutation).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n            called: true,\n          });\n        }\n\n        {\n          const {\n            query,\n            mutation: [, mutation],\n          } = await takeSnapshot();\n\n          expect(query).toStrictEqualTyped({\n            data: { todoCount: 1 },\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            loading: false,\n            previousData: { todoCount: 0 },\n            variables: {},\n          });\n\n          expect(mutation).toStrictEqualTyped({\n            data: CREATE_TODO_RESULT,\n            error: undefined,\n            loading: false,\n            called: true,\n          });\n        }\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n      await expect(onUpdatePromise).resolves.toBe(undefined);\n    });\n\n    it(\"refetchQueries with operation names should update cache\", async () => {\n      const variables = { description: \"Get milk!\" };\n      const mocks = [\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_1 },\n          delay: 20,\n        },\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n          },\n          delay: 20,\n        },\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_2 },\n          delay: 20,\n        },\n      ];\n\n      const link = new MockLink(mocks);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => ({\n            query: useQuery(GET_TODOS_QUERY),\n            mutation: useMutation(CREATE_TODO_MUTATION),\n          }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const {\n        mutation: [mutate],\n      } = getCurrentSnapshot();\n\n      await expect(\n        mutate({\n          variables,\n          refetchQueries: [\"getTodos\"],\n        })\n      ).resolves.toStrictEqualTyped({ data: CREATE_TODO_RESULT });\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_2,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: GET_TODOS_RESULT_1,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(client.readQuery({ query: GET_TODOS_QUERY })).toEqual(\n        mocks[2].result.data\n      );\n    });\n\n    it(\"refetchQueries with document nodes should update cache\", async () => {\n      const variables = { description: \"Get milk!\" };\n      const mocks = [\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_1 },\n          delay: 20,\n        },\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n          },\n          delay: 20,\n        },\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_2 },\n          delay: 20,\n        },\n      ];\n\n      const link = new MockLink(mocks);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => ({\n            query: useQuery(GET_TODOS_QUERY),\n            mutation: useMutation(CREATE_TODO_MUTATION),\n          }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const {\n        mutation: [mutate],\n      } = getCurrentSnapshot();\n\n      await expect(\n        mutate({\n          variables,\n          refetchQueries: [GET_TODOS_QUERY],\n        })\n      ).resolves.toStrictEqualTyped({ data: CREATE_TODO_RESULT });\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_2,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: GET_TODOS_RESULT_1,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: CREATE_TODO_RESULT,\n          error: undefined,\n          loading: false,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(client.readQuery({ query: GET_TODOS_QUERY })).toEqual(\n        mocks[2].result.data\n      );\n    });\n\n    it(\"refetchQueries should update cache after unmount\", async () => {\n      const variables = { description: \"Get milk!\" };\n      const mocks = [\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_1 },\n          delay: 20,\n        },\n        {\n          request: {\n            query: CREATE_TODO_MUTATION,\n            variables,\n          },\n          result: {\n            data: CREATE_TODO_RESULT,\n          },\n          delay: 20,\n        },\n        {\n          request: {\n            query: GET_TODOS_QUERY,\n          },\n          result: { data: GET_TODOS_RESULT_2 },\n          delay: 20,\n        },\n      ];\n\n      const link = new MockLink(mocks);\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, unmount } =\n        await renderHookToSnapshotStream(\n          () => ({\n            query: useQuery(GET_TODOS_QUERY),\n            mutation: useMutation(CREATE_TODO_MUTATION),\n          }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: false,\n          called: false,\n        });\n      }\n\n      const {\n        mutation: [mutate],\n      } = getCurrentSnapshot();\n\n      await expect(\n        mutate({\n          variables,\n          refetchQueries: [\"getTodos\"],\n          update() {\n            unmount();\n          },\n        })\n      ).resolves.toStrictEqualTyped({ data: CREATE_TODO_RESULT });\n\n      {\n        const {\n          query,\n          mutation: [, mutation],\n        } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: GET_TODOS_RESULT_1,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(mutation).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n          called: true,\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n\n      expect(client.readQuery({ query: GET_TODOS_QUERY })).toEqual(\n        GET_TODOS_RESULT_2\n      );\n    });\n\n    it(\"using onQueryUpdated callback should not prevent cache broadcast\", async () => {\n      // Mutating this array makes the tests below much more difficult to reason\n      // about, so instead we reassign the numbersArray variable to remove\n      // elements, without mutating the previous array object.\n      let numbersArray: ReadonlyArray<{ id: string; value: number }> = [\n        { id: \"1\", value: 324 },\n        { id: \"2\", value: 729 },\n        { id: \"3\", value: 987 },\n        { id: \"4\", value: 344 },\n        { id: \"5\", value: 72 },\n        { id: \"6\", value: 899 },\n        { id: \"7\", value: 222 },\n      ];\n\n      // Modifying this value means we can return a subset of our numbers array\n      // without needing to mutate or reassignn the original numbersArray.\n      let totalNumbers: number = numbersArray.length;\n\n      type TNumbersQuery = {\n        numbers: {\n          __typename: \"NumbersResult\";\n          id: string;\n          sum: number;\n          numbersArray: ReadonlyArray<{\n            id: string;\n            value: number;\n          }>;\n        };\n      };\n\n      function getNumbersData(length: number = totalNumbers): TNumbersQuery {\n        const numbers = numbersArray.slice(0, length);\n\n        return {\n          numbers: {\n            __typename: \"NumbersResult\",\n            id: \"numbersId\",\n            numbersArray: numbers,\n            sum: numbers.reduce((sum, b) => sum + b.value, 0),\n          },\n        };\n      }\n\n      const link = new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          setTimeout(() => {\n            const { operationName } = operation;\n            if (operationName === \"NumbersQuery\") {\n              observer.next({\n                data: getNumbersData(),\n              });\n            } else if (operationName === \"RemoveNumberMutation\") {\n              observer.next({\n                data: {\n                  removeLastNumber: getLastNumber(),\n                },\n              });\n\n              totalNumbers--;\n            }\n            observer.complete();\n          }, 50);\n        });\n      });\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache({\n          typePolicies: {\n            NumbersResult: {\n              fields: {\n                numbersArray: { merge: false },\n                sum(_, { readField }) {\n                  const numbersArray =\n                    readField<TNumbersQuery[\"numbers\"][\"numbersArray\"]>(\n                      \"numbersArray\"\n                    );\n                  return (numbersArray || []).reduce(\n                    (sum, item) => sum + item.value,\n                    0\n                  );\n                },\n              },\n            },\n          },\n        }),\n      });\n\n      const NumbersQuery: TypedDocumentNode<TNumbersQuery> = gql`\n        query NumbersQuery {\n          numbers {\n            id\n            sum\n            numbersArray {\n              id\n              value\n            }\n          }\n        }\n      `;\n\n      const RemoveNumberMutation = gql`\n        mutation RemoveNumberMutation {\n          removeLastNumber {\n            id\n          }\n        }\n      `;\n\n      const renderStream = createRenderStream({\n        initialSnapshot: {\n          useQueryResult: null as useQuery.Result<TNumbersQuery> | null,\n          useMutationResult: null as useMutation.ResultTuple<any, any> | null,\n        },\n      });\n\n      function App() {\n        renderStream.mergeSnapshot({\n          useQueryResult: useQuery(NumbersQuery),\n          useMutationResult: useMutation(RemoveNumberMutation, {\n            update(cache) {\n              const oldData = cache.readQuery({ query: NumbersQuery });\n              cache.writeQuery({\n                query: NumbersQuery,\n                data:\n                  oldData ?\n                    {\n                      ...oldData,\n                      numbers: {\n                        ...oldData.numbers,\n                        numbersArray: oldData.numbers.numbersArray.slice(0, -1),\n                      },\n                    }\n                  : {\n                      numbers: {\n                        __typename: \"NumbersResult\",\n                        id: \"numbersId\",\n                        sum: 0,\n                        numbersArray: [],\n                      },\n                    },\n              });\n            },\n          }),\n        });\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      async function getNextSnapshot() {\n        const { snapshot } = await renderStream.takeRender();\n\n        invariant(snapshot.useQueryResult);\n        invariant(snapshot.useMutationResult);\n\n        return {\n          useQueryResult: snapshot.useQueryResult,\n          useMutationResult: snapshot.useMutationResult,\n        };\n      }\n\n      function getLastNumber() {\n        const numbers = numbersArray.slice(0, totalNumbers);\n\n        return numbers[numbers.length - 1];\n      }\n\n      expect(getLastNumber()).toEqual({ id: \"7\", value: 222 });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n\n        expect(useQueryResult.loading).toBe(true);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.loading);\n        expect(useQueryResult.data).toBeUndefined();\n\n        expect(mutationResult.loading).toBe(false);\n        expect(mutationResult.called).toBe(false);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(7);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(false);\n        expect(mutationResult.called).toBe(false);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      const [mutate] =\n        renderStream.getCurrentRender().snapshot.useMutationResult!;\n\n      let promise = mutate();\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(7);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(true);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      // Not passing an onQueryUpdated callback should allow cache\n      // broadcasts to propagate as normal. The point of this test is to\n      // demonstrate that *adding* onQueryUpdated should not prevent cache\n      // broadcasts (see below for where we test that).\n      await expect(promise).resolves.toEqual({\n        data: {\n          removeLastNumber: {\n            id: \"7\",\n          },\n        },\n      });\n\n      expect(getLastNumber()).toEqual({ id: \"6\", value: 899 });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(6);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(true);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(6);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(false);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toEqual({ removeLastNumber: { id: \"7\" } });\n      }\n\n      promise = mutate({\n        // Adding this onQueryUpdated callback, which merely examines the\n        // updated query and its DiffResult, should not change the broadcast\n        // behavior of the ObservableQuery.\n        onQueryUpdated(oq, diff) {\n          expect(oq.queryName).toBe(\"NumbersQuery\");\n          expect(diff.result.numbers.numbersArray.length).toBe(5);\n          expect(diff.result.numbers.sum).toBe(2456);\n        },\n      });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(6);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(true);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      await expect(promise).resolves.toEqual({\n        data: {\n          removeLastNumber: {\n            id: \"6\",\n          },\n        },\n      });\n\n      expect(getLastNumber()).toEqual({ id: \"5\", value: 72 });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(5);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(true);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(5);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(false);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toEqual({ removeLastNumber: { id: \"6\" } });\n      }\n\n      promise = mutate({\n        onQueryUpdated(oq, diff) {\n          expect(oq.queryName).toBe(\"NumbersQuery\");\n          expect(diff.result.numbers.numbersArray.length).toBe(4);\n          expect(diff.result.numbers.sum).toBe(2384);\n          // Returning false from onQueryUpdated prevents the cache broadcast.\n          return false;\n        },\n      });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(5);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        expect(useQueryResult.data).toEqual(data);\n\n        expect(mutationResult.loading).toBe(true);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toBeUndefined();\n      }\n\n      await expect(promise).resolves.toEqual({\n        data: {\n          removeLastNumber: {\n            id: \"5\",\n          },\n        },\n      });\n\n      expect(getLastNumber()).toEqual({ id: \"4\", value: 344 });\n\n      {\n        const { useQueryResult, useMutationResult } = await getNextSnapshot();\n        const [, mutationResult] = useMutationResult;\n        const data = getNumbersData();\n\n        expect(data.numbers.numbersArray).toHaveLength(4);\n\n        expect(useQueryResult.loading).toBe(false);\n        expect(useQueryResult.networkStatus).toBe(NetworkStatus.ready);\n        // This mutation did not broadcast results, so we expect our numbers to\n        // equal the previous set.\n        expect(useQueryResult.data).toEqual(getNumbersData(5));\n\n        expect(mutationResult.loading).toBe(false);\n        expect(mutationResult.called).toBe(true);\n        expect(mutationResult.data).toEqual({ removeLastNumber: { id: \"5\" } });\n      }\n\n      await expect(renderStream).not.toRerender();\n    });\n\n    it(\"refetchQueries should work with BatchHttpLink\", async () => {\n      const MUTATION_1 = gql`\n        mutation DoSomething {\n          doSomething {\n            message\n          }\n        }\n      `;\n\n      const QUERY_1 = gql`\n        query Items {\n          items {\n            id\n          }\n        }\n      `;\n\n      fetchMock.restore();\n\n      const responseBodies = [\n        { data: { items: [{ id: 1 }, { id: 2 }] } },\n        { data: { doSomething: { message: \"success\" } } },\n        { data: { items: [{ id: 1 }, { id: 2 }, { id: 3 }] } },\n      ];\n\n      fetchMock.post(\n        \"/graphql\",\n        (url, opts) =>\n          new Promise((resolve) => {\n            resolve({\n              body: responseBodies.shift(),\n            });\n          })\n      );\n\n      const Test = () => {\n        const { data } = useQuery<any>(QUERY_1);\n        const [mutate] = useMutation<any>(MUTATION_1, {\n          awaitRefetchQueries: true,\n          refetchQueries: [QUERY_1],\n        });\n\n        const { items = [] } = data || {};\n\n        return (\n          <>\n            <button\n              onClick={() => {\n                return mutate();\n              }}\n              type=\"button\"\n            >\n              mutate\n            </button>\n            {items.map((c: any) => (\n              <div key={c.id}>item {c.id}</div>\n            ))}\n          </>\n        );\n      };\n\n      const client = new ApolloClient({\n        link: new BatchHttpLink({\n          uri: \"/graphql\",\n          batchMax: 10,\n        }),\n        cache: new InMemoryCache(),\n      });\n\n      render(\n        <ApolloProvider client={client}>\n          <Test />\n        </ApolloProvider>\n      );\n\n      await waitFor(() => screen.findByText(\"item 1\"));\n      await userEvent.click(screen.getByRole(\"button\", { name: /mutate/i }));\n      await waitFor(() => screen.findByText(\"item 3\"));\n    });\n  });\n});\n\ndescribe(\"data masking\", () => {\n  test(\"masks data returned from useMutation when dataMasking is `true`\", async () => {\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useMutation(mutation), {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [mutate] = getCurrentSnapshot();\n\n    await expect(mutate()).resolves.toStrictEqualTyped({\n      data: {\n        updateUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          updateUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n          },\n        },\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not mask data returned from useMutation when dataMasking is `false`\", async () => {\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n        age: number;\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useMutation(mutation), {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n        called: false,\n      });\n    }\n\n    const [mutate] = getCurrentSnapshot();\n\n    await expect(mutate()).resolves.toStrictEqualTyped({\n      data: {\n        updateUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      },\n    });\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n        called: true,\n      });\n    }\n\n    {\n      const [, result] = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          updateUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n        error: undefined,\n        loading: false,\n        called: true,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"passes masked data to onCompleted, does not pass masked data to update\", async () => {\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      };\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Record<string, never>> = gql`\n      mutation MaskedMutation {\n        updateUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: mutation },\n        result: {\n          data: {\n            updateUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache,\n      link: new MockLink(mocks),\n    });\n\n    const update = jest.fn();\n    const onCompleted = jest.fn();\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useMutation(mutation, { onCompleted, update }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    const [mutate] = await takeSnapshot();\n\n    await mutate();\n\n    expect(onCompleted).toHaveBeenCalledTimes(1);\n    expect(onCompleted).toHaveBeenCalledWith(\n      {\n        updateUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      },\n      expect.anything()\n    );\n\n    expect(update).toHaveBeenCalledTimes(1);\n    expect(update).toHaveBeenCalledWith(\n      cache,\n      {\n        data: {\n          updateUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n      },\n      { context: undefined, variables: {} }\n    );\n  });\n});\n\ndescribe.skip(\"Type Tests\", () => {\n  test(\"NoInfer prevents adding arbitrary additional variables\", () => {\n    const typedNode = {} as TypedDocumentNode<{ foo: string }, { bar: number }>;\n    useMutation(typedNode, {\n      variables: {\n        bar: 4,\n        // @ts-expect-error\n        nonExistingVariable: \"string\",\n      },\n    });\n  });\n\n  test(\"uses any as masked and unmasked type when using plain DocumentNode\", () => {\n    const mutation = gql`\n      mutation ($id: ID!) {\n        updateUser(id: $id) {\n          id\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const [mutate, { data }] = useMutation(mutation, {\n      optimisticResponse: { foo: \"foo\" },\n      updateQueries: {\n        TestQuery: (_, { mutationResult }) => {\n          expectTypeOf(mutationResult.data).toMatchTypeOf<any>();\n\n          return {};\n        },\n      },\n      refetchQueries(result) {\n        expectTypeOf(result.data).toMatchTypeOf<any>();\n\n        return \"active\";\n      },\n      onCompleted(data) {\n        expectTypeOf(data).toMatchTypeOf<any>();\n      },\n      update(_, result) {\n        expectTypeOf(result.data).toMatchTypeOf<any>();\n      },\n    });\n\n    expectTypeOf(data).toMatchTypeOf<any>();\n    expectTypeOf(mutate()).toMatchTypeOf<Promise<ApolloLink.Result<any>>>();\n  });\n\n  test(\"uses TData type when using plain TypedDocumentNode\", () => {\n    interface Mutation {\n      updateUser: {\n        __typename: \"User\";\n        id: string;\n        age: number;\n      };\n    }\n\n    interface Variables {\n      id: string;\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Variables> = gql`\n      mutation ($id: ID!) {\n        updateUser(id: $id) {\n          id\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const [mutate, { data }] = useMutation(mutation, {\n      variables: { id: \"1\" },\n      optimisticResponse: {\n        updateUser: { __typename: \"User\", id: \"1\", age: 30 },\n      },\n      updateQueries: {\n        TestQuery: (_, { mutationResult }) => {\n          expectTypeOf(mutationResult.data).toMatchTypeOf<\n            Mutation | DeepPartial<Mutation> | null | undefined\n          >();\n          if (mutationResult.dataState === \"streaming\") {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              DeepPartial<Mutation> | null | undefined\n            >();\n          }\n          if (mutationResult.dataState === \"complete\") {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              Mutation | null | undefined\n            >();\n          }\n\n          return {};\n        },\n      },\n      refetchQueries(result) {\n        expectTypeOf(result.data).toMatchTypeOf<Mutation | null | undefined>();\n\n        return \"active\";\n      },\n      onCompleted(data) {\n        expectTypeOf(data).toMatchTypeOf<Mutation>();\n      },\n      update(_, result) {\n        expectTypeOf(result.data).toMatchTypeOf<Mutation | null | undefined>();\n      },\n    });\n\n    expectTypeOf(data).toMatchTypeOf<Mutation | null | undefined>();\n    expectTypeOf(mutate()).toMatchTypeOf<\n      Promise<ApolloLink.Result<Mutation>>\n    >();\n  });\n\n  test(\"uses proper masked/unmasked type\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\": \"UserFieldsFragment\" };\n\n    type Mutation = {\n      updateUser: {\n        __typename: \"User\";\n        id: string;\n      } & { \" $fragmentRefs\": { UserFieldsFragment: UserFieldsFragment } };\n    };\n\n    type UnmaskedMutation = {\n      updateUser: {\n        __typename: \"User\";\n        id: string;\n        age: number;\n      };\n    };\n\n    interface Variables {\n      id: string;\n    }\n\n    const mutation: TypedDocumentNode<Mutation, Variables> = gql`\n      mutation ($id: ID!) {\n        updateUser(id: $id) {\n          id\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const [mutate, { data }] = useMutation(mutation, {\n      optimisticResponse: {\n        updateUser: { __typename: \"User\", id: \"1\", age: 30 },\n      },\n      updateQueries: {\n        TestQuery: (_, { mutationResult }) => {\n          expectTypeOf(mutationResult.data).toMatchTypeOf<\n            UnmaskedMutation | DeepPartial<UnmaskedMutation> | null | undefined\n          >();\n\n          if (mutationResult.dataState === \"streaming\") {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              DeepPartial<UnmaskedMutation> | null | undefined\n            >();\n          }\n          if (mutationResult.dataState === \"complete\") {\n            expectTypeOf(mutationResult.data).toMatchTypeOf<\n              UnmaskedMutation | null | undefined\n            >();\n          }\n\n          return {};\n        },\n      },\n      refetchQueries(result) {\n        expectTypeOf(result.data).toMatchTypeOf<\n          UnmaskedMutation | null | undefined\n        >();\n\n        return \"active\";\n      },\n      onCompleted(data) {\n        expectTypeOf(data).toMatchTypeOf<Mutation>();\n      },\n      update(_, result) {\n        expectTypeOf(result.data).toMatchTypeOf<\n          UnmaskedMutation | null | undefined\n        >();\n      },\n    });\n\n    expectTypeOf(data).toMatchTypeOf<Mutation | null | undefined>();\n    expectTypeOf(mutate({ variables: { id: \"1\" } })).toMatchTypeOf<\n      Promise<ApolloLink.Result<Mutation>>\n    >();\n  });\n\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const mutation = gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: {} });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: { foo: \"bar\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: { bar: \"baz\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    {\n      const [mutate] = useMutation(query);\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(query, {});\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(query, { variables: {} });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(query, { variables: { foo: \"bar\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n    {\n      const [mutate] = useMutation(query, { variables: { bar: \"baz\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { foo: \"bar\" } });\n      mutate({ variables: { bar: \"baz\" } });\n    }\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const mutation: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation);\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: {} });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    const mutation: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      // @ts-expect-error\n      mutate();\n      // @ts-expect-error\n      mutate({});\n      mutate({\n        // @ts-expect-error\n        variables: {},\n      });\n      mutate({\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      // @ts-expect-error\n      mutate();\n      // @ts-expect-error\n      mutate({});\n      mutate({\n        // @ts-expect-error\n        variables: {},\n      });\n      mutate({\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        // @ts-expect-error\n        variables: {},\n      });\n      // @ts-expect-error\n      mutate();\n      // @ts-expect-error\n      mutate({});\n      mutate({\n        // @ts-expect-error\n        variables: {},\n      });\n      mutate({\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: undefined });\n      // @ts-expect-error\n      mutate();\n      // @ts-expect-error\n      mutate({});\n      mutate({\n        // @ts-expect-error\n        variables: {},\n      });\n      mutate({\n        // @ts-expect-error\n        variables: undefined,\n      });\n      mutate({\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n      // @ts-expect-error\n      mutate();\n      // @ts-expect-error\n      mutate({});\n      mutate({\n        // @ts-expect-error\n        variables: {},\n      });\n      mutate({\n        // @ts-expect-error\n        variables: undefined,\n      });\n      mutate({\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n    }\n  });\n\n  test(\"optional variables are optional\", () => {\n    const mutation: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: {} });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: { limit: 10 } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          limit: 10,\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { limit: 10 } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          limit: 10,\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n  });\n\n  test(\"enforces required variables when TVariables includes required variables\", () => {\n    const mutation: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: {} });\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: { id: \"1\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      // The `mutate` function does not give us TS errors for missing required\n      // variables due to the mismatch in variables passed to `useMutation`, but\n      // we are ok with this tradeoff since fixing the invalid variable to\n      // `useMutation` will update the `mutate` function correctly.\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error\n          foo: \"bar\",\n        },\n      });\n    }\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const mutation: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    {\n      const [mutate] = useMutation(mutation);\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {});\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: {} });\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: { language: \"en\" },\n      });\n      // @ts-expect-error missing variables\n      mutate();\n      // @ts-expect-error missing variables\n      mutate({});\n      mutate({\n        // @ts-expect-error missing variables\n        variables: {},\n      });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, { variables: { id: \"1\" } });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: { id: \"1\", language: \"en\" },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n    {\n      const [mutate] = useMutation(mutation, {\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      mutate();\n      mutate({});\n      mutate({ variables: {} });\n      mutate({ variables: { id: \"1\" } });\n      mutate({ variables: { id: \"1\", language: \"en\" } });\n      mutate({\n        variables: {\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n      mutate({\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    }\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQuery/defer20220824.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\n\nimport {\n  ApolloClient,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { useQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  markAsStreaming,\n  mockDefer20220824,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\ntest(\"should handle deferred queries\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: {\n          name: \"Alice\",\n          __typename: \"Person\",\n        },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries in lists\", async () => {\n  const query = gql`\n    {\n      greetings {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        path: [\"greetings\", 0],\n      },\n    ],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Bob\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        path: [\"greetings\", 1],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        {\n          message: \"Hello again\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries in lists, merging arrays\", async () => {\n  const query = gql`\n    query DeferVariation {\n      allProducts {\n        delivery {\n          ...MyFragment @defer\n        }\n        sku\n        id\n      }\n    }\n    fragment MyFragment on DeliveryEstimates {\n      estimatedDelivery\n      fastestDelivery\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    hasNext: true,\n    incremental: [\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        path: [\"allProducts\", 0, \"delivery\"],\n      },\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        path: [\"allProducts\", 1, \"delivery\"],\n      },\n    ],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    variables: {},\n  });\n});\n\ntest(\"should handle deferred queries with fetch policy no-cache\", async () => {\n  const query = gql`\n    {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"no-cache\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: {\n          name: \"Alice\",\n          __typename: \"Person\",\n        },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries with errors returned on the incremental batched result\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      errors: [\n        {\n          message: \"homeWorld for character with ID 1000 could not be fetched.\",\n          path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\nit('should handle deferred queries with errors returned on the incremental batched result and errorPolicy \"all\"', async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n        extensions: {\n          thing1: \"foo\",\n          thing2: \"bar\",\n        },\n      },\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n        extensions: {\n          thing1: \"foo\",\n          thing2: \"bar\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          {\n            // the only difference with the previous test\n            // is that homeWorld is populated since errorPolicy: all\n            // populates both partial data and error.graphQLErrors\n            homeWorld: null,\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            // homeWorld is populated due to errorPolicy: all\n            homeWorld: \"Alderaan\",\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          heroFriends: [\n            { homeWorld: null, id: \"1000\", name: \"Luke Skywalker\" },\n            { homeWorld: \"Alderaan\", id: \"1003\", name: \"Leia Organa\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      errors: [\n        {\n          message: \"homeWorld for character with ID 1000 could not be fetched.\",\n          path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n        },\n      ],\n      extensions: {\n        thing1: \"foo\",\n        thing2: \"bar\",\n      },\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: {\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\nit('returns eventually consistent data from deferred queries with data in the cache while using a \"cache-and-network\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\nit('returns eventually consistent data from deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  // We know we are writing partial data to the cache so suppress the console\n  // warning.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    dataState: \"partial\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQuery/deferGraphQL17Alpha9.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\n\nimport {\n  ApolloClient,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { useQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\ntest(\"should handle deferred queries\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: {\n          name: \"Alice\",\n          __typename: \"Person\",\n        },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries in lists\", async () => {\n  const query = gql`\n    {\n      greetings {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    pending: [\n      { id: \"0\", path: [\"greetings\", 0] },\n      { id: \"1\", path: [\"greetings\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        {\n          message: \"Hello again\",\n          __typename: \"Greeting\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greetings: [\n        { message: \"Hello world\", __typename: \"Greeting\" },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Bob\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"1\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        {\n          message: \"Hello again\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greetings: [\n        {\n          message: \"Hello world\",\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        { message: \"Hello again\", __typename: \"Greeting\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries in lists, merging arrays\", async () => {\n  const query = gql`\n    query DeferVariation {\n      allProducts {\n        delivery {\n          ...MyFragment @defer\n        }\n        sku\n        id\n      }\n    }\n    fragment MyFragment on DeliveryEstimates {\n      estimatedDelivery\n      fastestDelivery\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    pending: [\n      { id: \"0\", path: [\"allProducts\", 0, \"delivery\"] },\n      { id: \"1\", path: [\"allProducts\", 1, \"delivery\"] },\n    ],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    hasNext: false,\n    incremental: [\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        id: \"0\",\n      },\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n            estimatedDelivery: \"6/25/2021\",\n            fastestDelivery: \"6/24/2021\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    variables: {},\n  });\n});\n\ntest(\"should handle deferred queries with fetch policy no-cache\", async () => {\n  const query = gql`\n    {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"no-cache\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: {\n            name: \"Alice\",\n            __typename: \"Person\",\n          },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: {\n          name: \"Alice\",\n          __typename: \"Person\",\n        },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle deferred queries with errors returned on the incremental batched result\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n        id: \"0\",\n      },\n      {\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      errors: [\n        {\n          message: \"homeWorld for character with ID 1000 could not be fetched.\",\n          path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('should handle deferred queries with errors returned on the incremental batched result and errorPolicy \"all\"', async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n        id: \"0\",\n        extensions: {\n          thing1: \"foo\",\n          thing2: \"bar\",\n        },\n      },\n      {\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n        id: \"1\",\n        extensions: {\n          thing1: \"foo\",\n          thing2: \"bar\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          {\n            // the only difference with the previous test\n            // is that homeWorld is populated since errorPolicy: all\n            // populates both partial data and error.graphQLErrors\n            homeWorld: null,\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            // homeWorld is populated due to errorPolicy: all\n            homeWorld: \"Alderaan\",\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        hero: {\n          heroFriends: [\n            { homeWorld: null, id: \"1000\", name: \"Luke Skywalker\" },\n            { homeWorld: \"Alderaan\", id: \"1003\", name: \"Leia Organa\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      errors: [\n        {\n          message: \"homeWorld for character with ID 1000 could not be fetched.\",\n          path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n        },\n      ],\n      extensions: {\n        thing1: \"foo\",\n        thing2: \"bar\",\n      },\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: {\n      hero: {\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from deferred queries with data in the cache while using a \"cache-and-network\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { __typename: \"Greeting\", message: \"Hello world\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  // We know we are writing partial data to the cache so suppress the console\n  // warning.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    dataState: \"partial\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  enqueueInitialChunk({\n    data: {\n      greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQuery/streamDefer20220824.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { from } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { useQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha2,\n  friendListSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha2(\n        friendListSchemaGraphQL17Alpha2,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntype Friend = (typeof friends)[number];\n\ntest(\"should handle streamed queries\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(() => useQuery(query), {\n    wrapper: createClientWrapper(client),\n  });\n  const { takeSnapshot } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n    }),\n  });\n\n  subject.next(friends[1]);\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      previousData: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      },\n    }),\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot({\n    expected: (previous) => ({\n      ...previous,\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      previousData: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n    }),\n  });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot({\n    expected: (previous) => ({\n      ...previous,\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n    }),\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle streamed queries with fetch policy no-cache\", async () => {\n  const { subject, stream } = asyncIterableSubject<Friend>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"no-cache\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle streamed queries with errors returned on the incremental batched result\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Error>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(new Error(\"Could not load friend\"));\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: undefined,\n    variables: {},\n  });\n\n  // Emit these to show that errorPolicy of none cuts off future updates\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('should handle streamed queries with errors returned on the incremental batched result and errorPolicy \"all\"', async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Error>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(new Error(\"Could not load friend\"));\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    }),\n    dataState: \"streaming\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from streamed queries with data in the cache while using a \"cache-and-network\" fetch policy', async () => {\n  const { subject, stream } = asyncIterableSubject<Friend>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => incoming,\n            },\n          },\n        },\n      },\n    }),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from streamed queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => incoming,\n            },\n          },\n        },\n      },\n    }),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  // We know we are writing partial data to the cache so suppress the console\n  // warning.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    client.writeQuery({\n      query,\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\" },\n          { __typename: \"Friend\", id: \"2\" },\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\" },\n        { __typename: \"Friend\", id: \"2\" },\n        { __typename: \"Friend\", id: \"3\" },\n      ],\n    },\n    dataState: \"partial\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\" },\n        { __typename: \"Friend\", id: \"2\" },\n        { __typename: \"Friend\", id: \"3\" },\n      ],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQuery/streamGraphQL17Alpha9.test.tsx",
    "content": "import {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { from } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { useQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha9,\n  friendListSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha9(\n        friendListSchemaGraphQL17Alpha9,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntype Friend = (typeof friends)[number];\n\ntest(\"should handle streamed queries\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle streamed queries with fetch policy no-cache\", async () => {\n  const { subject, stream } = asyncIterableSubject<Friend>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"no-cache\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"should handle streamed queries with errors returned on the incremental batched result\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Error>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(new Error(\"Could not load friend\"));\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: undefined,\n    variables: {},\n  });\n\n  // Emit these to show that errorPolicy of none cuts off future updates\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('should handle streamed queries with errors returned on the incremental batched result and errorPolicy \"all\"', async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Error>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(new Error(\"Could not load friend\"));\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    }),\n    dataState: \"streaming\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        null,\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      errors: [\n        {\n          message: \"Could not load friend\",\n          path: [\"friendList\", 1],\n        },\n      ],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from streamed queries with data in the cache while using a \"cache-and-network\" fetch policy', async () => {\n  const { subject, stream } = asyncIterableSubject<Friend>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => incoming,\n            },\n          },\n        },\n      },\n    }),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest('returns eventually consistent data from streamed queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => incoming,\n            },\n          },\n        },\n      },\n    }),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  // We know we are writing partial data to the cache so suppress the console\n  // warning.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    client.writeQuery({\n      query,\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\" },\n          { __typename: \"Friend\", id: \"2\" },\n          { __typename: \"Friend\", id: \"3\" },\n        ],\n      },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\" },\n        { __typename: \"Friend\", id: \"2\" },\n        { __typename: \"Friend\", id: \"3\" },\n      ],\n    },\n    dataState: \"partial\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  subject.next(friends[0]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\" },\n        { __typename: \"Friend\", id: \"2\" },\n        { __typename: \"Friend\", id: \"3\" },\n      ],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[1]);\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n    },\n    variables: {},\n  });\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: markAsStreaming({\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    }),\n    dataState: \"streaming\",\n    loading: true,\n    networkStatus: NetworkStatus.streaming,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n      ],\n    },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQuery.test.tsx",
    "content": "import {\n  act,\n  render,\n  renderHook,\n  screen,\n  waitFor,\n} from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport type { DocumentNode, GraphQLFormattedError } from \"graphql\";\nimport { GraphQLError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport type { ReactNode } from \"react\";\nimport React, { Fragment, useEffect, useState } from \"react\";\nimport { asapScheduler, EMPTY, Observable, observeOn, of, Subject } from \"rxjs\";\n\nimport type {\n  DataValue,\n  ErrorPolicy,\n  FetchPolicy,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  CombinedGraphQLErrors,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { LocalState } from \"@apollo/client/local-state\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport type { SkipToken } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  skipToken,\n  useLazyQuery,\n  useMutation,\n  useQuery,\n} from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  SimpleCaseData,\n  VariablesCaseVariables,\n} from \"@apollo/client/testing/internal\";\nimport {\n  createClientWrapper,\n  enableFakeTimers,\n  ObservableStream,\n  setupPaginatedCase,\n  setupSimpleCase,\n  setupVariablesCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial, Reference } from \"@apollo/client/utilities\";\nimport { concatPagination } from \"@apollo/client/utilities\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nconst IS_REACT_17 = React.version.startsWith(\"17\");\nconst IS_REACT_18 = React.version.startsWith(\"18\");\n\ndescribe(\"useQuery Hook\", () => {\n  describe(\"General use\", () => {\n    it(\"should handle a simple query\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"useQuery result is referentially stable\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        {\n          wrapper,\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      let oldResult: useQuery.Result<any, OperationVariables>;\n\n      {\n        const result = (oldResult = await takeSnapshot());\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(result).toBe(oldResult);\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"useQuery produces the expected renders initially\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        {\n          wrapper,\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"useQuery produces the expected frames when variables change\", async () => {\n      const query = gql`\n        query ($id: Int) {\n          hello(id: $id)\n        }\n      `;\n      const mocks = [\n        {\n          request: { query, variables: { id: 1 } },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query, variables: { id: 2 } },\n          result: { data: { hello: \"world 2\" } },\n        },\n      ];\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        (options) => useQuery(query, options),\n        { wrapper, initialProps: { variables: { id: 1 } } }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      await rerender({ variables: { id: 2 } });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n    });\n\n    // TODO: Refactor this test. This test does not test the thing it says it\n    // does as there is no cache interaction in this test. This is essentially\n    // just a repeat of prior tests that rerender and check the result.\n    it(\"should read and write results from the cache\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        {\n          wrapper,\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    });\n\n    it(\"should preserve functions between renders\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      const {\n        loading,\n        refetch,\n        fetchMore,\n        startPolling,\n        stopPolling,\n        subscribeToMore,\n      } = await takeSnapshot();\n      expect(loading).toBe(true);\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(refetch).toBe(result.refetch);\n        expect(fetchMore).toBe(result.fetchMore);\n        expect(startPolling).toBe(result.startPolling);\n        expect(stopPolling).toBe(result.stopPolling);\n        expect(subscribeToMore).toBe(result.subscribeToMore);\n      }\n\n      await rerender();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(refetch).toBe(result.refetch);\n        expect(fetchMore).toBe(result.fetchMore);\n        expect(startPolling).toBe(result.startPolling);\n        expect(stopPolling).toBe(result.stopPolling);\n        expect(subscribeToMore).toBe(result.subscribeToMore);\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Remove this test after PR is reviewed since this is basically a\n    // duplicate of \"useQuery produces the expected frames when variables change\"\n    it(\"should work with variables\", async () => {\n      const query = gql`\n        query ($id: Int) {\n          hello(id: $id)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query, variables: { id: 1 } },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query, variables: { id: 2 } },\n          result: { data: { hello: \"world 2\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id }) => useQuery(query, { variables: { id } }),\n        { wrapper, initialProps: { id: 1 } }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      await rerender({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n    });\n\n    it(\"should return the same results for the same variables\", async () => {\n      const query = gql`\n        query ($id: Int) {\n          hello(id: $id)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query, variables: { id: 1 } },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query, variables: { id: 2 } },\n          result: { data: { hello: \"world 2\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id }) => useQuery(query, { variables: { id } }),\n        { wrapper, initialProps: { id: 1 } }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      await rerender({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n\n      await rerender({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n    });\n\n    it(\"should work with variables 2\", async () => {\n      const query = gql`\n        query ($name: String) {\n          names(name: $name)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query, variables: { name: \"\" } },\n          result: { data: { names: [\"Alice\", \"Bob\", \"Eve\"] } },\n        },\n        {\n          request: { query, variables: { name: \"z\" } },\n          result: { data: { names: [] } },\n        },\n        {\n          request: { query, variables: { name: \"zz\" } },\n          result: { data: { names: [] } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ name }) => useQuery(query, { variables: { name } }),\n        { wrapper, initialProps: { name: \"\" } }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { name: \"\" },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { names: [\"Alice\", \"Bob\", \"Eve\"] },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { name: \"\" },\n        });\n      }\n\n      await rerender({ name: \"z\" });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { names: [\"Alice\", \"Bob\", \"Eve\"] },\n          variables: { name: \"z\" },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { names: [] },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { names: [\"Alice\", \"Bob\", \"Eve\"] },\n          variables: { name: \"z\" },\n        });\n      }\n\n      await rerender({ name: \"zz\" });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { names: [] },\n          variables: { name: \"zz\" },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { names: [] },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { names: [] },\n          variables: { name: \"zz\" },\n        });\n      }\n    });\n\n    // An unsuccessful attempt to reproduce https://github.com/apollographql/apollo-client/issues/9135.\n    it(\"should not return stale variables when stored in state\", async () => {\n      const query = gql`\n        query myQuery($name: String) {\n          hello(name: $name)\n        }\n      `;\n\n      const mutation = gql`\n        mutation myMutation($name: String) {\n          updateName(name: $name)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query, variables: { name: \"world 1\" } },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query: mutation, variables: { name: \"world 2\" } },\n          result: { data: { updateName: true } },\n        },\n        {\n          request: { query, variables: { name: \"world 2\" } },\n          result: { data: { hello: \"world 2\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      let setName: any;\n\n      using _disabledAct = disableActEnvironment();\n      // TODO: Take a deeper look into this to better understand what this is\n      // trying to test. There are a few problems with this:\n      //\n      // 1. We execute the mutation and a setState at the same time. What is\n      //    that meant to accomplish?\n      // 2. The update callback in the useMutation is writing data for none of\n      //    the results in the mocks. The mutation returns `updateName: true`,\n      //    yet the callback is trying to set a value from `data.updateGreeting`\n      // 3. The update callback in `useMutation` does not use `variables`, so\n      //    the written cache result does not affect any of the queries from the\n      //    `useQuery` returned here.\n      //\n      // My recommendation is to just delete the `useMutation` as part of this\n      // render callback as it doesn't seem to serve much of a purpose for this\n      // test.\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => {\n            const [name, setName1] = React.useState(\"world 1\");\n            setName = setName1;\n            return [\n              useQuery(query, { variables: { name } }),\n              useMutation<any>(mutation, {\n                update(cache, { data }) {\n                  cache.writeQuery({\n                    query,\n                    data: { hello: data.updateName },\n                  });\n                },\n              }),\n            ] as const;\n          },\n          {\n            wrapper: ({ children }) => (\n              <MockedProvider\n                mocks={mocks}\n                cache={cache}\n                mockLinkDefaultOptions={{ delay: 0 }}\n              >\n                {children}\n              </MockedProvider>\n            ),\n          }\n        );\n\n      {\n        const [useQueryResult] = await takeSnapshot();\n\n        expect(useQueryResult).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { name: \"world 1\" },\n        });\n      }\n\n      {\n        const [useQueryResult] = await takeSnapshot();\n\n        expect(useQueryResult).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { name: \"world 1\" },\n        });\n      }\n\n      const [, [mutate]] = getCurrentSnapshot();\n\n      void mutate({ variables: { name: \"world 2\" } });\n      setName(\"world 2\");\n\n      if (IS_REACT_17) {\n        {\n          const [useQueryResult] = await takeSnapshot();\n\n          expect(useQueryResult).toStrictEqualTyped({\n            data: { hello: \"world 1\" },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: undefined,\n            variables: { name: \"world 1\" },\n          });\n        }\n\n        {\n          const [useQueryResult] = await takeSnapshot();\n\n          expect(useQueryResult).toStrictEqualTyped({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.setVariables,\n            previousData: { hello: \"world 1\" },\n            variables: { name: \"world 2\" },\n          });\n        }\n      }\n\n      {\n        const [useQueryResult] = await takeSnapshot();\n\n        expect(useQueryResult).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { hello: \"world 1\" },\n          variables: { name: \"world 2\" },\n        });\n      }\n\n      {\n        const [useQueryResult] = await takeSnapshot();\n\n        expect(useQueryResult).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { name: \"world 2\" },\n        });\n      }\n\n      if (IS_REACT_18) {\n        const [useQueryResult] = await takeSnapshot();\n\n        expect(useQueryResult).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { name: \"world 2\" },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Rewrite this test\n    // Context: https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#warnings-for-some-updates-during-render\n    it(\"should not error when forcing an update with React >= 16.13.0\", async () => {\n      const CAR_QUERY: DocumentNode = gql`\n        query {\n          cars {\n            make\n            model\n            vin\n          }\n        }\n      `;\n\n      const CAR_RESULT_DATA = {\n        cars: [\n          {\n            make: \"Audi\",\n            model: \"RS8\",\n            vin: \"DOLLADOLLABILL\",\n            __typename: \"Car\",\n          },\n        ],\n      };\n      let wasUpdateErrorLogged = false;\n      const consoleError = console.error;\n      console.error = (msg: string) => {\n        console.log(msg);\n        wasUpdateErrorLogged = msg.indexOf(\"Cannot update a component\") > -1;\n      };\n\n      const CAR_MOCKS = [1, 2, 3, 4, 5, 6].map((something) => ({\n        request: {\n          query: CAR_QUERY,\n          variables: { something },\n        },\n        result: { data: CAR_RESULT_DATA },\n      }));\n\n      let renderCount = 0;\n\n      const InnerComponent = ({ something }: any) => {\n        const { loading, data } = useQuery(CAR_QUERY, {\n          fetchPolicy: \"network-only\",\n          variables: { something },\n        });\n        renderCount += 1;\n        if (loading) return null;\n        expect(wasUpdateErrorLogged).toBeFalsy();\n        expect(data).toEqual(CAR_RESULT_DATA);\n        return null;\n      };\n\n      function WrapperComponent({ something }: any) {\n        const { loading } = useQuery(CAR_QUERY, {\n          variables: { something },\n        });\n        return loading ? null : <InnerComponent something={something + 1} />;\n      }\n\n      render(\n        <MockedProvider link={new MockLink(CAR_MOCKS)}>\n          <Fragment>\n            <WrapperComponent something={1} />\n            <WrapperComponent something={3} />\n            <WrapperComponent something={5} />\n          </Fragment>\n        </MockedProvider>\n      );\n\n      await waitFor(() => {\n        expect(renderCount).toBe(6);\n      });\n      console.error = consoleError;\n    });\n\n    it(\"should tear down the query on unmount\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const client = new ApolloClient({\n        link: new ApolloLink(() => of({ data: { hello: \"world\" } })),\n        cache: new InMemoryCache(),\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      const { unmount } = renderHook(() => useQuery(query), { wrapper });\n\n      expect(client.getObservableQueries().size).toBe(1);\n      unmount();\n      await new Promise((resolve) => setTimeout(resolve));\n      expect(client.getObservableQueries().size).toBe(0);\n    });\n\n    it(\"should work with ssr: false\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { ssr: false }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    });\n\n    it(\"should keep `no-cache` results when the tree is re-rendered\", async () => {\n      const query1 = gql`\n        query people {\n          allPeople(first: 1) {\n            people {\n              name\n            }\n          }\n        }\n      `;\n\n      const query2 = gql`\n        query Things {\n          allThings {\n            thing {\n              description\n            }\n          }\n        }\n      `;\n\n      const allPeopleData = {\n        allPeople: { people: [{ name: \"Luke Skywalker\" }] },\n      };\n\n      const allThingsData = {\n        allThings: {\n          thing: [{ description: \"Thing 1\" }, { description: \"Thing 2\" }],\n        },\n      };\n\n      const link = new MockLink([\n        {\n          request: { query: query1 },\n          result: { data: allPeopleData },\n          delay: 3,\n        },\n        {\n          request: { query: query2 },\n          result: { data: allThingsData },\n          delay: 50,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => [useQuery(query1, { fetchPolicy: \"no-cache\" }), useQuery(query2)],\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const [result0, result1] = await takeSnapshot();\n\n        expect(result0).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(result1).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [result0, result1] = await takeSnapshot();\n\n        expect(result0).toStrictEqualTyped({\n          data: allPeopleData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(result1).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const [result0, result1] = await takeSnapshot();\n\n        expect(result0).toStrictEqualTyped({\n          data: allPeopleData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(result1).toStrictEqualTyped({\n          data: allThingsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender();\n\n      {\n        const [result0, result1] = await takeSnapshot();\n\n        expect(result0).toStrictEqualTyped({\n          data: allPeopleData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n\n        expect(result1).toStrictEqualTyped({\n          data: allThingsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"changing queries\", async () => {\n      const query1 = gql`\n        query {\n          hello\n        }\n      `;\n      const query2 = gql`\n        query {\n          hello\n          name\n        }\n      `;\n      const mocks = [\n        {\n          request: { query: query1 },\n          result: { data: { hello: \"world\" } },\n          delay: 20,\n        },\n        {\n          request: { query: query2 },\n          result: { data: { hello: \"world\", name: \"world\" } },\n          delay: 20,\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        // TODO: I don't think this needs to be a polling query as it has\n        // nothing to do with this test. This test checks to ensure that\n        // changing queries executes the new query and returns the right value.\n        // We should consider removing the pollling from this test and save it\n        // for a polling-specific test instead.\n        ({ query }) => useQuery(query, { pollInterval: 10 }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks} cache={cache}>\n              {children}\n            </MockedProvider>\n          ),\n          initialProps: { query: query1 },\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender({ query: query2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: mocks[1].result.data,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      // We do not include expect(takeSnapshot).not.toRerender() here because\n      // this is a polling query.\n    });\n\n    it(\"`cache-and-network` fetch policy\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n\n      const cache = new InMemoryCache();\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: { hello: \"from link\" } },\n          delay: 20,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache,\n      });\n\n      cache.writeQuery({ query, data: { hello: \"from cache\" } });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { fetchPolicy: \"cache-and-network\" }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      // TODO: FIXME\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"from cache\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"from link\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"from cache\" },\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should not use the cache when using `network-only`\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"from link\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      cache.writeQuery({\n        query,\n        data: { hello: \"from cache\" },\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { fetchPolicy: \"network-only\" }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks} cache={cache}>\n              {children}\n            </MockedProvider>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"from link\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Move this to ssr useQuery tests\n    it(\"should use the cache when in ssrMode and fetchPolicy is `network-only`\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: { hello: \"from link\" } },\n        },\n      ]);\n\n      const cache = new InMemoryCache();\n      cache.writeQuery({\n        query,\n        data: { hello: \"from cache\" },\n      });\n\n      const client = new ApolloClient({ link, cache, ssrMode: true });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { fetchPolicy: \"network-only\" }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"from cache\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Move this to ssr useQuery tests\n    it(\"should not hang when ssrMode is true but the cache is not populated for some reason\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: { hello: \"from link\" } },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n        ssrMode: true,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"from link\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/12458\n    it(\"returns correct result when cache updates after changing variables and skipping query\", async () => {\n      interface Data {\n        user: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        };\n      }\n\n      const query: TypedDocumentNode<Data, { id: number }> = gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id, skip }) => useQuery(query, { skip, variables: { id } }),\n        {\n          initialProps: { id: 1, skip: true },\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      client.writeQuery({\n        query,\n        variables: { id: 1 },\n        data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n      });\n      await rerender({ id: 1, skip: false });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      await rerender({ id: 2, skip: true });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        variables: { id: 2 },\n      });\n\n      client.writeQuery({\n        query,\n        variables: { id: 2 },\n        data: { user: { __typename: \"User\", id: 2, name: \"User 2\" } },\n      });\n\n      await rerender({ id: 2, skip: false });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 2, name: \"User 2\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        variables: { id: 2 },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"returns correct result when cache updates after changing variables and skipping query with skipToken\", async () => {\n      interface Data {\n        user: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        };\n      }\n\n      interface Variables {\n        id: number;\n      }\n\n      const query: TypedDocumentNode<Data, Variables> = gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: ApolloLink.empty(),\n        cache: new InMemoryCache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        (options: SkipToken | useQuery.Options<Data, Variables>) =>\n          useQuery(query, options),\n        {\n          initialProps: skipToken,\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n      const { takeSnapshot, rerender } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      client.writeQuery({\n        query,\n        variables: { id: 1 },\n        data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n      });\n      await rerender({ variables: { id: 1 } });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      await rerender(skipToken);\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n      client.writeQuery({\n        query,\n        variables: { id: 2 },\n        data: { user: { __typename: \"User\", id: 2, name: \"User 2\" } },\n      });\n\n      await rerender({ variables: { id: 2 } });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 2, name: \"User 2\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        variables: { id: 2 },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  it(\"does not rerender with cache updates when changing from skip: false to skip: true\", async () => {\n    interface Data {\n      user: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      };\n    }\n\n    const query: TypedDocumentNode<Data, { id: number }> = gql`\n      query ($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    client.writeQuery({\n      query,\n      variables: { id: 1 },\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = await renderHookToSnapshotStream(\n      ({ skip }) => useQuery(query, { skip, variables: { id: 1 } }),\n      {\n        initialProps: { skip: false },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n    const { takeSnapshot, rerender } = renderStream;\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: 1 },\n    });\n\n    await rerender({ skip: true });\n\n    await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n    client.writeQuery({\n      query,\n      variables: { id: 1 },\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1 (updated)\" } },\n    });\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"does not rerender with cache updates when changing options to skipToken\", async () => {\n    interface Data {\n      user: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      };\n    }\n\n    const query: TypedDocumentNode<Data, { id: number }> = gql`\n      query ($id: ID!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      link: ApolloLink.empty(),\n      cache: new InMemoryCache(),\n    });\n\n    client.writeQuery({\n      query,\n      variables: { id: 1 },\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n    });\n\n    type Opts = SkipToken | useQuery.Options<Data, { id: number }>;\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = await renderHookToSnapshotStream(\n      (options: Opts) => useQuery(query, options),\n      {\n        initialProps: { variables: { id: 1 } } as Opts,\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n    const { takeSnapshot, rerender } = renderStream;\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { id: 1 },\n    });\n\n    await rerender(skipToken);\n\n    await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n    client.writeQuery({\n      query,\n      variables: { id: 1 },\n      data: { user: { __typename: \"User\", id: 1, name: \"User 1 (updated)\" } },\n    });\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"can provide options.client without ApolloProvider\", async () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: { hello: \"from link\" } },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      // TODO: is this really needed for this test?\n      ssrMode: true,\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { client })\n      // We deliberately do not provide the usual ApolloProvider wrapper for\n      // this test, since we are providing the client directly to useQuery.\n      // {\n      //   wrapper: ({ children }) => (\n      //     <ApolloProvider client={client}>\n      //       {children}\n      //     </ApolloProvider>\n      //   ),\n      // }\n    );\n\n    {\n      const result = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const result = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: { hello: \"from link\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n  });\n\n  describe(\"<React.StrictMode>\", () => {\n    it(\"double-rendering should not trigger duplicate network requests\", async () => {\n      const query: TypedDocumentNode<{\n        linkCount: number;\n      }> = gql`\n        query Counter {\n          linkCount\n        }\n      `;\n\n      let linkCount = 0;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (request) =>\n            new Observable((observer) => {\n              if (request.operationName === \"Counter\") {\n                // Emit the value async so we can observe the loading state\n                setTimeout(() => {\n                  observer.next({\n                    data: {\n                      linkCount: ++linkCount,\n                    },\n                  });\n                  observer.complete();\n                });\n              }\n            })\n        ),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"cache-and-network\",\n            }),\n          {\n            wrapper: ({ children }) => (\n              <React.StrictMode>\n                <ApolloProvider client={client}>{children}</ApolloProvider>\n              </React.StrictMode>\n            ),\n          }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { linkCount: 1 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      function checkObservableQueries(expectedLinkCount: number) {\n        const obsQueries = client.getObservableQueries(\"all\");\n        const { observable } = getCurrentSnapshot();\n        expect(obsQueries.size).toBe(1);\n\n        const activeSet = new Set<typeof observable>();\n        const inactiveSet = new Set<typeof observable>();\n        obsQueries.forEach((obsQuery) => {\n          if (obsQuery.hasObservers()) {\n            expect(inactiveSet.has(obsQuery)).toBe(false);\n            activeSet.add(obsQuery);\n            expect(obsQuery.getCurrentResult()).toStrictEqualTyped({\n              loading: false,\n              networkStatus: NetworkStatus.ready,\n              data: {\n                linkCount: expectedLinkCount,\n              },\n              dataState: \"complete\",\n              partial: false,\n            });\n          } else {\n            expect(activeSet.has(obsQuery)).toBe(false);\n            inactiveSet.add(obsQuery);\n          }\n        });\n        expect(activeSet.size).toBe(1);\n        expect(inactiveSet.size).toBe(obsQueries.size - activeSet.size);\n      }\n\n      checkObservableQueries(1);\n\n      await expect(\n        getCurrentSnapshot().observable.reobserve()\n      ).resolves.toStrictEqualTyped({ data: { linkCount: 2 } });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { linkCount: 1 },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { linkCount: 2 },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { linkCount: 1 },\n          variables: {},\n        });\n      }\n\n      checkObservableQueries(2);\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"polling\", () => {\n    it(\"should support polling\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { pollInterval: 10 }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      }\n\n      getCurrentSnapshot().stopPolling();\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should start polling when skip goes from true to false\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      let count = 0;\n      const mocks = [\n        {\n          request: { query },\n          result: () => ({ data: { hello: `world ${++count}` } }),\n          delay: 10,\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        ({ skip }) => useQuery(query, { pollInterval: 80, skip }),\n        {\n          initialProps: { skip: false },\n          wrapper: ({ children }) => (\n            <MockedProvider\n              mocks={mocks}\n              cache={cache}\n              mockLinkDefaultOptions={{ delay: 0 }}\n            >\n              {children}\n            </MockedProvider>\n          ),\n        }\n      );\n      const { takeSnapshot, rerender } = renderStream;\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender({ skip: true });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        /* equal result */\n      });\n\n      await expect(takeSnapshot).not.toRerender({ timeout: 100 });\n\n      await rerender({ skip: false });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      }\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/13154\n    it(\"doesn't poll when initially skipped\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n\n      const requestHandler = jest.fn<\n        ReturnType<ApolloLink.RequestHandler>,\n        Parameters<ApolloLink.RequestHandler>\n      >(() => of({ data: { hello: \"world\" } }));\n\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: new ApolloLink(requestHandler),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        () => useQuery(query, { pollInterval: 80, skip: true }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n      const { takeSnapshot } = renderStream;\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender({ timeout: 100 });\n      expect(requestHandler).not.toHaveBeenCalled();\n    });\n\n    it(\"should start polling when changing skipToken to options\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      let count = 0;\n      const mocks = [\n        {\n          request: { query },\n          result: () => ({ data: { hello: `world ${++count}` } }),\n          delay: 10,\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      using _disabledAct = disableActEnvironment();\n\n      type Opts = SkipToken | useQuery.Options;\n      const renderStream = await renderHookToSnapshotStream(\n        (options: Opts) => useQuery(query, options),\n        {\n          initialProps: { pollInterval: 80 } as Opts,\n          wrapper: ({ children }) => (\n            <MockedProvider\n              mocks={mocks}\n              cache={cache}\n              mockLinkDefaultOptions={{ delay: 0 }}\n            >\n              {children}\n            </MockedProvider>\n          ),\n        }\n      );\n      const { takeSnapshot, rerender } = renderStream;\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender(skipToken);\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        /* equal result */\n      });\n\n      await expect(takeSnapshot).not.toRerender({ timeout: 100 });\n\n      await rerender({ pollInterval: 80 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      }\n    });\n\n    // TODO: Move out of \"polling\" query tests since this doesn't test polling\n    it(\"should return data from network when clients default fetch policy set to network-only\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const data = { hello: \"world\" };\n      const mocks = [\n        {\n          request: { query },\n          result: { data },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      cache.writeQuery({\n        query,\n        data: { hello: \"world 2\" },\n      });\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider\n          mocks={mocks}\n          cache={cache}\n          defaultOptions={{ watchQuery: { fetchPolicy: \"network-only\" } }}\n        >\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should stop polling when component unmounts\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks: MockLink.MockedResponse[] = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n\n      const link = new MockLink(mocks);\n      const requestSpy = jest.spyOn(link, \"request\");\n      const wrapper = ({ children }: any) => (\n        <MockedProvider link={link} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, unmount } = await renderHookToSnapshotStream(\n        () => useQuery(query, { pollInterval: 20 }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n        expect(requestSpy).toHaveBeenCalled();\n      }\n\n      const requestCount = requestSpy.mock.calls.length;\n      expect(requestCount).toBeGreaterThan(0);\n\n      unmount();\n\n      expect(requestSpy).toHaveBeenCalledTimes(requestCount);\n\n      await expect(\n        waitFor(\n          () => {\n            const newRequestCount = requestSpy.mock.calls.length;\n            expect(newRequestCount).toBeGreaterThan(requestCount);\n          },\n          { interval: 1, timeout: 40 }\n        )\n      ).rejects.toThrow();\n\n      requestSpy.mockRestore();\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/9431\n    // https://github.com/apollographql/apollo-client/issues/11750\n    it(\"stops polling when component unmounts with cache-and-network fetch policy\", async () => {\n      const query: TypedDocumentNode<{ hello: string }> = gql`\n        query {\n          hello\n        }\n      `;\n\n      const mocks: MockLink.MockedResponse[] = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n          delay: 20,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n          delay: 20,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n          delay: 20,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n\n      const link = new MockLink(mocks);\n      const requestSpy = jest.spyOn(link, \"request\");\n\n      const client = new ApolloClient({\n        queryDeduplication: false,\n        link,\n        cache,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, unmount } = await renderHookToSnapshotStream(\n        () =>\n          useQuery(query, {\n            pollInterval: 50,\n            fetchPolicy: \"cache-and-network\",\n          }),\n        {\n          wrapper: ({ children }: any) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n      expect(requestSpy).toHaveBeenCalledTimes(1);\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.poll,\n        previousData: undefined,\n        variables: {},\n      });\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n      expect(requestSpy).toHaveBeenCalledTimes(2);\n\n      unmount();\n\n      expect(requestSpy).toHaveBeenCalledTimes(2);\n    });\n\n    it(\"should stop polling when component is unmounted in Strict Mode\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const link = new MockLink(mocks);\n      const requestSpy = jest.spyOn(link, \"request\");\n      const wrapper = ({ children }: any) => (\n        <React.StrictMode>\n          <MockedProvider link={link} cache={cache}>\n            {children}\n          </MockedProvider>\n        </React.StrictMode>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, unmount } = await renderHookToSnapshotStream(\n        () => useQuery(query, { pollInterval: 10 }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      const requestSpyCallCount = requestSpy.mock.calls.length;\n      expect(requestSpy).toHaveBeenCalledTimes(requestSpyCallCount);\n\n      unmount();\n\n      expect(requestSpy).toHaveBeenCalledTimes(requestSpyCallCount);\n      await expect(\n        waitFor(\n          () => {\n            expect(requestSpy).toHaveBeenCalledTimes(requestSpyCallCount + 1);\n          },\n          { interval: 1, timeout: 20 }\n        )\n      ).rejects.toThrow();\n      expect(requestSpy).toHaveBeenCalledTimes(requestSpyCallCount);\n\n      requestSpy.mockRestore();\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/9431\n    // https://github.com/apollographql/apollo-client/issues/11750\n    it(\"stops polling when component unmounts in strict mode with cache-and-network fetch policy\", async () => {\n      const query: TypedDocumentNode<{ hello: string }> = gql`\n        query {\n          hello\n        }\n      `;\n\n      const mocks: MockLink.MockedResponse[] = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n          delay: 3,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n          delay: 3,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n          delay: 3,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n\n      const link = new MockLink(mocks);\n      const requestSpy = jest.spyOn(link, \"request\");\n\n      const client = new ApolloClient({ link, cache });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, unmount } = await renderHookToSnapshotStream(\n        () =>\n          useQuery(query, {\n            pollInterval: 25,\n            fetchPolicy: \"cache-and-network\",\n          }),\n        {\n          wrapper: ({ children }: any) => (\n            <React.StrictMode>\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            </React.StrictMode>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n        expect(requestSpy).toHaveBeenCalledTimes(1);\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: undefined,\n          variables: {},\n        });\n        expect(requestSpy).toHaveBeenCalledTimes(2);\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n        expect(requestSpy).toHaveBeenCalledTimes(2);\n      }\n\n      unmount();\n\n      await expect(takeSnapshot).not.toRerender({ timeout: 50 });\n      // TODO rarely seeing 3 here investigate further\n      expect(requestSpy).toHaveBeenCalledTimes(2);\n    });\n\n    it(\"should start and stop polling in Strict Mode\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 4\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const link = new MockLink(mocks);\n      const requestSpy = jest.spyOn(link, \"request\");\n      const wrapper = ({ children }: any) => (\n        <React.StrictMode>\n          <MockedProvider link={link} cache={cache}>\n            {children}\n          </MockedProvider>\n        </React.StrictMode>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { pollInterval: 20 }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      getCurrentSnapshot().stopPolling();\n\n      await expect(takeSnapshot).not.toRerender({ timeout: 50 });\n\n      getCurrentSnapshot().startPolling(20);\n\n      expect(requestSpy).toHaveBeenCalledTimes(2);\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 4\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 3\" },\n          variables: {},\n        });\n      }\n\n      expect(requestSpy).toHaveBeenCalledTimes(4);\n      requestSpy.mockRestore();\n    });\n\n    // TODO: This test does not really check for an error so we should probably\n    // do something different. That said, there are several other tests that\n    // call stopPolling on its own so we should either move this up in the test\n    // suite, or delete it as its tested from other tests.\n    it(\"should not throw an error if stopPolling is called manually\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: { hello: \"world\" },\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, unmount } =\n        await renderHookToSnapshotStream(() => useQuery(query), {\n          wrapper,\n        });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      unmount();\n      getCurrentSnapshot().stopPolling();\n    });\n\n    it(\"updates poll interval when rerendering with different pollInterval\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n      let count = 0;\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider\n          mocks={[\n            {\n              request: { query },\n              result: () => ({ data: { hello: `world ${++count}` } }),\n              delay: 10,\n              maxUsageCount: Number.POSITIVE_INFINITY,\n            },\n          ]}\n        >\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        ({ pollInterval }) => useQuery(query, { pollInterval }),\n        { initialProps: { pollInterval: 50 }, wrapper }\n      );\n\n      const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n        }),\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n\n      await rerender({ pollInterval: 100 });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot();\n      await expect(renderStream).not.toRerender({ timeout: 50 });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        // We waited 50ms before, so waiting another 55ms + 50ms = 105ms\n        timeout: 55,\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n        }),\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 3\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 2\" },\n        variables: {},\n      });\n\n      getCurrentSnapshot().stopPolling();\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"stops polling when rerendering with pollInterval 0\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n      let count = 0;\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider\n          mocks={[\n            {\n              request: { query },\n              result: () => ({ data: { hello: `world ${++count}` } }),\n              delay: 10,\n              maxUsageCount: Number.POSITIVE_INFINITY,\n            },\n          ]}\n        >\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        ({ pollInterval }) => useQuery(query, { pollInterval }),\n        { initialProps: { pollInterval: 50 }, wrapper }\n      );\n\n      const { takeSnapshot, rerender } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n        }),\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n\n      await rerender({ pollInterval: 0 });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot();\n      await expect(renderStream).not.toRerender();\n    });\n\n    it(\"starts polling when rerendering with pollInterval > 0\", async () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n      let count = 0;\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider\n          mocks={[\n            {\n              request: { query },\n              result: () => ({ data: { hello: `world ${++count}` } }),\n              delay: 10,\n              maxUsageCount: Number.POSITIVE_INFINITY,\n            },\n          ]}\n        >\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        ({ pollInterval }) => useQuery(query, { pollInterval }),\n        {\n          initialProps: { pollInterval: undefined as number | undefined },\n          wrapper,\n        }\n      );\n\n      const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ pollInterval: 50 });\n\n      await expect(renderStream).toRerenderWithSimilarSnapshot();\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.poll,\n        }),\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n\n      getCurrentSnapshot().stopPolling();\n    });\n\n    describe(\"should prevent fetches when `skipPollAttempt` returns `false`\", () => {\n      it(\"when defined as a global default option\", async () => {\n        using _ = enableFakeTimers();\n        const skipPollAttempt = jest.fn().mockImplementation(() => false);\n\n        const query = gql`\n          {\n            hello\n          }\n        `;\n        const link = new MockLink(\n          [\n            {\n              request: { query },\n              result: { data: { hello: \"world 1\" } },\n            },\n            {\n              request: { query },\n              result: { data: { hello: \"world 2\" } },\n            },\n            {\n              request: { query },\n              result: { data: { hello: \"world 3\" } },\n            },\n          ],\n          { defaultOptions: { delay: 0 } }\n        );\n\n        const client = new ApolloClient({\n          link,\n          cache: new InMemoryCache(),\n          defaultOptions: {\n            watchQuery: {\n              skipPollAttempt,\n            },\n          },\n        });\n\n        const wrapper = ({ children }: any) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        );\n\n        const { result } = renderHook(\n          () => useQuery(query, { pollInterval: 10 }),\n          { wrapper }\n        );\n\n        expect(result.current).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        await waitFor(\n          () => {\n            expect(result.current).toStrictEqualTyped({\n              data: { hello: \"world 1\" },\n              dataState: \"complete\",\n              loading: false,\n              networkStatus: NetworkStatus.ready,\n              previousData: undefined,\n              variables: {},\n            });\n          },\n          { interval: 1 }\n        );\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        skipPollAttempt.mockImplementation(() => true);\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        skipPollAttempt.mockImplementation(() => false);\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      });\n\n      it(\"when defined for a single query\", async () => {\n        using _ = enableFakeTimers();\n        const skipPollAttempt = jest.fn().mockImplementation(() => false);\n\n        const query = gql`\n          {\n            hello\n          }\n        `;\n        const mocks = [\n          {\n            request: { query },\n            result: { data: { hello: \"world 1\" } },\n          },\n          {\n            request: { query },\n            result: { data: { hello: \"world 2\" } },\n          },\n          {\n            request: { query },\n            result: { data: { hello: \"world 3\" } },\n          },\n        ];\n\n        const cache = new InMemoryCache();\n        const wrapper = ({ children }: any) => (\n          <MockedProvider\n            mocks={mocks}\n            cache={cache}\n            // This test uses fake timers and does not expect a delay\n            mockLinkDefaultOptions={{ delay: 0 }}\n            showWarnings={false}\n          >\n            {children}\n          </MockedProvider>\n        );\n\n        const { result } = renderHook(\n          () =>\n            useQuery(query, {\n              pollInterval: 10,\n              skipPollAttempt,\n            }),\n          { wrapper }\n        );\n\n        expect(result.current).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n\n        await waitFor(\n          () => {\n            expect(result.current).toStrictEqualTyped({\n              data: { hello: \"world 1\" },\n              dataState: \"complete\",\n              loading: false,\n              networkStatus: NetworkStatus.ready,\n              previousData: undefined,\n              variables: {},\n            });\n          },\n          { interval: 1 }\n        );\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        skipPollAttempt.mockImplementation(() => true);\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n\n        skipPollAttempt.mockImplementation(() => false);\n\n        await jest.advanceTimersByTimeAsync(12);\n        expect(result.current).toStrictEqualTyped({\n          data: { hello: \"world 3\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: {},\n        });\n      });\n    });\n  });\n\n  describe(\"Error handling\", () => {\n    it(\"should pass along GraphQL errors\", async () => {\n      const query = gql`\n        query TestQuery {\n          rates(currency: \"USD\") {\n            rate\n          }\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error\")],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({ errors: [{ message: \"error\" }] }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    });\n\n    it(\"removes partial data from result when response has errors\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: { hello: null },\n            errors: [{ message: 'Could not fetch \"hello\"' }],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            data: { hello: null },\n            errors: [{ message: 'Could not fetch \"hello\"' }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('returns partial data and discards GraphQL errors when using an `errorPolicy` set to \"ignore\"', async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: { hello: null },\n            errors: [new GraphQLError('Could not fetch \"hello\"')],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { errorPolicy: \"ignore\" }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: null },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('returns no data and discards network errors when using an `errorPolicy` set to \"ignore\"', async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const networkError = new Error(\"Could not fetch\");\n      const mocks = [\n        {\n          request: { query },\n          error: networkError,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { errorPolicy: \"ignore\" }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('returns partial data when returning GraphQL errors while using an `errorPolicy` set to \"all\"', async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: { hello: null },\n            errors: [new GraphQLError('Could not fetch \"hello\"')],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { errorPolicy: \"all\" }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: null },\n          dataState: \"complete\",\n          error: new CombinedGraphQLErrors({\n            data: { hello: null },\n            errors: [{ message: 'Could not fetch \"hello\"' }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it('returns no data when returning network errors while using an `errorPolicy` set to \"all\"', async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const networkError = new Error(\"Could not fetch\");\n      const mocks = [\n        {\n          request: { query },\n          error: networkError,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query, { errorPolicy: \"all\" }),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: networkError,\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should persist errors on re-render if they are still valid\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error\")],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({ errors: [{ message: \"error\" }] }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await rerender();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({ errors: [{ message: \"error\" }] }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Rewrite this test using renderHookToSnapshotStream\n    it(\"should not return partial data from cache on refetch with errorPolicy: none (default) and notifyOnNetworkStatusChange: true\", async () => {\n      const query = gql`\n        {\n          dogs {\n            id\n            breed\n          }\n        }\n      `;\n\n      const GET_DOG_DETAILS = gql`\n        query dog($breed: String!) {\n          dog(breed: $breed) {\n            id\n            unexisting\n          }\n          dogs {\n            id\n            breed\n          }\n        }\n      `;\n\n      const dogData = [\n        {\n          id: \"Z1fdFgU\",\n          breed: \"affenpinscher\",\n          __typename: \"Dog\",\n        },\n        {\n          id: \"ZNDtCU\",\n          breed: \"airedale\",\n          __typename: \"Dog\",\n        },\n      ];\n\n      const detailsMock = (breed: string) => ({\n        request: { query: GET_DOG_DETAILS, variables: { breed } },\n        result: {\n          errors: [\n            { message: `Cannot query field \"unexisting\" on type \"Dog\".` },\n          ],\n        },\n      });\n\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { dogs: dogData } },\n        },\n        // use the same mock for the initial query on select change\n        // and subsequent refetch() call\n        detailsMock(\"airedale\"),\n        detailsMock(\"airedale\"),\n      ];\n      const Dogs: React.FC<{\n        onDogSelected: (event: React.ChangeEvent<HTMLSelectElement>) => void;\n      }> = ({ onDogSelected }) => {\n        const { loading, error, data } = useQuery<{\n          dogs: { id: string; breed: string }[];\n        }>(query);\n\n        if (loading) return <>Loading...</>;\n        if (error) return <>{`Error! ${error.message}`}</>;\n\n        return (\n          <select name=\"dog\" onChange={onDogSelected}>\n            {data?.dogs.map((dog) => (\n              <option key={dog.id} value={dog.breed}>\n                {dog.breed}\n              </option>\n            ))}\n          </select>\n        );\n      };\n\n      const DogDetails: React.FC<{\n        breed: string;\n      }> = ({ breed }) => {\n        const { loading, error, data, refetch, networkStatus } = useQuery(\n          GET_DOG_DETAILS,\n          {\n            variables: { breed },\n            notifyOnNetworkStatusChange: true,\n          }\n        );\n        if (networkStatus === 4) return <p>Refetching!</p>;\n        if (loading) return <p>Loading!</p>;\n        return (\n          <div>\n            <div>{data ? \"Partial data rendered\" : null}</div>\n\n            <div>{error ? `Error!: ${error}` : \"Rendering!\"}</div>\n            <button onClick={() => refetch()}>Refetch!</button>\n          </div>\n        );\n      };\n\n      const ParentComponent: React.FC = () => {\n        const [selectedDog, setSelectedDog] = useState<null | string>(null);\n        function onDogSelected(event: React.ChangeEvent<HTMLSelectElement>) {\n          setSelectedDog(event.target.value);\n        }\n        return (\n          <MockedProvider mocks={mocks}>\n            <div>\n              {selectedDog && <DogDetails breed={selectedDog} />}\n              <Dogs onDogSelected={onDogSelected} />\n            </div>\n          </MockedProvider>\n        );\n      };\n\n      render(<ParentComponent />);\n\n      // on initial load, the list of dogs populates the dropdown\n      await screen.findByText(\"affenpinscher\");\n\n      // the user selects a different dog from the dropdown which\n      // fires the GET_DOG_DETAILS query, retuning an error\n      const user = userEvent.setup();\n      await user.selectOptions(\n        screen.getByRole(\"combobox\"),\n        screen.getByRole(\"option\", { name: \"airedale\" })\n      );\n\n      // With the default errorPolicy of 'none', the error is rendered\n      // and partial data is not\n      await screen.findByText(/Error!: CombinedGraphQLErrors:/);\n      expect(screen.queryByText(/partial data rendered/i)).toBeNull();\n\n      // When we call refetch...\n      await user.click(screen.getByRole(\"button\", { name: /Refetch!/i }));\n\n      // The error is still present, and partial data still not rendered\n      await screen.findByText(/Error!: CombinedGraphQLErrors:/);\n      expect(screen.queryByText(/partial data rendered/i)).toBeNull();\n    });\n\n    // TODO: Rewrite this test using renderHookToSnapshotStream\n    it(\"should return partial data from cache on refetch\", async () => {\n      const GET_DOG_DETAILS = gql`\n        query dog($breed: String!) {\n          dog(breed: $breed) {\n            id\n          }\n        }\n      `;\n      const detailsMock = (breed: string) => ({\n        request: { query: GET_DOG_DETAILS, variables: { breed } },\n        result: {\n          data: {\n            dog: {\n              id: \"ZNDtCU\",\n              __typename: \"Dog\",\n            },\n          },\n        },\n      });\n\n      const mocks = [\n        // use the same mock for the initial query on select change\n        // and subsequent refetch() call\n        detailsMock(\"airedale\"),\n        detailsMock(\"airedale\"),\n      ];\n\n      const DogDetails: React.FC<{\n        breed?: string;\n      }> = ({ breed = \"airedale\" }) => {\n        const { data, refetch, networkStatus } = useQuery(GET_DOG_DETAILS, {\n          variables: { breed },\n        });\n        if (networkStatus === 1) return <p>Loading!</p>;\n        return (\n          // Render existing results, but dim the UI until the results\n          // have finished loading...\n          <div style={{ opacity: networkStatus === 4 ? 0.5 : 1 }}>\n            <div>{data ? \"Data rendered\" : null}</div>\n            <button onClick={() => refetch()}>Refetch!</button>\n          </div>\n        );\n      };\n\n      const ParentComponent: React.FC = () => {\n        return (\n          <MockedProvider mocks={mocks}>\n            <DogDetails />\n          </MockedProvider>\n        );\n      };\n\n      render(<ParentComponent />);\n\n      const user = userEvent.setup();\n\n      await waitFor(\n        () => {\n          expect(screen.getByText(\"Loading!\")).toBeTruthy();\n        },\n        { interval: 1 }\n      );\n\n      await waitFor(\n        () => {\n          expect(screen.getByText(\"Data rendered\")).toBeTruthy();\n        },\n        { interval: 1 }\n      );\n\n      // When we call refetch...\n      await user.click(screen.getByRole(\"button\", { name: /Refetch!/i }));\n\n      // Data from the cache remains onscreen while network request\n      // is made\n      expect(screen.getByText(\"Data rendered\")).toBeTruthy();\n    });\n\n    it(\"should not persist errors when variables change\", async () => {\n      const query = gql`\n        query hello($id: ID) {\n          hello(id: $id)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: {\n            query,\n            variables: { id: 1 },\n          },\n          result: {\n            errors: [new GraphQLError(\"error\")],\n          },\n        },\n        {\n          request: {\n            query,\n            variables: { id: 2 },\n          },\n          result: {\n            data: { hello: \"world 2\" },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: { id: 1 },\n          },\n          result: {\n            data: { hello: \"world 1\" },\n          },\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id }) => useQuery(query, { variables: { id } }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n          initialProps: { id: 1 },\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({ errors: [{ message: \"error\" }] }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      await rerender({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: undefined,\n          variables: { id: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 2 },\n        });\n      }\n\n      await rerender({ id: 1 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: { hello: \"world 2\" },\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 2\" },\n          variables: { id: 1 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should render multiple errors when refetching with notifyOnNetworkStatusChange: true\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error 1\")],\n          },\n        },\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error 2\")],\n          },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { notifyOnNetworkStatusChange: true }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"error 1\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).rejects.toEqual(\n        new CombinedGraphQLErrors({ errors: [{ message: \"error 2\" }] })\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"error 2\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should render multiple errors when refetching with notifyOnNetworkStatusChange: false\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error 1\")],\n          },\n        },\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"error 2\")],\n          },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { notifyOnNetworkStatusChange: false }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"error 1\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).rejects.toEqual(\n        new CombinedGraphQLErrors({ errors: [{ message: \"error 2\" }] })\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"error 2\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should render the same error on refetch\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"same error\")],\n          },\n        },\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"same error\")],\n          },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query), { wrapper });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"same error\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).rejects.toEqual(\n        new CombinedGraphQLErrors({ errors: [{ message: \"same error\" }] })\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"same error\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should render data and errors with refetch\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"same error\")],\n          },\n        },\n        {\n          request: { query },\n          result: {\n            data: { hello: \"world\" },\n          },\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: {\n            errors: [new GraphQLError(\"same error\")],\n          },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query), { wrapper });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"same error\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await getCurrentSnapshot().refetch();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).rejects.toEqual(\n        new CombinedGraphQLErrors({ errors: [{ message: \"same error\" }] })\n      );\n\n      {\n        const result = await takeSnapshot();\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          // TODO: Is this correct behavior here?\n          data: { hello: \"world\" },\n          dataState: \"complete\",\n          error: new CombinedGraphQLErrors({\n            errors: [{ message: \"same error\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    });\n  });\n\n  describe(\"Pagination\", () => {\n    const query = gql`\n      query letters($limit: Int) {\n        letters(limit: $limit) {\n          name\n          position\n        }\n      }\n    `;\n\n    const ab = [\n      { name: \"A\", position: 1 },\n      { name: \"B\", position: 2 },\n    ];\n\n    const cd = [\n      { name: \"C\", position: 3 },\n      { name: \"D\", position: 4 },\n    ];\n\n    // TODO: Include an offset variable so that these tests more closely\n    // resemble a real-world paginated API\n    const mocks = [\n      {\n        request: { query, variables: { limit: 2 } },\n        result: {\n          data: {\n            letters: ab,\n          },\n        },\n      },\n      {\n        request: { query, variables: { limit: 2 } },\n        result: {\n          data: {\n            letters: cd,\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    it(\"should fetchMore with updateQuery\", async () => {\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery<any>(query, { variables: { limit: 2 } }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      const fetchMoreResult = await getCurrentSnapshot().fetchMore({\n        variables: { limit: 2 },\n        updateQuery: (prev, { fetchMoreResult }) => ({\n          letters: prev.letters.concat(fetchMoreResult.letters),\n        }),\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: { letters: cd },\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab.concat(cd) },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { letters: ab },\n          variables: { limit: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should fetchMore with updateQuery and notifyOnNetworkStatusChange\", async () => {\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks}>{children}</MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery<any>(query, {\n              variables: { limit: 2 },\n              notifyOnNetworkStatusChange: true,\n            }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      const fetchMoreResult = await getCurrentSnapshot().fetchMore({\n        variables: { limit: 2 },\n        updateQuery: (prev, { fetchMoreResult }) => ({\n          letters: prev.letters.concat(fetchMoreResult.letters),\n        }),\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: { letters: cd },\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab.concat(cd) },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { letters: ab },\n          variables: { limit: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"fetchMore with concatPagination\", async () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              letters: concatPagination(),\n            },\n          },\n        },\n      });\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { variables: { limit: 2 } }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      const fetchMoreResult = await getCurrentSnapshot().fetchMore({\n        variables: { limit: 2 },\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: { letters: cd },\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab.concat(cd) },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { letters: ab },\n          variables: { limit: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"fetchMore with concatPagination and notifyOnNetworkStatusChange\", async () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              letters: concatPagination(),\n            },\n          },\n        },\n      });\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              variables: { limit: 2 },\n              notifyOnNetworkStatusChange: true,\n            }),\n          { wrapper }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      const fetchMoreResult = await getCurrentSnapshot().fetchMore({\n        variables: { limit: 2 },\n      });\n\n      expect(fetchMoreResult).toStrictEqualTyped({\n        data: { letters: cd },\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { letters: ab.concat(cd) },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { letters: ab },\n          variables: { limit: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // https://github.com/apollographql/apollo-client/issues/11965\n    it(\"should only execute single network request when calling fetchMore with no-cache fetch policy\", async () => {\n      let fetches: Array<{ variables: Record<string, unknown> }> = [];\n      const { query, data } = setupPaginatedCase();\n\n      const link = new ApolloLink((operation) => {\n        fetches.push({ variables: operation.variables });\n\n        const { offset = 0, limit = 2 } = operation.variables;\n        const letters = data.slice(offset, offset + limit);\n\n        return new Observable((observer) => {\n          setTimeout(() => {\n            observer.next({ data: { letters } });\n            observer.complete();\n          }, 10);\n        });\n      });\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"no-cache\",\n              variables: { limit: 2 },\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      // loading\n      await takeSnapshot();\n      // finished loading\n      await takeSnapshot();\n\n      expect(fetches).toStrictEqual([{ variables: { limit: 2 } }]);\n\n      const { fetchMore } = getCurrentSnapshot();\n\n      await fetchMore({\n        variables: { offset: 2 },\n        updateQuery: (_, { fetchMoreResult }) => fetchMoreResult,\n      });\n\n      expect(fetches).toStrictEqual([\n        { variables: { limit: 2 } },\n        { variables: { limit: 2, offset: 2 } },\n      ]);\n    });\n\n    it(\"uses updateQuery to update the result of the query with no-cache queries\", async () => {\n      const { query, link } = setupPaginatedCase();\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"no-cache\",\n              variables: { limit: 2 },\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      const { fetchMore } = getCurrentSnapshot();\n\n      let fetchMorePromise = fetchMore({\n        variables: { offset: 2 },\n        updateQuery: (prev, { fetchMoreResult }) => ({\n          letters: prev.letters.concat(fetchMoreResult.letters),\n        }),\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n            ],\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: undefined,\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n              { __typename: \"Letter\", letter: \"C\", position: 3 },\n              { __typename: \"Letter\", letter: \"D\", position: 4 },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n            ],\n          },\n          variables: { limit: 2 },\n        });\n\n        // Ensure we store the merged result as the last result\n        expect(result.observable.getCurrentResult().data).toEqual({\n          letters: [\n            { __typename: \"Letter\", letter: \"A\", position: 1 },\n            { __typename: \"Letter\", letter: \"B\", position: 2 },\n            { __typename: \"Letter\", letter: \"C\", position: 3 },\n            { __typename: \"Letter\", letter: \"D\", position: 4 },\n          ],\n        });\n      }\n\n      await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"C\", position: 3 },\n            { __typename: \"Letter\", letter: \"D\", position: 4 },\n          ],\n        },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n\n      fetchMorePromise = fetchMore({\n        variables: { offset: 4 },\n        updateQuery: (_, { fetchMoreResult }) => fetchMoreResult,\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n              { __typename: \"Letter\", letter: \"C\", position: 3 },\n              { __typename: \"Letter\", letter: \"D\", position: 4 },\n            ],\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.fetchMore,\n          previousData: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n            ],\n          },\n          variables: { limit: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            letters: [\n              { __typename: \"Letter\", letter: \"E\", position: 5 },\n              { __typename: \"Letter\", letter: \"F\", position: 6 },\n            ],\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            letters: [\n              { __typename: \"Letter\", letter: \"A\", position: 1 },\n              { __typename: \"Letter\", letter: \"B\", position: 2 },\n              { __typename: \"Letter\", letter: \"C\", position: 3 },\n              { __typename: \"Letter\", letter: \"D\", position: 4 },\n            ],\n          },\n          variables: { limit: 2 },\n        });\n\n        expect(result.observable.getCurrentResult().data).toEqual({\n          letters: [\n            { __typename: \"Letter\", letter: \"E\", position: 5 },\n            { __typename: \"Letter\", letter: \"F\", position: 6 },\n          ],\n        });\n      }\n\n      await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"E\", position: 5 },\n            { __typename: \"Letter\", letter: \"F\", position: 6 },\n          ],\n        },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"throws when using fetchMore without updateQuery for no-cache queries\", async () => {\n      const { query, link } = setupPaginatedCase();\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"no-cache\",\n              variables: { limit: 2 },\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      // loading\n      await takeSnapshot();\n      // finished loading\n      await takeSnapshot();\n\n      const { fetchMore } = getCurrentSnapshot();\n\n      expect(() => fetchMore({ variables: { offset: 2 } })).toThrow(\n        new InvariantError(\n          \"You must provide an `updateQuery` function when using `fetchMore` with a `no-cache` fetch policy.\"\n        )\n      );\n    });\n\n    it(\"does not write to cache when using fetchMore with no-cache queries\", async () => {\n      const { query, data } = setupPaginatedCase();\n\n      const link = new ApolloLink((operation) => {\n        const { offset = 0, limit = 2 } = operation.variables;\n        const letters = data.slice(offset, offset + limit);\n\n        return new Observable((observer) => {\n          setTimeout(() => {\n            observer.next({ data: { letters } });\n            observer.complete();\n          }, 10);\n        });\n      });\n\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"no-cache\",\n              variables: { limit: 2 },\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      // initial loading\n      await takeSnapshot();\n\n      // Initial result\n      await takeSnapshot();\n\n      const { fetchMore } = getCurrentSnapshot();\n      await fetchMore({\n        variables: { offset: 2 },\n        updateQuery: (_, { fetchMoreResult }) => fetchMoreResult,\n      });\n\n      expect(client.extract()).toStrictEqual({});\n    });\n\n    it(\"does not allow fetchMore for cache-only queries\", async () => {\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () =>\n            useQuery(query, {\n              fetchPolicy: \"cache-only\",\n              variables: { limit: 2 },\n            }),\n          {\n            wrapper: ({ children }: any) => (\n              <MockedProvider mocks={mocks}>{children}</MockedProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { limit: 2 },\n      });\n\n      expect(() =>\n        getCurrentSnapshot().fetchMore({ variables: { limit: 2 } })\n      ).toThrow(\n        new InvariantError(\n          \"Cannot execute `fetchMore` for 'cache-only' query 'letters'. Please use a different fetch policy.\"\n        )\n      );\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"regression test for issue #8600\", async () => {\n      const cache = new InMemoryCache({\n        typePolicies: {\n          Country: {\n            fields: {\n              cities: {\n                keyArgs: [\"size\"],\n                merge(existing, incoming, { args }) {\n                  if (!args) return incoming;\n\n                  const items = existing ? existing.slice(0) : [];\n\n                  const offset = args.offset ?? 0;\n                  for (let i = 0; i < incoming.length; ++i) {\n                    items[offset + i] = incoming[i];\n                  }\n\n                  return items;\n                },\n              },\n            },\n          },\n          CityInfo: {\n            merge: true,\n          },\n        },\n      });\n\n      const GET_COUNTRIES = gql`\n        query GetCountries {\n          countries {\n            id\n            ...WithSmallCities\n            ...WithAirQuality\n          }\n        }\n        fragment WithSmallCities on Country {\n          biggestCity {\n            id\n          }\n          smallCities: cities(size: SMALL) {\n            id\n          }\n        }\n        fragment WithAirQuality on Country {\n          biggestCity {\n            id\n            info {\n              airQuality\n            }\n          }\n        }\n      `;\n\n      const countries = [\n        {\n          __typename: \"Country\",\n          id: 123,\n          biggestCity: {\n            __typename: \"City\",\n            id: 234,\n            info: {\n              __typename: \"CityInfo\",\n              airQuality: 0,\n            },\n          },\n          smallCities: [{ __typename: \"City\", id: 345 }],\n        },\n      ];\n\n      const wrapper = ({ children }: any) => (\n        <MockedProvider\n          mocks={[\n            {\n              request: { query: GET_COUNTRIES },\n              result: { data: { countries } },\n            },\n          ]}\n          cache={cache}\n        >\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(GET_COUNTRIES),\n        { wrapper }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { countries },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11400\n  it(\"does not return partial data unexpectedly when one query errors, then another succeeds with overlapping data\", async () => {\n    interface Query1 {\n      person: {\n        __typename: \"Person\";\n        id: number;\n        firstName: string;\n        alwaysFails: boolean;\n      } | null;\n    }\n\n    interface Query2 {\n      person: { __typename: \"Person\"; id: number; lastName: string } | null;\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const user = userEvent.setup();\n\n    const query1: TypedDocumentNode<Query1, Variables> = gql`\n      query PersonQuery1($id: ID!) {\n        person(id: $id) {\n          id\n          firstName\n          alwaysFails\n        }\n      }\n    `;\n\n    const query2: TypedDocumentNode<Query2, Variables> = gql`\n      query PersonQuery2($id: ID!) {\n        person(id: $id) {\n          id\n          lastName\n        }\n      }\n    `;\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        useQueryResult: null as useQuery.Result<Query1, Variables> | null,\n        useLazyQueryResult: null as useLazyQuery.Result<\n          Query2,\n          Variables\n        > | null,\n      },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: query1, variables: { id: 1 } },\n          result: {\n            data: { person: null },\n            errors: [new GraphQLError(\"Intentional error\")],\n          },\n          maxUsageCount: Number.POSITIVE_INFINITY,\n          delay: 20,\n        },\n        {\n          request: { query: query2, variables: { id: 1 } },\n          result: {\n            data: { person: { __typename: \"Person\", id: 1, lastName: \"Doe\" } },\n          },\n          delay: 20,\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const useQueryResult = useQuery(query1, {\n        variables: { id: 1 },\n        // This is necessary to reproduce the behavior\n        notifyOnNetworkStatusChange: true,\n      });\n\n      const [execute, useLazyQueryResult] = useLazyQuery(query2, {\n        notifyOnNetworkStatusChange: true,\n      });\n\n      renderStream.replaceSnapshot({ useQueryResult, useLazyQueryResult });\n\n      return (\n        <>\n          <button onClick={() => execute({ variables: { id: 1 } })}>\n            Run 2nd query\n          </button>\n          <button\n            onClick={() => {\n              // Intentionally use reobserve here as opposed to refetch to\n              // ensure we check against reported cache results with cache-first\n              // and notifyOnNetworkStatusChange\n              void useQueryResult.observable.reobserve();\n            }}\n          >\n            Reload 1st query\n          </button>\n        </>\n      );\n    }\n\n    await renderStream.render(<App />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await user.click(screen.getByText(\"Run 2nd query\"));\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      // ensure we aren't setting a value on the observable query that contains\n      // the partial result\n      expect(\n        snapshot.useQueryResult?.observable.getCurrentResult()!\n      ).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: { person: { __typename: \"Person\", id: 1, lastName: \"Doe\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await user.click(screen.getByText(\"Reload 1st query\"));\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: { person: { __typename: \"Person\", id: 1, lastName: \"Doe\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      // ensure we aren't setting a value on the observable query that contains\n      // the partial result\n      expect(\n        snapshot.useQueryResult?.observable.getCurrentResult()!\n      ).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        partial: true,\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: { person: { __typename: \"Person\", id: 1, lastName: \"Doe\" } },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"rerenders errored query for full cache write\", async () => {\n    interface Query1 {\n      person: {\n        __typename: \"Person\";\n        id: number;\n        firstName: string;\n      } | null;\n    }\n\n    interface Query2 {\n      person: {\n        __typename: \"Person\";\n        id: number;\n        firstName: string;\n        lastName: string;\n      } | null;\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const user = userEvent.setup();\n\n    const query1: TypedDocumentNode<Query1, Variables> = gql`\n      query PersonQuery1($id: ID!) {\n        person(id: $id) {\n          id\n          firstName\n        }\n      }\n    `;\n\n    const query2: TypedDocumentNode<Query2, Variables> = gql`\n      query PersonQuery2($id: ID!) {\n        person(id: $id) {\n          id\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        useQueryResult: null as useQuery.Result<Query1, Variables> | null,\n        useLazyQueryResult: null as useLazyQuery.Result<\n          Query2,\n          Variables\n        > | null,\n      },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: query1, variables: { id: 1 } },\n          result: {\n            data: { person: null },\n            errors: [new GraphQLError(\"Intentional error\")],\n          },\n          delay: 20,\n        },\n        {\n          request: { query: query2, variables: { id: 1 } },\n          result: {\n            data: {\n              person: {\n                __typename: \"Person\",\n                id: 1,\n                firstName: \"John\",\n                lastName: \"Doe\",\n              },\n            },\n          },\n          delay: 20,\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const useQueryResult = useQuery(query1, {\n        variables: { id: 1 },\n        // This is necessary to reproduce the behavior\n        notifyOnNetworkStatusChange: true,\n      });\n\n      const [execute, useLazyQueryResult] = useLazyQuery(query2, {\n        notifyOnNetworkStatusChange: true,\n      });\n\n      renderStream.replaceSnapshot({ useQueryResult, useLazyQueryResult });\n\n      return (\n        <button onClick={() => execute({ variables: { id: 1 } })}>\n          Run 2nd query\n        </button>\n      );\n    }\n\n    await renderStream.render(<App />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await user.click(screen.getByText(\"Run 2nd query\"));\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      // We don't see the update from the cache for one more render cycle, hence\n      // why this is still showing the error result even though the result from\n      // the other query has finished and re-rendered.\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: {\n          person: {\n            __typename: \"Person\",\n            id: 1,\n            firstName: \"John\",\n            lastName: \"Doe\",\n          },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: {\n          person: {\n            __typename: \"Person\",\n            id: 1,\n            firstName: \"John\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: {\n          person: {\n            __typename: \"Person\",\n            id: 1,\n            firstName: \"John\",\n            lastName: \"Doe\",\n          },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"does not rerender or refetch queries with errors for partial cache writes with returnPartialData: true\", async () => {\n    interface Query1 {\n      person: {\n        __typename: \"Person\";\n        id: number;\n        firstName: string;\n        alwaysFails: boolean;\n      } | null;\n    }\n\n    interface Query2 {\n      person: {\n        __typename: \"Person\";\n        id: number;\n        lastName: string;\n      } | null;\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const user = userEvent.setup();\n\n    const query1: TypedDocumentNode<Query1, Variables> = gql`\n      query PersonQuery1($id: ID!) {\n        person(id: $id) {\n          id\n          firstName\n          alwaysFails\n        }\n      }\n    `;\n\n    const query2: TypedDocumentNode<Query2, Variables> = gql`\n      query PersonQuery2($id: ID!) {\n        person(id: $id) {\n          id\n          lastName\n        }\n      }\n    `;\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        useQueryResult: null as useQuery.Result<Query1, Variables> | null,\n        useLazyQueryResult: null as useLazyQuery.Result<\n          Query2,\n          Variables\n        > | null,\n      },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query: query1, variables: { id: 1 } },\n          result: {\n            data: { person: null },\n            errors: [new GraphQLError(\"Intentional error\")],\n          },\n          delay: 20,\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n        {\n          request: { query: query2, variables: { id: 1 } },\n          result: {\n            data: {\n              person: {\n                __typename: \"Person\",\n                id: 1,\n                lastName: \"Doe\",\n              },\n            },\n          },\n          delay: 20,\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const useQueryResult = useQuery(query1, {\n        variables: { id: 1 },\n        notifyOnNetworkStatusChange: true,\n        returnPartialData: true,\n      });\n\n      const [execute, useLazyQueryResult] = useLazyQuery(query2, {\n        notifyOnNetworkStatusChange: true,\n      });\n\n      renderStream.replaceSnapshot({ useQueryResult, useLazyQueryResult });\n\n      return (\n        <button onClick={() => execute({ variables: { id: 1 } })}>\n          Run 2nd query\n        </button>\n      );\n    }\n\n    await renderStream.render(<App />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: false,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await user.click(screen.getByText(\"Run 2nd query\"));\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        called: true,\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { person: null },\n          errors: [{ message: \"Intentional error\" }],\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(snapshot.useLazyQueryResult!).toStrictEqualTyped({\n        data: {\n          person: {\n            __typename: \"Person\",\n            id: 1,\n            lastName: \"Doe\",\n          },\n        },\n        dataState: \"complete\",\n        called: true,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"delivers the full network response when a merge function returns an incomplete result\", async () => {\n    const query = gql`\n      query {\n        author {\n          id\n          name\n          post {\n            id\n            title\n          }\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query },\n          result: {\n            data: {\n              author: {\n                __typename: \"Author\",\n                id: 1,\n                name: \"Author Lee\",\n                post: {\n                  __typename: \"Post\",\n                  id: 1,\n                  title: \"Title\",\n                },\n              },\n            },\n          },\n          delay: 20,\n        },\n      ]),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Author: {\n            fields: {\n              post: {\n                merge: () => {\n                  return {};\n                },\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const result = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const result = await takeSnapshot();\n\n      expect(result).toStrictEqualTyped({\n        data: {\n          author: {\n            __typename: \"Author\",\n            id: 1,\n            name: \"Author Lee\",\n            post: {\n              __typename: \"Post\",\n              id: 1,\n              title: \"Title\",\n            },\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"triggers a network request and rerenders with the new result when a mutation causes a partial cache update due to an incomplete merge function result\", async () => {\n    const query = gql`\n      query {\n        author {\n          id\n          name\n          post {\n            id\n            title\n          }\n        }\n      }\n    `;\n    const mutation = gql`\n      mutation {\n        updateAuthor {\n          author {\n            id\n            name\n            post {\n              id\n              title\n            }\n          }\n        }\n      }\n    `;\n\n    const user = userEvent.setup();\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        useQueryResult: null as useQuery.Result | null,\n      },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query },\n          result: {\n            data: {\n              author: {\n                __typename: \"Author\",\n                id: 1,\n                name: \"Author Lee\",\n                post: {\n                  __typename: \"Post\",\n                  id: 1,\n                  title: \"Title\",\n                },\n              },\n            },\n          },\n          delay: 20,\n        },\n        {\n          request: { query },\n          result: {\n            data: {\n              author: {\n                __typename: \"Author\",\n                id: 1,\n                name: \"Author Lee (refetch)\",\n                post: {\n                  __typename: \"Post\",\n                  id: 1,\n                  title: \"Title\",\n                },\n              },\n            },\n          },\n          delay: 20,\n        },\n        {\n          request: { query: mutation },\n          result: {\n            data: {\n              updateAuthor: {\n                author: {\n                  __typename: \"Author\",\n                  id: 1,\n                  name: \"Author Lee (mutation)\",\n                  post: {\n                    __typename: \"Post\",\n                    id: 1,\n                    title: \"Title\",\n                  },\n                },\n              },\n            },\n          },\n          delay: 20,\n        },\n      ]),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Author: {\n            fields: {\n              post: {\n                // this is necessary to reproduce the issue\n                merge: () => {\n                  return {};\n                },\n              },\n            },\n          },\n        },\n      }),\n    });\n\n    function App() {\n      const useQueryResult = useQuery(query);\n      const [mutate] = useMutation(mutation);\n\n      renderStream.replaceSnapshot({ useQueryResult });\n\n      return <button onClick={() => mutate()}>Run mutation</button>;\n    }\n\n    await renderStream.render(<App />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: {\n          author: {\n            __typename: \"Author\",\n            id: 1,\n            name: \"Author Lee\",\n            post: {\n              __typename: \"Post\",\n              id: 1,\n              title: \"Title\",\n            },\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await user.click(screen.getByText(\"Run mutation\"));\n    // Mutation started\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: {\n          author: {\n            __typename: \"Author\",\n            id: 1,\n            name: \"Author Lee\",\n            post: {\n              __typename: \"Post\",\n              id: 1,\n              title: \"Title\",\n            },\n          },\n        },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    // Mutation completed\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.useQueryResult!).toStrictEqualTyped({\n        data: {\n          author: {\n            __typename: \"Author\",\n            id: 1,\n            // Because of the merge function returning an incomplete result, we\n            // don't expect to see the value returned from the mutation. The\n            // partial result from the mutation causes a network fetch which\n            // renders the refetched result.\n            name: \"Author Lee (refetch)\",\n            post: {\n              __typename: \"Post\",\n              id: 1,\n              title: \"Title\",\n            },\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          author: {\n            __typename: \"Author\",\n            id: 1,\n            name: \"Author Lee\",\n            post: {\n              __typename: \"Post\",\n              id: 1,\n              title: \"Title\",\n            },\n          },\n        },\n        variables: {},\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  describe(\"Refetching\", () => {\n    it(\"refetching with different variables\", async () => {\n      const query = gql`\n        query ($id: Int) {\n          hello(id: $id)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query, variables: { id: 1 } },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query, variables: { id: 2 } },\n          result: { data: { hello: \"world 2\" } },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { variables: { id: 1 } }),\n          { wrapper }\n        );\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      await getCurrentSnapshot().refetch({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: { id: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"refetching after an error\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query },\n          error: new Error(\"This is an error!\"),\n          delay: 10,\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n          delay: 10,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query), {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks} cache={cache}>\n              {children}\n            </MockedProvider>\n          ),\n        });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).rejects.toEqual(\n        new Error(\"This is an error!\")\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          error: new Error(\"This is an error!\"),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n      });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 1\" },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: { hello: \"world 2\" },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: { hello: \"world 1\" },\n          variables: {},\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"allows refetch on a cache-only query\", async () => {\n      const query = gql`\n        query Greeting {\n          hello\n        }\n      `;\n      const link = new ApolloLink(() =>\n        of({\n          data: { hello: \"world\" },\n        })\n      );\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { fetchPolicy: \"cache-only\" }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    describe(\"refetchWritePolicy\", () => {\n      const query = gql`\n        query GetPrimes($min: number, $max: number) {\n          primes(min: $min, max: $max)\n        }\n      `;\n\n      const mocks = [\n        {\n          request: {\n            query,\n            variables: { min: 0, max: 12 },\n          },\n          result: {\n            data: {\n              primes: [2, 3, 5, 7, 11],\n            },\n          },\n        },\n        {\n          request: {\n            query,\n            variables: { min: 12, max: 30 },\n          },\n          result: {\n            data: {\n              primes: [13, 17, 19, 23, 29],\n            },\n          },\n          delay: 25,\n        },\n      ];\n\n      it('should support explicit \"overwrite\"', async () => {\n        const mergeParams: [any, any][] = [];\n        const cache = new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                primes: {\n                  keyArgs: false,\n                  merge(existing, incoming) {\n                    mergeParams.push([existing, incoming]);\n                    return existing ? existing.concat(incoming) : incoming;\n                  },\n                },\n              },\n            },\n          },\n        });\n\n        const wrapper = ({ children }: any) => (\n          <MockedProvider mocks={mocks} cache={cache}>\n            {children}\n          </MockedProvider>\n        );\n\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot, getCurrentSnapshot } =\n          await renderHookToSnapshotStream(\n            () =>\n              useQuery(query, {\n                variables: { min: 0, max: 12 },\n                // This is the key line in this test.\n                refetchWritePolicy: \"overwrite\",\n              }),\n            { wrapper }\n          );\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n        }\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [2, 3, 5, 7, 11] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n        }\n\n        expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n        await expect(\n          getCurrentSnapshot().refetch({ min: 12, max: 30 })\n        ).resolves.toStrictEqualTyped({\n          data: { primes: [13, 17, 19, 23, 29] },\n        });\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            // We get the stale data because we configured keyArgs: false.\n            data: { primes: [2, 3, 5, 7, 11] },\n            dataState: \"complete\",\n            loading: true,\n            // This networkStatus is setVariables instead of refetch because we\n            // called refetch with new variables.\n            networkStatus: NetworkStatus.refetch,\n            previousData: undefined,\n            variables: { min: 12, max: 30 },\n          });\n        }\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [13, 17, 19, 23, 29] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: { primes: [2, 3, 5, 7, 11] },\n            variables: { min: 12, max: 30 },\n          });\n        }\n\n        expect(mergeParams).toEqual([\n          [undefined, [2, 3, 5, 7, 11]],\n          // Without refetchWritePolicy: \"overwrite\", this array will be\n          // all 10 primes (2 through 29) together.\n          [undefined, [13, 17, 19, 23, 29]],\n        ]);\n      });\n\n      it('should support explicit \"merge\"', async () => {\n        const mergeParams: [any, any][] = [];\n        const cache = new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                primes: {\n                  keyArgs: false,\n                  merge(existing, incoming) {\n                    mergeParams.push([existing, incoming]);\n                    return existing ? [...existing, ...incoming] : incoming;\n                  },\n                },\n              },\n            },\n          },\n        });\n\n        const wrapper = ({ children }: any) => (\n          <MockedProvider mocks={mocks} cache={cache}>\n            {children}\n          </MockedProvider>\n        );\n\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot, getCurrentSnapshot } =\n          await renderHookToSnapshotStream(\n            () =>\n              useQuery(query, {\n                variables: { min: 0, max: 12 },\n                // This is the key line in this test.\n                refetchWritePolicy: \"merge\",\n              }),\n            { wrapper }\n          );\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n        }\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [2, 3, 5, 7, 11] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n        }\n\n        expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n        await expect(\n          getCurrentSnapshot().refetch({ min: 12, max: 30 })\n        ).resolves.toStrictEqualTyped({\n          data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n        });\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            // We get the stale data because we configured keyArgs: false.\n            data: { primes: [2, 3, 5, 7, 11] },\n            dataState: \"complete\",\n            loading: true,\n            // This networkStatus is setVariables instead of refetch because we\n            // called refetch with new variables.\n            networkStatus: NetworkStatus.refetch,\n            previousData: undefined,\n            variables: { min: 12, max: 30 },\n          });\n        }\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: { primes: [2, 3, 5, 7, 11] },\n            variables: { min: 12, max: 30 },\n          });\n        }\n\n        expect(mergeParams).toEqual([\n          [undefined, [2, 3, 5, 7, 11]],\n          // This indicates concatenation happened.\n          [\n            [2, 3, 5, 7, 11],\n            [13, 17, 19, 23, 29],\n          ],\n        ]);\n      });\n\n      it('should assume default refetchWritePolicy value is \"overwrite\"', async () => {\n        const mergeParams: [any, any][] = [];\n        const cache = new InMemoryCache({\n          typePolicies: {\n            Query: {\n              fields: {\n                primes: {\n                  keyArgs: false,\n                  merge(existing, incoming) {\n                    mergeParams.push([existing, incoming]);\n                    return existing ? existing.concat(incoming) : incoming;\n                  },\n                },\n              },\n            },\n          },\n        });\n\n        const wrapper = ({ children }: any) => (\n          <MockedProvider mocks={mocks} cache={cache}>\n            {children}\n          </MockedProvider>\n        );\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot, getCurrentSnapshot } =\n          await renderHookToSnapshotStream(\n            () =>\n              useQuery(query, {\n                variables: { min: 0, max: 12 },\n                // Intentionally not passing refetchWritePolicy.\n              }),\n            { wrapper }\n          );\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: undefined,\n            dataState: \"empty\",\n            loading: true,\n            networkStatus: NetworkStatus.loading,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n        }\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [2, 3, 5, 7, 11] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: undefined,\n            variables: { min: 0, max: 12 },\n          });\n          expect(mergeParams.shift()).toEqual([void 0, [2, 3, 5, 7, 11]]);\n        }\n\n        await expect(\n          getCurrentSnapshot().refetch({ min: 12, max: 30 })\n        ).resolves.toStrictEqualTyped({\n          data: { primes: [13, 17, 19, 23, 29] },\n        });\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: {\n              // We get the stale data because we configured keyArgs: false.\n              primes: [2, 3, 5, 7, 11],\n            },\n            dataState: \"complete\",\n            loading: true,\n            // This networkStatus is setVariables instead of refetch because we\n            // called refetch with new variables.\n            networkStatus: NetworkStatus.refetch,\n            previousData: undefined,\n            variables: { min: 12, max: 30 },\n          });\n        }\n\n        {\n          const result = await takeSnapshot();\n\n          expect(result).toStrictEqualTyped({\n            data: { primes: [13, 17, 19, 23, 29] },\n            dataState: \"complete\",\n            loading: false,\n            networkStatus: NetworkStatus.ready,\n            previousData: { primes: [2, 3, 5, 7, 11] },\n            variables: { min: 12, max: 30 },\n          });\n          expect(mergeParams.shift()).toEqual(\n            // Without refetchWritePolicy: \"overwrite\", this array will be\n            // all 10 primes (2 through 29) together.\n            [undefined, [13, 17, 19, 23, 29]]\n          );\n        }\n      });\n    });\n\n    it(\"keeps cache consistency when a call to refetchQueries is interrupted with another query caused by changing variables and the second query returns before the first one\", async () => {\n      const CAR_QUERY_BY_ID = gql`\n        query Car($id: Int) {\n          car(id: $id) {\n            make\n            model\n          }\n        }\n      `;\n\n      const mocks = {\n        1: [\n          {\n            car: {\n              make: \"Audi\",\n              model: \"A4\",\n              __typename: \"Car\",\n            },\n          },\n          {\n            car: {\n              make: \"Audi\",\n              model: \"A3\", // Changed\n              __typename: \"Car\",\n            },\n          },\n        ],\n        2: [\n          {\n            car: {\n              make: \"Audi\",\n              model: \"RS8\",\n              __typename: \"Car\",\n            },\n          },\n        ],\n      };\n\n      const link = new ApolloLink(\n        (operation) =>\n          new Observable((observer) => {\n            if (operation.variables.id === 1) {\n              // Queries for this ID return after a delay\n              setTimeout(() => {\n                const data = mocks[1].splice(0, 1).pop();\n                observer.next({ data });\n                observer.complete();\n              }, 100);\n            } else if (operation.variables.id === 2) {\n              // Queries for this ID return immediately\n              const data = mocks[2].splice(0, 1).pop();\n              // Delay execution so we can obseve the loading state\n              setTimeout(() => {\n                observer.next({ data });\n                observer.complete();\n              });\n            } else {\n              observer.error(new Error(\"Unexpected query\"));\n            }\n          })\n      );\n      const client = new ApolloClient({ cache: new InMemoryCache(), link });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id }) =>\n          useQuery(CAR_QUERY_BY_ID, {\n            variables: { id },\n            fetchPolicy: \"network-only\",\n          }),\n        {\n          initialProps: { id: 1 },\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            car: {\n              __typename: \"Car\",\n              make: \"Audi\",\n              model: \"A4\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      void client.refetchObservableQueries();\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            car: {\n              __typename: \"Car\",\n              make: \"Audi\",\n              model: \"A4\",\n            },\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n          previousData: undefined,\n          variables: { id: 1 },\n        });\n      }\n\n      // Rerender with new variables before the refetch request completes\n      await rerender({ id: 2 });\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.setVariables,\n          previousData: {\n            car: {\n              __typename: \"Car\",\n              make: \"Audi\",\n              model: \"A4\",\n            },\n          },\n          variables: { id: 2 },\n        });\n      }\n\n      {\n        const result = await takeSnapshot();\n\n        expect(result).toStrictEqualTyped({\n          data: {\n            car: {\n              __typename: \"Car\",\n              make: \"Audi\",\n              model: \"RS8\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            car: {\n              __typename: \"Car\",\n              make: \"Audi\",\n              model: \"A4\",\n            },\n          },\n          variables: { id: 2 },\n        });\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"Optimistic data\", () => {\n    it(\"should display rolled back optimistic data when an error occurs\", async () => {\n      if (IS_REACT_17) {\n        // this test is currently broken in React 17 with RTL 16 and needs further investigation\n        return;\n      }\n      const query = gql`\n        query AllCars {\n          cars {\n            id\n            make\n            model\n          }\n        }\n      `;\n\n      const carsData = {\n        cars: [\n          {\n            id: 1,\n            make: \"Audi\",\n            model: \"RS8\",\n            __typename: \"Car\",\n          },\n        ],\n      };\n\n      const mutation = gql`\n        mutation AddCar {\n          addCar {\n            id\n            make\n            model\n          }\n        }\n      `;\n\n      const carData = {\n        id: 2,\n        make: \"Ford\",\n        model: \"Pinto\",\n        __typename: \"Car\",\n      };\n\n      const allCarsData = {\n        cars: [carsData.cars[0], carData],\n      };\n\n      const mocks = [\n        {\n          request: { query },\n          result: { data: carsData },\n        },\n        {\n          request: { query: mutation },\n          error: new Error(\"Oh no!\"),\n          delay: 500,\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      const onError = jest.fn();\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => ({\n            mutation: useMutation<any>(mutation, {\n              optimisticResponse: { addCar: carData },\n              update(cache, { data }) {\n                cache.modify({\n                  fields: {\n                    cars(existing, { readField }) {\n                      const newCarRef = cache.writeFragment({\n                        data: data!.addCar,\n                        fragment: gql`\n                          fragment NewCar on Car {\n                            id\n                            make\n                            model\n                          }\n                        `,\n                      });\n\n                      if (\n                        existing.some(\n                          (ref: Reference) =>\n                            readField(\"id\", ref) === data!.addCar.id\n                        )\n                      ) {\n                        return existing;\n                      }\n\n                      return [...existing, newCarRef];\n                    },\n                  },\n                });\n              },\n              onError,\n            }),\n            query: useQuery(query),\n          }),\n          { wrapper }\n        );\n\n      {\n        const { query } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const { query } = await takeSnapshot();\n\n        expect(query).toStrictEqualTyped({\n          data: carsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      const mutate = getCurrentSnapshot().mutation[0];\n      void mutate().catch(() => {});\n\n      {\n        // The mutation ran and is loading the result. The query stays at not\n        // loading as nothing has changed for the query, but optimistic data is\n        // rendered.\n        let { query, mutation } = await takeSnapshot();\n\n        while (!mutation[1].loading) {\n          // useMutation seems to sometimes have an extra render\n          // before it enters `loading` state - this test doesn't test\n          // that part of that hook so we just work around it\n          ({ query, mutation } = await takeSnapshot());\n        }\n        expect(mutation[1].loading).toBe(true);\n        expect(query).toStrictEqualTyped({\n          data: allCarsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: carsData,\n          variables: {},\n        });\n      }\n\n      expect(onError).toHaveBeenCalledTimes(0);\n      {\n        const { query, mutation } = await takeSnapshot();\n        // The mutation ran and is loading the result. The query stays at\n        // not loading as nothing has changed for the query.\n        expect(mutation[1].loading).toBe(true);\n        expect(query).toStrictEqualTyped({\n          data: carsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: allCarsData,\n          variables: {},\n        });\n      }\n\n      {\n        const { query, mutation } = await takeSnapshot();\n        // The mutation has completely finished, leaving the query with access to\n        // the original cache data.\n        expect(mutation[1].loading).toBe(false);\n        expect(query).toStrictEqualTyped({\n          data: carsData,\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: allCarsData,\n          variables: {},\n        });\n      }\n\n      expect(onError).toHaveBeenCalledTimes(1);\n      expect(onError.mock.calls[0][0].message).toBe(\"Oh no!\");\n    });\n  });\n\n  describe(\"Client Resolvers\", () => {\n    it(\"should receive up to date @client(always: true) fields on entity update\", async () => {\n      const query = gql`\n        query GetClientData($id: ID) {\n          clientEntity(id: $id) @client(always: true) {\n            id\n            title\n            titleLength @client(always: true)\n          }\n        }\n      `;\n\n      const mutation = gql`\n        mutation AddOrUpdate {\n          addOrUpdate(id: $id, title: $title) @client\n        }\n      `;\n\n      const fragment = gql`\n        fragment ClientDataFragment on ClientData {\n          id\n          title\n        }\n      `;\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(() => of({ data: {} })),\n        localState: new LocalState({\n          resolvers: {\n            ClientData: {\n              titleLength(data) {\n                return data.title.length;\n              },\n            },\n            Query: {\n              clientEntity(_root, { id }, { client }) {\n                const { cache } = client;\n\n                return cache.readFragment({\n                  id: cache.identify({ id, __typename: \"ClientData\" }),\n                  fragment,\n                });\n              },\n            },\n            Mutation: {\n              addOrUpdate(_root, { id, title }, { client }) {\n                const { cache } = client;\n\n                return cache.writeFragment({\n                  id: cache.identify({ id, __typename: \"ClientData\" }),\n                  fragment,\n                  data: { id, title, __typename: \"ClientData\" },\n                });\n              },\n            },\n          },\n        }),\n      });\n\n      const entityId = 1;\n      const shortTitle = \"Short\";\n      const longerTitle = \"A little longer\";\n      await client.mutate({\n        mutation,\n        variables: {\n          id: entityId,\n          title: shortTitle,\n        },\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        () => useQuery(query, { variables: { id: entityId } }),\n        { wrapper }\n      );\n      const { takeSnapshot } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: entityId },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          clientEntity: {\n            id: entityId,\n            title: shortTitle,\n            titleLength: shortTitle.length,\n            __typename: \"ClientData\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: entityId },\n      });\n\n      void client.mutate({\n        mutation,\n        variables: {\n          id: entityId,\n          title: longerTitle,\n        },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          clientEntity: {\n            id: entityId,\n            title: longerTitle,\n            titleLength: longerTitle.length,\n            __typename: \"ClientData\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          clientEntity: {\n            id: entityId,\n            title: shortTitle,\n            titleLength: shortTitle.length,\n            __typename: \"ClientData\",\n          },\n        },\n        variables: { id: entityId },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"Skipping\", () => {\n    const query = gql`\n      query greeting($someVar: Boolean) {\n        hello\n      }\n    `;\n    const mocks = [\n      {\n        request: { query },\n        result: { data: { hello: \"world\" } },\n      },\n      {\n        request: {\n          query,\n          variables: { someVar: true },\n        },\n        result: { data: { hello: \"world\" } },\n      },\n    ];\n\n    it(\"should skip running a query when `skip` is `true`\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ skip }) => useQuery(query, { skip }),\n        { wrapper, initialProps: { skip: true } }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ skip: false });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should skip running a query when providing skipToken\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        (options: SkipToken | useQuery.Options | undefined) =>\n          useQuery(query, options),\n        { wrapper, initialProps: skipToken }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender();\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should not make network requests when `skip` is `true`\", async () => {\n      const linkFn = jest.fn();\n      const link = new ApolloLink((o, f) => {\n        linkFn();\n        return f ? f(o) : EMPTY;\n      }).concat(new MockLink(mocks));\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ skip, variables }) => useQuery(query, { skip, variables }),\n        { wrapper, initialProps: { skip: false, variables: undefined as any } }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ skip: true, variables: { someVar: true } });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world\" },\n        variables: { someVar: true },\n      });\n\n      expect(linkFn).toHaveBeenCalledTimes(1);\n    });\n\n    it(\"should not make network requests when using skipToken\", async () => {\n      const linkFn = jest.fn();\n      const link = new ApolloLink((o, f) => {\n        linkFn();\n        return f ? f(o) : EMPTY;\n      }).concat(new MockLink(mocks));\n      const client = new ApolloClient({\n        link,\n        cache: new InMemoryCache(),\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      type Opts = SkipToken | useQuery.Options;\n      using _disabledAct = disableActEnvironment();\n      const renderStream = await renderHookToSnapshotStream(\n        (options: Opts) => useQuery(query, options),\n        { wrapper, initialProps: { variables: undefined } as Opts }\n      );\n      const { takeSnapshot, rerender } = renderStream;\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender(skipToken);\n\n      // new variables aren't applied yet so we see the same value returned\n      await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n      expect(linkFn).toHaveBeenCalledTimes(1);\n    });\n\n    it(\"should tear down the query if `skip` is `true`\", async () => {\n      const client = new ApolloClient({\n        link: new ApolloLink(() => of({ data: { hello: \"world\" } })),\n        cache: new InMemoryCache(),\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      const { unmount } = renderHook(() => useQuery(query, { skip: true }), {\n        wrapper,\n      });\n\n      expect(client.getObservableQueries(\"all\").size).toBe(1);\n      unmount();\n      await wait(0);\n      expect(client.getObservableQueries(\"all\").size).toBe(0);\n    });\n\n    it(\"should tear down the query if using skipToken\", async () => {\n      const client = new ApolloClient({\n        link: new ApolloLink(() => of({ data: { hello: \"world\" } })),\n        cache: new InMemoryCache(),\n      });\n\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      const { unmount } = renderHook(() => useQuery(query, skipToken), {\n        wrapper,\n      });\n\n      expect(client.getObservableQueries(\"all\").size).toBe(1);\n      unmount();\n      await wait(0);\n      expect(client.getObservableQueries(\"all\").size).toBe(0);\n    });\n\n    it(\"should treat fetchPolicy standby like skip\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ fetchPolicy }) => useQuery(query, { fetchPolicy }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n          initialProps: { fetchPolicy: \"standby\" as any },\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ fetchPolicy: \"cache-first\" });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"client.refetchQueries should not refetch queries that start with skipToken until they have been executed\", async () => {\n      const query = gql`\n        query getAuthor($id: ID!) {\n          author(id: $id) {\n            firstName\n            lastName\n          }\n        }\n      `;\n      const data = {\n        author: {\n          firstName: \"John\",\n          lastName: \"Smith\",\n        },\n      };\n      const secondReqData = {\n        author: {\n          firstName: \"Jane\",\n          lastName: \"Johnson\",\n        },\n      };\n\n      const operationSubject = new Subject<ApolloLink.Operation>();\n      const link = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink((operation, forward) => {\n          operationSubject.next(operation);\n          return forward(operation);\n        }).concat(link),\n      });\n\n      const operationStream = new ObservableStream(operationSubject);\n      const wrapper = ({ children }: any) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          (options: SkipToken | useQuery.Options<any, any>) =>\n            useQuery(query, options),\n          { wrapper, initialProps: skipToken }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n      expect(getCurrentSnapshot().observable[\"variablesUnknown\"]).toBe(true);\n      await expect(operationStream).not.toEmitAnything();\n\n      void client.refetchQueries({ include: [query] });\n      await expect(takeSnapshot).not.toRerender();\n      await expect(operationStream).not.toEmitAnything();\n\n      await rerender({ variables: { id: \"1234\" } });\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { id: \"1234\" },\n      });\n      await expect(operationStream).toEmitNext();\n\n      link.simulateResult({ result: { data } });\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: \"1234\" },\n      });\n\n      link.simulateResult({ result: { data: secondReqData } }, true);\n      await client.refetchQueries({ include: [query] });\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: secondReqData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data,\n        variables: { id: \"1234\" },\n      });\n    });\n\n    it(\"should not automatically set `data` to `undefined` when `skip` becomes `true`\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ skip }) => useQuery(query, { skip }),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n          initialProps: { skip: false },\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ skip: true });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should not automatically set `data` to `undefined` when providing skipToken\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        (options: SkipToken | undefined) => useQuery(query, options),\n        {\n          wrapper: ({ children }) => (\n            <MockedProvider mocks={mocks}>{children}</MockedProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender(skipToken);\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // Amusingly, #8270 thinks this is a bug, but #9101 thinks this is not.\n    it(\"should refetch when skip is true\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const link = new ApolloLink(() =>\n        of({\n          data: { hello: \"world\" },\n        })\n      );\n\n      const requestSpy = jest.spyOn(link, \"request\");\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(\n          () => useQuery(query, { skip: true }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      const refetchResult = await getCurrentSnapshot().refetch();\n\n      expect(refetchResult).toStrictEqualTyped({\n        data: { hello: \"world\" },\n      });\n\n      expect(requestSpy).toHaveBeenCalledTimes(1);\n      requestSpy.mockRestore();\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should refetch when providing skipToken\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const link = new ApolloLink(() =>\n        of({\n          data: { hello: \"world\" },\n        })\n      );\n\n      const requestSpy = jest.spyOn(link, \"request\");\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query, skipToken), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      const refetchResult = await getCurrentSnapshot().refetch();\n\n      expect(refetchResult).toStrictEqualTyped({\n        data: { hello: \"world\" },\n      });\n\n      expect(requestSpy).toHaveBeenCalledTimes(1);\n      requestSpy.mockRestore();\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should set correct initialFetchPolicy even if skip:true\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      let linkCount = 0;\n      const link = new ApolloLink(() =>\n        // Emit the value  async so we can observe the loading state\n        of({ data: { hello: ++linkCount } }).pipe(observeOn(asapScheduler))\n      );\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      const correctInitialFetchPolicy: WatchQueryFetchPolicy =\n        \"cache-and-network\";\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ skip }) =>\n            useQuery(query, {\n              // Skipping equates to using a fetchPolicy of \"standby\", but that\n              // should not mean we revert to standby whenever we want to go back to\n              // the initial fetchPolicy (e.g. when variables change).\n              skip,\n              fetchPolicy: correctInitialFetchPolicy,\n            }),\n          {\n            initialProps: {\n              skip: true,\n            },\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      function check(\n        expectedFetchPolicy: WatchQueryFetchPolicy,\n        expectedInitialFetchPolicy: WatchQueryFetchPolicy\n      ) {\n        const { observable } = getCurrentSnapshot();\n        const { fetchPolicy, initialFetchPolicy } = observable.options;\n\n        expect(fetchPolicy).toBe(expectedFetchPolicy);\n        expect(initialFetchPolicy).toBe(expectedInitialFetchPolicy);\n      }\n\n      check(\"standby\", correctInitialFetchPolicy);\n\n      await rerender({ skip: false });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 1 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      check(correctInitialFetchPolicy, correctInitialFetchPolicy);\n\n      const reasons: string[] = [];\n\n      const result = await getCurrentSnapshot().observable.reobserve({\n        variables: {\n          newVar: true,\n        },\n        nextFetchPolicy(currentFetchPolicy, context) {\n          expect(currentFetchPolicy).toBe(\"cache-and-network\");\n          expect(context.initialFetchPolicy).toBe(\"cache-and-network\");\n          reasons.push(context.reason);\n          return currentFetchPolicy;\n        },\n      });\n\n      expect(result).toStrictEqualTyped({ data: { hello: 2 } });\n      expect(reasons).toEqual([\"variables-changed\", \"after-fetch\"]);\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 1 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { newVar: true },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 2 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: 1 },\n        variables: { newVar: true },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should set correct initialFetchPolicy when using skipToken\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      let linkCount = 0;\n      const link = new ApolloLink(() =>\n        // Emit the value  async so we can observe the loading state\n        of({ data: { hello: ++linkCount } }).pipe(observeOn(asapScheduler))\n      );\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          (options: SkipToken | useQuery.Options) => useQuery(query, options),\n          {\n            initialProps: skipToken,\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      function check(\n        expectedFetchPolicy: WatchQueryFetchPolicy,\n        expectedInitialFetchPolicy: WatchQueryFetchPolicy\n      ) {\n        const { observable } = getCurrentSnapshot();\n        const { fetchPolicy, initialFetchPolicy } = observable.options;\n\n        expect(fetchPolicy).toBe(expectedFetchPolicy);\n        expect(initialFetchPolicy).toBe(expectedInitialFetchPolicy);\n      }\n\n      check(\"standby\", \"cache-first\");\n\n      await rerender({ fetchPolicy: \"cache-and-network\" });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 1 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      check(\"cache-and-network\", \"cache-and-network\");\n\n      const reasons: string[] = [];\n\n      const result = await getCurrentSnapshot().observable.reobserve({\n        variables: {\n          newVar: true,\n        },\n        nextFetchPolicy(currentFetchPolicy, context) {\n          expect(currentFetchPolicy).toBe(\"cache-and-network\");\n          expect(context.initialFetchPolicy).toBe(\"cache-and-network\");\n          reasons.push(context.reason);\n          return currentFetchPolicy;\n        },\n      });\n\n      expect(result).toStrictEqualTyped({ data: { hello: 2 } });\n      expect(reasons).toEqual([\"variables-changed\", \"after-fetch\"]);\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 1 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: undefined,\n        variables: { newVar: true },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: 2 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: 1 },\n        variables: { newVar: true },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should prioritize a `nextFetchPolicy` function over a `fetchPolicy` option when changing variables\", async () => {\n      const query = gql`\n        query ($id: ID!) {\n          user(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n      const link = new MockLink([\n        {\n          request: { query, variables: () => true },\n          result: ({ id }) => ({\n            data: { user: { __typename: \"User\", id, name: `User ${id}` } },\n          }),\n          maxUsageCount: Number.POSITIVE_INFINITY,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      client.writeQuery({\n        query,\n        variables: { id: 1 },\n        data: { user: { __typename: \"User\", id: 1, name: \"Cached User 1\" } },\n      });\n      client.writeQuery({\n        query,\n        variables: { id: 2 },\n        data: { user: { __typename: \"User\", id: 2, name: \"Cached User 2\" } },\n      });\n\n      const nextFetchPolicy: ApolloClient.WatchQueryOptions<\n        any,\n        OperationVariables\n      >[\"nextFetchPolicy\"] = jest.fn((_, context) => {\n        if (context.reason === \"variables-changed\") {\n          return \"cache-and-network\";\n        } else if (context.reason === \"after-fetch\") {\n          return \"cache-only\";\n        }\n        throw new Error(\"should never happen\");\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ variables }) =>\n            useQuery(query, {\n              fetchPolicy: \"network-only\",\n              variables,\n              nextFetchPolicy,\n            }),\n          {\n            initialProps: {\n              variables: { id: 1 },\n            },\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      // We skip the cache and go to the network\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(nextFetchPolicy).toHaveBeenCalledTimes(1);\n      expect(nextFetchPolicy).toHaveBeenNthCalledWith(\n        1,\n        \"network-only\",\n        expect.objectContaining({ reason: \"after-fetch\" })\n      );\n      // `nextFetchPolicy(..., {reason: \"after-fetch\"})` changed it to\n      // cache-only\n      expect(getCurrentSnapshot().observable.options.fetchPolicy).toBe(\n        \"cache-only\"\n      );\n\n      await rerender({\n        variables: { id: 2 },\n      });\n\n      expect(nextFetchPolicy).toHaveBeenNthCalledWith(\n        2,\n        // has been reset to the initial `fetchPolicy` of \"network-only\" because\n        // we changed variables, then `nextFetchPolicy` is called\n        \"network-only\",\n        expect.objectContaining({\n          reason: \"variables-changed\",\n        })\n      );\n\n      // We now see the effects of cache-and-network applied\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 2, name: \"Cached User 2\" } },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: { user: { __typename: \"User\", id: 1, name: \"User 1\" } },\n        variables: { id: 2 },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { user: { __typename: \"User\", id: 2, name: \"User 2\" } },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          user: { __typename: \"User\", id: 2, name: \"Cached User 2\" },\n        },\n        variables: { id: 2 },\n      });\n\n      expect(nextFetchPolicy).toHaveBeenCalledTimes(3);\n      expect(nextFetchPolicy).toHaveBeenNthCalledWith(\n        3,\n        \"cache-and-network\",\n        expect.objectContaining({\n          reason: \"after-fetch\",\n        })\n      );\n      // `nextFetchPolicy(..., {reason: \"after-fetch\"})` changed it to\n      // cache-only\n      expect(getCurrentSnapshot().observable.options.fetchPolicy).toBe(\n        \"cache-only\"\n      );\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"Missing Fields\", () => {\n    it(\"should log debug messages about MissingFieldErrors from the cache\", async () => {\n      using consoleSpy = spyOnConsole(\"error\");\n\n      const carQuery: DocumentNode = gql`\n        query cars($id: Int) {\n          cars(id: $id) {\n            id\n            make\n            model\n            vin\n            __typename\n          }\n        }\n      `;\n\n      const carData = {\n        cars: [\n          {\n            id: 1,\n            make: \"Audi\",\n            model: \"RS8\",\n            vine: \"DOLLADOLLABILL\",\n            __typename: \"Car\",\n          },\n        ],\n      };\n\n      const mocks = [\n        {\n          request: { query: carQuery, variables: { id: 1 } },\n          result: { data: carData },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(carQuery, { variables: { id: 1 } }),\n        { wrapper }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: carData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 1 },\n      });\n\n      expect(consoleSpy.error).toHaveBeenCalled();\n      expect(consoleSpy.error).toHaveBeenLastCalledWith(\n        `Missing field '%s' while writing result %o`,\n        \"vin\",\n        {\n          id: 1,\n          make: \"Audi\",\n          model: \"RS8\",\n          vine: \"DOLLADOLLABILL\",\n          __typename: \"Car\",\n        }\n      );\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should return partial cache data when `returnPartialData` is true\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n\n      const fullQuery = gql`\n        query {\n          cars {\n            make\n            model\n            repairs {\n              date\n              description\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query: fullQuery,\n        data: {\n          cars: [\n            {\n              __typename: \"Car\",\n              make: \"Ford\",\n              model: \"Mustang\",\n              vin: \"PONY123\",\n              repairs: [\n                {\n                  __typename: \"Repair\",\n                  date: \"2019-05-08\",\n                  description: \"Could not get after it.\",\n                },\n              ],\n            },\n          ],\n        },\n      });\n\n      const partialQuery = gql`\n        query {\n          cars {\n            repairs {\n              date\n              cost\n            }\n          }\n        }\n      `;\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(partialQuery, { returnPartialData: true }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          cars: [\n            {\n              __typename: \"Car\",\n              repairs: [\n                {\n                  __typename: \"Repair\",\n                  date: \"2019-05-08\",\n                },\n              ],\n            },\n          ],\n        },\n        dataState: \"partial\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    });\n\n    it(\"should not return partial cache data when `returnPartialData` is false\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: ApolloLink.empty(),\n      });\n\n      const fullQuery = gql`\n        query {\n          cars {\n            make\n            model\n            repairs {\n              date\n              description\n            }\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query: fullQuery,\n        data: {\n          cars: [\n            {\n              __typename: \"Car\",\n              make: \"Ford\",\n              model: \"Mustang\",\n              vin: \"PONY123\",\n              repairs: [\n                {\n                  __typename: \"Repair\",\n                  date: \"2019-05-08\",\n                  description: \"Could not get after it.\",\n                },\n              ],\n            },\n          ],\n        },\n      });\n\n      const partialQuery = gql`\n        query {\n          cars {\n            repairs {\n              date\n              cost\n            }\n          }\n        }\n      `;\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(partialQuery, { returnPartialData: false }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n    });\n\n    it(\"should not return partial cache data when `returnPartialData` is false and new variables are passed in\", async () => {\n      const cache = new InMemoryCache();\n      const client = new ApolloClient({\n        cache,\n        link: new ApolloLink(() => {\n          return new Observable((observer) => {\n            setTimeout(() => {\n              observer.next({ data: null });\n              observer.complete();\n            }, 10);\n          });\n        }),\n      });\n\n      const query = gql`\n        query MyCar($id: ID) {\n          car(id: $id) {\n            id\n            make\n          }\n        }\n      `;\n\n      const partialQuery = gql`\n        query MyCar($id: ID) {\n          car(id: $id) {\n            id\n            make\n            model\n          }\n        }\n      `;\n\n      cache.writeQuery({\n        query,\n        variables: { id: 1 },\n        data: {\n          car: {\n            __typename: \"Car\",\n            id: 1,\n            make: \"Ford\",\n            model: \"Pinto\",\n          },\n        },\n      });\n\n      cache.writeQuery({\n        query: partialQuery,\n        variables: { id: 2 },\n        data: {\n          car: {\n            __typename: \"Car\",\n            id: 2,\n            make: \"Ford\",\n            model: \"Pinto\",\n          },\n        },\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ id }) => {\n          return useQuery(partialQuery, {\n            variables: { id },\n            returnPartialData: false,\n          });\n        },\n        {\n          initialProps: { id: 2 },\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          car: {\n            __typename: \"Car\",\n            id: 2,\n            make: \"Ford\",\n            model: \"Pinto\",\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { id: 2 },\n      });\n\n      await rerender({ id: 1 });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: {\n          car: {\n            __typename: \"Car\",\n            id: 2,\n            make: \"Ford\",\n            model: \"Pinto\",\n          },\n        },\n        variables: { id: 1 },\n      });\n    });\n  });\n\n  describe(\"Previous data\", () => {\n    it(\"should persist previous data when a query is re-run\", async () => {\n      const query = gql`\n        query car {\n          car {\n            id\n            make\n          }\n        }\n      `;\n\n      const data1 = {\n        car: {\n          id: 1,\n          make: \"Venturi\",\n          __typename: \"Car\",\n        },\n      };\n\n      const data2 = {\n        car: {\n          id: 2,\n          make: \"Wiesmann\",\n          __typename: \"Car\",\n        },\n      };\n\n      const mocks = [\n        { request: { query }, result: { data: data1 } },\n        { request: { query }, result: { data: data2 }, delay: 10 },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query), { wrapper });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await getCurrentSnapshot().refetch();\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data1,\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should persist result.previousData across multiple results\", async () => {\n      const query: TypedDocumentNode<\n        {\n          car: {\n            id: number;\n            make: string;\n            __typename: \"Car\";\n          };\n        },\n        {\n          vin?: string;\n        }\n      > = gql`\n        query car($vin: String) {\n          car(vin: $vin) {\n            id\n            make\n          }\n        }\n      `;\n\n      const data1 = {\n        car: {\n          id: 1,\n          make: \"Venturi\",\n          __typename: \"Car\" as const,\n        },\n      };\n\n      const data2 = {\n        car: {\n          id: 2,\n          make: \"Wiesmann\",\n          __typename: \"Car\" as const,\n        },\n      };\n\n      const data3 = {\n        car: {\n          id: 3,\n          make: \"Beetle\",\n          __typename: \"Car\" as const,\n        },\n      };\n\n      const mocks = [\n        { request: { query }, result: { data: data1 } },\n        { request: { query }, result: { data: data2 }, delay: 100 },\n        {\n          request: {\n            query,\n            variables: { vin: \"ABCDEFG0123456789\" },\n          },\n          result: { data: data3 },\n        },\n      ];\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider mocks={mocks} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot } =\n        await renderHookToSnapshotStream(() => useQuery(query), { wrapper });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      setTimeout(() => getCurrentSnapshot().refetch());\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data1,\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data2,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data1,\n        variables: {},\n      });\n\n      void getCurrentSnapshot().refetch({ vin: \"ABCDEFG0123456789\" });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: data2,\n        variables: { vin: \"ABCDEFG0123456789\" },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: data3,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: data2,\n        variables: { vin: \"ABCDEFG0123456789\" },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    it(\"should persist result.previousData even if query changes\", async () => {\n      const aQuery: TypedDocumentNode<{\n        a: string;\n      }> = gql`\n        query A {\n          a\n        }\n      `;\n\n      const abQuery: TypedDocumentNode<{\n        a: string;\n        b: number;\n      }> = gql`\n        query AB {\n          a\n          b\n        }\n      `;\n\n      const bQuery: TypedDocumentNode<{\n        b: number;\n      }> = gql`\n        query B {\n          b\n        }\n      `;\n\n      let stringOfAs = \"\";\n      let countOfBs = 0;\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (request) =>\n            new Observable((observer) => {\n              setTimeout(() => {\n                switch (request.operationName) {\n                  case \"A\": {\n                    observer.next({\n                      data: {\n                        a: (stringOfAs += \"a\"),\n                      },\n                    });\n                    break;\n                  }\n                  case \"AB\": {\n                    observer.next({\n                      data: {\n                        a: (stringOfAs += \"a\"),\n                        b: (countOfBs += 1),\n                      },\n                    });\n                    break;\n                  }\n                  case \"B\": {\n                    observer.next({\n                      data: {\n                        b: (countOfBs += 1),\n                      },\n                    });\n                    break;\n                  }\n                }\n                observer.complete();\n              }, 10);\n            })\n        ),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, getCurrentSnapshot, rerender } =\n        await renderHookToSnapshotStream(\n          ({ query }) => {\n            return useQuery(query, { fetchPolicy: \"cache-and-network\" });\n          },\n          {\n            initialProps: { query: aQuery as DocumentNode },\n            wrapper: ({ children }: any) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { a: \"a\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await rerender({ query: abQuery });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: { a: \"a\" },\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { a: \"aa\", b: 1 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { a: \"a\" },\n        variables: {},\n      });\n\n      const result = await getCurrentSnapshot().observable.reobserve();\n\n      expect(result).toStrictEqualTyped({\n        data: { a: \"aaa\", b: 2 },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { a: \"aa\", b: 1 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: { a: \"a\" },\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { a: \"aaa\", b: 2 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { a: \"aa\", b: 1 },\n        variables: {},\n      });\n\n      await rerender({ query: bQuery });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { b: 2 },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: { a: \"aaa\", b: 2 },\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { b: 3 },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { b: 2 },\n        variables: {},\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n\n    // TODO: Determine if this test is needed or is already covered by other\n    // tests such as changing variables (since those tests check all returned\n    // hook properties)\n    it(\"should be cleared when variables change causes cache miss\", async () => {\n      const peopleData = [\n        { id: 1, name: \"John Smith\", gender: \"male\", __typename: \"Person\" },\n        { id: 2, name: \"Sara Smith\", gender: \"female\", __typename: \"Person\" },\n        { id: 3, name: \"Budd Deey\", gender: \"nonbinary\", __typename: \"Person\" },\n        {\n          id: 4,\n          name: \"Johnny Appleseed\",\n          gender: \"male\",\n          __typename: \"Person\",\n        },\n        { id: 5, name: \"Ada Lovelace\", gender: \"female\", __typename: \"Person\" },\n      ];\n\n      const link = new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          const { gender } = operation.variables;\n          void wait(300).then(() => {\n            observer.next({\n              data: {\n                people:\n                  gender === \"all\" ? peopleData\n                  : gender ?\n                    peopleData.filter((person) => person.gender === gender)\n                  : peopleData,\n              },\n            });\n            observer.complete();\n          });\n        });\n      });\n\n      type Person = {\n        __typename: string;\n        id: number;\n        name: string;\n      };\n\n      const query: TypedDocumentNode<{\n        people: Person[];\n      }> = gql`\n        query AllPeople($gender: String!) {\n          people(gender: $gender) {\n            id\n            name\n          }\n        }\n      `;\n\n      const cache = new InMemoryCache();\n      const wrapper = ({ children }: any) => (\n        <MockedProvider link={link} cache={cache}>\n          {children}\n        </MockedProvider>\n      );\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n        ({ gender }: { gender: string }) =>\n          useQuery(query, {\n            variables: { gender },\n            fetchPolicy: \"network-only\",\n          }),\n        { wrapper, initialProps: { gender: \"all\" } }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { gender: \"all\" },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          people: peopleData.map(({ gender, ...person }) => person),\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { gender: \"all\" },\n      });\n\n      await rerender({ gender: \"female\" });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.setVariables,\n        previousData: {\n          people: peopleData.map(({ gender, ...person }) => person),\n        },\n        variables: { gender: \"female\" },\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: {\n          people: peopleData\n            .filter((person) => person.gender === \"female\")\n            .map(({ gender, ...person }) => person),\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: {\n          people: peopleData.map(({ gender, ...person }) => person),\n        },\n        variables: { gender: \"female\" },\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  describe(\"defaultOptions\", () => {\n    it(\"should allow polling options to be passed to the client\", async () => {\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const cache = new InMemoryCache();\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: { hello: \"world 1\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 2\" } },\n        },\n        {\n          request: { query },\n          result: { data: { hello: \"world 3\" } },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        defaultOptions: {\n          watchQuery: {\n            pollInterval: 10,\n          },\n        },\n        cache,\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useQuery(query),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 1\" },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.poll,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 2\" },\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.poll,\n        previousData: { hello: \"world 1\" },\n        variables: {},\n      });\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: { hello: \"world 3\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: { hello: \"world 2\" },\n        variables: {},\n      });\n    });\n  });\n\n  describe(\"multiple useQuery calls per component\", () => {\n    type ABFields = {\n      id: number;\n      name: string;\n    };\n\n    const aQuery: TypedDocumentNode<{\n      a: ABFields;\n    }> = gql`\n      query A {\n        a {\n          id\n          name\n        }\n      }\n    `;\n\n    const bQuery: TypedDocumentNode<{\n      b: ABFields;\n    }> = gql`\n      query B {\n        b {\n          id\n          name\n        }\n      }\n    `;\n\n    const aData = {\n      a: {\n        __typename: \"A\",\n        id: 65,\n        name: \"ay\",\n      },\n    };\n\n    const bData = {\n      b: {\n        __typename: \"B\",\n        id: 66,\n        name: \"bee\",\n      },\n    };\n\n    function makeClient() {\n      return new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new ApolloLink(\n          (operation) =>\n            new Observable((observer) => {\n              switch (operation.operationName) {\n                case \"A\":\n                  setTimeout(() => {\n                    observer.next({ data: aData });\n                    observer.complete();\n                  });\n                  break;\n                case \"B\":\n                  setTimeout(() => {\n                    observer.next({ data: bData });\n                    observer.complete();\n                  }, 10);\n                  break;\n              }\n            })\n        ),\n      });\n    }\n\n    async function check(\n      aFetchPolicy: WatchQueryFetchPolicy,\n      bFetchPolicy: WatchQueryFetchPolicy\n    ) {\n      const client = makeClient();\n      const { result } = renderHook(\n        () => ({\n          a: useQuery(aQuery, { fetchPolicy: aFetchPolicy }),\n          b: useQuery(bQuery, { fetchPolicy: bFetchPolicy }),\n        }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      expect(result.current.a).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n      expect(result.current.b).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await waitFor(() => {\n        expect(result.current.a.loading).toBe(false);\n        expect(result.current.b.loading).toBe(false);\n      });\n\n      expect(result.current.a).toStrictEqualTyped({\n        data: aData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n      expect(result.current.b).toStrictEqualTyped({\n        data: bData,\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    // TODO: Eventually move the \"check\" code back into these test so we can\n    // check them render-by-render with renderHookToSnapshotStream\n    it(\"cache-first for both\", () => check(\"cache-first\", \"cache-first\"));\n\n    it(\"cache-first first, cache-and-network second\", () =>\n      check(\"cache-first\", \"cache-and-network\"));\n\n    it(\"cache-first first, network-only second\", () =>\n      check(\"cache-first\", \"network-only\"));\n\n    it(\"cache-and-network for both\", () =>\n      check(\"cache-and-network\", \"cache-and-network\"));\n\n    it(\"cache-and-network first, cache-first second\", () =>\n      check(\"cache-and-network\", \"cache-first\"));\n\n    it(\"cache-and-network first, network-only second\", () =>\n      check(\"cache-and-network\", \"network-only\"));\n\n    it(\"network-only for both\", () => check(\"network-only\", \"network-only\"));\n\n    it(\"network-only first, cache-first second\", () =>\n      check(\"network-only\", \"cache-first\"));\n\n    it(\"network-only first, cache-and-network second\", () =>\n      check(\"network-only\", \"cache-and-network\"));\n  });\n\n  describe(\"regression test issue #9204\", () => {\n    // TODO: See if we can rewrite this with renderHookToSnapshotStream and\n    // check output of hook to ensure its a stable object\n    it(\"should handle a simple query\", async () => {\n      const query: TypedDocumentNode<\n        { hello: string },\n        Record<string, never>\n      > = gql`\n        {\n          hello\n        }\n      `;\n      const mocks = [\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ];\n\n      const Component = ({\n        query,\n      }: {\n        query: TypedDocumentNode<{ hello: string }, Record<string, never>>;\n      }) => {\n        const [counter, setCounter] = useState(0);\n        const result = useQuery(query);\n\n        useEffect(() => {\n          /**\n           * IF the return value from useQuery changes on each render,\n           * this component will re-render in an infinite loop.\n           */\n          if (counter > 10) {\n            console.error(`Too many results (${counter})`);\n          } else {\n            setCounter((c) => c + 1);\n          }\n        }, [result, result.data]);\n\n        if (result.loading) return null;\n\n        return (\n          <div>\n            {result.data!.hello}\n            {counter}\n          </div>\n        );\n      };\n\n      render(\n        <MockedProvider mocks={mocks}>\n          <Component query={query} />\n        </MockedProvider>\n      );\n\n      await waitFor(() => {\n        expect(screen.getByText(\"world2\")).toBeTruthy();\n      });\n    });\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/10222\n  describe(\"regression test issue #10222\", () => {\n    it(\"maintains initial fetch policy when component unmounts and remounts\", async () => {\n      let helloCount = 1;\n      const query = gql`\n        {\n          hello\n        }\n      `;\n      const link = new ApolloLink(() => {\n        return new Observable((observer) => {\n          const timer = setTimeout(() => {\n            observer.next({ data: { hello: `hello ${helloCount++}` } });\n            observer.complete();\n          }, 50);\n\n          return () => {\n            clearTimeout(timer);\n          };\n        });\n      });\n\n      const cache = new InMemoryCache();\n\n      const client = new ApolloClient({\n        link,\n        cache,\n      });\n\n      let setShow: Function;\n      const Toggler = ({ children }: { children: ReactNode }) => {\n        const [show, _setShow] = useState(true);\n        setShow = _setShow;\n\n        return show ? <>{children}</> : null;\n      };\n\n      const { result } = renderHook(\n        () =>\n          useQuery(query, {\n            fetchPolicy: \"network-only\",\n            nextFetchPolicy: \"cache-first\",\n          }),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>\n              <Toggler>{children}</Toggler>\n            </ApolloProvider>\n          ),\n        }\n      );\n\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await waitFor(() => {\n        expect(result.current.loading).toBe(false);\n      });\n\n      expect(result.current).toStrictEqualTyped({\n        data: { hello: \"hello 1\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      expect(cache.readQuery({ query })).toEqual({ hello: \"hello 1\" });\n\n      act(() => {\n        setShow(false);\n      });\n\n      act(() => {\n        setShow(true);\n      });\n\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await waitFor(() => {\n        expect(result.current.loading).toBe(false);\n      });\n\n      expect(result.current).toStrictEqualTyped({\n        data: { hello: \"hello 2\" },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      expect(cache.readQuery({ query })).toEqual({ hello: \"hello 2\" });\n    });\n  });\n\n  describe(\"interaction with `prioritizeCacheValues`\", () => {\n    const cacheData = { something: \"foo\" };\n    const networkData = { something: \"bar\" };\n    type TestQueryValue = typeof cacheData;\n\n    test.each<{\n      fetchPolicy: WatchQueryFetchPolicy;\n      populateCache: boolean;\n      expectedSnapshots: Array<\n        Pick<\n          useQuery.Result<\n            TestQueryValue,\n            OperationVariables,\n            \"empty\" | \"complete\" | \"streaming\"\n          >,\n          | \"loading\"\n          | \"data\"\n          | \"networkStatus\"\n          | \"dataState\"\n          | \"error\"\n          | \"previousData\"\n          | \"variables\"\n        >\n      >;\n      expectedFetchCount: number;\n    }>([\n      // cache-first is the default behavior with `prioritizeCacheValues`\n      {\n        fetchPolicy: \"cache-first\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: true,\n            data: undefined,\n            networkStatus: NetworkStatus.loading,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n          {\n            loading: false,\n            data: networkData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"cache-first\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: cacheData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // cache-only should never cause network requests\n      {\n        fetchPolicy: \"cache-only\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: undefined,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      {\n        fetchPolicy: \"cache-only\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: cacheData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // cache-and-network should avoid fetching if cache is populated\n      {\n        fetchPolicy: \"cache-and-network\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: true,\n            data: undefined,\n            networkStatus: NetworkStatus.loading,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n          {\n            loading: false,\n            data: networkData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"cache-and-network\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: cacheData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // `network-only` should return a loading result and make a network request\n      // if values are missing from cache, but if cache values are present,\n      // during `prioritizeCacheValues` it is actually allowed to immediately\n      // read from the cache and avoid a network request\n      {\n        fetchPolicy: \"network-only\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: true,\n            data: undefined,\n            networkStatus: NetworkStatus.loading,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n          {\n            loading: false,\n            data: networkData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"network-only\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: cacheData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      // no-cache should always fetch and never read from the cache\n      {\n        fetchPolicy: \"no-cache\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: true,\n            data: undefined,\n            networkStatus: NetworkStatus.loading,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n          {\n            loading: false,\n            data: networkData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      {\n        fetchPolicy: \"no-cache\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: true,\n            data: undefined,\n            networkStatus: NetworkStatus.loading,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n          {\n            loading: false,\n            data: networkData,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"complete\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 1,\n      },\n      // `standby` should never show a loading state or cause network requests\n      {\n        fetchPolicy: \"standby\",\n        populateCache: false,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: undefined,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n      {\n        fetchPolicy: \"standby\",\n        populateCache: true,\n        expectedSnapshots: [\n          {\n            loading: false,\n            data: undefined,\n            networkStatus: NetworkStatus.ready,\n            dataState: \"empty\" as const,\n            previousData: undefined,\n            variables: {},\n          },\n        ],\n        expectedFetchCount: 0,\n      },\n    ])(\n      \"fetchPolicy: '$fetchPolicy' with prioritizeCacheValues (cache populated: $populateCache)\",\n      async ({\n        fetchPolicy,\n        populateCache,\n        expectedSnapshots,\n        expectedFetchCount,\n      }) => {\n        using _disabledAct = disableActEnvironment();\n\n        const query: TypedDocumentNode<TestQueryValue> = gql`\n          query {\n            something\n          }\n        `;\n\n        const link = new MockLink([\n          { request: { query }, result: { data: networkData } },\n        ]);\n        const linkSpy = jest.spyOn(link, \"request\");\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link,\n        });\n\n        if (populateCache) {\n          client.writeQuery({ query, data: cacheData });\n        }\n\n        client.prioritizeCacheValues = true;\n\n        const { takeSnapshot } = await renderHookToSnapshotStream(\n          () => useQuery(query, { fetchPolicy }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n        for (const expected of expectedSnapshots) {\n          await expect(takeSnapshot()).resolves.toStrictEqualTyped(\n            expected as useQuery.Result<\n              TestQueryValue,\n              OperationVariables,\n              \"empty\" | \"complete\" | \"streaming\"\n            >\n          );\n        }\n\n        await expect(takeSnapshot).not.toRerender();\n        expect(linkSpy).toHaveBeenCalledTimes(expectedFetchCount);\n      }\n    );\n  });\n\n  test(\"calling `clearStore` while a query is running puts the hook into an error state\", async () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    let requests = 0;\n    link.onSetup(() => requests++);\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await wait(10);\n    expect(requests).toBe(1);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n\n    await client.clearStore();\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new InvariantError(\n        \"Store reset while query was in flight (not completed in link chain)\"\n      ),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables: {},\n    });\n\n    link.simulateResult({ result: { data: { hello: \"Greetings\" } } }, true);\n    await expect(takeSnapshot).not.toRerender({ timeout: 50 });\n    expect(requests).toBe(1);\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11938\n  it(\"does not emit `data` on previous fetch when a 2nd fetch is kicked off and the result returns an error when errorPolicy is none\", async () => {\n    const query = gql`\n      query {\n        user {\n          id\n          name\n        }\n      }\n    `;\n\n    const graphQLError: GraphQLFormattedError = { message: \"Cannot get name\" };\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: { user: { __typename: \"User\", id: \"1\", name: null } },\n          errors: [graphQLError],\n        },\n        delay: 10,\n        maxUsageCount: Number.POSITIVE_INFINITY,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query), {\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: {},\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        data: { user: { __typename: \"User\", id: \"1\", name: null } },\n        errors: [graphQLError],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables: {},\n    });\n\n    const { refetch } = getCurrentSnapshot();\n\n    refetch().catch(() => {});\n    refetch().catch(() => {});\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables: {},\n    });\n\n    if (IS_REACT_17) {\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        error: new CombinedGraphQLErrors({\n          data: { user: { __typename: \"User\", id: \"1\", name: null } },\n          errors: [graphQLError],\n        }),\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n        previousData: undefined,\n        variables: {},\n      });\n    }\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({\n        data: { user: { __typename: \"User\", id: \"1\", name: null } },\n        errors: [graphQLError],\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables: {},\n    });\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 200 });\n  });\n\n  test(\"initializes with loading: false on an empty cache when using `cache-only`\", async () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { fetchPolicy: \"cache-only\" }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"initializes with loading: false on an partial cache when using `cache-only` with returnPartialData: true\", async () => {\n    const query = gql`\n      query {\n        user {\n          id\n          name\n        }\n      }\n    `;\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    client.writeQuery({\n      query: gql`\n        query {\n          user {\n            id\n          }\n        }\n      `,\n      data: { user: { __typename: \"User\", id: \"1\" } },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useQuery(query, { returnPartialData: true, fetchPolicy: \"cache-only\" }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user: { __typename: \"User\", id: \"1\" } },\n      dataState: \"partial\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  describe(\"data masking\", () => {\n    it(\"masks queries when dataMasking is `true`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query);\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: undefined,\n          dataState: \"empty\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      await expect(renderStream).not.toRerender();\n    });\n\n    it(\"does not mask query when dataMasking is `false`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      // We have to use Unmasked here since the default is to preserve types\n      const query: TypedDocumentNode<\n        Unmasked<Query>,\n        Record<string, never>\n      > = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: false,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<\n          useQuery.Result<Unmasked<Query>, Record<string, never>>\n        >();\n\n      function App() {\n        const result = useQuery(query);\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      // loading\n      await renderStream.takeRender();\n\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n\n      await expect(renderStream).not.toRerender();\n    });\n\n    it(\"does not mask query by default\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<\n        Unmasked<Query>,\n        Record<string, never>\n      > = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<\n          useQuery.Result<Unmasked<Query>, Record<string, never>>\n        >();\n\n      function App() {\n        const result = useQuery(query);\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      // loading\n      await renderStream.takeRender();\n\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 30,\n          },\n        },\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: {},\n      });\n    });\n\n    it(\"masks queries updated by the cache\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query);\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      // loading\n      await renderStream.takeRender();\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User (updated)\",\n            age: 35,\n          },\n        },\n      });\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (updated)\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          variables: {},\n        });\n      }\n    });\n\n    it(\"does not rerender when updating field in named fragment\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User\",\n                age: 30,\n              },\n            },\n          },\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query);\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      // loading\n      await renderStream.takeRender();\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 35,\n          },\n        },\n      });\n\n      await expect(renderStream).not.toRerender();\n\n      expect(client.readQuery({ query })).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 35,\n        },\n      });\n    });\n\n    it.each([\"cache-first\", \"cache-only\"] as FetchPolicy[])(\n      \"masks result from cache when using with %s fetch policy\",\n      async (fetchPolicy) => {\n        type UserFieldsFragment = {\n          __typename: \"User\";\n          age: number;\n        } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n        interface Query {\n          currentUser: {\n            __typename: \"User\";\n            id: number;\n            name: string;\n          } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n        }\n\n        const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n          query MaskedQuery {\n            currentUser {\n              id\n              name\n              ...UserFields\n            }\n          }\n\n          fragment UserFields on User {\n            age\n          }\n        `;\n\n        const mocks = [\n          {\n            request: { query },\n            result: {\n              data: {\n                currentUser: {\n                  __typename: \"User\",\n                  id: 1,\n                  name: \"Test User\",\n                  age: 30,\n                },\n              },\n            },\n          },\n        ];\n\n        const client = new ApolloClient({\n          dataMasking: true,\n          cache: new InMemoryCache(),\n          link: new MockLink(mocks),\n        });\n\n        client.writeQuery({\n          query,\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        });\n\n        const renderStream =\n          createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n        function App() {\n          const result = useQuery(query, { fetchPolicy });\n\n          renderStream.replaceSnapshot(result);\n\n          return null;\n        }\n\n        using _disabledAct = disableActEnvironment();\n        await renderStream.render(<App />, {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    );\n\n    it(\"masks cache and network result when using cache-and-network fetch policy\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User (server)\",\n                age: 35,\n              },\n            },\n          },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User\",\n            age: 34,\n          },\n        },\n      });\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query, { fetchPolicy: \"cache-and-network\" });\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          dataState: \"complete\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n            },\n          },\n          variables: {},\n        });\n      }\n    });\n\n    it(\"masks partial cache data when returnPartialData is `true`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: \"Test User (server)\",\n                age: 35,\n              },\n            },\n          },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      {\n        using _ = spyOnConsole(\"error\");\n\n        client.writeQuery({\n          query,\n          data: {\n            // @ts-expect-error writing partial result\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              age: 34,\n            },\n          },\n        });\n      }\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query, { returnPartialData: true });\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n            },\n          } as Query,\n          dataState: \"partial\",\n          loading: true,\n          networkStatus: NetworkStatus.loading,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n            },\n          },\n          dataState: \"complete\",\n          loading: false,\n          networkStatus: NetworkStatus.ready,\n          previousData: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n            },\n          } as Query,\n          variables: {},\n        });\n      }\n    });\n\n    it(\"masks partial data returned from data on errors with errorPolicy `all`\", async () => {\n      type UserFieldsFragment = {\n        __typename: \"User\";\n        age: number;\n      } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n      interface Query {\n        currentUser: {\n          __typename: \"User\";\n          id: number;\n          name: string | null;\n        } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n      }\n\n      const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n        query MaskedQuery {\n          currentUser {\n            id\n            name\n            ...UserFields\n          }\n        }\n\n        fragment UserFields on User {\n          age\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query },\n          result: {\n            data: {\n              currentUser: {\n                __typename: \"User\",\n                id: 1,\n                name: null,\n                age: 34,\n              },\n            },\n            errors: [new GraphQLError(\"Couldn't get name\")],\n          },\n          delay: 20,\n        },\n      ];\n\n      const client = new ApolloClient({\n        dataMasking: true,\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const renderStream =\n        createRenderStream<useQuery.Result<Query, Record<string, never>>>();\n\n      function App() {\n        const result = useQuery(query, { errorPolicy: \"all\" });\n\n        renderStream.replaceSnapshot(result);\n\n        return null;\n      }\n\n      using _disabledAct = disableActEnvironment();\n      await renderStream.render(<App />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      // loading\n      await renderStream.takeRender();\n\n      {\n        const { snapshot } = await renderStream.takeRender();\n\n        expect(snapshot).toStrictEqualTyped({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: null,\n            },\n          },\n          dataState: \"complete\",\n          error: new CombinedGraphQLErrors({\n            data: {\n              currentUser: { __typename: \"User\", id: 1, name: null, age: 34 },\n            },\n            errors: [{ message: \"Couldn't get name\" }],\n          }),\n          loading: false,\n          networkStatus: NetworkStatus.error,\n          previousData: undefined,\n          variables: {},\n        });\n      }\n    });\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/12229\n  it('sets data to undefined when changing variables with a \"network-only\" fetch policy and notifyOnNetworkStatusChange: true', async () => {\n    const query = gql`\n      query ($for: String!) {\n        greeting\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { for: \"Bob\" } },\n        result: { data: { greeting: \"Hello, Bob\" } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { for: \"Sally\" } },\n        result: { data: { greeting: \"Hello, Sally\" } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { for: \"Bob\" } },\n        result: { data: { greeting: \"Hello again, Bob\" } },\n        delay: 20,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      (props) =>\n        useQuery(query, {\n          variables: { for: props.for },\n          fetchPolicy: \"network-only\",\n          notifyOnNetworkStatusChange: true,\n        }),\n      {\n        initialProps: { for: \"Bob\" },\n        wrapper: ({ children }) => (\n          <MockedProvider mocks={mocks}>{children}</MockedProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: { for: \"Bob\" },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { greeting: \"Hello, Bob\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: { for: \"Bob\" },\n    });\n\n    await rerender({ for: \"Sally\" });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: { greeting: \"Hello, Bob\" },\n      variables: { for: \"Sally\" },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { greeting: \"Hello, Sally\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello, Bob\" },\n      variables: { for: \"Sally\" },\n    });\n\n    await rerender({ for: \"Bob\" });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.setVariables,\n      previousData: { greeting: \"Hello, Sally\" },\n      variables: { for: \"Bob\" },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { greeting: \"Hello again, Bob\" },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { greeting: \"Hello, Sally\" },\n      variables: { for: \"Bob\" },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n});\n\ntest(\"applies `errorPolicy` on next fetch when it changes between renders\", async () => {\n  const query: TypedDocumentNode<\n    {\n      character: { __typename: \"Character\"; id: string; name: string } | null;\n    },\n    VariablesCaseVariables\n  > = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n          },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: null,\n          },\n          errors: [{ message: \"Could not find character 1\" }],\n        },\n        delay: 20,\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ errorPolicy }: { errorPolicy: ErrorPolicy }) =>\n      useQuery(query, {\n        // Use network-only to show no network requests are made between\n        // renders\n        fetchPolicy: \"network-only\",\n        errorPolicy,\n        variables: { id: \"1\" },\n      }),\n    {\n      initialProps: { errorPolicy: \"none\" },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await rerender({ errorPolicy: \"all\" });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  const { refetch } = getCurrentSnapshot();\n  void refetch();\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: null,\n    },\n    dataState: \"complete\",\n    error: new CombinedGraphQLErrors({\n      data: { character: null },\n      errors: [{ message: \"Could not find character 1\" }],\n    }),\n    loading: false,\n    networkStatus: NetworkStatus.error,\n    previousData: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n    },\n    variables: { id: \"1\" },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `context` on next fetch when it changes between renders\", async () => {\n  const query = gql`\n    query {\n      context\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      const context = operation.getContext();\n\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({ data: { context: { source: context.source } } });\n          observer.complete();\n        }, 20);\n      });\n    }),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ context }) => useQuery(query, { context, fetchPolicy: \"network-only\" }),\n    {\n      initialProps: { context: { source: \"initialHookValue\" } },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { context: { source: \"initialHookValue\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await rerender({ context: { source: \"rerender\" } });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n    data: { context: { source: \"rerender\" } },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { context: { source: \"initialHookValue\" } },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { context: { source: \"rerender\" } },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { context: { source: \"initialHookValue\" } },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `refetchWritePolicy` on next fetch when it changes between renders\", async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 20,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 30, max: 50 } },\n      result: { data: { primes: [31, 37, 41, 43, 47] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ refetchWritePolicy }) =>\n      useQuery(query, {\n        fetchPolicy: \"network-only\",\n        refetchWritePolicy,\n        variables: { min: 0, max: 12 },\n      }),\n    {\n      initialProps: { refetchWritePolicy: \"merge\" as RefetchWritePolicy },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: { min: 0, max: 12 },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: mocks[0].result.data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: { min: 0, max: 12 },\n  });\n\n  expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n  const { refetch } = getCurrentSnapshot();\n\n  void refetch({ min: 12, max: 30 });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    previousData: mocks[0].result.data,\n    variables: { min: 12, max: 30 },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: mocks[0].result.data,\n    variables: { min: 12, max: 30 },\n  });\n\n  expect(mergeParams).toEqual([\n    [undefined, [2, 3, 5, 7, 11]],\n    [\n      [2, 3, 5, 7, 11],\n      [13, 17, 19, 23, 29],\n    ],\n  ]);\n\n  await rerender({ refetchWritePolicy: \"overwrite\" });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  void refetch({ min: 30, max: 50 });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    previousData: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n    variables: { min: 30, max: 50 },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: mocks[2].result.data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n    variables: { min: 30, max: 50 },\n  });\n\n  expect(mergeParams).toEqual([\n    [undefined, [2, 3, 5, 7, 11]],\n    [\n      [2, 3, 5, 7, 11],\n      [13, 17, 19, 23, 29],\n    ],\n    [undefined, [31, 37, 41, 43, 47]],\n  ]);\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies `returnPartialData` on next fetch when it changes between renders\", async () => {\n  const fullQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n        name\n      }\n    }\n  `;\n\n  const partialQuery = gql`\n    query ($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query: fullQuery, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Doctor Strange\",\n            },\n          },\n        },\n        delay: 20,\n      },\n      {\n        request: { query: fullQuery, variables: { id: \"2\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"2\",\n              name: \"Hulk\",\n            },\n          },\n        },\n        delay: 20,\n      },\n    ]),\n  });\n\n  client.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  client.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"2\" } },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ id, returnPartialData }) =>\n      useQuery(fullQuery, { returnPartialData, variables: { id } }),\n    {\n      initialProps: { id: \"1\", returnPartialData: false },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { takeSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await rerender({ id: \"1\", returnPartialData: true });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  await rerender({ id: \"2\", returnPartialData: true });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"2\" },\n    },\n    dataState: \"partial\",\n    loading: true,\n    networkStatus: NetworkStatus.setVariables,\n    previousData: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Doctor Strange\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Hulk\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      character: { __typename: \"Character\", id: \"2\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"applies updated `fetchPolicy` on next fetch when it changes between renders\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n    },\n    variables: { id: \"1\" },\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ id, fetchPolicy }) =>\n      useQuery(query, { fetchPolicy, variables: { id } }),\n    {\n      initialProps: {\n        id: \"1\",\n        fetchPolicy: \"cache-first\" as WatchQueryFetchPolicy,\n      },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: { id: \"1\" },\n  });\n\n  await rerender({ id: \"1\", fetchPolicy: \"cache-and-network\" });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  await rerender({ id: \"2\", fetchPolicy: \"cache-and-network\" });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.setVariables,\n    previousData: {\n      character: { __typename: \"Character\", id: \"1\", name: \"Spider-Cache\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"executes fetchPolicy when changing from standby to non-standby\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      greeting: \"Hello from cache\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ fetchPolicy }) => useQuery(query, { fetchPolicy }),\n    {\n      initialProps: {\n        fetchPolicy: \"standby\" as WatchQueryFetchPolicy,\n      },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await rerender({ fetchPolicy: \"cache-first\" });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: \"Hello from cache\",\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"unsubscribes from cache when changing from non-standby -> standby fetch policy\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ fetchPolicy }) => useQuery(query, { fetchPolicy }),\n    {\n      initialProps: {\n        fetchPolicy: \"cache-first\" as WatchQueryFetchPolicy,\n      },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: \"Hello\",\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await rerender({ fetchPolicy: \"standby\" });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n  await expect(takeSnapshot).not.toRerender();\n\n  expect(cache[\"watches\"].size).toBe(0);\n});\n\ntest(\"rerenders with latest cache value when in standby changing to non-standby\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ fetchPolicy }) => useQuery(query, { fetchPolicy }),\n    {\n      initialProps: {\n        fetchPolicy: \"cache-first\" as WatchQueryFetchPolicy,\n      },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: \"Hello\",\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await rerender({ fetchPolicy: \"standby\" });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  client.writeQuery({ query, data: { greeting: \"Hello updated\" } });\n\n  await expect(takeSnapshot).not.toRerender();\n\n  await rerender({ fetchPolicy: \"cache-first\" });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: {\n      greeting: \"Hello updated\",\n    },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { greeting: \"Hello\" },\n    variables: {},\n  });\n});\n\ntest(\"renders loading states at appropriate times on next fetch after updating `notifyOnNetworkStatusChange`\", async () => {\n  const { query } = setupSimpleCase();\n\n  let count = 0;\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query },\n        result: () => ({ data: { greeting: `Hello ${++count}` } }),\n        maxUsageCount: Number.POSITIVE_INFINITY,\n      },\n    ]),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ notifyOnNetworkStatusChange }) =>\n      useQuery(query, {\n        notifyOnNetworkStatusChange,\n        fetchPolicy: \"network-only\",\n      }),\n    {\n      initialProps: { notifyOnNetworkStatusChange: false },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n  const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 1\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: {},\n  });\n\n  await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 2\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 2\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { greeting: \"Hello 1\" },\n    variables: {},\n  });\n\n  await rerender({ notifyOnNetworkStatusChange: true });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 3\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 2\" },\n    dataState: \"complete\",\n    loading: true,\n    networkStatus: NetworkStatus.refetch,\n    previousData: { greeting: \"Hello 1\" },\n    variables: {},\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 3\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { greeting: \"Hello 2\" },\n    variables: {},\n  });\n\n  await rerender({ notifyOnNetworkStatusChange: false });\n\n  await expect(renderStream).toRerenderWithSimilarSnapshot();\n\n  await expect(getCurrentSnapshot().refetch()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 4\" },\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: { greeting: \"Hello 4\" },\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: { greeting: \"Hello 3\" },\n    variables: {},\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\n// https://github.com/apollographql/apollo-client/issues/11328\ntest(\"rerenders if refetch returns same result for different variables with notifyOnNetworkStatusChange: false\", async () => {\n  type Data = typeof data;\n  type Vars = { first: number };\n  const query: TypedDocumentNode<Data, Vars> = gql`\n    query people($first: Int!) {\n      allPeople(first: $first) {\n        people {\n          name\n          friends(id: $first) {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const variables1: Vars = { first: 1 };\n  const variables2: Vars = { first: 2 };\n  const data = {\n    allPeople: {\n      __typename: \"AllPeople\",\n      people: [\n        {\n          __typename: \"Person\",\n          name: \"Luke Skywalker\",\n          friends: [{ __typename: \"Person\", name: \"r2d2\" }],\n        },\n      ],\n    },\n  };\n\n  const link = new MockLink([\n    {\n      request: { query, variables: variables1 },\n      result: { data },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n    },\n    {\n      request: { query, variables: variables2 },\n      result: { data },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ variables }) =>\n      useQuery(query, { variables, notifyOnNetworkStatusChange: false }),\n    {\n      initialProps: { variables: variables1 },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { takeSnapshot, getCurrentSnapshot } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: variables1,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: variables1,\n  });\n\n  await expect(\n    getCurrentSnapshot().refetch(variables2)\n  ).resolves.toStrictEqualTyped({ data });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: variables2,\n  });\n\n  await expect(\n    getCurrentSnapshot().refetch(variables1)\n  ).resolves.toStrictEqualTyped({ data });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: variables1,\n  });\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"rerenders if changing variables returns same result for different variables with notifyOnNetworkStatusChange: false\", async () => {\n  type Data = typeof data;\n  type Vars = { first: number };\n  const query: TypedDocumentNode<Data, Vars> = gql`\n    query people($first: Int!) {\n      allPeople(first: $first) {\n        people {\n          name\n          friends(id: $first) {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const variables1: Vars = { first: 1 };\n  const variables2: Vars = { first: 2 };\n  const data = {\n    allPeople: {\n      __typename: \"AllPeople\",\n      people: [\n        {\n          __typename: \"Person\",\n          name: \"Luke Skywalker\",\n          friends: [{ __typename: \"Person\", name: \"r2d2\" }],\n        },\n      ],\n    },\n  };\n\n  const link = new MockLink([\n    {\n      request: { query, variables: variables1 },\n      result: { data },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n    },\n    {\n      request: { query, variables: variables2 },\n      result: { data },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n    },\n  ]);\n\n  const client = new ApolloClient({\n    link,\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = await renderHookToSnapshotStream(\n    ({ variables }) =>\n      useQuery(query, { variables, notifyOnNetworkStatusChange: false }),\n    {\n      initialProps: { variables: variables1 },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { takeSnapshot, getCurrentSnapshot, rerender } = renderStream;\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.loading,\n    previousData: undefined,\n    variables: variables1,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: undefined,\n    variables: variables1,\n  });\n\n  await rerender({ variables: variables2 });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data: undefined,\n    dataState: \"empty\",\n    loading: true,\n    networkStatus: NetworkStatus.setVariables,\n    previousData: data,\n    variables: variables2,\n  });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: data,\n    variables: variables2,\n  });\n\n  await expect(\n    getCurrentSnapshot().refetch(variables1)\n  ).resolves.toStrictEqualTyped({ data });\n\n  await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n    data,\n    dataState: \"complete\",\n    loading: false,\n    networkStatus: NetworkStatus.ready,\n    previousData: data,\n    variables: variables1,\n  });\n\n  await expect(renderStream).not.toRerender();\n});\n\n{\n  interface Query {\n    id?: number;\n    name?: string;\n  }\n  interface QueryVariables {\n    shouldSkip: boolean;\n    shouldInclude: boolean;\n  }\n  type Result = Pick<\n    ReturnType<typeof useQuery<Query, QueryVariables>>,\n    | \"data\"\n    | \"dataState\"\n    | \"loading\"\n    | \"networkStatus\"\n    | \"previousData\"\n    | \"variables\"\n  >;\n  test.each<[WatchQueryFetchPolicy, ...Array<Result>]>([\n    [\n      \"cache-and-network\",\n      {\n        data: {},\n        dataState: \"complete\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n      {\n        data: {},\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n    ],\n    [\n      \"cache-first\",\n      {\n        data: {},\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n    ],\n    [\n      \"network-only\",\n      {\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n      {\n        data: {},\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n    ],\n    [\n      \"no-cache\",\n      {\n        data: undefined,\n        dataState: \"empty\",\n        loading: true,\n        networkStatus: NetworkStatus.loading,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n      {\n        data: {},\n        dataState: \"complete\",\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n        previousData: undefined,\n        variables: { shouldSkip: true, shouldInclude: false },\n      },\n    ],\n  ])(\n    \"returns `data: {}` and `dataState: 'complete'` when all fields are skipped (using fetchPolicy: %s)\",\n    async (fetchPolicy, ...expectedResults) => {\n      const query: TypedDocumentNode<Query, QueryVariables> = gql`\n        query TestQuery($shouldSkip: Boolean!, $shouldInclude: Boolean!) {\n          id @skip(if: $shouldSkip)\n          name @include(if: $shouldInclude)\n        }\n      `;\n\n      const link = new MockLink([\n        {\n          request: {\n            query,\n            variables: { shouldSkip: true, shouldInclude: false },\n          },\n          result: { data: {} },\n          delay: 20,\n        },\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () =>\n          useQuery(query, {\n            variables: { shouldSkip: true, shouldInclude: false },\n            fetchPolicy,\n          }) satisfies Result as Result,\n        { wrapper: createClientWrapper(client) }\n      );\n\n      for (const expectedResult of expectedResults) {\n        await expect(takeSnapshot()).resolves.toStrictEqualTyped(\n          expectedResult\n        );\n      }\n\n      await expect(takeSnapshot).not.toRerender();\n    }\n  );\n}\n\ndescribe.skip(\"Type Tests\", () => {\n  test(\"returns narrowed TData in default case\", () => {\n    const { query } = setupSimpleCase();\n\n    const { data, dataState } = useQuery(query);\n\n    expectTypeOf(dataState).toEqualTypeOf<\"empty\" | \"streaming\" | \"complete\">();\n\n    if (dataState === \"complete\") {\n      expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n    }\n\n    if (dataState === \"streaming\") {\n      expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n    }\n\n    if (dataState === \"empty\") {\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n  });\n\n  test(\"returns DeepPartial<TData> with returnPartialData: true\", () => {\n    const { query } = setupSimpleCase();\n\n    const { data, dataState } = useQuery(query, { returnPartialData: true });\n\n    expectTypeOf(dataState).toEqualTypeOf<\n      \"empty\" | \"streaming\" | \"complete\" | \"partial\"\n    >();\n\n    if (dataState === \"complete\") {\n      expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n    }\n\n    if (dataState === \"partial\") {\n      expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n    }\n\n    if (dataState === \"streaming\") {\n      expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n    }\n\n    if (dataState === \"empty\") {\n      expectTypeOf(data).toEqualTypeOf<undefined>();\n    }\n  });\n\n  test(\"NoInfer prevents adding arbitrary additional variables\", () => {\n    const typedNode = {} as TypedDocumentNode<{ foo: string }, { bar: number }>;\n    const { variables } = useQuery(typedNode, {\n      variables: {\n        bar: 4,\n        // @ts-expect-error\n        nonExistingVariable: \"string\",\n      },\n    });\n    variables?.bar;\n    // @ts-expect-error\n    variables?.nonExistingVariable;\n  });\n\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const query = gql``;\n\n    useQuery(query);\n    useQuery(query, {});\n    useQuery(query, { variables: {} });\n    useQuery(query, { variables: { foo: \"bar\" } });\n    useQuery(query, { variables: { bar: \"baz\" } });\n\n    let skip!: boolean;\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(query, skip ? skipToken : {});\n    useQuery(query, skip ? skipToken : { variables: {} });\n    useQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n    useQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    useQuery(query);\n    useQuery(query, {});\n    useQuery(query, { variables: {} });\n    useQuery(query, { variables: { foo: \"bar\" } });\n    useQuery(query, { variables: { bar: \"baz\" } });\n\n    let skip!: boolean;\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(query, skip ? skipToken : {});\n    useQuery(query, skip ? skipToken : { variables: {} });\n    useQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n    useQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const query: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    useQuery(query);\n    useQuery(query, {});\n    useQuery(query, { variables: {} });\n    useQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(query, skip ? skipToken : {});\n    useQuery(query, skip ? skipToken : { variables: {} });\n    useQuery(\n      query,\n      // @ts-expect-error unknown variables\n      skip ? skipToken : { variables: { foo: \"bar\" } }\n    );\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    // @ts-expect-error\n    useQuery(query);\n    // @ts-expect-error\n    useQuery(query, {});\n    useQuery(query, {\n      // @ts-expect-error\n      variables: {},\n    });\n    useQuery(query, {\n      // @ts-expect-error\n      variables: undefined,\n    });\n    useQuery(query, {\n      // @ts-expect-error\n      variables: {\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : {}\n    );\n    useQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : { variables: {} }\n    );\n    useQuery(\n      query,\n      // @ts-expect-error\n      skip ? skipToken : { variables: undefined }\n    );\n    useQuery(\n      query,\n      // @ts-expect-error unknown variables\n      skip ? skipToken : { variables: { foo: \"bar\" } }\n    );\n  });\n\n  test(\"optional variables are optional\", () => {\n    const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    useQuery(query);\n    useQuery(query, {});\n    useQuery(query, { variables: {} });\n    useQuery(query, { variables: { limit: 10 } });\n    useQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useQuery(query, {\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(query, skip ? skipToken : {});\n    useQuery(query, skip ? skipToken : { variables: {} });\n    useQuery(query, skip ? skipToken : { variables: { limit: 10 } });\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            limit: 10,\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n\n  test(\"enforces required variables when TVariables includes required variables\", () => {\n    const query: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    // @ts-expect-error empty variables\n    useQuery(query);\n    // @ts-expect-error empty variables\n    useQuery(query, {});\n    // @ts-expect-error empty variables\n    useQuery(query, { variables: {} });\n    useQuery(query, { variables: { id: \"1\" } });\n    useQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error missing variables option\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(\n      query,\n      // @ts-expect-error missing variables option\n      skip ? skipToken : {}\n    );\n    useQuery(\n      query,\n      // @ts-expect-error missing required variables\n      skip ? skipToken : { variables: {} }\n    );\n    useQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    // @ts-expect-error empty variables\n    useQuery(query);\n    // @ts-expect-error empty variables\n    useQuery(query, {});\n    // @ts-expect-error empty variables\n    useQuery(query, { variables: {} });\n    useQuery(query, { variables: { id: \"1\" } });\n    useQuery(query, {\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    useQuery(query, { variables: { id: \"1\", language: \"en\" } });\n    useQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useQuery(query, {\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n\n    let skip!: boolean;\n    // @ts-expect-error missing variables option\n    useQuery(query, skip ? skipToken : undefined);\n    useQuery(\n      query,\n      // @ts-expect-error missing variables option\n      skip ? skipToken : {}\n    );\n    useQuery(\n      query,\n      // @ts-expect-error missing required variables\n      skip ? skipToken : { variables: {} }\n    );\n    useQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n    useQuery(\n      query,\n      skip ? skipToken : { variables: { id: \"1\", language: \"en\" } }\n    );\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n    useQuery(\n      query,\n      skip ? skipToken : (\n        {\n          variables: {\n            id: \"1\",\n            language: \"en\",\n            // @ts-expect-error unknown variables\n            foo: \"bar\",\n          },\n        }\n      )\n    );\n  });\n\n  test(\"always returns empty data/dataState with unconditional skipToken\", () => {\n    const query: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    const { data, dataState, variables } = useQuery(query, skipToken);\n\n    expectTypeOf(data).toEqualTypeOf<undefined>();\n    expectTypeOf(dataState).toEqualTypeOf<\"empty\">();\n    expectTypeOf(variables).toEqualTypeOf<Record<string, never>>();\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useQueryRefHandlers.test.tsx",
    "content": "import { screen } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport React, { Suspense } from \"react\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  createQueryPreloader,\n  useBackgroundQuery,\n  useLoadableQuery,\n  useQueryRefHandlers,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  PaginatedCaseData,\n  SimpleCaseData,\n} from \"@apollo/client/testing/internal\";\nimport {\n  createClientWrapper,\n  setupPaginatedCase,\n  setupSimpleCase,\n} from \"@apollo/client/testing/internal\";\nimport { concatPagination } from \"@apollo/client/utilities\";\nimport { getMainDefinition } from \"@apollo/client/utilities/internal\";\n\nimport type {\n  SubscribeToMoreFunction,\n  SubscribeToMoreUpdateQueryFn,\n} from \"../../../core/watchQueryOptions.js\";\n\ntest(\"does not interfere with updates from useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    // We can ignore the return result here since we are testing the mechanics\n    // of this hook to ensure it doesn't interfere with the updates from\n    // useReadQuery\n    useQueryRefHandlers(queryRef);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook />\n      </Suspense>\n    );\n  }\n\n  const { rerender } = await renderStream.render(<App />, {\n    wrapper: createClientWrapper(client),\n  });\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({ query, data: { greeting: \"Hello again\" } });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender(<App />);\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"refetches and resuspends when calling refetch\", async () => {\n  const { query, mocks: defaultMocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n\n  const mocks = [\n    defaultMocks[0],\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello again\" } },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { refetch } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button onClick={() => refetch()}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest('honors refetchWritePolicy set to \"merge\"', async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  interface QueryData {\n    primes: number[];\n  }\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<QueryData> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    refetchWritePolicy: \"merge\",\n    variables: { min: 0, max: 12 },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { refetch } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest('honors refetchWritePolicy set to \"overwrite\"', async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  interface QueryData {\n    primes: number[];\n  }\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<QueryData> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    refetchWritePolicy: \"overwrite\",\n    variables: { min: 0, max: 12 },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { refetch } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [undefined, [13, 17, 19, 23, 29]],\n    ]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest('defaults refetchWritePolicy to \"overwrite\"', async () => {\n  const query: TypedDocumentNode<\n    { primes: number[] },\n    { min: number; max: number }\n  > = gql`\n    query GetPrimes($min: number, $max: number) {\n      primes(min: $min, max: $max)\n    }\n  `;\n\n  interface QueryData {\n    primes: number[];\n  }\n\n  const mocks = [\n    {\n      request: { query, variables: { min: 0, max: 12 } },\n      result: { data: { primes: [2, 3, 5, 7, 11] } },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { min: 12, max: 30 } },\n      result: { data: { primes: [13, 17, 19, 23, 29] } },\n      delay: 10,\n    },\n  ];\n\n  const mergeParams: [number[] | undefined, number[]][] = [];\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          primes: {\n            keyArgs: false,\n            merge(existing: number[] | undefined, incoming: number[]) {\n              mergeParams.push([existing, incoming]);\n              return existing ? existing.concat(incoming) : incoming;\n            },\n          },\n        },\n      },\n    },\n  });\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<QueryData> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    variables: { min: 0, max: 12 },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { refetch } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button onClick={() => refetch({ min: 12, max: 30 })}>Refetch</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [2, 3, 5, 7, 11] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { primes: [13, 17, 19, 23, 29] },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [undefined, [13, 17, 19, 23, 29]],\n    ]);\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"`refetch` works with startTransition\", async () => {\n  type Variables = {\n    id: string;\n  };\n\n  interface Data {\n    todo: {\n      id: string;\n      name: string;\n      completed: boolean;\n    };\n  }\n  const user = userEvent.setup();\n\n  const query: TypedDocumentNode<Data, Variables> = gql`\n    query TodoItemQuery($id: ID!) {\n      todo(id: $id) {\n        id\n        name\n        completed\n      }\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse[] = [\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n      },\n      delay: 10,\n    },\n    {\n      request: { query, variables: { id: \"1\" } },\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n      },\n      delay: 10,\n    },\n  ];\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      isPending: false,\n      result: null as useReadQuery.Result<Data> | null,\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, { variables: { id: \"1\" } });\n\n  function App() {\n    useTrackRenders();\n    const { refetch } = useQueryRefHandlers(queryRef);\n    const [isPending, startTransition] = React.useTransition();\n\n    renderStream.mergeSnapshot({ isPending });\n\n    return (\n      <>\n        <button\n          disabled={isPending}\n          onClick={() => {\n            startTransition(() => {\n              void refetch();\n            });\n          }}\n        >\n          Refetch\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <Todo />\n        </Suspense>\n      </>\n    );\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function Todo() {\n    useTrackRenders();\n    const result = useReadQuery(queryRef);\n    const { todo } = result.data;\n\n    renderStream.mergeSnapshot({ result });\n\n    return (\n      <div data-testid=\"todo\">\n        {todo.name}\n        {todo.completed && \" (completed)\"}\n      </div>\n    );\n  }\n\n  await renderStream.render(<App />);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  const button = screen.getByText(\"Refetch\");\n  await user.click(button);\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, Todo]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: true,\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, Todo]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"`refetch` works with startTransition from useBackgroundQuery and usePreloadedQueryHandlers\", async () => {\n  const { query, mocks: defaultMocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n\n  const mocks = [\n    defaultMocks[0],\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello again\" } },\n      delay: 20,\n    },\n    {\n      request: { query },\n      result: { data: { greeting: \"You again?\" } },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      useBackgroundQueryIsPending: false,\n      usePreloadedQueryHandlersIsPending: false,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({ queryRef }: { queryRef: QueryRef<SimpleCaseData> }) {\n    useTrackRenders();\n    const [isPending, startTransition] = React.useTransition();\n    const { refetch } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({\n      usePreloadedQueryHandlersIsPending: isPending,\n      result: useReadQuery(queryRef),\n    });\n\n    return (\n      <button\n        onClick={() =>\n          startTransition(() => {\n            void refetch();\n          })\n        }\n      >\n        Refetch from child\n      </button>\n    );\n  }\n\n  function App() {\n    useTrackRenders();\n    const [isPending, startTransition] = React.useTransition();\n    const [queryRef, { refetch }] = useBackgroundQuery(query);\n\n    renderStream.mergeSnapshot({ useBackgroundQueryIsPending: isPending });\n\n    return (\n      <>\n        <button\n          onClick={() =>\n            startTransition(() => {\n              void refetch();\n            })\n          }\n        >\n          Refetch from parent\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch from parent\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: true,\n      usePreloadedQueryHandlersIsPending: false,\n      result: {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      usePreloadedQueryHandlersIsPending: false,\n      result: {\n        data: { greeting: \"Hello again\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch from child\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      usePreloadedQueryHandlersIsPending: true,\n      result: {\n        data: { greeting: \"Hello again\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      usePreloadedQueryHandlersIsPending: false,\n      result: {\n        data: { greeting: \"You again?\" },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"refetches from queryRefs produced by useBackgroundQuery\", async () => {\n  const { query, mocks: defaultMocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n\n  const mocks = [\n    defaultMocks[0],\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello again\" } },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({ queryRef }: { queryRef: QueryRef<SimpleCaseData> }) {\n    const { refetch } = useQueryRefHandlers(queryRef);\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return <button onClick={() => refetch()}>Refetch</button>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"refetches from queryRefs produced by useLoadableQuery\", async () => {\n  const { query, mocks: defaultMocks } = setupSimpleCase();\n\n  const user = userEvent.setup();\n\n  const mocks = [\n    defaultMocks[0],\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello again\" } },\n      delay: 20,\n    },\n  ];\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({ queryRef }: { queryRef: QueryRef<SimpleCaseData> }) {\n    const { refetch } = useQueryRefHandlers(queryRef);\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return <button onClick={() => refetch()}>Refetch</button>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Refetch\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello again\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"resuspends when calling `fetchMore`\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    }),\n    link,\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button\n          onClick={() => fetchMore({ variables: { limit: 2, offset: 2 } })}\n        >\n          Load next\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </>\n    );\n  }\n\n  const queryRef = preloadQuery(query);\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"properly uses `updateQuery` when calling `fetchMore`\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button\n          onClick={() =>\n            fetchMore({\n              variables: { limit: 2, offset: 2 },\n              updateQuery: (prev, { fetchMoreResult }) => ({\n                letters: prev.letters.concat(fetchMoreResult.letters),\n              }),\n            })\n          }\n        >\n          Load next\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </>\n    );\n  }\n\n  const queryRef = preloadQuery(query);\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"properly uses cache field policies when calling `fetchMore` without `updateQuery`\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: concatPagination(),\n          },\n        },\n      },\n    }),\n    link,\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    return (\n      <>\n        <button\n          onClick={() => fetchMore({ variables: { limit: 2, offset: 2 } })}\n        >\n          Load next\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </>\n    );\n  }\n\n  const queryRef = preloadQuery(query);\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"paginates from queryRefs produced by useBackgroundQuery\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    }),\n    link,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({\n    queryRef,\n  }: {\n    queryRef: QueryRef<PaginatedCaseData>;\n  }) {\n    useTrackRenders();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return (\n      <button onClick={() => fetchMore({ variables: { limit: 2, offset: 2 } })}>\n        Load next\n      </button>\n    );\n  }\n\n  function App() {\n    useTrackRenders();\n    const [queryRef] = useBackgroundQuery(query);\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook queryRef={queryRef} />\n      </Suspense>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"paginates from queryRefs produced by useLoadableQuery\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    }),\n    link,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({\n    queryRef,\n  }: {\n    queryRef: QueryRef<PaginatedCaseData>;\n  }) {\n    useTrackRenders();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return (\n      <button onClick={() => fetchMore({ variables: { limit: 2, offset: 2 } })}>\n        Load next\n      </button>\n    );\n  }\n\n  function App() {\n    useTrackRenders();\n    const [loadQuery, queryRef] = useLoadableQuery(query);\n\n    return (\n      <>\n        <button onClick={() => loadQuery()}>Load query</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {queryRef && <ReadQueryHook queryRef={queryRef} />}\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  // initial render\n  await renderStream.takeRender();\n\n  await user.click(screen.getByText(\"Load query\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"`fetchMore` works with startTransition\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    }),\n    link,\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      isPending: false,\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [isPending, startTransition] = React.useTransition();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({ isPending });\n\n    return (\n      <>\n        <button\n          onClick={() =>\n            startTransition(() => {\n              void fetchMore({ variables: { offset: 2, limit: 2 } });\n            })\n          }\n        >\n          Load next\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </>\n    );\n  }\n\n  const queryRef = preloadQuery(query);\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Load next\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: true,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"A\", position: 1 },\n            { __typename: \"Letter\", letter: \"B\", position: 2 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      isPending: false,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"C\", position: 3 },\n            { __typename: \"Letter\", letter: \"D\", position: 4 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"`fetchMore` works with startTransition from useBackgroundQuery and useQueryRefHandlers\", async () => {\n  const { query, link } = setupPaginatedCase();\n\n  const user = userEvent.setup();\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: { keyArgs: false },\n          },\n        },\n      },\n    }),\n    link,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      useBackgroundQueryIsPending: false,\n      useQueryRefHandlersIsPending: false,\n      result: null as useReadQuery.Result<PaginatedCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook({\n    queryRef,\n  }: {\n    queryRef: QueryRef<PaginatedCaseData>;\n  }) {\n    useTrackRenders();\n    const [isPending, startTransition] = React.useTransition();\n    const { fetchMore } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({\n      useQueryRefHandlersIsPending: isPending,\n      result: useReadQuery(queryRef),\n    });\n\n    return (\n      <button\n        onClick={() =>\n          startTransition(() => {\n            void fetchMore({ variables: { offset: 4, limit: 2 } });\n          })\n        }\n      >\n        Paginate from child\n      </button>\n    );\n  }\n\n  function App() {\n    useTrackRenders();\n    const [isPending, startTransition] = React.useTransition();\n    const [queryRef, { fetchMore }] = useBackgroundQuery(query);\n\n    renderStream.mergeSnapshot({ useBackgroundQueryIsPending: isPending });\n\n    return (\n      <>\n        <button\n          onClick={() =>\n            startTransition(() => {\n              void fetchMore({ variables: { offset: 2, limit: 2 } });\n            })\n          }\n        >\n          Paginate from parent\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook queryRef={queryRef} />\n        </Suspense>\n      </>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await user.click(screen.getByText(\"Paginate from parent\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: true,\n      useQueryRefHandlersIsPending: false,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"A\", position: 1 },\n            { __typename: \"Letter\", letter: \"B\", position: 2 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      useQueryRefHandlersIsPending: false,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"C\", position: 3 },\n            { __typename: \"Letter\", letter: \"D\", position: 4 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await user.click(screen.getByText(\"Paginate from child\"));\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      useQueryRefHandlersIsPending: true,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"C\", position: 3 },\n            { __typename: \"Letter\", letter: \"D\", position: 4 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot).toStrictEqualTyped({\n      useBackgroundQueryIsPending: false,\n      useQueryRefHandlersIsPending: false,\n      result: {\n        data: {\n          letters: [\n            { __typename: \"Letter\", letter: \"E\", position: 5 },\n            { __typename: \"Letter\", letter: \"F\", position: 6 },\n          ],\n        },\n        dataState: \"complete\",\n        error: undefined,\n        networkStatus: NetworkStatus.ready,\n      },\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"can subscribe to subscriptions and react to cache updates via `subscribeToMore`\", async () => {\n  interface SubscriptionData {\n    greetingUpdated: string;\n  }\n\n  type UpdateQueryFn = SubscribeToMoreUpdateQueryFn<\n    SimpleCaseData,\n    Record<string, never>,\n    SubscriptionData\n  >;\n\n  const subscription: TypedDocumentNode<\n    SubscriptionData,\n    Record<string, never>\n  > = gql`\n    subscription {\n      greetingUpdated\n    }\n  `;\n\n  const { mocks, query } = setupSimpleCase();\n\n  const wsLink = new MockSubscriptionLink();\n  const mockLink = new MockLink(mocks);\n\n  const link = ApolloLink.split(\n    ({ query }) => {\n      const definition = getMainDefinition(query);\n\n      return (\n        definition.kind === \"OperationDefinition\" &&\n        definition.operation === \"subscription\"\n      );\n    },\n    wsLink,\n    mockLink\n  );\n\n  const client = new ApolloClient({ link, cache: new InMemoryCache() });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      subscribeToMore: null as SubscribeToMoreFunction<\n        SimpleCaseData,\n        Record<string, never>\n      > | null,\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <p>Loading</p>;\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders();\n    // We can ignore the return result here since we are testing the mechanics\n    // of this hook to ensure it doesn't interfere with the updates from\n    // useReadQuery\n    const { subscribeToMore } = useQueryRefHandlers(queryRef);\n\n    renderStream.mergeSnapshot({ subscribeToMore });\n\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ReadQueryHook />\n      </Suspense>\n    );\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  const updateQuery = jest.fn<\n    ReturnType<UpdateQueryFn>,\n    Parameters<UpdateQueryFn>\n  >((_, { subscriptionData: { data } }) => {\n    return { greeting: data.greetingUpdated };\n  });\n\n  const { snapshot } = renderStream.getCurrentRender();\n\n  snapshot.subscribeToMore!({ document: subscription, updateQuery });\n\n  wsLink.simulateResult({\n    result: {\n      data: {\n        greetingUpdated: \"Subscription hello\",\n      },\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Subscription hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(updateQuery).toHaveBeenCalledTimes(1);\n  expect(updateQuery).toHaveBeenCalledWith(\n    { greeting: \"Hello\" },\n    {\n      complete: true,\n      previousData: { greeting: \"Hello\" },\n      subscriptionData: {\n        data: { greetingUpdated: \"Subscription hello\" },\n      },\n      variables: {},\n    }\n  );\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useReactiveVar.test.tsx",
    "content": "import { act, render, screen, waitFor } from \"@testing-library/react\";\nimport React, { StrictMode, useEffect } from \"react\";\n\nimport { makeVar } from \"@apollo/client\";\nimport { useReactiveVar } from \"@apollo/client/react\";\n\nconst IS_REACT_18 = React.version.startsWith(\"18\");\nconst IS_REACT_19 = React.version.startsWith(\"19\");\n\ndescribe(\"useReactiveVar Hook\", () => {\n  it(\"works with one component\", async () => {\n    const counterVar = makeVar(0);\n    let renderCount = 0;\n\n    function Component() {\n      const count = useReactiveVar(counterVar);\n\n      useEffect(() => {\n        switch (++renderCount) {\n          case 1:\n            expect(count).toBe(0);\n            counterVar(count + 1);\n            break;\n          case 2:\n            expect(count).toBe(1);\n            counterVar(counterVar() + 2);\n            break;\n          case 3:\n            expect(count).toBe(3);\n            break;\n          default:\n            console.error(`too many (${renderCount}) renders`);\n        }\n      });\n\n      return null;\n    }\n\n    render(<Component />);\n\n    await waitFor(() => {\n      expect(renderCount).toBe(3);\n    });\n    await waitFor(() => {\n      expect(counterVar()).toBe(3);\n    });\n  });\n\n  it(\"works when two components share a variable\", async () => {\n    const counterVar = makeVar(0);\n\n    let parentRenderCount = 0;\n    function Parent() {\n      const count = useReactiveVar(counterVar);\n\n      switch (++parentRenderCount) {\n        case 1:\n          expect(count).toBe(0);\n          break;\n        case 2:\n          expect(count).toBe(1);\n          break;\n        case 3:\n          expect(count).toBe(11);\n          break;\n        default:\n          throw new Error(`too many (${parentRenderCount}) parent renders`);\n      }\n\n      return <Child />;\n    }\n\n    let childRenderCount = 0;\n    function Child() {\n      const count = useReactiveVar(counterVar);\n\n      switch (++childRenderCount) {\n        case 1:\n          expect(count).toBe(0);\n          break;\n        case 2:\n          expect(count).toBe(1);\n          break;\n        case 3:\n          expect(count).toBe(11);\n          break;\n        default:\n          throw new Error(`too many (${childRenderCount}) child renders`);\n      }\n\n      return null;\n    }\n\n    render(<Parent />);\n\n    await waitFor(() => {\n      expect(parentRenderCount).toBe(1);\n    });\n\n    await waitFor(() => {\n      expect(childRenderCount).toBe(1);\n    });\n\n    expect(counterVar()).toBe(0);\n    act(() => {\n      counterVar(1);\n    });\n\n    await waitFor(() => {\n      expect(parentRenderCount).toBe(2);\n    });\n    await waitFor(() => {\n      expect(childRenderCount).toBe(2);\n    });\n\n    expect(counterVar()).toBe(1);\n    act(() => {\n      counterVar(counterVar() + 10);\n    });\n\n    await waitFor(() => {\n      expect(parentRenderCount).toBe(3);\n    });\n    await waitFor(() => {\n      expect(childRenderCount).toBe(3);\n    });\n\n    expect(counterVar()).toBe(11);\n  });\n\n  it(\"does not update if component has been unmounted\", async () => {\n    const counterVar = makeVar(0);\n    let renderCount = 0;\n    let attemptedUpdateAfterUnmount = false;\n\n    function Component() {\n      const count = useReactiveVar(counterVar);\n\n      useEffect(() => {\n        if (count < 3) {\n          expect(count).toBe(renderCount++);\n          counterVar(count + 1);\n        }\n\n        if (count === 3) {\n          expect(count).toBe(3);\n          setTimeout(() => {\n            unmount();\n            setTimeout(() => {\n              counterVar(counterVar() * 2);\n              attemptedUpdateAfterUnmount = true;\n            }, 10);\n          }, 10);\n        }\n      });\n\n      return null;\n    }\n\n    // To detect updates of unmounted components, we have to monkey-patch\n    // the console.error method.\n    const consoleErrorArgs: any[][] = [];\n    const { error } = console;\n    console.error = function (...args: any[]) {\n      consoleErrorArgs.push(args);\n      return error.apply(this, args);\n    };\n\n    const { unmount } = render(<Component />);\n\n    await waitFor(() => {\n      expect(attemptedUpdateAfterUnmount).toBe(true);\n    });\n    await waitFor(() => {\n      expect(renderCount).toBe(3);\n    });\n    await waitFor(() => {\n      expect(counterVar()).toBe(6);\n    });\n    await waitFor(() => {\n      expect(consoleErrorArgs).toEqual([]);\n    });\n    console.error = error;\n  });\n\n  describe(\"useEffect\", () => {\n    it(\"works if updated higher in the component tree\", async () => {\n      const counterVar = makeVar(0);\n\n      function ComponentOne() {\n        const count = useReactiveVar(counterVar);\n\n        useEffect(() => {\n          counterVar(1);\n        }, []);\n\n        return <div>{count}</div>;\n      }\n\n      function ComponentTwo() {\n        const count = useReactiveVar(counterVar);\n\n        return <div>{count}</div>;\n      }\n\n      render(\n        <>\n          <ComponentOne />\n          <ComponentTwo />\n        </>\n      );\n\n      await waitFor(() => {\n        expect(screen.getAllByText(\"1\")).toHaveLength(2);\n      });\n    });\n\n    it(\"works if updated lower in the component tree\", async () => {\n      const counterVar = makeVar(0);\n\n      function ComponentOne() {\n        const count = useReactiveVar(counterVar);\n\n        return <div>{count}</div>;\n      }\n\n      function ComponentTwo() {\n        const count = useReactiveVar(counterVar);\n\n        useEffect(() => {\n          counterVar(1);\n        }, []);\n\n        return <div>{count}</div>;\n      }\n\n      render(\n        <>\n          <ComponentOne />\n          <ComponentTwo />\n        </>\n      );\n\n      await waitFor(() => {\n        expect(screen.getAllByText(\"1\")).toHaveLength(2);\n      });\n    });\n\n    it(\"works with strict mode\", async () => {\n      const counterVar = makeVar(0);\n      const mock = jest.fn();\n\n      function Component() {\n        const count = useReactiveVar(counterVar);\n        useEffect(() => {\n          mock(count);\n        }, [count]);\n\n        useEffect(() => {\n          void Promise.resolve().then(() => {\n            counterVar(counterVar() + 1);\n          });\n        }, []);\n\n        return <div />;\n      }\n\n      render(\n        <StrictMode>\n          <Component />\n        </StrictMode>\n      );\n\n      await waitFor(() => {\n        if (IS_REACT_18 || IS_REACT_19) {\n          expect(mock).toHaveBeenCalledTimes(3);\n          expect(mock).toHaveBeenNthCalledWith(1, 0);\n          expect(mock).toHaveBeenNthCalledWith(2, 0);\n          expect(mock).toHaveBeenNthCalledWith(3, 2);\n        } else {\n          expect(mock).toHaveBeenCalledTimes(2);\n          expect(mock).toHaveBeenNthCalledWith(1, 0);\n          expect(mock).toHaveBeenNthCalledWith(2, 1);\n        }\n      });\n    });\n\n    it(\"works with multiple synchronous calls\", async () => {\n      const counterVar = makeVar(0);\n      function Component() {\n        const count = useReactiveVar(counterVar);\n\n        return <div>{count}</div>;\n      }\n\n      render(<Component />);\n      void Promise.resolve().then(() => {\n        counterVar(1);\n        counterVar(2);\n        counterVar(3);\n        counterVar(4);\n        counterVar(5);\n        counterVar(6);\n        counterVar(7);\n        counterVar(8);\n        counterVar(9);\n        counterVar(10);\n      });\n\n      await waitFor(() => {\n        expect(screen.getAllByText(\"10\")).toHaveLength(1);\n      });\n    });\n\n    it(\"should survive many rerenderings despite racing asynchronous updates\", (done) => {\n      const rv = makeVar(0);\n\n      function App() {\n        const value = useReactiveVar(rv);\n        return (\n          <div className=\"App\">\n            <h1>{value}</h1>\n          </div>\n        );\n      }\n\n      const goalCount = 1000;\n      let updateCount = 0;\n      let stopped = false;\n\n      function spam() {\n        if (stopped) return;\n        try {\n          if (++updateCount <= goalCount) {\n            act(() => {\n              rv(updateCount);\n              setTimeout(spam, Math.random() * 10);\n            });\n          } else {\n            stopped = true;\n            expect(rv()).toBe(goalCount);\n            void screen\n              .findByText(String(goalCount))\n              .then((element) => {\n                expect(element.nodeName.toLowerCase()).toBe(\"h1\");\n              })\n              .then(done);\n          }\n        } catch (e) {\n          stopped = true;\n          throw e;\n        }\n      }\n      spam();\n      spam();\n      spam();\n      spam();\n\n      render(\n        <StrictMode>\n          <App />\n        </StrictMode>\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSubscription.test.tsx",
    "content": "import { waitFor } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { expectTypeOf } from \"expect-type\";\nimport type { GraphQLFormattedError } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type { DefaultContext, TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink } from \"@apollo/client\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport {\n  CombinedGraphQLErrors,\n  CombinedProtocolErrors,\n} from \"@apollo/client/errors\";\nimport { ApolloProvider, useSubscription } from \"@apollo/client/react\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  mockMultipartSubscriptionStream,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nconst IS_REACT_17 = React.version.startsWith(\"17\");\n\ndescribe(\"useSubscription Hook\", () => {\n  it(\"should handle a simple subscription properly\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\", \"Mercedes\", \"Hyundai\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[1].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(results[2]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[2].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(results[3]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[3].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should call onError after error results\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\", \"Mercedes\", \"Hyundai\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const errorResult = {\n      result: { data: { car: { make: null } }, errors: [{ message: \"test\" }] },\n    };\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onError = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription, { onError }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(errorResult);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: errorResult.result.data,\n        errors: [{ message: \"test\" }],\n      }),\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(onError).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenCalledWith(\n      new CombinedGraphQLErrors({\n        data: errorResult.result.data,\n        errors: [{ message: \"test\" }],\n      })\n    );\n  });\n\n  it(\"can continue to receive new results after an error\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\", \"Mercedes\", \"Hyundai\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const errorResult = {\n      result: { data: { car: { make: null } }, errors: [{ message: \"test\" }] },\n    };\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onError = jest.fn();\n    const onData = jest.fn();\n    const onComplete = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription, { onError, onData, onComplete }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenLastCalledWith({\n      client,\n      data: {\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n    expect(onError).toHaveBeenCalledTimes(0);\n    expect(onComplete).toHaveBeenCalledTimes(0);\n\n    link.simulateResult(errorResult);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: new CombinedGraphQLErrors({\n        data: errorResult.result.data,\n        errors: [{ message: \"test\" }],\n      }),\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenLastCalledWith(\n      new CombinedGraphQLErrors({\n        data: errorResult.result.data,\n        errors: [{ message: \"test\" }],\n      })\n    );\n    expect(onComplete).toHaveBeenCalledTimes(0);\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[1].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(2);\n    expect(onData).toHaveBeenLastCalledWith({\n      client,\n      data: {\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n    expect(onError).toHaveBeenCalledTimes(1);\n    expect(onComplete).toHaveBeenCalledTimes(0);\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should call onComplete after subscription is complete\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\n      {\n        result: { data: { car: { make: \"Audi\" } } },\n      },\n    ];\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onComplete = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription, { onComplete }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateComplete();\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(onComplete).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should cleanup after the subscription component has been unmounted\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\n      {\n        result: { data: { car: { make: \"Pagani\" } } },\n      },\n    ];\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, unmount } = await renderHookToSnapshotStream(\n      () =>\n        useSubscription(subscription, {\n          onData,\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenCalledWith({\n      client,\n      data: {\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n\n    // After the component has been unmounted, the internal\n    // ObservableQuery should be stopped, meaning it shouldn't\n    // receive any new data (so the onDataCount should\n    // stay at 1).\n    unmount();\n    link.simulateResult(results[0]);\n\n    await wait(100);\n    expect(onData).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"should never execute a subscription with the skip option\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const onSetup = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(onSetup);\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn();\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, unmount, rerender } =\n      await renderHookToSnapshotStream(\n        ({ variables }) =>\n          useSubscription(subscription, { variables, skip: true, onData }),\n        {\n          initialProps: {\n            variables: {\n              foo: \"bar\",\n            },\n          },\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n    });\n\n    await rerender({ variables: { foo: \"bar2\" } });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(onSetup).toHaveBeenCalledTimes(0);\n    expect(onData).toHaveBeenCalledTimes(0);\n    unmount();\n  });\n\n  it(\"should create a subscription after skip has changed from true to a falsy value\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\n      {\n        result: { data: { car: { make: \"Pagani\" } } },\n      },\n      {\n        result: { data: { car: { make: \"Scoop\" } } },\n      },\n    ];\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ skip }) => useSubscription(subscription, { skip }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n        initialProps: { skip: true },\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n    });\n\n    await rerender({ skip: false });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    await rerender({ skip: true });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n    });\n\n    // ensure state persists across rerenders\n    await rerender({ skip: true });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    // ensure state persists across rerenders\n    await rerender({ skip: false });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[1].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should share context set in options\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    let context: string;\n    const link = new MockSubscriptionLink();\n    const contextLink = new ApolloLink((operation, forward) => {\n      context = operation.getContext()?.make;\n      return forward(operation);\n    });\n    const client = new ApolloClient({\n      link: ApolloLink.concat(contextLink, link),\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useSubscription(subscription, {\n          context: { make: \"Audi\" },\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[1].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(context!).toBe(\"Audi\");\n  });\n\n  it(\"should share extensions set in options\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    let extensions: string;\n    const link = new MockSubscriptionLink();\n    const extensionsLink = new ApolloLink((operation, forward) => {\n      extensions = operation.extensions.make;\n      return forward(operation);\n    });\n    const client = new ApolloClient({\n      link: ApolloLink.concat(extensionsLink, link),\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useSubscription(subscription, {\n          extensions: { make: \"Audi\" },\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[0].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: results[1].result.data,\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(extensions!).toBe(\"Audi\");\n  });\n\n  it(\"should handle multiple subscriptions properly\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => ({\n        sub1: useSubscription(subscription),\n        sub2: useSubscription(subscription),\n      }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { sub1, sub2 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    link.simulateResult(results[0]);\n\n    if (IS_REACT_17) {\n      const { sub1, sub2 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    {\n      const { sub1, sub2 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    link.simulateResult(results[1]);\n\n    if (IS_REACT_17) {\n      const { sub1, sub2 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    {\n      const { sub1, sub2 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should handle immediate completions gracefully\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    // Simulating the behavior of HttpLink, which calls next and complete in sequence.\n    link.simulateResult(\n      { result: { data: { car: { __typename: \"Car\", make: \"Audi\" } } } },\n      /* complete */ true\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { car: { __typename: \"Car\", make: \"Audi\" } },\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should handle immediate completions with multiple subscriptions gracefully\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => ({\n        sub1: useSubscription(subscription),\n        sub2: useSubscription(subscription),\n        sub3: useSubscription(subscription),\n      }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { sub1, sub2, sub3 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(sub3).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    // Simulating the behavior of HttpLink, which calls next and complete in sequence.\n    link.simulateResult(\n      { result: { data: { car: { __typename: \"Car\", make: \"Audi\" } } } },\n      /* complete */ true\n    );\n\n    if (IS_REACT_17) {\n      {\n        const { sub1, sub2, sub3 } = await takeSnapshot();\n\n        expect(sub1).toStrictEqualTyped({\n          data: { car: { __typename: \"Car\", make: \"Audi\" } },\n          error: undefined,\n          loading: false,\n        });\n\n        expect(sub2).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        expect(sub3).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      {\n        const { sub1, sub2, sub3 } = await takeSnapshot();\n\n        expect(sub1).toStrictEqualTyped({\n          data: { car: { __typename: \"Car\", make: \"Audi\" } },\n          error: undefined,\n          loading: false,\n        });\n\n        expect(sub2).toStrictEqualTyped({\n          data: { car: { __typename: \"Car\", make: \"Audi\" } },\n          error: undefined,\n          loading: false,\n        });\n\n        expect(sub3).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n    }\n\n    {\n      const { sub1, sub2, sub3 } = await takeSnapshot();\n\n      expect(sub1).toStrictEqualTyped({\n        data: { car: { __typename: \"Car\", make: \"Audi\" } },\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub2).toStrictEqualTyped({\n        data: { car: { __typename: \"Car\", make: \"Audi\" } },\n        error: undefined,\n        loading: false,\n      });\n\n      expect(sub3).toStrictEqualTyped({\n        data: { car: { __typename: \"Car\", make: \"Audi\" } },\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  describe(\"query deduplication\", () => {\n    test(\"deduplicates subscriptions by default\", async () => {\n      const subscription = gql`\n        subscription {\n          car {\n            make\n          }\n        }\n      `;\n\n      const results = [\"Audi\", \"BMW\"].map((make) => ({\n        result: { data: { car: { make } } },\n      }));\n\n      const onSubscribe = jest.fn();\n      const onUnsubscribe = jest.fn();\n      const link = new MockSubscriptionLink();\n      link.onSetup(onSubscribe);\n      link.onUnsubscribe(onUnsubscribe);\n\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      const { render, takeRender, mergeSnapshot, replaceSnapshot } =\n        createRenderStream<Record<number, useSubscription.Result<any>>>({\n          initialSnapshot: {},\n        });\n\n      function Subscription({ idx }: { idx: number }) {\n        mergeSnapshot({ [idx]: useSubscription(subscription) });\n        return null;\n      }\n\n      function App({ count }: { count: number }) {\n        replaceSnapshot({});\n\n        return (\n          <>\n            {Array.from({ length: count }).map((_, idx) => {\n              return <Subscription key={idx} idx={idx} />;\n            })}\n          </>\n        );\n      }\n\n      using _disabledAct = disableActEnvironment();\n      const { rerender } = await render(<App count={2} />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n      link.simulateResult(results[0]);\n\n      if (IS_REACT_17) {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await rerender(<App count={3} />);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(1);\n      expect(onUnsubscribe).not.toHaveBeenCalled();\n\n      link.simulateResult(results[1]);\n\n      if (IS_REACT_17) {\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[0].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await expect(takeRender).not.toRerender();\n    });\n\n    test(\"does not deduplicate new request after previous is unsubscribed\", async () => {\n      const subscription = gql`\n        subscription {\n          car {\n            make\n          }\n        }\n      `;\n\n      const results = [\"Audi\", \"BMW\"].map((make) => ({\n        result: { data: { car: { make } } },\n      }));\n\n      const onSubscribe = jest.fn();\n      const onUnsubscribe = jest.fn();\n      const link = new MockSubscriptionLink();\n      link.onSetup(onSubscribe);\n      link.onUnsubscribe(onUnsubscribe);\n\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      const { render, takeRender, mergeSnapshot, replaceSnapshot } =\n        createRenderStream<Record<number, useSubscription.Result<any>>>({\n          initialSnapshot: {},\n        });\n\n      function Subscription({\n        idx,\n        context,\n      }: {\n        idx: number;\n        context: DefaultContext;\n      }) {\n        mergeSnapshot({ [idx]: useSubscription(subscription, { context }) });\n        return null;\n      }\n\n      function App({\n        count,\n        context,\n      }: {\n        count: number;\n        context: DefaultContext;\n      }) {\n        replaceSnapshot({});\n\n        return (\n          <>\n            {Array.from({ length: count }).map((_, idx) => {\n              return <Subscription key={idx} idx={idx} context={context} />;\n            })}\n          </>\n        );\n      }\n\n      using _disabledAct = disableActEnvironment();\n      const { rerender } = await render(\n        <App count={1} context={{ count: 1 }} />,\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(1);\n      expect(link.operation!.getContext()).toMatchObject({ count: 1 });\n\n      link.simulateResult(results[0]);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await rerender(<App count={0} context={{ count: 1 }} />);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot).toStrictEqualTyped({});\n      }\n\n      await wait(0);\n\n      expect(onSubscribe).toHaveBeenCalledTimes(1);\n      expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n\n      await rerender(<App count={1} context={{ count: 2 }} />);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(2);\n      expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n      expect(link.operation!.getContext()).toMatchObject({ count: 2 });\n\n      link.simulateResult(results[1]);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await expect(takeRender).not.toRerender();\n    });\n\n    test(\"does not deduplicate requests when disabling queryDeduplication\", async () => {\n      const subscription = gql`\n        subscription {\n          car {\n            make\n          }\n        }\n      `;\n\n      const results = [\"Audi\", \"BMW\"].map((make) => ({\n        result: { data: { car: { make } } },\n      }));\n\n      const onSubscribe = jest.fn();\n      const onUnsubscribe = jest.fn();\n      const link = new MockSubscriptionLink();\n      link.onSetup(onSubscribe);\n      link.onUnsubscribe(onUnsubscribe);\n\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      const { render, takeRender, mergeSnapshot, replaceSnapshot } =\n        createRenderStream<Record<number, useSubscription.Result<any>>>({\n          initialSnapshot: {},\n        });\n\n      function Subscription({ idx }: { idx: number }) {\n        mergeSnapshot({\n          [idx]: useSubscription(subscription, {\n            context: { queryDeduplication: false },\n          }),\n        });\n        return null;\n      }\n\n      function App({ count }: { count: number }) {\n        replaceSnapshot({});\n\n        return (\n          <>\n            {Array.from({ length: count }).map((_, idx) => {\n              return <Subscription key={idx} idx={idx} />;\n            })}\n          </>\n        );\n      }\n\n      using _disabledAct = disableActEnvironment();\n      const { rerender } = await render(<App count={2} />, {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      });\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n      link.simulateResult(results[0]);\n\n      if (IS_REACT_17) {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await rerender(<App count={3} />);\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(3);\n      expect(onUnsubscribe).not.toHaveBeenCalled();\n\n      link.simulateResult(results[1]);\n\n      if (IS_REACT_17) {\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[0].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await expect(takeRender).not.toRerender();\n    });\n\n    test(\"can mix deduplicated subscriptions\", async () => {\n      const subscription = gql`\n        subscription {\n          car {\n            make\n          }\n        }\n      `;\n\n      const results = [\"Audi\", \"BMW\"].map((make) => ({\n        result: { data: { car: { make } } },\n      }));\n\n      const onSubscribe = jest.fn();\n      const onUnsubscribe = jest.fn();\n      const link = new MockSubscriptionLink();\n      link.onSetup(onSubscribe);\n      link.onUnsubscribe(onUnsubscribe);\n\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      const { render, takeRender, mergeSnapshot, replaceSnapshot } =\n        createRenderStream<Record<number, useSubscription.Result<any>>>({\n          initialSnapshot: {},\n        });\n\n      function Subscription({\n        idx,\n        options,\n      }: {\n        idx: number;\n        options: useSubscription.Options;\n      }) {\n        mergeSnapshot({ [idx]: useSubscription(subscription, options) });\n        return null;\n      }\n\n      function App({ options }: { options: useSubscription.Options[] }) {\n        replaceSnapshot({});\n\n        return (\n          <>\n            {options.map((opts, idx) => {\n              return <Subscription key={idx} idx={idx} options={opts} />;\n            })}\n          </>\n        );\n      }\n\n      using _disabledAct = disableActEnvironment();\n      const { rerender } = await render(\n        <App\n          options={[\n            { context: { queryDeduplication: true } },\n            { context: { queryDeduplication: true } },\n          ]}\n        />,\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n      link.simulateResult(results[0]);\n\n      if (IS_REACT_17) {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await rerender(\n        <App\n          options={[\n            { context: { queryDeduplication: true } },\n            { context: { queryDeduplication: true } },\n            { context: { queryDeduplication: false } },\n          ]}\n        />\n      );\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[0].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      expect(onSubscribe).toHaveBeenCalledTimes(2);\n      expect(onUnsubscribe).not.toHaveBeenCalled();\n\n      link.simulateResult(results[1]);\n\n      if (IS_REACT_17) {\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[0].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n\n        {\n          const { snapshot } = await takeRender();\n\n          expect(snapshot[0]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[1]).toStrictEqualTyped({\n            data: results[1].result.data,\n            error: undefined,\n            loading: false,\n          });\n\n          expect(snapshot[2]).toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n        }\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      await expect(takeRender).not.toRerender();\n    });\n  });\n\n  describe(\"multipart subscriptions\", () => {\n    it(\"should handle a simple subscription properly\", async () => {\n      const { httpLink, enqueueProtocolErrors } =\n        mockMultipartSubscriptionStream();\n\n      const subscription = gql`\n        subscription ANewDieWasCreated {\n          aNewDieWasCreated {\n            die {\n              color\n              roll\n              sides\n            }\n          }\n        }\n      `;\n\n      const client = new ApolloClient({\n        link: httpLink,\n        cache: new Cache(),\n      });\n\n      using _disabledAct = disableActEnvironment();\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        () => useSubscription(subscription),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        }\n      );\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      enqueueProtocolErrors([\n        {\n          message: \"cannot read message from websocket\",\n          extensions: {\n            code: \"WEBSOCKET_MESSAGE_ERROR\",\n          },\n        },\n      ]);\n\n      await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n        data: undefined,\n        error: new CombinedProtocolErrors([\n          {\n            message: \"cannot read message from websocket\",\n            extensions: {\n              code: \"WEBSOCKET_MESSAGE_ERROR\",\n            },\n          },\n        ]),\n        loading: false,\n      });\n\n      await expect(takeSnapshot).not.toRerender();\n    });\n  });\n\n  it(\"should handle simple subscription after old in-flight teardown immediately \\\nfollowed by new in-flight setup\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ coin }) => {\n        const heads = useSubscription(subscription, {\n          variables: {},\n          skip: coin === \"tails\",\n          context: { coin: \"heads\" },\n        });\n        const tails = useSubscription(subscription, {\n          variables: {},\n          skip: coin === \"heads\",\n          context: { coin: \"tails\" },\n        });\n        return { heads, tails };\n      },\n      {\n        initialProps: {\n          coin: \"heads\",\n        },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { heads, tails } = await takeSnapshot();\n\n      expect(heads).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(tails).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await rerender({ coin: \"tails\" });\n\n    {\n      const { heads, tails } = await takeSnapshot();\n\n      expect(heads).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(tails).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    await wait(20);\n\n    link.simulateResult(results[0]);\n\n    {\n      const { heads, tails } = await takeSnapshot();\n\n      expect(heads).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(tails).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await rerender({ coin: \"heads\" });\n\n    {\n      const { heads, tails } = await takeSnapshot();\n\n      expect(heads).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(tails).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    link.simulateResult(results[1]);\n\n    {\n      const { heads, tails } = await takeSnapshot();\n\n      expect(heads).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(tails).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  describe(\"errorPolicy\", () => {\n    async function setup(\n      initialProps: useSubscription.Options<{ totalLikes: number }, {}>\n    ) {\n      const subscription: TypedDocumentNode<{ totalLikes: number }, {}> = gql`\n        subscription ($id: ID!) {\n          totalLikes\n        }\n      `;\n      const errorBoundaryOnError = jest.fn();\n      const link = new MockSubscriptionLink();\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n      const wrapper = ({ children }: { children: any }) => (\n        <ApolloProvider client={client}>\n          <ErrorBoundary onError={errorBoundaryOnError} fallback={<>error</>}>\n            {children}\n          </ErrorBoundary>\n        </ApolloProvider>\n      );\n      const { takeSnapshot } = await renderHookToSnapshotStream(\n        (options: useSubscription.Options<{ totalLikes: number }, {}>) =>\n          useSubscription(subscription, options),\n        {\n          initialProps,\n          wrapper,\n        }\n      );\n      const graphQlErrorResult = {\n        result: {\n          data: { totalLikes: 42 },\n          errors: [{ message: \"test\" }],\n        },\n      } satisfies MockSubscriptionLink.Result;\n      const protocolErrorResult = {\n        error: new Error(\"Socket closed with event -1: I'm a test!\"),\n      } satisfies MockSubscriptionLink.Result;\n      return {\n        client,\n        link,\n        errorBoundaryOnError,\n        takeSnapshot,\n        graphQlErrorResult,\n        protocolErrorResult,\n      };\n    }\n    describe(\"GraphQL error\", () => {\n      it.each([undefined, \"none\"] as const)(\n        \"`errorPolicy: '%s'`: returns `{ error }`, calls `onError`\",\n        async (errorPolicy) => {\n          const onData = jest.fn();\n          const onError = jest.fn();\n          using _disabledAct = disableActEnvironment();\n          const {\n            takeSnapshot,\n            link,\n            graphQlErrorResult,\n            errorBoundaryOnError,\n          } = await setup({ errorPolicy, onError, onData });\n\n          await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n\n          link.simulateResult(graphQlErrorResult);\n\n          {\n            const snapshot = await takeSnapshot();\n            expect(snapshot).toStrictEqualTyped({\n              loading: false,\n              error: new CombinedGraphQLErrors(graphQlErrorResult.result!),\n              data: undefined,\n            });\n          }\n\n          expect(onError).toHaveBeenCalledTimes(1);\n          expect(onError).toHaveBeenCalledWith(\n            new CombinedGraphQLErrors(graphQlErrorResult.result!)\n          );\n          expect(onData).toHaveBeenCalledTimes(0);\n          expect(errorBoundaryOnError).toHaveBeenCalledTimes(0);\n        }\n      );\n      it(\"`errorPolicy: 'all'`: returns `{ error, data }`, calls `onError`\", async () => {\n        const onData = jest.fn();\n        const onError = jest.fn();\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot, link, graphQlErrorResult, errorBoundaryOnError } =\n          await setup({ errorPolicy: \"all\", onError, onData });\n\n        await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        link.simulateResult(graphQlErrorResult);\n\n        {\n          const snapshot = await takeSnapshot();\n          expect(snapshot).toStrictEqualTyped({\n            loading: false,\n            error: new CombinedGraphQLErrors(graphQlErrorResult.result!),\n            data: { totalLikes: 42 },\n          });\n        }\n\n        expect(onError).toHaveBeenCalledTimes(1);\n        expect(onError).toHaveBeenCalledWith(\n          new CombinedGraphQLErrors(graphQlErrorResult.result!)\n        );\n        expect(onData).toHaveBeenCalledTimes(0);\n        expect(errorBoundaryOnError).toHaveBeenCalledTimes(0);\n      });\n\n      it(\"`errorPolicy: 'ignore'`: returns `{ data }`, calls `onData`\", async () => {\n        const onData = jest.fn();\n        const onError = jest.fn();\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot, link, graphQlErrorResult, errorBoundaryOnError } =\n          await setup({\n            errorPolicy: \"ignore\",\n            onError,\n            onData,\n          });\n\n        await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        link.simulateResult(graphQlErrorResult);\n\n        {\n          const snapshot = await takeSnapshot();\n          expect(snapshot).toStrictEqualTyped({\n            loading: false,\n            error: undefined,\n            data: { totalLikes: 42 },\n          });\n        }\n\n        expect(onError).toHaveBeenCalledTimes(0);\n        expect(onData).toHaveBeenCalledTimes(1);\n        expect(onData).toHaveBeenCalledWith({\n          client: expect.anything(),\n          data: {\n            data: { totalLikes: 42 },\n            loading: false,\n            // should this be undefined?\n            error: undefined,\n            variables: undefined,\n          },\n        });\n        expect(errorBoundaryOnError).toHaveBeenCalledTimes(0);\n      });\n    });\n\n    describe(\"protocol error\", () => {\n      it.each([undefined, \"none\", \"all\"] as const)(\n        \"`errorPolicy: '%s'`: returns `{ error }`, calls `onError`\",\n        async (errorPolicy) => {\n          const { httpLink, enqueueProtocolErrors } =\n            mockMultipartSubscriptionStream();\n\n          const subscription: TypedDocumentNode<{ totalLikes: number }, {}> =\n            gql`\n              subscription ($id: ID!) {\n                totalLikes\n              }\n            `;\n          const client = new ApolloClient({\n            link: httpLink,\n            cache: new Cache(),\n          });\n\n          const onData = jest.fn();\n          const onError = jest.fn();\n          const onComplete = jest.fn();\n\n          using _disabledAct = disableActEnvironment();\n          const { takeSnapshot } = await renderHookToSnapshotStream(\n            () =>\n              useSubscription(subscription, {\n                errorPolicy,\n                onError,\n                onData,\n                onComplete,\n              }),\n            {\n              wrapper: ({ children }) => (\n                <ApolloProvider client={client}>{children}</ApolloProvider>\n              ),\n            }\n          );\n\n          await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n            data: undefined,\n            error: undefined,\n            loading: true,\n          });\n\n          enqueueProtocolErrors([\n            { message: \"Socket closed with event -1: I'm a test!\" },\n          ]);\n\n          const expectedError = new CombinedProtocolErrors([\n            { message: \"Socket closed with event -1: I'm a test!\" },\n          ]);\n\n          await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n            data: undefined,\n            error: expectedError,\n            loading: false,\n          });\n\n          expect(onError).toHaveBeenCalledTimes(1);\n          expect(onError).toHaveBeenCalledWith(expectedError);\n          expect(onData).toHaveBeenCalledTimes(0);\n          expect(onComplete).toHaveBeenCalledTimes(1);\n        }\n      );\n\n      it(\"`errorPolicy: 'ignore'`: does not rerender, calls `onComplete`\", async () => {\n        const { httpLink, enqueueProtocolErrors } =\n          mockMultipartSubscriptionStream();\n\n        const subscription: TypedDocumentNode<{ totalLikes: number }, {}> = gql`\n          subscription ($id: ID!) {\n            totalLikes\n          }\n        `;\n        const client = new ApolloClient({\n          link: httpLink,\n          cache: new Cache(),\n        });\n\n        const onData = jest.fn();\n        const onError = jest.fn();\n        const onComplete = jest.fn();\n\n        using _disabledAct = disableActEnvironment();\n        const { takeSnapshot } = await renderHookToSnapshotStream(\n          () =>\n            useSubscription(subscription, {\n              errorPolicy: \"ignore\",\n              onError,\n              onData,\n              onComplete,\n            }),\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n        await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n\n        enqueueProtocolErrors([\n          { message: \"Socket closed with event -1: I'm a test!\" },\n        ]);\n\n        await expect(takeSnapshot).not.toRerender();\n\n        expect(onError).toHaveBeenCalledTimes(0);\n        expect(onData).toHaveBeenCalledTimes(0);\n        expect(onComplete).toHaveBeenCalledTimes(1);\n      });\n    });\n  });\n});\n\ndescribe(\"`restart` callback\", () => {\n  async function setup(\n    initialProps: useSubscription.Options<\n      { totalLikes: number },\n      { id: string }\n    >\n  ) {\n    const subscription: TypedDocumentNode<\n      { totalLikes: number },\n      { id: string }\n    > = gql`\n      subscription ($id: ID!) {\n        totalLikes(postId: $id)\n      }\n    `;\n    const onSubscribe = jest.fn();\n    const onUnsubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(onSubscribe);\n    link.onUnsubscribe(onUnsubscribe);\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n    const { takeSnapshot, getCurrentSnapshot, rerender } =\n      await renderHookToSnapshotStream(\n        (\n          options: useSubscription.Options<\n            { totalLikes: number },\n            { id: string }\n          >\n        ) => useSubscription(subscription, options),\n        {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n          initialProps,\n        }\n      );\n    return {\n      client,\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n      rerender,\n    };\n  }\n\n  it(\"can restart a running subscription\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const {\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n    } = await setup({\n      variables: { id: \"1\" },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ result: { data: { totalLikes: 1 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 1 },\n        error: undefined,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    getCurrentSnapshot().restart();\n\n    await expect(takeSnapshot).not.toRerender();\n\n    await waitFor(() => expect(onUnsubscribe).toHaveBeenCalledTimes(1));\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n    link.simulateResult({ result: { data: { totalLikes: 2 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 2 },\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"will use the most recently passed in options\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const {\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n      rerender,\n    } = await setup({\n      variables: { id: \"1\" },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ result: { data: { totalLikes: 1 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 1 },\n        error: undefined,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    void rerender({ variables: { id: \"2\" } });\n\n    await waitFor(() => expect(onUnsubscribe).toHaveBeenCalledTimes(1));\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n    expect(link.operation?.variables).toStrictEqual({ id: \"2\" });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ result: { data: { totalLikes: 1000 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 1000 },\n        error: undefined,\n      });\n    }\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n    expect(link.operation?.variables).toStrictEqual({ id: \"2\" });\n\n    getCurrentSnapshot().restart();\n\n    await waitFor(() => expect(onUnsubscribe).toHaveBeenCalledTimes(2));\n    expect(onSubscribe).toHaveBeenCalledTimes(3);\n    expect(link.operation?.variables).toStrictEqual({ id: \"2\" });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    link.simulateResult({ result: { data: { totalLikes: 1005 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 1005 },\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"can restart a subscription that has completed\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const {\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n    } = await setup({\n      variables: { id: \"1\" },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ result: { data: { totalLikes: 1 } } }, true);\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 1 },\n        error: undefined,\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    getCurrentSnapshot().restart();\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    await waitFor(() => expect(onSubscribe).toHaveBeenCalledTimes(2));\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult({ result: { data: { totalLikes: 2 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 2 },\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"can restart a subscription that has graphql errors\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const {\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n    } = await setup({\n      variables: { id: \"1\" },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    const error: GraphQLFormattedError = { message: \"error\" };\n    link.simulateResult({\n      result: { errors: [error] },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: undefined,\n        error: new CombinedGraphQLErrors({ errors: [error] }),\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    getCurrentSnapshot().restart();\n\n    await waitFor(() => expect(onSubscribe).toHaveBeenCalledTimes(2));\n    await wait(0);\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n\n    await expect(takeSnapshot).not.toRerender();\n\n    link.simulateResult({ result: { data: { totalLikes: 2 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 2 },\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"can restart a subscription that has network errors\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const {\n      link,\n      takeSnapshot,\n      getCurrentSnapshot,\n      onSubscribe,\n      onUnsubscribe,\n    } = await setup({\n      variables: { id: \"1\" },\n    });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ error: new Error(\"Oops\") });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: undefined,\n        error: new Error(\"Oops\"),\n      });\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    // A network error completes the observable so unsubscribe is called\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    getCurrentSnapshot().restart();\n\n    await waitFor(() => expect(onSubscribe).toHaveBeenCalledTimes(2));\n    await wait(0);\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    link.simulateResult({ result: { data: { totalLikes: 2 } } });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: { totalLikes: 2 },\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"will not restart a subscription that has been `skip`ped\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot, onSubscribe, onUnsubscribe } =\n      await setup({\n        variables: { id: \"1\" },\n        skip: true,\n      });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        data: undefined,\n        error: undefined,\n      });\n    }\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(0);\n\n    expect(() => getCurrentSnapshot().restart()).toThrow(\n      new InvariantError(\"A subscription that is skipped cannot be restarted.\")\n    );\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onUnsubscribe).toHaveBeenCalledTimes(0);\n    expect(onSubscribe).toHaveBeenCalledTimes(0);\n  });\n\n  test(\"can restart a deduplicated subscription\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const results = [\"Audi\", \"BMW\", \"Honda\", \"Toyota\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const onSubscribe = jest.fn();\n    const onUnsubscribe = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(onSubscribe);\n    link.onUnsubscribe(onUnsubscribe);\n\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const {\n      render,\n      takeRender,\n      mergeSnapshot,\n      replaceSnapshot,\n      getCurrentRender,\n    } = createRenderStream<Record<number, useSubscription.Result<any>>>({\n      initialSnapshot: {},\n    });\n\n    function Subscription({ idx }: { idx: number }) {\n      mergeSnapshot({ [idx]: useSubscription(subscription) });\n      return null;\n    }\n\n    function App({ count }: { count: number }) {\n      replaceSnapshot({});\n\n      return (\n        <>\n          {Array.from({ length: count }).map((_, idx) => {\n            return <Subscription key={idx} idx={idx} />;\n          })}\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender } = await render(<App count={2} />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    expect(onSubscribe).toHaveBeenCalledTimes(1);\n\n    link.simulateResult(results[0]);\n\n    if (IS_REACT_17) {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    getCurrentRender().snapshot[0].restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(1);\n    expect(onSubscribe).toHaveBeenCalledTimes(2);\n\n    // Calling restart on a non-errored/completed result should not rerender\n    await expect(takeRender).not.toRerender();\n\n    link.simulateResult(results[1]);\n\n    if (IS_REACT_17) {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    getCurrentRender().snapshot[1].restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(2);\n    expect(onSubscribe).toHaveBeenCalledTimes(3);\n\n    // Calling restart on a non-errored/completed result should not rerender\n    await expect(takeRender).not.toRerender();\n\n    await rerender(<App count={3} />);\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[2]).toStrictEqualTyped({\n        data: undefined,\n        error: undefined,\n        loading: true,\n      });\n    }\n\n    link.simulateResult(results[2]);\n\n    if (IS_REACT_17) {\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[1].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: undefined,\n          error: undefined,\n          loading: true,\n        });\n      }\n    }\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[2].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[2].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[2]).toStrictEqualTyped({\n        data: results[2].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    getCurrentRender().snapshot[2].restart();\n\n    expect(onUnsubscribe).toHaveBeenCalledTimes(3);\n    expect(onSubscribe).toHaveBeenCalledTimes(4);\n\n    // Calling restart on a non-errored/completed result should not rerender\n    await expect(takeRender).not.toRerender();\n\n    link.simulateResult(results[3]);\n\n    if (IS_REACT_17) {\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[3].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n\n      {\n        const { snapshot } = await takeRender();\n\n        expect(snapshot[0]).toStrictEqualTyped({\n          data: results[3].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[1]).toStrictEqualTyped({\n          data: results[3].result.data,\n          error: undefined,\n          loading: false,\n        });\n\n        expect(snapshot[2]).toStrictEqualTyped({\n          data: results[2].result.data,\n          error: undefined,\n          loading: false,\n        });\n      }\n    }\n\n    {\n      const { snapshot } = await takeRender();\n\n      expect(snapshot[0]).toStrictEqualTyped({\n        data: results[3].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[1]).toStrictEqualTyped({\n        data: results[3].result.data,\n        error: undefined,\n        loading: false,\n      });\n\n      expect(snapshot[2]).toStrictEqualTyped({\n        data: results[3].result.data,\n        error: undefined,\n        loading: false,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n});\n\ndescribe(\"ignoreResults\", () => {\n  const subscription = gql`\n    subscription {\n      car {\n        make\n      }\n    }\n  `;\n\n  const results = [\"Audi\", \"BMW\"].map((make) => ({\n    result: { data: { car: { make } } },\n  }));\n\n  it(\"should not rerender when ignoreResults is true, but will call `onData` and `onComplete`\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn((() => {}) as useSubscription.Options[\"onData\"]);\n    const onError = jest.fn((() => {}) as useSubscription.Options[\"onError\"]);\n    const onComplete = jest.fn(\n      (() => {}) as useSubscription.Options[\"onComplete\"]\n    );\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useSubscription(subscription, {\n          ignoreResults: true,\n          onData,\n          onError,\n          onComplete,\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    const snapshot = await takeSnapshot();\n    expect(snapshot).toStrictEqualTyped({\n      loading: false,\n      error: undefined,\n      data: undefined,\n    });\n\n    link.simulateResult(results[0]);\n    await wait(0);\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenLastCalledWith({\n      client,\n      data: {\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n    expect(onError).toHaveBeenCalledTimes(0);\n    expect(onComplete).toHaveBeenCalledTimes(0);\n\n    link.simulateResult(results[1], true);\n    await wait(0);\n\n    expect(onData).toHaveBeenCalledTimes(2);\n    expect(onData).toHaveBeenLastCalledWith({\n      client,\n      data: {\n        data: results[1].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n    expect(onError).toHaveBeenCalledTimes(0);\n    expect(onComplete).toHaveBeenCalledTimes(1);\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should not rerender when ignoreResults is true and an error occurs\", async () => {\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn((() => {}) as useSubscription.Options[\"onData\"]);\n    const onError = jest.fn((() => {}) as useSubscription.Options[\"onError\"]);\n    const onComplete = jest.fn(\n      (() => {}) as useSubscription.Options[\"onComplete\"]\n    );\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () =>\n        useSubscription(subscription, {\n          ignoreResults: true,\n          onData,\n          onError,\n          onComplete,\n        }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    const snapshot = await takeSnapshot();\n    expect(snapshot).toStrictEqualTyped({\n      loading: false,\n      error: undefined,\n      data: undefined,\n    });\n\n    link.simulateResult(results[0]);\n    await wait(0);\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenLastCalledWith({\n      client,\n      data: {\n        data: results[0].result.data,\n        error: undefined,\n        loading: false,\n        variables: undefined,\n      },\n    });\n    expect(onError).toHaveBeenCalledTimes(0);\n    expect(onComplete).toHaveBeenCalledTimes(0);\n\n    const error = new Error(\"test\");\n    link.simulateResult({ error });\n    await wait(0);\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenCalledTimes(1);\n    expect(onError).toHaveBeenLastCalledWith(error);\n    expect(onComplete).toHaveBeenCalledTimes(1);\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"can switch from `ignoreResults: true` to `ignoreResults: false` and will start rerendering, without creating a new subscription\", async () => {\n    const subscriptionCreated = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(subscriptionCreated);\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn((() => {}) as useSubscription.Options[\"onData\"]);\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ ignoreResults }: { ignoreResults: boolean }) =>\n        useSubscription(subscription, {\n          ignoreResults,\n          onData,\n        }),\n      {\n        initialProps: { ignoreResults: true },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    if (!IS_REACT_17) {\n      await wait(0);\n      expect(subscriptionCreated).toHaveBeenCalledTimes(1);\n    }\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        error: undefined,\n        data: undefined,\n      });\n      expect(onData).toHaveBeenCalledTimes(0);\n    }\n\n    link.simulateResult(results[0]);\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onData).toHaveBeenCalledTimes(1);\n\n    await rerender({ ignoreResults: false });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        error: undefined,\n        // `data` appears immediately after changing to `ignoreResults: false`\n        data: results[0].result.data,\n      });\n      // `onData` should not be called again for the same result\n      expect(onData).toHaveBeenCalledTimes(1);\n    }\n\n    link.simulateResult(results[1]);\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        error: undefined,\n        data: results[1].result.data,\n      });\n      expect(onData).toHaveBeenCalledTimes(2);\n    }\n\n    // a second subscription should not have been started\n    expect(subscriptionCreated).toHaveBeenCalledTimes(1);\n  });\n\n  it(\"can switch from `ignoreResults: false` to `ignoreResults: true` and will stop rerendering, without creating a new subscription\", async () => {\n    const subscriptionCreated = jest.fn();\n    const link = new MockSubscriptionLink();\n    link.onSetup(subscriptionCreated);\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    const onData = jest.fn((() => {}) as useSubscription.Options[\"onData\"]);\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n      ({ ignoreResults }) =>\n        useSubscription(subscription, { ignoreResults, onData }),\n      {\n        initialProps: { ignoreResults: false },\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    if (!IS_REACT_17) {\n      await wait(0);\n      expect(subscriptionCreated).toHaveBeenCalledTimes(1);\n    }\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: true,\n        error: undefined,\n        data: undefined,\n      });\n      expect(onData).toHaveBeenCalledTimes(0);\n    }\n\n    link.simulateResult(results[0]);\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        error: undefined,\n        data: results[0].result.data,\n      });\n      expect(onData).toHaveBeenCalledTimes(1);\n    }\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n\n    await rerender({ ignoreResults: true });\n\n    {\n      const snapshot = await takeSnapshot();\n      expect(snapshot).toStrictEqualTyped({\n        loading: false,\n        error: undefined,\n        // switching back to the default `ignoreResults: true` return value\n        data: undefined,\n      });\n      // `onData` should not be called again\n      expect(onData).toHaveBeenCalledTimes(1);\n    }\n\n    link.simulateResult(results[1]);\n\n    await expect(takeSnapshot).not.toRerender({ timeout: 20 });\n    expect(onData).toHaveBeenCalledTimes(2);\n\n    // a second subscription should not have been started\n    expect(subscriptionCreated).toHaveBeenCalledTimes(1);\n  });\n});\n\ndescribe(\"data masking\", () => {\n  test(\"masks data returned when dataMasking is `true`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new Cache(),\n      link,\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        addedComment: {\n          __typename: \"Comment\",\n          id: 1,\n        },\n      },\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"does not mask data returned from subscriptions when dataMasking is `false`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new Cache(),\n      link,\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        addedComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Test comment\",\n          author: \"Test User\",\n        },\n      },\n      error: undefined,\n      loading: false,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"masks data passed to onData callback when dataMasking is `true`\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new Cache(),\n      link,\n    });\n\n    const onData = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription, { onData }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        addedComment: {\n          __typename: \"Comment\",\n          id: 1,\n        },\n      },\n      error: undefined,\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenCalledWith({\n      client,\n      data: {\n        data: { addedComment: { __typename: \"Comment\", id: 1 } },\n        loading: false,\n        error: undefined,\n        variables: undefined,\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  test(\"uses unmasked data when using the @unmask directive\", async () => {\n    const subscription = gql`\n      subscription NewCommentSubscription {\n        addedComment {\n          id\n          ...CommentFields @unmask\n        }\n      }\n\n      fragment CommentFields on Comment {\n        comment\n        author\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new Cache(),\n      link,\n    });\n\n    const onData = jest.fn();\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useSubscription(subscription, { onData }),\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      error: undefined,\n      loading: true,\n    });\n\n    link.simulateResult({\n      result: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n      },\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        addedComment: {\n          __typename: \"Comment\",\n          id: 1,\n          comment: \"Test comment\",\n          author: \"Test User\",\n        },\n      },\n      error: undefined,\n      loading: false,\n    });\n\n    expect(onData).toHaveBeenCalledTimes(1);\n    expect(onData).toHaveBeenCalledWith({\n      client: expect.anything(),\n      data: {\n        data: {\n          addedComment: {\n            __typename: \"Comment\",\n            id: 1,\n            comment: \"Test comment\",\n            author: \"Test User\",\n          },\n        },\n        loading: false,\n        error: undefined,\n        variables: undefined,\n      },\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n});\n\ndescribe.skip(\"Type Tests\", () => {\n  test(\"uses masked types when using masked document\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Subscription {\n      userUpdated: {\n        __typename: \"User\";\n        id: string;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const subscription: TypedDocumentNode<Subscription> = gql``;\n\n    const { data } = useSubscription(subscription, {\n      onData: ({ data }) => {\n        expectTypeOf(data.data).toEqualTypeOf<Subscription | undefined>();\n      },\n    });\n\n    expectTypeOf(data).toEqualTypeOf<Subscription | undefined>();\n  });\n\n  test(\"uses unmodified type when using TypedDocumentNode\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Subscription {\n      userUpdated: {\n        __typename: \"User\";\n        id: string;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const subscription: TypedDocumentNode<Subscription> = gql``;\n\n    const { data } = useSubscription(subscription, {\n      onData: ({ data }) => {\n        expectTypeOf(data.data).toEqualTypeOf<Subscription | undefined>();\n      },\n    });\n\n    expectTypeOf(data).toEqualTypeOf<Subscription | undefined>();\n  });\n\n  test(\"variables are optional and can be anything with an DocumentNode\", () => {\n    const subscription = gql``;\n\n    useSubscription(subscription);\n    useSubscription(subscription, {});\n    useSubscription(subscription, { variables: {} });\n    useSubscription(subscription, { variables: { foo: \"bar\" } });\n    useSubscription(subscription, { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const subscription: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    useSubscription(subscription);\n    useSubscription(subscription, {});\n    useSubscription(subscription, { variables: {} });\n    useSubscription(subscription, { variables: { foo: \"bar\" } });\n    useSubscription(subscription, { variables: { bar: \"baz\" } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    const subscription: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    useSubscription(subscription);\n    useSubscription(subscription, {});\n    useSubscription(subscription, { variables: {} });\n    useSubscription(subscription, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    const subscription: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    // @ts-expect-error\n    useSubscription(subscription);\n    // @ts-expect-error\n    useSubscription(subscription, {});\n    useSubscription(subscription, {\n      // @ts-expect-error\n      variables: {},\n    });\n    useSubscription(subscription, {\n      // @ts-expect-error\n      variables: undefined,\n    });\n    useSubscription(subscription, {\n      // @ts-expect-error\n      variables: {\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"optional variables are optional\", () => {\n    const subscription: TypedDocumentNode<\n      { posts: string[] },\n      { limit?: number }\n    > = gql``;\n\n    useSubscription(subscription);\n    useSubscription(subscription, {});\n    useSubscription(subscription, { variables: {} });\n    useSubscription(subscription, { variables: { limit: 10 } });\n    useSubscription(subscription, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useSubscription(subscription, {\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"enforces required variables when TVariables includes required variables\", () => {\n    const subscription: TypedDocumentNode<\n      { character: string },\n      { id: string }\n    > = gql``;\n\n    // @ts-expect-error empty variables\n    useSubscription(subscription);\n    // @ts-expect-error empty variables\n    useSubscription(subscription, {});\n    useSubscription(subscription, {\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    useSubscription(subscription, { variables: { id: \"1\" } });\n    useSubscription(subscription, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useSubscription(subscription, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    const subscription: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    // @ts-expect-error empty variables\n    useSubscription(subscription);\n    // @ts-expect-error empty variables\n    useSubscription(subscription, {});\n    // @ts-expect-error empty variables\n    useSubscription(subscription, { variables: {} });\n    useSubscription(subscription, { variables: { id: \"1\" } });\n    useSubscription(subscription, {\n      // @ts-expect-error missing required variables\n      variables: { language: \"en\" },\n    });\n    useSubscription(subscription, { variables: { id: \"1\", language: \"en\" } });\n    useSubscription(subscription, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    useSubscription(subscription, {\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseFragment/arrays.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport { screen, waitFor } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport React, { Suspense } from \"react\";\n\nimport type { StoreObject, TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, gql, InMemoryCache } from \"@apollo/client\";\nimport { useSuspenseFragment } from \"@apollo/client/react\";\nimport { createClientWrapper } from \"@apollo/client/testing/internal\";\n\nasync function renderUseSuspenseFragment<TData, Props = never>(\n  renderHook: (props: Props) => useSuspenseFragment.Result<TData>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseFragment({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseFragment\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <UseSuspenseFragment props={props} />\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useSuspenseFragment.Result<TData>\n  >({ skipNonTrackingRenders: true });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  return { takeRender, rerender };\n}\n\ntest(\"renders array and does not suspend array for `from` array when written to cache\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  const { renderedComponents, snapshot } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      { __typename: \"Item\", id: 5, text: \"Item #5\" },\n    ],\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"updates items in the array with cache writes\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 2,\n      text: \"Item #2 updated\",\n    },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  client.cache.batch({\n    update: (cache) => {\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 1,\n          text: \"Item #1 from batch\",\n        },\n      });\n\n      cache.writeFragment({\n        fragment,\n        data: {\n          __typename: \"Item\",\n          id: 5,\n          text: \"Item #5 from batch\",\n        },\n      });\n    },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1 from batch\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5 from batch\" },\n      ],\n    });\n  }\n\n  // should not cause rerender since its an item not watched\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 6,\n      text: \"Item #6 ignored\",\n    },\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend and returns null array for null `from` array\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () => useSuspenseFragment({ fragment, from: [null, null, null] }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  const { renderedComponents, snapshot } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: [null, null, null],\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"handles mixed array of identifiers in `from`\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [{ __typename: \"Item\", id: 1 }, \"Item:2\", null],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  const { renderedComponents, snapshot } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: [\n      { __typename: \"Item\", id: 1, text: \"Item #1\" },\n      { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      null,\n    ],\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend and returns empty array for empty `from` array\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () => useSuspenseFragment({ fragment, from: [] }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  const { renderedComponents, snapshot } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: [],\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends until all items are complete\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  await expect(takeRender).not.toRerender({ timeout: 20 });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  await expect(takeRender).not.toRerender({ timeout: 20 });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends until all items are complete with partially complete results on initial render\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 2; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends when an item changes from complete to partial\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const { cache } = client;\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderUseSuspenseFragment(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n          { __typename: \"Item\", id: 5 },\n        ],\n      }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  cache.modify({\n    id: cache.identify({ __typename: \"Item\", id: 1 }),\n    fields: {\n      text: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1 is back\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1 is back\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"handles changing array size\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  for (let i = 1; i <= 5; i++) {\n    client.writeFragment({\n      fragment,\n      data: { __typename: \"Item\", id: i, text: `Item #${i}` },\n    });\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderUseSuspenseFragment(\n    ({ from }) => useSuspenseFragment({ fragment, from }),\n    {\n      initialProps: {\n        from: [\n          { __typename: \"Item\", id: 1 },\n          { __typename: \"Item\", id: 2 },\n        ],\n      },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      ],\n    });\n  }\n\n  await rerender({\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  await rerender({\n    from: [\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 5 },\n    ],\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n  }\n\n  await rerender({\n    from: [],\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [],\n    });\n  }\n\n  await rerender({\n    from: [{ __typename: \"Item\", id: 6 }],\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 6, text: \"Item #6\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [{ __typename: \"Item\", id: 6, text: \"Item #6\" }],\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"rendering same items in multiple useSuspenseFragment hooks allows for rerendering a different array in the other\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n  });\n\n  function UseSuspenseFragment({\n    id,\n    items,\n  }: {\n    id: number;\n    items: StoreObject[];\n  }) {\n    useTrackRenders({ name: `useSuspenseFragment ${id}` });\n    mergeSnapshot({\n      [`items${id}`]: useSuspenseFragment({ fragment, from: items }),\n    });\n\n    return null;\n  }\n\n  function SuspenseFallback({ id }: { id: number }) {\n    // Reset snapshot so it doesn't seem like the useSuspenseFragment hook\n    // rendered\n    mergeSnapshot({ [`items${id}`]: undefined });\n    useTrackRenders({ name: `SuspenseFallback ${id}` });\n\n    return null;\n  }\n\n  function App({\n    items1,\n    items2,\n  }: {\n    items1: StoreObject[];\n    items2: StoreObject[];\n  }) {\n    return (\n      <>\n        <Suspense fallback={<SuspenseFallback id={1} />}>\n          <UseSuspenseFragment id={1} items={items1} />\n        </Suspense>\n        <Suspense fallback={<SuspenseFallback id={2} />}>\n          <UseSuspenseFragment id={2} items={items2} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { render, takeRender, mergeSnapshot } = createRenderStream<{\n    items1: useSuspenseFragment.Result<Item[]> | undefined;\n    items2: useSuspenseFragment.Result<Item[]> | undefined;\n  }>({\n    skipNonTrackingRenders: true,\n    initialSnapshot: { items1: undefined, items2: undefined },\n  });\n\n  const initialItems = [\n    { __typename: \"Item\", id: 1 },\n    { __typename: \"Item\", id: 2 },\n  ];\n\n  const { rerender } = await render(\n    <App items1={initialItems} items2={initialItems} />,\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"SuspenseFallback 2\",\n      \"SuspenseFallback 1\",\n    ]);\n    expect(snapshot).toStrictEqualTyped({\n      items1: undefined,\n      items2: undefined,\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useSuspenseFragment 2\",\n      \"useSuspenseFragment 1\",\n    ]);\n    expect(snapshot).toStrictEqual({\n      items1: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        ],\n      },\n      items2: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        ],\n      },\n    });\n  }\n  await waitFor(() => expect(cache).toHaveNumWatches(2));\n\n  await rerender(\n    <App\n      items1={initialItems}\n      items2={[...initialItems, { __typename: \"Item\", id: 5 }]}\n    />\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"SuspenseFallback 2\",\n      \"useSuspenseFragment 1\",\n    ]);\n    expect(snapshot).toStrictEqual({\n      items1: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        ],\n      },\n      items2: undefined,\n    });\n  }\n  await waitFor(() => expect(cache).toHaveNumWatches(3));\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment 2\"]);\n    expect(snapshot).toStrictEqual({\n      items1: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        ],\n      },\n      items2: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n          { __typename: \"Item\", id: 5, text: \"Item #5\" },\n        ],\n      },\n    });\n  }\n\n  await rerender(\n    <App items1={initialItems} items2={[{ __typename: \"Item\", id: 2 }]} />\n  );\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useSuspenseFragment 2\",\n      \"useSuspenseFragment 1\",\n    ]);\n    expect(snapshot).toStrictEqual({\n      items1: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        ],\n      },\n      items2: {\n        data: [{ __typename: \"Item\", id: 2, text: \"Item #2\" }],\n      },\n    });\n  }\n  await waitFor(() => expect(cache).toHaveNumWatches(3));\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\n      \"useSuspenseFragment 2\",\n      \"useSuspenseFragment 1\",\n    ]);\n    expect(snapshot).toStrictEqual({\n      items1: {\n        data: [\n          { __typename: \"Item\", id: 1, text: \"Item #1\" },\n          { __typename: \"Item\", id: 2, text: \"Item #2 updated\" },\n        ],\n      },\n      items2: {\n        data: [{ __typename: \"Item\", id: 2, text: \"Item #2 updated\" }],\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"works with transitions\", async () => {\n  type Item = {\n    __typename: string;\n    id: number;\n    text?: string;\n  };\n\n  const fragment: TypedDocumentNode<Item> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const user = userEvent.setup();\n\n  function UseSuspenseFragment({ items }: { items: StoreObject[] }) {\n    useTrackRenders({ name: \"useSuspenseFragment\" });\n    replaceSnapshot(useSuspenseFragment({ fragment, from: items }));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function App() {\n    const [items, setItems] = React.useState([\n      { __typename: \"Item\", id: 1 },\n      { __typename: \"Item\", id: 2 },\n    ]);\n    const [isPending, startTransition] = React.useTransition();\n\n    return (\n      <>\n        <button\n          disabled={isPending}\n          onClick={() => {\n            startTransition(() => {\n              setItems((prev) => [...prev, { __typename: \"Item\", id: 5 }]);\n            });\n          }}\n        >\n          Change items\n        </button>\n        <Suspense fallback={<SuspenseFallback />}>\n          <UseSuspenseFragment items={items} />\n        </Suspense>\n      </>\n    );\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { render, takeRender, replaceSnapshot } = createRenderStream<\n    useSuspenseFragment.Result<Item[]>\n  >({ skipNonTrackingRenders: true });\n\n  await render(<App />, { wrapper: createClientWrapper(client) });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqualTyped([\"SuspenseFallback\"]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqualTyped([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      ],\n    });\n  }\n\n  const button = screen.getByText(\"Change items\");\n  await user.click(button);\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqual({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n      ],\n    });\n    expect(button).toBeDisabled();\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 5, text: \"Item #5\" },\n  });\n\n  {\n    const { renderedComponents, snapshot } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseFragment\"]);\n    expect(snapshot).toStrictEqual({\n      data: [\n        { __typename: \"Item\", id: 1, text: \"Item #1\" },\n        { __typename: \"Item\", id: 2, text: \"Item #2\" },\n        { __typename: \"Item\", id: 5, text: \"Item #5\" },\n      ],\n    });\n    expect(button).not.toBeDisabled();\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseFragment.test.tsx",
    "content": "import { act, renderHook, screen, waitFor } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport React, { Suspense } from \"react\";\n\nimport type {\n  FragmentType,\n  MaybeMasked,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  DocumentTransform,\n  gql,\n  InMemoryCache,\n} from \"@apollo/client\";\nimport { ApolloProvider, useSuspenseFragment } from \"@apollo/client/react\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\nimport { renderAsync, spyOnConsole } from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nfunction createDefaultRenderStream<TData = unknown>() {\n  return createRenderStream({\n    initialSnapshot: {\n      result: null as useSuspenseFragment.Result<MaybeMasked<TData>> | null,\n    },\n  });\n}\n\nfunction createDefaultTrackedComponents() {\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  return { SuspenseFallback };\n}\n\ntest(\"validates the GraphQL document is a fragment\", () => {\n  using _ = spyOnConsole(\"error\");\n\n  const fragment = gql`\n    query ShouldThrow {\n      createException\n    }\n  `;\n\n  expect(() => {\n    renderHook(\n      () => useSuspenseFragment({ fragment, from: { __typename: \"Nope\" } }),\n      { wrapper: ({ children }) => <MockedProvider>{children}</MockedProvider> }\n    );\n  }).toThrow(\n    new InvariantError(\n      \"Found a query operation named 'ShouldThrow'. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n    )\n  );\n});\n\ntest(\"throws if no client is provided\", () => {\n  using _spy = spyOnConsole(\"error\");\n  expect(() =>\n    renderHook(() =>\n      useSuspenseFragment({\n        fragment: gql`\n          fragment ShouldThrow on Error {\n            shouldThrow\n          }\n        `,\n        from: {},\n      })\n    )\n  ).toThrow(/pass an ApolloClient/);\n});\n\ntest(\"suspends until cache value is complete\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { render, takeRender, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => {\n        return <ApolloProvider client={client}>{children}</ApolloProvider>;\n      },\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"updates when the cache updates\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { takeRender, render, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1 (updated)\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1 (updated)\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"resuspends when data goes missing until complete again\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { takeRender, render, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  client.cache.modify({\n    id: \"Item:1\",\n    fields: {\n      text: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1 (updated)\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1 (updated)\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend and returns cache data when data is already in the cache\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { takeRender, render, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Cached\" },\n  });\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Cached\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"receives cache updates after initial result when data is written to the cache before mounted\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { takeRender, render, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Cached\" },\n  });\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Cached\",\n      },\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Updated\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Updated\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"allows the client to be overridden\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const defaultClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  defaultClient.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Should not be used\" },\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        client,\n        from: { __typename: \"Item\", id: 1 },\n      }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={defaultClient}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { data } = await takeSnapshot();\n\n  expect(data).toEqual({ __typename: \"Item\", id: 1, text: \"Item #1\" });\n});\n\ntest(\"suspends until data is complete when changing `from` with no data written to cache\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const { takeRender, replaceSnapshot, render } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  function App({ id }: { id: number }) {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  const { rerender } = await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={1} />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  await rerender(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={2} />\n    </Suspense>\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 2,\n        text: \"Item #2\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend when changing `from` with data already written to cache\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const { takeRender, replaceSnapshot, render } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  function App({ id }: { id: number }) {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  const { rerender } = await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={1} />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  await rerender(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={2} />\n    </Suspense>\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 2,\n        text: \"Item #2\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\nit(\"does not rerender when fields with @nonreactive change\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text @nonreactive\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({ fragment, from: { __typename: \"Item\", id: 1 } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1 (updated)\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\nit(\"does not rerender when fields with @nonreactive on nested fragment change\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      ...ItemFields @nonreactive\n    }\n\n    fragment ItemFields on Item {\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        fragmentName: \"ItemFragment\",\n        from: { __typename: \"Item\", id: 1 },\n      }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"ItemFragment\",\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1 (updated)\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\n// TODO: Update when https://github.com/apollographql/apollo-client/issues/12003 is fixed\nit.failing(\n  \"warns and suspends when passing parent object to `from` when key fields are missing\",\n  async () => {\n    using _ = spyOnConsole(\"warn\");\n\n    interface Fragment {\n      age: number;\n    }\n\n    const fragment: TypedDocumentNode<Fragment, Record<string, never>> = gql`\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    });\n\n    const { replaceSnapshot, render, takeRender } =\n      createDefaultRenderStream<Fragment>();\n    const { SuspenseFallback } = createDefaultTrackedComponents();\n\n    function App() {\n      const result = useSuspenseFragment({\n        fragment,\n        from: { __typename: \"User\" },\n      });\n\n      replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await render(\n      <Suspense fallback={<SuspenseFallback />}>\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      \"Could not identify object passed to `from` for '%s' fragment, either because the object is non-normalized or the key fields are missing. If you are masking this object, please ensure the key fields are requested by the parent object.\",\n      \"UserFields\"\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n  }\n);\n\ntest(\"returns null if `from` is `null`\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () => useSuspenseFragment({ fragment, from: null }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  const { data } = await takeSnapshot();\n\n  expect(data).toBeNull();\n});\n\ntest(\"returns cached value when `from` changes from `null` to non-null value\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n    ({ id }) =>\n      useSuspenseFragment({\n        fragment,\n        from: id === null ? null : { __typename: \"Item\", id },\n      }),\n    {\n      initialProps: { id: null as null | number },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toBeNull();\n  }\n\n  await rerender({ id: 1 });\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"returns null value when `from` changes from non-null value to `null`\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot, rerender } = await renderHookToSnapshotStream(\n    ({ id }) =>\n      useSuspenseFragment({\n        fragment,\n        from: id === null ? null : { __typename: \"Item\", id },\n      }),\n    {\n      initialProps: { id: 1 as null | number },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    });\n  }\n\n  await rerender({ id: null });\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toBeNull();\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"suspends until cached value is available when `from` changes from `null` to non-null value\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const { takeRender, render, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment | null>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  function App({ id }: { id: number | null }) {\n    useTrackRenders();\n    const result = useSuspenseFragment({\n      fragment,\n      from: id === null ? null : { __typename: \"Item\", id },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  const { rerender } = await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={null} />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({ data: null });\n  }\n\n  await rerender(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App id={1} />\n    </Suspense>\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n  }\n\n  client.writeFragment({\n    fragment,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"returns masked fragment when data masking is enabled\", async () => {\n  type Post = {\n    __typename: \"Post\";\n    id: number;\n    title: string;\n  } & { \" $fragmentRefs\"?: { PostFields: PostFields } };\n\n  type PostFields = {\n    __typename: \"Post\";\n    updatedAt: string;\n  } & { \" $fragmentName\"?: \"PostFields\" };\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<Post> = gql`\n    fragment PostFragment on Post {\n      id\n      title\n      ...PostFields\n    }\n\n    fragment PostFields on Post {\n      updatedAt\n    }\n  `;\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"PostFragment\",\n    data: {\n      __typename: \"Post\",\n      id: 1,\n      title: \"Blog post\",\n      updatedAt: \"2024-01-01\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        fragmentName: \"PostFragment\",\n        from: { __typename: \"Post\", id: 1 },\n      }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const snapshot = await takeSnapshot();\n\n    expect(snapshot).toEqual({\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n      },\n    });\n  }\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"does not rerender for cache writes to masked fields\", async () => {\n  type Post = {\n    __typename: \"Post\";\n    id: number;\n    title: string;\n  } & { \" $fragmentRefs\"?: { PostFields: PostFields } };\n\n  type PostFields = {\n    __typename: \"Post\";\n    updatedAt: string;\n  } & { \" $fragmentName\"?: \"PostFields\" };\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const fragment: TypedDocumentNode<Post> = gql`\n    fragment PostFragment on Post {\n      id\n      title\n      ...PostFields\n    }\n\n    fragment PostFields on Post {\n      updatedAt\n    }\n  `;\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"PostFragment\",\n    data: {\n      __typename: \"Post\",\n      id: 1,\n      title: \"Blog post\",\n      updatedAt: \"2024-01-01\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({\n        fragment,\n        fragmentName: \"PostFragment\",\n        from: { __typename: \"Post\", id: 1 },\n      }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const snapshot = await takeSnapshot();\n\n    expect(snapshot).toEqual({\n      data: {\n        __typename: \"Post\",\n        id: 1,\n        title: \"Blog post\",\n      },\n    });\n  }\n\n  client.writeFragment({\n    fragment,\n    fragmentName: \"PostFragment\",\n    data: {\n      __typename: \"Post\",\n      id: 1,\n      title: \"Blog post\",\n      updatedAt: \"2024-02-01\",\n    },\n  });\n\n  await expect(takeSnapshot).not.toRerender();\n});\n\ntest(\"updates child fragments for cache updates to masked fields\", async () => {\n  type Post = {\n    __typename: \"Post\";\n    id: number;\n    title: string;\n  } & { \" $fragmentRefs\"?: { PostFields: PostFields } };\n\n  type PostFields = {\n    __typename: \"Post\";\n    updatedAt: string;\n  } & { \" $fragmentName\"?: \"PostFields\" };\n\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n  });\n\n  const postFieldsFragment: TypedDocumentNode<PostFields> = gql`\n    fragment PostFields on Post {\n      updatedAt\n    }\n  `;\n\n  const postFragment: TypedDocumentNode<Post> = gql`\n    fragment PostFragment on Post {\n      id\n      title\n      ...PostFields\n    }\n\n    ${postFieldsFragment}\n  `;\n\n  client.writeFragment({\n    fragment: postFragment,\n    fragmentName: \"PostFragment\",\n    data: {\n      __typename: \"Post\",\n      id: 1,\n      title: \"Blog post\",\n      updatedAt: \"2024-01-01\",\n    },\n  });\n\n  const { render, mergeSnapshot, takeRender } = createRenderStream({\n    initialSnapshot: {\n      parent: null as useSuspenseFragment.Result<Post> | null,\n      child: null as useSuspenseFragment.Result<PostFields> | null,\n    },\n  });\n\n  function Parent() {\n    useTrackRenders();\n    const parent = useSuspenseFragment({\n      fragment: postFragment,\n      fragmentName: \"PostFragment\",\n      from: { __typename: \"Post\", id: 1 },\n    });\n\n    mergeSnapshot({ parent });\n\n    return <Child post={parent.data} />;\n  }\n\n  function Child({ post }: { post: FragmentType<PostFields> }) {\n    useTrackRenders();\n    const child = useSuspenseFragment({\n      fragment: postFieldsFragment,\n      from: post,\n    });\n\n    mergeSnapshot({ child });\n    return null;\n  }\n\n  using _disabledAct = disableActEnvironment();\n  await render(<Parent />, {\n    wrapper: ({ children }) => (\n      <ApolloProvider client={client}>{children}</ApolloProvider>\n    ),\n  });\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toEqual({\n      parent: {\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n        },\n      },\n      child: {\n        data: {\n          __typename: \"Post\",\n          updatedAt: \"2024-01-01\",\n        },\n      },\n    });\n  }\n\n  client.writeFragment({\n    fragment: postFragment,\n    fragmentName: \"PostFragment\",\n    data: {\n      __typename: \"Post\",\n      id: 1,\n      title: \"Blog post\",\n      updatedAt: \"2024-02-01\",\n    },\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([Child]);\n    expect(snapshot).toEqual({\n      parent: {\n        data: {\n          __typename: \"Post\",\n          id: 1,\n          title: \"Blog post\",\n        },\n      },\n      child: {\n        data: {\n          __typename: \"Post\",\n          updatedAt: \"2024-02-01\",\n        },\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"tears down the subscription on unmount\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { unmount, takeSnapshot } = await renderHookToSnapshotStream(\n    () =>\n      useSuspenseFragment({ fragment, from: { __typename: \"Item\", id: 1 } }),\n    {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({ __typename: \"Item\", id: 1, text: \"Item #1\" });\n  }\n\n  expect(cache).toHaveNumWatches(1);\n\n  unmount();\n\n  // Cleanup happens async so we just need to ensure it happens sometime after\n  // mount\n  await waitFor(() => expect(cache).toHaveNumWatches(0));\n});\n\ntest(\"tears down all watches when rendering multiple records\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({ cache, link: ApolloLink.empty() });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 2, text: \"Item #2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { unmount, rerender, takeSnapshot } = await renderHookToSnapshotStream(\n    ({ id }) =>\n      useSuspenseFragment({ fragment, from: { __typename: \"Item\", id } }),\n    {\n      initialProps: { id: 1 },\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    }\n  );\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({ __typename: \"Item\", id: 1, text: \"Item #1\" });\n  }\n\n  await rerender({ id: 2 });\n\n  {\n    const { data } = await takeSnapshot();\n\n    expect(data).toEqual({ __typename: \"Item\", id: 2, text: \"Item #2\" });\n  }\n\n  unmount();\n\n  // Cleanup happens async so we just need to ensure it happens sometime after\n  // mount\n  await waitFor(() => expect(cache).toHaveNumWatches(0));\n});\n\ntest(\"tears down watches after default autoDisposeTimeoutMs if component never renders again after suspending\", async () => {\n  jest.useFakeTimers();\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const cache = new InMemoryCache();\n  const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({ link, cache });\n\n  function App() {\n    const [showItem, setShowItem] = React.useState(true);\n\n    return (\n      <ApolloProvider client={client}>\n        <button onClick={() => setShowItem(false)}>Hide item</button>\n        {showItem && (\n          <Suspense fallback=\"Loading item...\">\n            <Item />\n          </Suspense>\n        )}\n      </ApolloProvider>\n    );\n  }\n\n  function Item() {\n    const { data } = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    return <span>{data.text}</span>;\n  }\n\n  await renderAsync(<App />);\n\n  // Ensure <Greeting /> suspends immediately\n  expect(screen.getByText(\"Loading item...\")).toBeInTheDocument();\n\n  // Hide the greeting before it finishes loading data\n  await act(() => user.click(screen.getByText(\"Hide item\")));\n\n  expect(screen.queryByText(\"Loading item...\")).not.toBeInTheDocument();\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  // clear the microtask queue\n  await act(() => Promise.resolve());\n\n  expect(cache).toHaveNumWatches(1);\n\n  jest.advanceTimersByTime(30_000);\n  // Run unsubscribe timeouts from cache watches\n  jest.runOnlyPendingTimers();\n\n  expect(cache).toHaveNumWatches(0);\n\n  jest.useRealTimers();\n});\n\ntest(\"tears down watches after configured autoDisposeTimeoutMs if component never renders again after suspending\", async () => {\n  jest.useFakeTimers();\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });\n  const link = new MockSubscriptionLink();\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({\n    link,\n    cache,\n    defaultOptions: {\n      react: {\n        suspense: {\n          autoDisposeTimeoutMs: 5000,\n        },\n      },\n    },\n  });\n\n  function App() {\n    const [showItem, setShowItem] = React.useState(true);\n\n    return (\n      <ApolloProvider client={client}>\n        <button onClick={() => setShowItem(false)}>Hide item</button>\n        {showItem && (\n          <Suspense fallback=\"Loading item...\">\n            <Item />\n          </Suspense>\n        )}\n      </ApolloProvider>\n    );\n  }\n\n  function Item() {\n    const { data } = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    return <span>{data.text}</span>;\n  }\n\n  await renderAsync(<App />);\n\n  // Ensure <Greeting /> suspends immediately\n  expect(screen.getByText(\"Loading item...\")).toBeInTheDocument();\n\n  // Hide the greeting before it finishes loading data\n  await act(() => user.click(screen.getByText(\"Hide item\")));\n\n  expect(screen.queryByText(\"Loading item...\")).not.toBeInTheDocument();\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  // clear the microtask queue\n  await act(() => Promise.resolve());\n\n  expect(cache).toHaveNumWatches(1);\n\n  jest.advanceTimersByTime(5000);\n  // Run unsubscribe timeouts from cache watches\n  jest.runOnlyPendingTimers();\n\n  expect(cache).toHaveNumWatches(0);\n\n  jest.useRealTimers();\n});\n\ntest(\"cancels autoDisposeTimeoutMs if the component renders before timer finishes\", async () => {\n  jest.useFakeTimers();\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n    }\n  `;\n\n  const link = new MockSubscriptionLink();\n  const cache = new InMemoryCache();\n  const client = new ApolloClient({ link, cache });\n\n  function App() {\n    return (\n      <ApolloProvider client={client}>\n        <Suspense fallback=\"Loading item...\">\n          <Item />\n        </Suspense>\n      </ApolloProvider>\n    );\n  }\n\n  function Item() {\n    const { data } = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    return <span>{data.text}</span>;\n  }\n\n  await renderAsync(<App />);\n\n  // Ensure <Greeting /> suspends immediately\n  expect(screen.getByText(\"Loading item...\")).toBeInTheDocument();\n\n  client.writeFragment({\n    fragment,\n    data: { __typename: \"Item\", id: 1, text: \"Item #1\" },\n  });\n\n  // clear the microtask queue\n  await act(() => Promise.resolve());\n\n  await waitFor(() => {\n    expect(screen.getByText(\"Item #1\")).toBeInTheDocument();\n  });\n\n  jest.advanceTimersByTime(30_000);\n\n  expect(cache).toHaveNumWatches(1);\n\n  jest.useRealTimers();\n});\n\ntest(\"runs custom document transforms\", async () => {\n  interface ItemFragment {\n    __typename: \"Item\";\n    id: number;\n    text: string;\n  }\n\n  const { render, takeRender, replaceSnapshot } =\n    createDefaultRenderStream<ItemFragment>();\n  const { SuspenseFallback } = createDefaultTrackedComponents();\n\n  const documentTransform = new DocumentTransform((document) => {\n    return removeDirectivesFromDocument(\n      [{ name: \"custom\", remove: true }],\n      document\n    )!;\n  });\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: ApolloLink.empty(),\n    documentTransform,\n  });\n\n  const fragment: TypedDocumentNode<ItemFragment> = gql`\n    fragment ItemFragment on Item {\n      id\n      text\n      description @custom\n    }\n  `;\n\n  function App() {\n    useTrackRenders();\n\n    const result = useSuspenseFragment({\n      fragment,\n      from: { __typename: \"Item\", id: 1 },\n    });\n\n    replaceSnapshot({ result });\n\n    return null;\n  }\n\n  client.writeFragment({\n    fragment: gql`\n      fragment ItemFragment on Item {\n        id\n        text\n      }\n    `,\n    data: {\n      __typename: \"Item\",\n      id: 1,\n      text: \"Item #1\",\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  await render(\n    <Suspense fallback={<SuspenseFallback />}>\n      <App />\n    </Suspense>,\n    {\n      wrapper: ({ children }) => {\n        return <ApolloProvider client={client}>{children}</ApolloProvider>;\n      },\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([App]);\n    expect(snapshot.result).toEqual({\n      data: {\n        __typename: \"Item\",\n        id: 1,\n        text: \"Item #1\",\n      },\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ndescribe.skip(\"type tests\", () => {\n  test(\"returns TData when from is a non-null value\", () => {\n    type Data = { foo: string };\n    const fragment: TypedDocumentNode<Data> = gql``;\n\n    {\n      const { data } = useSuspenseFragment({\n        fragment,\n        from: { __typename: \"Query\" },\n      });\n\n      expectTypeOf(data).branded.toEqualTypeOf<Data>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Data>({\n        fragment: gql``,\n        from: { __typename: \"Query\" },\n      });\n\n      expectTypeOf(data).branded.toEqualTypeOf<Data>();\n    }\n  });\n\n  test(\"returns null when from is null\", () => {\n    type Data = { foo: string };\n    type Vars = Record<string, never>;\n    const fragment: TypedDocumentNode<Data, Vars> = gql``;\n\n    {\n      const { data } = useSuspenseFragment({ fragment, from: null });\n\n      expectTypeOf(data).branded.toEqualTypeOf<null>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Data>({\n        fragment: gql``,\n        from: null,\n      });\n\n      expectTypeOf(data).branded.toEqualTypeOf<null>();\n    }\n  });\n\n  test(\"returns TData | null when from is nullable\", () => {\n    type Post = { __typename: \"Post\"; id: number };\n    type Vars = Record<string, never>;\n    const fragment: TypedDocumentNode<Post, Vars> = gql``;\n    const author = {} as { post: Post | null };\n\n    {\n      const { data } = useSuspenseFragment({ fragment, from: author.post });\n\n      expectTypeOf(data).branded.toEqualTypeOf<Post | null>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Post>({\n        fragment: gql``,\n        from: author.post,\n      });\n\n      expectTypeOf(data).branded.toEqualTypeOf<Post | null>();\n    }\n  });\n\n  test(\"returns null[] when `from` is null[]\", () => {\n    type Data = { foo: string };\n    type Vars = Record<string, never>;\n    const fragment: TypedDocumentNode<Data, Vars> = gql``;\n\n    {\n      const { data } = useSuspenseFragment({ fragment, from: [null] });\n\n      expectTypeOf(data).toEqualTypeOf<Array<null>>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Data>({\n        fragment: gql``,\n        from: [null],\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Array<null>>();\n    }\n  });\n\n  test(\"returns Array<TData | null> when `from` includes null with non-null\", () => {\n    type Data = { foo: string };\n    type Vars = Record<string, never>;\n    const fragment: TypedDocumentNode<Data, Vars> = gql``;\n\n    {\n      const { data } = useSuspenseFragment({\n        fragment,\n        from: [null, { __typename: \"Item\", id: 1 }],\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Array<Data | null>>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Data>({\n        fragment: gql``,\n        from: [null, { __typename: \"Item\", id: 1 }],\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Array<Data | null>>();\n    }\n  });\n\n  test(\"returns TData[] when `from` includes array of non-null\", () => {\n    type Data = { foo: string };\n    type Vars = Record<string, never>;\n    const fragment: TypedDocumentNode<Data, Vars> = gql``;\n\n    {\n      const { data } = useSuspenseFragment({\n        fragment,\n        from: [{ __typename: \"Item\", id: 1 }],\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Array<Data>>();\n    }\n\n    {\n      const { data } = useSuspenseFragment<Data>({\n        fragment: gql``,\n        from: [{ __typename: \"Item\", id: 1 }],\n      });\n\n      expectTypeOf(data).toEqualTypeOf<Array<Data>>();\n    }\n  });\n\n  test(\"variables are optional and can be anything with an untyped DocumentNode\", () => {\n    const fragment = gql``;\n\n    useSuspenseFragment({ fragment, from: null });\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { foo: \"bar\" } });\n    useSuspenseFragment({ fragment, from: null, variables: { bar: \"baz\" } });\n  });\n\n  it(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n    const fragment: TypedDocumentNode<{ greeting: string }> = gql``;\n\n    useSuspenseFragment({ fragment, from: null });\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { foo: \"bar\" } });\n    useSuspenseFragment({ fragment, from: null, variables: { bar: \"baz\" } });\n  });\n\n  it(\"variables are optional and can be anything with OperationVariables on a TypedDocumentNode\", () => {\n    const fragment: TypedDocumentNode<\n      { greeting: string },\n      OperationVariables\n    > = gql``;\n\n    useSuspenseFragment({ fragment, from: null });\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { foo: \"bar\" } });\n    useSuspenseFragment({ fragment, from: null, variables: { bar: \"baz\" } });\n  });\n\n  it(\"variables are optional when TVariables are empty\", () => {\n    const fragment: TypedDocumentNode<\n      { greeting: string },\n      Record<string, never>\n    > = gql``;\n\n    useSuspenseFragment({ fragment, from: null });\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    // @ts-expect-error unknown variable\n    useSuspenseFragment({ fragment, from: null, variables: { foo: \"bar\" } });\n  });\n\n  it(\"is invalid with TVariables as `never`\", () => {\n    const fragment: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n    // @ts-expect-error\n    useSuspenseFragment({ fragment, from: null });\n    // @ts-expect-error\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    // @ts-expect-error no variables argument allowed\n    useSuspenseFragment({ fragment, from: null, variables: { foo: \"bar\" } });\n  });\n\n  it(\"optional variables are optional to useSuspenseFragment\", () => {\n    const fragment: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n      gql``;\n\n    useSuspenseFragment({ fragment, from: null });\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { limit: 10 } });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  it(\"enforces required variables when TVariables includes required variables\", () => {\n    const fragment: TypedDocumentNode<{ character: string }, { id: string }> =\n      gql``;\n\n    // @ts-expect-error missing variables argument\n    useSuspenseFragment({ fragment, from: null });\n    // @ts-expect-error empty variables\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { id: \"1\" } });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  it(\"requires variables with mixed TVariables\", () => {\n    const fragment: TypedDocumentNode<\n      { character: string },\n      { id: string; language?: string }\n    > = gql``;\n\n    // @ts-expect-error missing variables argument\n    useSuspenseFragment({ fragment, from: null });\n    // @ts-expect-error empty variables\n    useSuspenseFragment({ fragment, from: null, variables: {} });\n    useSuspenseFragment({ fragment, from: null, variables: { id: \"1\" } });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      // @ts-expect-error missing required variable\n      variables: { language: \"en\" },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: { id: \"1\", language: \"en\" },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    useSuspenseFragment({\n      fragment,\n      from: null,\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/defer20220824.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { delay, of, throwError } from \"rxjs\";\n\nimport type { ErrorLike, OperationVariables } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  markAsStreaming,\n  mockDefer20220824,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useSuspenseQuery.Result<TData, TVariables>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseQuery({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseQuery\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseSuspenseQuery props={props} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot, getCurrentRender } =\n    createRenderStream<\n      useSuspenseQuery.Result<TData, TVariables> | { error: ErrorLike }\n    >();\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n\n    invariant(\"data\" in snapshot, \"Snapshot is not a hook snapshot\");\n\n    return snapshot;\n  }\n\n  return { getCurrentSnapshot, takeRender, rerender };\n}\n\ntest(\"suspends deferred queries until initial chunk loads then streams in data as it loads\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest.each<useSuspenseQuery.FetchPolicy>([\n  \"cache-first\",\n  \"network-only\",\n  \"no-cache\",\n  \"cache-and-network\",\n])(\n  'suspends deferred queries until initial chunk loads then streams in data as it loads when using a \"%s\" fetch policy',\n  async (fetchPolicy) => {\n    const query = gql`\n      query {\n        greeting {\n          message\n          ... on Greeting @defer {\n            recipient {\n              name\n            }\n          }\n        }\n      }\n    `;\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDefer20220824();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: httpLink,\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy }),\n      {\n        wrapper: createClientWrapper(client),\n      }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n    }\n\n    enqueueInitialChunk({\n      data: {\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      },\n      hasNext: true,\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    enqueueSubsequentChunk({\n      incremental: [\n        {\n          data: {\n            recipient: { name: \"Alice\", __typename: \"Person\" },\n            __typename: \"Greeting\",\n          },\n          path: [\"greeting\"],\n        },\n      ],\n      hasNext: false,\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          greeting: {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  }\n);\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-first\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  const { snapshot, renderedComponents } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n  const cache = new InMemoryCache();\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useSuspenseQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          message: \"Hello cached\",\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends deferred queries with lists and properly patches results\", async () => {\n  const query = gql`\n    query {\n      greetings {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        { __typename: \"Greeting\", message: \"Hello world\" },\n        { __typename: \"Greeting\", message: \"Hello again\" },\n      ],\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          { __typename: \"Greeting\", message: \"Hello world\" },\n          { __typename: \"Greeting\", message: \"Hello again\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n        path: [\"greetings\", 0],\n      },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Hello again\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Bob\" },\n        },\n        path: [\"greetings\", 1],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Hello again\",\n            recipient: { __typename: \"Person\", name: \"Bob\" },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends queries with deferred fragments in lists and properly merges arrays\", async () => {\n  const query = gql`\n    query DeferVariation {\n      allProducts {\n        delivery {\n          ...MyFragment @defer\n        }\n        sku\n        id\n      }\n    }\n\n    fragment MyFragment on DeliveryEstimates {\n      estimatedDelivery\n      fastestDelivery\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        allProducts: [\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-federation\",\n            sku: \"federation\",\n          },\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-studio\",\n            sku: \"studio\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    hasNext: false,\n    incremental: [\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        path: [\"allProducts\", 0, \"delivery\"],\n      },\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        path: [\"allProducts\", 1, \"delivery\"],\n      },\n    ],\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        allProducts: [\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n              estimatedDelivery: \"6/25/2021\",\n              fastestDelivery: \"6/24/2021\",\n            },\n            id: \"apollo-federation\",\n            sku: \"federation\",\n          },\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n              estimatedDelivery: \"6/25/2021\",\n              fastestDelivery: \"6/24/2021\",\n            },\n            id: \"apollo-studio\",\n            sku: \"studio\",\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"incrementally rerenders data returned by a `refetch` for a deferred query\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Goodbye\",\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Bob\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Goodbye\",\n        recipient: {\n          __typename: \"Person\",\n          name: \"Bob\",\n        },\n      },\n    },\n  });\n});\n\ntest(\"incrementally renders data returned after skipping a deferred query\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using __disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderSuspenseHook(\n    ({ skip }) => useSuspenseQuery(query, { skip }),\n    {\n      initialProps: { skip: true },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await rerender({ skip: false });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\n// https://github.com/apollographql/apollo-client/issues/11034\ntest(\"incrementally rerenders data returned by a `fetchMore` for a deferred query\", async () => {\n  const query = gql`\n    query ($offset: Int) {\n      greetings(offset: $offset) {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          greetings: offsetLimitPagination(),\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { variables: { offset: 0 } }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [{ __typename: \"Greeting\", message: \"Hello world\" }],\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [{ __typename: \"Greeting\", message: \"Hello world\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        path: [\"greetings\", 0],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const fetchMorePromise = getCurrentSnapshot().fetchMore({\n    variables: { offset: 1 },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n        },\n      ],\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Goodbye\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n        path: [\"greetings\", 0],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Goodbye\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Bob\",\n            },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n    data: {\n      greetings: [\n        {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Bob\",\n          },\n        },\n      ],\n    },\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws network errors returned by deferred queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return throwError(() => new Error(\"Could not fetch\")).pipe(delay(20));\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new Error(\"Could not fetch\"),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws graphql errors returned by deferred queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk } = mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    errors: [{ message: \"Could not fetch greeting\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws errors returned by deferred queries that include partial data\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return of({\n        data: { greeting: null },\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }).pipe(delay(20));\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: { greeting: null },\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"discards partial data and throws errors returned in incremental chunks\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      // This chunk is ignored since errorPolicy `none` throws away partial\n      // data\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              {\n                id: \"1000\",\n                name: \"Luke Skywalker\",\n                homeWorld: null,\n              },\n              {\n                id: \"1003\",\n                name: \"Leia Organa\",\n                homeWorld: \"Alderaan\",\n              },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and does not throw errors returned in incremental chunks but returns them in `error` property with errorPolicy set to `all`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      // Unlike the default (errorPolicy = `none`), this data will be\n      // added to the final result\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              {\n                id: \"1000\",\n                name: \"Luke Skywalker\",\n                homeWorld: null,\n              },\n              {\n                id: \"1003\",\n                name: \"Leia Organa\",\n                homeWorld: \"Alderaan\",\n              },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and discards errors returned in incremental chunks with errorPolicy set to `ignore`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"can refetch and respond to cache updates after encountering an error in an incremental chunk for a deferred query when `errorPolicy` is `all`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\" },\n          { id: \"1003\", name: \"Leia Organa\" },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\" },\n            { id: \"1003\", name: \"Leia Organa\" },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n              { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\" },\n          { id: \"1003\", name: \"Leia Organa\" },\n        ],\n      },\n    },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        path: [\"hero\", \"heroFriends\", 0],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n      {\n        path: [\"hero\", \"heroFriends\", 1],\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n          { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n  });\n\n  client.cache.updateQuery<any>({ query }, (data) => ({\n    hero: {\n      ...data.hero,\n      name: \"C3PO\",\n    },\n  }));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"C3PO\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/deferGraphQL17Alpha9.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { delay, of, throwError } from \"rxjs\";\n\nimport type { ErrorLike, OperationVariables } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\nimport {\n  createClientWrapper,\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useSuspenseQuery.Result<TData, TVariables>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseQuery({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseQuery\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseSuspenseQuery props={props} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot, getCurrentRender } =\n    createRenderStream<\n      useSuspenseQuery.Result<TData, TVariables> | { error: ErrorLike }\n    >({ skipNonTrackingRenders: true });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n\n    invariant(\"data\" in snapshot, \"Snapshot is not a hook snapshot\");\n\n    return snapshot;\n  }\n\n  return { getCurrentSnapshot, takeRender, rerender };\n}\n\ntest(\"suspends deferred queries until initial chunk loads then streams in data as it loads\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest.each<useSuspenseQuery.FetchPolicy>([\n  \"cache-first\",\n  \"network-only\",\n  \"no-cache\",\n  \"cache-and-network\",\n])(\n  'suspends deferred queries until initial chunk loads then streams in data as it loads when using a \"%s\" fetch policy',\n  async (fetchPolicy) => {\n    const query = gql`\n      query {\n        greeting {\n          message\n          ... on Greeting @defer {\n            recipient {\n              name\n            }\n          }\n        }\n      }\n    `;\n\n    const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n      mockDeferStreamGraphQL17Alpha9();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: httpLink,\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy }),\n      {\n        wrapper: createClientWrapper(client),\n      }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n    }\n\n    enqueueInitialChunk({\n      data: {\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      },\n      pending: [{ id: \"0\", path: [\"greeting\"] }],\n      hasNext: true,\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    enqueueSubsequentChunk({\n      incremental: [\n        {\n          data: {\n            recipient: { name: \"Alice\", __typename: \"Person\" },\n            __typename: \"Greeting\",\n          },\n          id: \"0\",\n        },\n      ],\n      completed: [{ id: \"0\" }],\n      hasNext: false,\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          greeting: {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  }\n);\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-first\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello world\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  const { snapshot, renderedComponents } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: {\n      greeting: {\n        message: \"Hello world\",\n        __typename: \"Greeting\",\n        recipient: { __typename: \"Person\", name: \"Alice\" },\n      },\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n  const cache = new InMemoryCache();\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    cache,\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useSuspenseQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend deferred queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Hello cached\",\n        recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n      },\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          message: \"Hello cached\",\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Cached Alice\" },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends deferred queries with lists and properly patches results\", async () => {\n  const query = gql`\n    query {\n      greetings {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        { __typename: \"Greeting\", message: \"Hello world\" },\n        { __typename: \"Greeting\", message: \"Hello again\" },\n      ],\n    },\n    pending: [\n      { id: \"0\", path: [\"greetings\", 0] },\n      { id: \"1\", path: [\"greetings\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          { __typename: \"Greeting\", message: \"Hello world\" },\n          { __typename: \"Greeting\", message: \"Hello again\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Hello again\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          __typename: \"Greeting\",\n          recipient: { __typename: \"Person\", name: \"Bob\" },\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: { __typename: \"Person\", name: \"Alice\" },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Hello again\",\n            recipient: { __typename: \"Person\", name: \"Bob\" },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends queries with deferred fragments in lists and properly merges arrays\", async () => {\n  const query = gql`\n    query DeferVariation {\n      allProducts {\n        delivery {\n          ...MyFragment @defer\n        }\n        sku\n        id\n      }\n    }\n\n    fragment MyFragment on DeliveryEstimates {\n      estimatedDelivery\n      fastestDelivery\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      allProducts: [\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-federation\",\n          sku: \"federation\",\n        },\n        {\n          __typename: \"Product\",\n          delivery: {\n            __typename: \"DeliveryEstimates\",\n          },\n          id: \"apollo-studio\",\n          sku: \"studio\",\n        },\n      ],\n    },\n    pending: [\n      { id: \"0\", path: [\"allProducts\", 0, \"delivery\"] },\n      { id: \"1\", path: [\"allProducts\", 1, \"delivery\"] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        allProducts: [\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-federation\",\n            sku: \"federation\",\n          },\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n            },\n            id: \"apollo-studio\",\n            sku: \"studio\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    hasNext: false,\n    incremental: [\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        id: \"0\",\n      },\n      {\n        data: {\n          __typename: \"DeliveryEstimates\",\n          estimatedDelivery: \"6/25/2021\",\n          fastestDelivery: \"6/24/2021\",\n        },\n        id: \"1\",\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        allProducts: [\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n              estimatedDelivery: \"6/25/2021\",\n              fastestDelivery: \"6/24/2021\",\n            },\n            id: \"apollo-federation\",\n            sku: \"federation\",\n          },\n          {\n            __typename: \"Product\",\n            delivery: {\n              __typename: \"DeliveryEstimates\",\n              estimatedDelivery: \"6/25/2021\",\n              fastestDelivery: \"6/24/2021\",\n            },\n            id: \"apollo-studio\",\n            sku: \"studio\",\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"incrementally rerenders data returned by a `refetch` for a deferred query\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Goodbye\",\n      },\n    },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Bob\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      greeting: {\n        __typename: \"Greeting\",\n        message: \"Goodbye\",\n        recipient: {\n          __typename: \"Person\",\n          name: \"Bob\",\n        },\n      },\n    },\n  });\n});\n\ntest(\"incrementally renders data returned after skipping a deferred query\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using __disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderSuspenseHook(\n    ({ skip }) => useSuspenseQuery(query, { skip }),\n    {\n      initialProps: { skip: true },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await rerender({ skip: false });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { __typename: \"Greeting\", message: \"Hello world\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Alice\",\n          },\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\n// https://github.com/apollographql/apollo-client/issues/11034\ntest(\"incrementally rerenders data returned by a `fetchMore` for a deferred query\", async () => {\n  const query = gql`\n    query ($offset: Int) {\n      greetings(offset: $offset) {\n        message\n        ... @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          greetings: offsetLimitPagination(),\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: httpLink,\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { variables: { offset: 0 } }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [{ __typename: \"Greeting\", message: \"Hello world\" }],\n    },\n    pending: [{ id: \"0\", path: [\"greetings\", 0] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [{ __typename: \"Greeting\", message: \"Hello world\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const fetchMorePromise = getCurrentSnapshot().fetchMore({\n    variables: { offset: 1 },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      greetings: [\n        {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n        },\n      ],\n    },\n    pending: [{ id: \"0\", path: [\"greetings\", 0] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Goodbye\",\n          },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Bob\", __typename: \"Person\" },\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        greetings: [\n          {\n            __typename: \"Greeting\",\n            message: \"Hello world\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Alice\",\n            },\n          },\n          {\n            __typename: \"Greeting\",\n            message: \"Goodbye\",\n            recipient: {\n              __typename: \"Person\",\n              name: \"Bob\",\n            },\n          },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n    data: {\n      greetings: [\n        {\n          __typename: \"Greeting\",\n          message: \"Goodbye\",\n          recipient: {\n            __typename: \"Person\",\n            name: \"Bob\",\n          },\n        },\n      ],\n    },\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws network errors returned by deferred queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return throwError(() => new Error(\"Could not fetch\")).pipe(delay(20));\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new Error(\"Could not fetch\"),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws graphql errors returned by deferred queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return of({\n        data: null,\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }).pipe(delay(20));\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: null,\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws errors returned by deferred queries that include partial data\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return of({\n        data: { greeting: null },\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }).pipe(delay(20));\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: { greeting: null },\n        errors: [{ message: \"Could not fetch greeting\" }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"discards partial data and throws errors returned in incremental chunks\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        id: \"0\",\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      // This chunk is ignored since errorPolicy `none` throws away partial\n      // data\n      {\n        id: \"1\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              {\n                id: \"1000\",\n                name: \"Luke Skywalker\",\n                homeWorld: null,\n              },\n              {\n                id: \"1003\",\n                name: \"Leia Organa\",\n                homeWorld: \"Alderaan\",\n              },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and does not throw errors returned in incremental chunks but returns them in `error` property with errorPolicy set to `all`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        id: \"0\",\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      // Unlike the default (errorPolicy = `none`), this data will be\n      // added to the final result\n      {\n        id: \"1\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              {\n                id: \"1000\",\n                name: \"Luke Skywalker\",\n                homeWorld: null,\n              },\n              {\n                id: \"1003\",\n                name: \"Leia Organa\",\n                homeWorld: \"Alderaan\",\n              },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and discards errors returned in incremental chunks with errorPolicy set to `ignore`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          {\n            id: \"1000\",\n            name: \"Luke Skywalker\",\n          },\n          {\n            id: \"1003\",\n            name: \"Leia Organa\",\n          },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        id: \"0\",\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      {\n        id: \"1\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            {\n              id: \"1000\",\n              name: \"Luke Skywalker\",\n              homeWorld: null,\n            },\n            {\n              id: \"1003\",\n              name: \"Leia Organa\",\n              homeWorld: \"Alderaan\",\n            },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"can refetch and respond to cache updates after encountering an error in an incremental chunk for a deferred query when `errorPolicy` is `all`\", async () => {\n  const query = gql`\n    query {\n      hero {\n        name\n        heroFriends {\n          id\n          name\n          ... @defer {\n            homeWorld\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\" },\n          { id: \"1003\", name: \"Leia Organa\" },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\" },\n            { id: \"1003\", name: \"Leia Organa\" },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        id: \"0\",\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n        data: {\n          homeWorld: null,\n        },\n      },\n      {\n        id: \"1\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          hero: {\n            heroFriends: [\n              { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n              { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n            ],\n            name: \"R2-D2\",\n          },\n        },\n        errors: [\n          {\n            message:\n              \"homeWorld for character with ID 1000 could not be fetched.\",\n            path: [\"hero\", \"heroFriends\", 0, \"homeWorld\"],\n          },\n        ],\n      }),\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: {\n      hero: {\n        name: \"R2-D2\",\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\" },\n          { id: \"1003\", name: \"Leia Organa\" },\n        ],\n      },\n    },\n    pending: [\n      { id: \"0\", path: [\"hero\", \"heroFriends\", 0] },\n      { id: \"1\", path: [\"hero\", \"heroFriends\", 1] },\n    ],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: null },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        id: \"0\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n      {\n        id: \"1\",\n        data: {\n          homeWorld: \"Alderaan\",\n        },\n      },\n    ],\n    completed: [{ id: \"0\" }, { id: \"1\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"R2-D2\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      hero: {\n        heroFriends: [\n          { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n          { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n        ],\n        name: \"R2-D2\",\n      },\n    },\n  });\n\n  client.cache.updateQuery<any>({ query }, (data) => ({\n    hero: {\n      ...data.hero,\n      name: \"C3PO\",\n    },\n  }));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        hero: {\n          heroFriends: [\n            { id: \"1000\", name: \"Luke Skywalker\", homeWorld: \"Alderaan\" },\n            { id: \"1003\", name: \"Leia Organa\", homeWorld: \"Alderaan\" },\n          ],\n          name: \"C3PO\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/skipToken.test.tsx",
    "content": "import { disableActEnvironment } from \"@testing-library/react-render-stream\";\nimport { gql } from \"graphql-tag\";\nimport { delay, of, Subject } from \"rxjs\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { skipToken, useSuspenseQuery } from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport {\n  createClientWrapper,\n  createMockWrapper,\n  ObservableStream,\n  setupVariablesCase,\n} from \"@apollo/client/testing/internal\";\n\nimport { renderUseSuspenseQuery } from \"./testUtils.js\";\n\n// https://github.com/apollographql/apollo-client/issues/12989\ntest(\"maintains variables when switching to `skipToken` and calling `refetchQueries` while skipped after initial request\", async () => {\n  const { query } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    link: new ApolloLink((operation) => {\n      return of(\n        operation.variables.id === \"1\" ?\n          {\n            data: {\n              character: {\n                __typename: \"Character\",\n                id: \"1\",\n                name: \"Spider-Man\",\n              },\n            },\n          }\n        : {\n            data: null,\n            errors: [\n              { message: `Fetched wrong id: ${operation.variables.id}` },\n            ],\n          }\n      ).pipe(delay(10));\n    }),\n    cache: new InMemoryCache(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderUseSuspenseQuery(\n    ({ id }) =>\n      useSuspenseQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n  }\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n\n  await expect(\n    client.refetchQueries({ include: [query] })\n  ).resolves.toStrictEqualTyped([\n    {\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n    },\n  ]);\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"suspends and fetches when changing variables when no longer using skipToken\", async () => {\n  const { query, mocks } = setupVariablesCase({ delay: 200 });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderUseSuspenseQuery(\n    ({ id }) =>\n      useSuspenseQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createMockWrapper({ mocks }),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n  }\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n\n  await rerender({ id: \"2\" });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n  }\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Black Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"does not suspend for data in the cache when changing variables when no longer using skipToken\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  const client = new ApolloClient({\n    link: new MockLink(mocks),\n    cache: new InMemoryCache(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n    },\n    variables: { id: \"2\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderUseSuspenseQuery(\n    ({ id }) =>\n      useSuspenseQuery(\n        query,\n        id === undefined ? skipToken : { variables: { id } }\n      ),\n    {\n      initialProps: { id: \"1\" as string | undefined },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n  }\n\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: undefined });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await rerender({ id: \"2\" });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"2\", name: \"Cached Widow\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"client.refetchQueries should not refetch queries that start with skipToken until they have been executed\", async () => {\n  const query = gql`\n    query getAuthor($id: ID!) {\n      author(id: $id) {\n        firstName\n        lastName\n      }\n    }\n  `;\n  const data = {\n    author: {\n      firstName: \"John\",\n      lastName: \"Smith\",\n    },\n  };\n  const secondReqData = {\n    author: {\n      firstName: \"Jane\",\n      lastName: \"Johnson\",\n    },\n  };\n\n  const operationSubject = new Subject<ApolloLink.Operation>();\n  const link = new MockSubscriptionLink();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation, forward) => {\n      operationSubject.next(operation);\n      return forward(operation);\n    }).concat(link),\n  });\n\n  const operationStream = new ObservableStream(operationSubject);\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderUseSuspenseQuery(\n    (options) => useSuspenseQuery(query, options),\n    {\n      initialProps: skipToken as\n        | typeof skipToken\n        | useSuspenseQuery.Options<{ id: string }>,\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  await expect(operationStream).not.toEmitAnything();\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  void client.refetchQueries({ include: [query] });\n  await expect(operationStream).not.toEmitAnything();\n  await expect(takeRender).not.toRerender();\n\n  await rerender({ variables: { id: \"1234\" } });\n  await expect(operationStream).toEmitNext();\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n  }\n\n  link.simulateResult({ result: { data } }, true);\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data,\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  void client.refetchQueries({ include: [query] });\n  await expect(operationStream).toEmitNext();\n  link.simulateResult({ result: { data: secondReqData } }, true);\n  {\n    const { snapshot } = await takeRender();\n\n    expect(snapshot).toStrictEqualTyped({\n      data: secondReqData,\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/streamDefer20220824.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport type { Subject } from \"rxjs\";\nimport { delay, from, throwError } from \"rxjs\";\n\nimport type { ErrorLike, OperationVariables } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha2,\n  friendListSchemaGraphQL17Alpha2,\n  markAsStreaming,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useSuspenseQuery.Result<TData, TVariables>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseQuery({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseQuery\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseSuspenseQuery props={props} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot, getCurrentRender } =\n    createRenderStream<\n      useSuspenseQuery.Result<TData, TVariables> | { error: ErrorLike }\n    >({ skipNonTrackingRenders: true });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n\n    invariant(\"data\" in snapshot, \"Snapshot is not a hook snapshot\");\n\n    return snapshot;\n  }\n\n  return { getCurrentSnapshot, takeRender, rerender };\n}\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha2(\n        friendListSchemaGraphQL17Alpha2,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntype Friend = (typeof friends)[number];\n\ntest(\"suspends streamed queries until initial chunk loads then streams in data as it loads\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async () => {\n        return stream;\n      },\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest.each<useSuspenseQuery.FetchPolicy>([\n  \"cache-first\",\n  \"network-only\",\n  \"no-cache\",\n  \"cache-and-network\",\n])(\n  'suspends streamed queries until initial chunk loads then streams in data as it loads when using a \"%s\" fetch policy',\n  async (fetchPolicy) => {\n    const { stream, subject } = asyncIterableSubject();\n\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: createLink({ friendList: () => stream }),\n      incrementalHandler: new Defer20220824Handler(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy }),\n      { wrapper: createClientWrapper(client) }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n    }\n\n    subject.next(friends[0]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[1]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          ],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[2]);\n    subject.complete();\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  }\n);\n\ntest('does not suspend streamed queries with data in the cache and using a \"cache-first\" fetch policy', async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    // Use a query without `@stream` to ensure it doesn't affect the cache\n    query: gql`\n      query {\n        friendList {\n          id\n          name\n        }\n      }\n    `,\n    data: {\n      friendList: friends.map((friend) => ({\n        __typename: \"Friend\",\n        ...friend,\n      })),\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  const { snapshot, renderedComponents } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: {\n      friendList: friends.map((friend) => ({\n        __typename: \"Friend\",\n        ...friend,\n      })),\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend streamed queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { subject, stream } = asyncIterableSubject();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: {\n            merge: (_, incoming) => incoming,\n          },\n        },\n      },\n    },\n  });\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        friendList: friends.map((friend) => ({\n          __typename: \"Friend\",\n          id: String(friend.id),\n        })),\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    cache,\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useSuspenseQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: friends.map((friend) => ({\n          __typename: \"Friend\",\n          id: String(friend.id),\n        })),\n      },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend streamed queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (_, incoming) => incoming,\n            },\n          },\n        },\n      },\n    }),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"incrementally rerenders data returned by a `refetch` for a streamed query\", async () => {\n  let subject!: Subject<Friend>;\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => {\n        const iterable = asyncIterableSubject<Friend>();\n        subject = iterable.subject;\n\n        return iterable.stream;\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next({ id: 1, name: \"Luke (refetch)\" });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next({ id: 2, name: \"Han (refetch)\" });\n  subject.next({ id: 3, name: \"Leia (refetch)\" });\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia (refetch)\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia (refetch)\" },\n      ],\n    },\n  });\n});\n\ntest(\"incrementally renders data returned after skipping a streamed query\", async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using __disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderSuspenseHook(\n    ({ skip }) => useSuspenseQuery(query, { skip }),\n    {\n      initialProps: { skip: true },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await rerender({ skip: false });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\n// https://github.com/apollographql/apollo-client/issues/11034\ntest(\"incrementally rerenders data returned by a `fetchMore` for a streamed query\", async () => {\n  let subject!: Subject<Friend>;\n  const query = gql`\n    query ($offset: Int) {\n      friendList(offset: $offset) @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: offsetLimitPagination(),\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => {\n        const iterator = asyncIterableSubject<Friend>();\n        subject = iterator.subject;\n\n        return iterator.stream;\n      },\n    }),\n    cache,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { variables: { offset: 0 } }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const fetchMorePromise = getCurrentSnapshot().fetchMore({\n    variables: { offset: 2 },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[2]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next({ id: 4, name: \"Chewbacca\" });\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          { __typename: \"Friend\", id: \"4\", name: \"Chewbacca\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        { __typename: \"Friend\", id: \"4\", name: \"Chewbacca\" },\n      ],\n    },\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws network errors returned by streamed queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return throwError(() => new Error(\"Could not fetch\")).pipe(delay(20));\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new Error(\"Could not fetch\"),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws graphql errors returned by streamed queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async () => {\n        await wait(20);\n        throw new Error(\"Could not get friend list\");\n      },\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: { friendList: null },\n        errors: [\n          { message: \"Could not get friend list\", path: [\"friendList\"] },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"discards partial data and throws errors returned in incremental chunks\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async function* () {\n        for await (const friend of stream) {\n          if (friend.id === 2) {\n            throw new Error(\"Could not get friend\");\n          }\n\n          yield friend;\n        }\n      },\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and does not throw errors returned in incremental chunks but returns them in `error` property with errorPolicy set to `all`\", async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(new Error(\"Could not get friend\"));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            null,\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and discards errors returned in incremental chunks with errorPolicy set to `ignore`\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Error>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: () => stream,\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(new Error(\"Could not get friend\"));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"can refetch and respond to cache updates after encountering an error in an incremental chunk for a streamed query when `errorPolicy` is `all`\", async () => {\n  let subject!: Subject<Friend | Error>;\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: () => {\n        const iterable = asyncIterableSubject<Friend | Error>();\n        subject = iterable.subject;\n\n        return iterable.stream;\n      },\n    }),\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(new Error(\"Could not get friend\"));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            null,\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n  });\n\n  client.cache.updateQuery<any>({ query }, (data) => ({\n    friendList: [\n      { ...data.friendList[0], name: \"Luke (updated)\" },\n      ...data.friendList.slice(1),\n    ],\n  }));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke (updated)\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/streamGraphQL17Alpha9.test.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport type { Subject } from \"rxjs\";\nimport { delay, from, throwError } from \"rxjs\";\n\nimport type { ErrorLike, OperationVariables } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport { useSuspenseQuery } from \"@apollo/client/react\";\nimport {\n  asyncIterableSubject,\n  createClientWrapper,\n  executeSchemaGraphQL17Alpha9,\n  friendListSchemaGraphQL17Alpha9,\n  markAsStreaming,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport { offsetLimitPagination } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nasync function renderSuspenseHook<\n  TData,\n  TVariables extends OperationVariables,\n  Props = never,\n>(\n  renderHook: (\n    props: Props extends never ? undefined : Props\n  ) => useSuspenseQuery.Result<TData, TVariables>,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseQuery({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseQuery\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"ErrorBoundary\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseSuspenseQuery props={props} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot, getCurrentRender } =\n    createRenderStream<\n      useSuspenseQuery.Result<TData, TVariables> | { error: ErrorLike }\n    >({ skipNonTrackingRenders: true });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n\n    invariant(\"data\" in snapshot, \"Snapshot is not a hook snapshot\");\n\n    return snapshot;\n  }\n\n  return { getCurrentSnapshot, takeRender, rerender };\n}\n\nfunction createLink(rootValue?: unknown) {\n  return new ApolloLink((operation) => {\n    return from(\n      executeSchemaGraphQL17Alpha9(\n        friendListSchemaGraphQL17Alpha9,\n        operation.query,\n        rootValue\n      )\n    );\n  });\n}\n\nconst friends = [\n  { name: \"Luke\", id: 1 },\n  { name: \"Han\", id: 2 },\n  { name: \"Leia\", id: 3 },\n];\n\ntype Friend = (typeof friends)[number];\n\ntest(\"suspends streamed queries until initial chunk loads then streams in data as it loads\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async () => {\n        return stream;\n      },\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest.each<useSuspenseQuery.FetchPolicy>([\n  \"cache-first\",\n  \"network-only\",\n  \"no-cache\",\n  \"cache-and-network\",\n])(\n  'suspends streamed queries until initial chunk loads then streams in data as it loads when using a \"%s\" fetch policy',\n  async (fetchPolicy) => {\n    const { stream, subject } = asyncIterableSubject();\n\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: createLink({ friendList: () => stream }),\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy }),\n      { wrapper: createClientWrapper(client) }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n    }\n\n    subject.next(friends[0]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[1]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          ],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[2]);\n    subject.complete();\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  }\n);\n\ntest('does not suspend streamed queries with data in the cache and using a \"cache-first\" fetch policy', async () => {\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  cache.writeQuery({\n    // Use a query without `@stream` to ensure it doesn't affect the cache\n    query: gql`\n      query {\n        friendList {\n          id\n          name\n        }\n      }\n    `,\n    data: {\n      friendList: friends.map((friend) => ({\n        __typename: \"Friend\",\n        ...friend,\n      })),\n    },\n  });\n\n  const client = new ApolloClient({\n    cache,\n    link: ApolloLink.empty(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  const { snapshot, renderedComponents } = await takeRender();\n\n  expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n  expect(snapshot).toStrictEqualTyped({\n    data: {\n      friendList: friends.map((friend) => ({\n        __typename: \"Friend\",\n        ...friend,\n      })),\n    },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend streamed queries with partial data in the cache and using a \"cache-first\" fetch policy with `returnPartialData`', async () => {\n  const { subject, stream } = asyncIterableSubject();\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache();\n\n  // We are intentionally writing partial data to the cache. Supress console\n  // warnings to avoid unnecessary noise in the test.\n  {\n    using _consoleSpy = spyOnConsole(\"error\");\n    cache.writeQuery({\n      query,\n      data: {\n        friendList: friends.map((friend) => ({\n          __typename: \"Friend\",\n          id: String(friend.id),\n        })),\n      },\n    });\n  }\n\n  const client = new ApolloClient({\n    cache,\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () =>\n      useSuspenseQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n      }),\n    {\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: friends.map((friend) => ({\n          __typename: \"Friend\",\n          id: String(friend.id),\n        })),\n      },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest('does not suspend streamed queries with data in the cache and using a \"cache-and-network\" fetch policy', async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  client.writeQuery({\n    query,\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n      ],\n    },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { fetchPolicy: \"cache-and-network\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Cached Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Cached Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Cached Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"incrementally rerenders data returned by a `refetch` for a streamed query\", async () => {\n  let subject!: Subject<Friend>;\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => {\n        const iterable = asyncIterableSubject<Friend>();\n        subject = iterable.subject;\n\n        return iterable.stream;\n      },\n    }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next({ id: 1, name: \"Luke (refetch)\" });\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next({ id: 2, name: \"Han (refetch)\" });\n  subject.next({ id: 3, name: \"Leia (refetch)\" });\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia (refetch)\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke (refetch)\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han (refetch)\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia (refetch)\" },\n      ],\n    },\n  });\n});\n\ntest(\"incrementally renders data returned after skipping a streamed query\", async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    link: createLink({ friendList: () => stream }),\n    cache: new InMemoryCache(),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using __disabledAct = disableActEnvironment();\n  const { takeRender, rerender } = await renderSuspenseHook(\n    ({ skip }) => useSuspenseQuery(query, { skip }),\n    {\n      initialProps: { skip: true },\n      wrapper: createClientWrapper(client),\n    }\n  );\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await rerender({ skip: false });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\n// https://github.com/apollographql/apollo-client/issues/11034\ntest(\"incrementally rerenders data returned by a `fetchMore` for a streamed query\", async () => {\n  let subject!: Subject<Friend>;\n  const query = gql`\n    query ($offset: Int) {\n      friendList(offset: $offset) @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const cache = new InMemoryCache({\n    typePolicies: {\n      Query: {\n        fields: {\n          friendList: offsetLimitPagination(),\n        },\n      },\n    },\n  });\n\n  const client = new ApolloClient({\n    link: createLink({\n      friendList: () => {\n        const iterator = asyncIterableSubject<Friend>();\n        subject = iterator.subject;\n\n        return iterator.stream;\n      },\n    }),\n    cache,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { variables: { offset: 0 } }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  const fetchMorePromise = getCurrentSnapshot().fetchMore({\n    variables: { offset: 2 },\n  });\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[2]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next({ id: 4, name: \"Chewbacca\" });\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          { __typename: \"Friend\", id: \"4\", name: \"Chewbacca\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(fetchMorePromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        { __typename: \"Friend\", id: \"4\", name: \"Chewbacca\" },\n      ],\n    },\n  });\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws network errors returned by streamed queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink(() => {\n      return throwError(() => new Error(\"Could not fetch\")).pipe(delay(20));\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new Error(\"Could not fetch\"),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"throws graphql errors returned by streamed queries\", async () => {\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async () => {\n        await wait(20);\n        throw new Error(\"Could not get friend list\");\n      },\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: { friendList: null },\n        errors: [\n          { message: \"Could not get friend list\", path: [\"friendList\"] },\n        ],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"discards partial data and throws errors returned in incremental chunks\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend>();\n  using _consoleSpy = spyOnConsole(\"error\");\n\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async function* () {\n        for await (const friend of stream) {\n          if (friend.id === 2) {\n            throw new Error(\"Could not get friend\");\n          }\n\n          yield friend;\n        }\n      },\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorBoundary\"]);\n    expect(snapshot).toStrictEqualTyped({\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\"] }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and does not throw errors returned in incremental chunks but returns them in `error` property with errorPolicy set to `all`\", async () => {\n  const { stream, subject } = asyncIterableSubject();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({ friendList: () => stream }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(Promise.reject(new Error(\"Could not get friend\")));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  subject.next(friends[2]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            null,\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            null,\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"adds partial data and discards errors returned in incremental chunks with errorPolicy set to `ignore`\", async () => {\n  const { stream, subject } = asyncIterableSubject<Friend | Promise<Friend>>();\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: () => stream,\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(Promise.reject(new Error(\"Could not get friend\")));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\ntest(\"can refetch and respond to cache updates after encountering an error in an incremental chunk for a streamed query when `errorPolicy` is `all`\", async () => {\n  let subject!: Subject<Promise<Friend> | Friend>;\n  const query = gql`\n    query {\n      friendList @stream(initialCount: 1) {\n        id\n        name\n      }\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: createLink({\n      friendList: async () => {\n        const iterable = asyncIterableSubject<Promise<Friend> | Friend>();\n        subject = iterable.subject;\n\n        return iterable.stream;\n      },\n    }),\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { takeRender, getCurrentSnapshot } = await renderSuspenseHook(\n    () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n    { wrapper: createClientWrapper(client) }\n  );\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(Promise.reject(new Error(\"Could not get friend\")));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [{ __typename: \"Friend\", id: \"1\", name: \"Luke\" }, null],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.error,\n      error: new CombinedGraphQLErrors({\n        data: {\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            null,\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        },\n        errors: [{ message: \"Could not get friend\", path: [\"friendList\", 1] }],\n      }),\n    });\n  }\n\n  const refetchPromise = getCurrentSnapshot().refetch();\n\n  {\n    const { renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"SuspenseFallback\"]);\n  }\n\n  subject.next(friends[0]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          null,\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[1]);\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: markAsStreaming({\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      }),\n      dataState: \"streaming\",\n      networkStatus: NetworkStatus.streaming,\n      error: undefined,\n    });\n  }\n\n  subject.next(friends[2]);\n  subject.complete();\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(refetchPromise).resolves.toStrictEqualTyped({\n    data: {\n      friendList: [\n        { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n        { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n        { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n      ],\n    },\n  });\n\n  client.cache.updateQuery<any>({ query }, (data) => ({\n    friendList: [\n      { ...data.friendList[0], name: \"Luke (updated)\" },\n      ...data.friendList.slice(1),\n    ],\n  }));\n\n  {\n    const { snapshot, renderedComponents } = await takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n    expect(snapshot).toStrictEqualTyped({\n      data: {\n        friendList: [\n          { __typename: \"Friend\", id: \"1\", name: \"Luke (updated)\" },\n          { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n          { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n        ],\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n\n  await expect(takeRender).not.toRerender();\n});\n\n// caused by https://github.com/apollographql/apollo-client/blob/566e24960e7ca46809c5247eccd9be1b756a97da/src/core/QueryInfo.ts#L327\n// changing this now might be considered breaking and needs further evaulation\ntest.failing(\n  \"reports data as partial if a cache merge function returns partial data\",\n  async () => {\n    using _TODO_REMOVE_ME_AFTER_DECIDING_COMMENT = spyOnConsole(\"error\");\n    const { subject, stream } = asyncIterableSubject();\n\n    const query = gql`\n      query {\n        friendList @stream(initialCount: 1) {\n          id\n          name\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            friendList: {\n              merge: (existing = [], incoming, { cache }) => {\n                const max = Math.max(existing.length, incoming.length);\n                const results = [];\n\n                for (let i = 0; i < max; i++) {\n                  results[i] = incoming[i] ? incoming[i] : existing[i];\n                }\n\n                return results;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    // We are intentionally writing partial data to the cache. Supress console\n    // warnings to avoid unnecessary noise in the test.\n    {\n      using _consoleSpy = spyOnConsole(\"error\");\n      cache.writeQuery({\n        query,\n        data: {\n          friendList: friends.map((friend) => ({\n            __typename: \"Friend\",\n            id: String(friend.id),\n          })),\n        },\n      });\n    }\n\n    const client = new ApolloClient({\n      cache,\n      link: createLink({ friendList: () => stream }),\n      incrementalHandler: new GraphQL17Alpha9Handler(),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"cache-first\",\n          returnPartialData: true,\n        }),\n      {\n        wrapper: createClientWrapper(client),\n      }\n    );\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          friendList: friends.map((friend) => ({\n            __typename: \"Friend\",\n            id: String(friend.id),\n          })),\n        },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[0]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\" },\n            { __typename: \"Friend\", id: \"3\" },\n          ],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[1]);\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n            { __typename: \"Friend\", id: \"3\" },\n          ],\n        }),\n        dataState: \"streaming\",\n        networkStatus: NetworkStatus.streaming,\n        error: undefined,\n      });\n    }\n\n    subject.next(friends[2]);\n    subject.complete();\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: markAsStreaming({\n          friendList: [\n            { __typename: \"Friend\", id: \"1\", name: \"Luke\" },\n            { __typename: \"Friend\", id: \"2\", name: \"Han\" },\n            { __typename: \"Friend\", id: \"3\", name: \"Leia\" },\n          ],\n        }),\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  }\n);\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery/testUtils.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type { ErrorLike, OperationVariables } from \"@apollo/client\";\nimport type { useSuspenseQuery } from \"@apollo/client/react\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nexport async function renderUseSuspenseQuery<\n  TData,\n  TVariables extends OperationVariables,\n  Props = never,\n>(\n  renderHook: (props: any) => any,\n  options: Pick<RenderOptions, \"wrapper\"> & { initialProps?: Props }\n) {\n  function UseSuspenseQuery({ props }: { props: Props | undefined }) {\n    useTrackRenders({ name: \"useSuspenseQuery\" });\n    replaceSnapshot(renderHook(props as any));\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"<Suspense />\" });\n\n    return null;\n  }\n\n  function ErrorFallback() {\n    useTrackRenders({ name: \"<ErrorBoundary />\" });\n\n    return null;\n  }\n\n  function App({ props }: { props: Props | undefined }) {\n    return (\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary\n          FallbackComponent={ErrorFallback}\n          onError={(error) => replaceSnapshot({ error })}\n        >\n          <UseSuspenseQuery props={props} />\n        </ErrorBoundary>\n      </Suspense>\n    );\n  }\n\n  const { render, takeRender, replaceSnapshot, getCurrentRender } =\n    createRenderStream<\n      useSuspenseQuery.Result<TData, TVariables> | { error: ErrorLike }\n    >({ skipNonTrackingRenders: true });\n\n  const utils = await render(<App props={options.initialProps} />, options);\n\n  function rerender(props: Props) {\n    return utils.rerender(<App props={props} />);\n  }\n\n  function getCurrentSnapshot() {\n    const { snapshot } = getCurrentRender();\n\n    invariant(\"data\" in snapshot, \"Snapshot is not a hook snapshot\");\n\n    return snapshot;\n  }\n\n  return { getCurrentSnapshot, rerender, takeRender };\n}\n"
  },
  {
    "path": "src/react/hooks/__tests__/useSuspenseQuery.test.tsx",
    "content": "import type { RenderHookOptions } from \"@testing-library/react\";\nimport { act, renderHook, screen, waitFor } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { equal } from \"@wry/equality\";\nimport { expectTypeOf } from \"expect-type\";\nimport type { GraphQLFormattedError } from \"graphql\";\nimport { GraphQLError } from \"graphql\";\nimport React, { Fragment, StrictMode, Suspense, useTransition } from \"react\";\nimport type { FallbackProps } from \"react-error-boundary\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { delay, Observable, of } from \"rxjs\";\n\nimport type {\n  ApolloCache,\n  DataValue,\n  DocumentNode,\n  ErrorPolicy,\n  ObservableQuery,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport type { Incremental } from \"@apollo/client/incremental\";\nimport { NotImplementedHandler } from \"@apollo/client/incremental\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport {\n  ApolloProvider,\n  skipToken,\n  useSuspenseQuery,\n} from \"@apollo/client/react\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  PaginatedCaseData,\n  PaginatedCaseVariables,\n} from \"@apollo/client/testing/internal\";\nimport {\n  actAsync,\n  createClientWrapper,\n  createMockWrapper,\n  renderAsync,\n  renderHookAsync,\n  setupPaginatedCase,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\nimport {\n  concatPagination,\n  offsetLimitPagination,\n} from \"@apollo/client/utilities\";\nimport { compact, getMainDefinition } from \"@apollo/client/utilities/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport type {\n  RefetchWritePolicy,\n  WatchQueryFetchPolicy,\n} from \"../../../core/watchQueryOptions.js\";\n\nimport { renderUseSuspenseQuery } from \"./useSuspenseQuery/testUtils.js\";\n\nconst IS_REACT_19 = React.version.startsWith(\"19\");\n\ntype RenderSuspenseHookOptions<Props> = Omit<\n  RenderHookOptions<Props>,\n  \"wrapper\"\n> & {\n  client?: ApolloClient;\n  incrementalHandler?: Incremental.Handler<any>;\n  link?: ApolloLink;\n  cache?: ApolloCache;\n  mocks?: MockLink.MockedResponse[];\n  strictMode?: boolean;\n};\n\ninterface Renders<Result> {\n  errors: Error[];\n  errorCount: number;\n  suspenseCount: number;\n  count: number;\n  frames: Result[];\n}\n\ninterface SimpleQueryData {\n  greeting: string;\n}\n\n/**\n * @deprecated\n * Use the `renderUseSuspenseQuery` helper from utils which uses render streams\n * instead of function call render counting.\n */\nasync function renderSuspenseHook<Result, Props>(\n  render: (initialProps: Props) => Result,\n  options: RenderSuspenseHookOptions<Props> = {}\n) {\n  function SuspenseFallback() {\n    renders.suspenseCount++;\n\n    return <div>loading</div>;\n  }\n\n  const renders: Renders<Result> = {\n    errors: [],\n    errorCount: 0,\n    suspenseCount: 0,\n    count: 0,\n    frames: [],\n  };\n\n  const { mocks = [], strictMode, ...renderHookOptions } = options;\n\n  const client =\n    options.client ||\n    new ApolloClient({\n      cache: options.cache || new InMemoryCache(),\n      link: options.link || new MockLink(mocks),\n      incrementalHandler:\n        options.incrementalHandler || new NotImplementedHandler(),\n    });\n\n  const { rerender, ...view } = await renderHookAsync(\n    (props) => {\n      renders.count++;\n\n      const view = render(props);\n\n      renders.frames.push(view);\n\n      return view;\n    },\n    {\n      ...renderHookOptions,\n      wrapper: ({ children }) => {\n        const Wrapper = strictMode ? StrictMode : Fragment;\n\n        return (\n          <Wrapper>\n            <Suspense fallback={<SuspenseFallback />}>\n              <ErrorBoundary\n                fallback={<div>Error</div>}\n                onError={(error) => {\n                  renders.errorCount++;\n                  renders.errors.push(error);\n                }}\n              >\n                <ApolloProvider client={client}>{children}</ApolloProvider>\n              </ErrorBoundary>\n            </Suspense>\n          </Wrapper>\n        );\n      },\n    }\n  );\n\n  return {\n    ...view,\n    renders,\n    rerenderAsync: (props?: Props | undefined) =>\n      actAsync(() => rerender(props)),\n  };\n}\n\nfunction useSimpleQueryCase() {\n  const query: TypedDocumentNode<SimpleQueryData, Record<string, never>> = gql`\n    query UserQuery {\n      greeting\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: 20,\n    },\n  ];\n\n  return { query, mocks };\n}\n\ndeclare namespace usePaginatedCase {\n  interface QueryData {\n    letters: {\n      letter: string;\n      position: number;\n    }[];\n  }\n\n  interface Variables {\n    limit?: number;\n    offset?: number;\n  }\n}\nfunction usePaginatedCase({ delay = 10 } = {}) {\n  const query: TypedDocumentNode<\n    usePaginatedCase.QueryData,\n    usePaginatedCase.Variables\n  > = gql`\n    query letters($limit: Int, $offset: Int) {\n      letters(limit: $limit) {\n        letter\n        position\n      }\n    }\n  `;\n\n  const data = \"ABCDEFG\".split(\"\").map((letter, index) => ({\n    __typename: \"Letter\",\n    letter,\n    position: index + 1,\n  }));\n\n  const link = new ApolloLink((operation) => {\n    const { offset = 0, limit = 2 } = operation.variables;\n    const letters = data.slice(offset, offset + limit);\n\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { letters } });\n        observer.complete();\n      }, delay);\n    });\n  });\n\n  return { query, link, data };\n}\n\ninterface ErrorCaseData {\n  currentUser: {\n    id: string;\n    name: string | null;\n  };\n}\n\nfunction useErrorCase<TData extends ErrorCaseData>({\n  data,\n  networkError,\n  graphQLErrors,\n}: {\n  data?: Unmasked<TData>;\n  networkError?: Error;\n  graphQLErrors?: GraphQLError[];\n} = {}) {\n  const query: TypedDocumentNode<TData, Record<string, never>> = gql`\n    query MyQuery {\n      currentUser {\n        id\n        name\n      }\n    }\n  `;\n\n  const mock: MockLink.MockedResponse<TData> = compact({\n    request: { query },\n    result: (data || graphQLErrors) && compact({ data, errors: graphQLErrors }),\n    error: networkError,\n  });\n\n  return { query, mocks: [mock] };\n}\n\ninterface VariablesCaseData {\n  character: {\n    id: string;\n    name: string;\n  };\n}\n\ninterface VariablesCaseVariables {\n  id: string;\n}\n\nfunction useVariablesQueryCase() {\n  const CHARACTERS = [\"Spider-Man\", \"Black Widow\", \"Iron Man\", \"Hulk\"];\n\n  const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n    gql`\n      query CharacterQuery($id: ID!) {\n        character(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n  const mocks = CHARACTERS.map((name, index) => ({\n    request: { query, variables: { id: String(index + 1) } },\n    result: {\n      data: {\n        character: { __typename: \"Character\", id: String(index + 1), name },\n      },\n    },\n    // React runs layout effects much later in React 18 which means tracked\n    // components aren't captured correctly, specifically when changing\n    // variables that cause the component to suspend.\n    delay: IS_REACT_19 ? 20 : 200,\n  }));\n\n  return { query, mocks };\n}\n\ntype CharacterFragment = {\n  __typename: \"Character\";\n  name: string;\n} & { \" $fragmentName\"?: \"CharacterFragment\" };\n\ninterface MaskedVariablesCaseData {\n  character: {\n    __typename: \"Character\";\n    id: string;\n  } & { \" $fragmentRefs\"?: { CharacterFragment: CharacterFragment } };\n}\n\ninterface UnmaskedVariablesCaseData {\n  character: {\n    __typename: \"Character\";\n    id: string;\n    name: string;\n  };\n}\n\nfunction useMaskedVariablesQueryCase() {\n  const CHARACTERS = [\"Spider-Man\", \"Black Widow\", \"Iron Man\", \"Hulk\"];\n\n  const document = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n        ...CharacterFragment\n      }\n    }\n\n    fragment CharacterFragment on Character {\n      name\n    }\n  `;\n\n  const query: TypedDocumentNode<\n    MaskedVariablesCaseData,\n    VariablesCaseVariables\n  > = document;\n\n  const unmaskedQuery: TypedDocumentNode<\n    MaskedVariablesCaseData,\n    VariablesCaseVariables\n  > = document;\n\n  const mocks = CHARACTERS.map((name, index) => ({\n    request: { query, variables: { id: String(index + 1) } },\n    result: {\n      data: {\n        character: { __typename: \"Character\", id: String(index + 1), name },\n      },\n    },\n  }));\n\n  return { query, unmaskedQuery, mocks };\n}\n\nfunction wait(delay: number) {\n  return new Promise((resolve) => setTimeout(resolve, delay));\n}\n\ndescribe(\"useSuspenseQuery\", () => {\n  it(\"validates the GraphQL query as a query\", () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const query = gql`\n      mutation ShouldThrow {\n        createException\n      }\n    `;\n\n    expect(() => {\n      renderHook(() => useSuspenseQuery(query), {\n        wrapper: ({ children }) => <MockedProvider>{children}</MockedProvider>,\n      });\n    }).toThrow(\n      new InvariantError(\n        \"Running a query requires a graphql query, but a mutation was used instead.\"\n      )\n    );\n  });\n\n  it(\"ensures a valid fetch policy is used\", () => {\n    const INVALID_FETCH_POLICIES = [\"cache-only\", \"standby\"];\n    using _consoleSpy = spyOnConsole(\"error\");\n    const { query } = useSimpleQueryCase();\n\n    INVALID_FETCH_POLICIES.forEach((fetchPolicy: any) => {\n      expect(() => {\n        renderHook(() => useSuspenseQuery(query, { fetchPolicy }), {\n          wrapper: ({ children }) => (\n            <MockedProvider>{children}</MockedProvider>\n          ),\n        });\n      }).toThrow(\n        new InvariantError(\n          `The fetch policy \\`${fetchPolicy}\\` is not supported with suspense.`\n        )\n      );\n    });\n  });\n\n  it(\"ensures a valid fetch policy is used when defined via global options\", () => {\n    const INVALID_FETCH_POLICIES: WatchQueryFetchPolicy[] = [\n      \"cache-only\",\n      \"standby\",\n    ];\n    using _consoleSpy = spyOnConsole(\"error\");\n    const { query } = useSimpleQueryCase();\n\n    INVALID_FETCH_POLICIES.forEach((fetchPolicy) => {\n      expect(() => {\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link: new MockLink([]),\n          defaultOptions: {\n            watchQuery: {\n              fetchPolicy,\n            },\n          },\n        });\n\n        renderHook(() => useSuspenseQuery(query), {\n          wrapper: ({ children }) => (\n            <ApolloProvider client={client}>{children}</ApolloProvider>\n          ),\n        });\n      }).toThrow(\n        new InvariantError(\n          `The fetch policy \\`${fetchPolicy}\\` is not supported with suspense.`\n        )\n      );\n    });\n  });\n\n  it(\"suspends a query and returns results\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const Component = () => {\n      const result = useSuspenseQuery(query);\n      replaceSnapshot(result);\n      return <div>{result.data.greeting}</div>;\n    };\n\n    const App = () => {\n      return (\n        <Suspense fallback={<div>loading</div>}>\n          <ErrorBoundary fallback={<div>Error</div>}>\n            <Component />\n          </ErrorBoundary>\n        </Suspense>\n      );\n    };\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender, replaceSnapshot, render } = createRenderStream<\n      useSuspenseQuery.Result<\n        SimpleQueryData,\n        OperationVariables,\n        \"complete\" | \"streaming\"\n      >\n    >({ snapshotDOM: true });\n    await render(<App />, {\n      wrapper: ({ children }) => (\n        <ApolloProvider client={client}>{children}</ApolloProvider>\n      ),\n    });\n\n    {\n      // ensure the hook suspends immediately\n      const { withinDOM, snapshot } = await takeRender();\n      expect(withinDOM().getByText(\"loading\")).toBeInTheDocument();\n      expect(snapshot).toBeUndefined();\n    }\n\n    {\n      const { withinDOM, snapshot } = await takeRender();\n      expect(withinDOM().queryByText(\"loading\")).not.toBeInTheDocument();\n      expect(withinDOM().getByText(\"Hello\")).toBeInTheDocument();\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"suspends a query with variables and returns results\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"returns the same results for the same variables\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { mocks, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    const previousResult = result.current;\n\n    await rerenderAsync({ id: \"1\" });\n\n    expect(result.current).toBe(previousResult);\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"ensures result is referentially stable\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { mocks, initialProps: { id: \"1\" } }\n    );\n\n    expect(screen.getByText(\"loading\")).toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    const previousResult = result.current;\n\n    await rerenderAsync({ id: \"1\" });\n\n    expect(result.current).toBe(previousResult);\n  });\n\n  it(\"ensures refetch, fetchMore, and subscribeToMore are referentially stable even after result data has changed\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    const { result } = await renderSuspenseHook(() => useSuspenseQuery(query), {\n      client,\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    const previousResult = result.current;\n\n    act(() => {\n      client.writeQuery({\n        query,\n        data: { greeting: \"Updated cache greeting\" },\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual({\n        greeting: \"Updated cache greeting\",\n      });\n    });\n\n    expect(result.current.fetchMore).toBe(previousResult.fetchMore);\n    expect(result.current.refetch).toBe(previousResult.refetch);\n    expect(result.current.subscribeToMore).toBe(previousResult.subscribeToMore);\n  });\n\n  it(\"tears down the query on unmount\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => of(mocks[0].result)),\n      cache: new InMemoryCache(),\n    });\n\n    const { result, unmount } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      { client }\n    );\n\n    await waitFor(() =>\n      expect(result.current.data).toEqual(mocks[0].result.data)\n    );\n\n    expect(client.getObservableQueries().size).toBe(1);\n    expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n    unmount();\n\n    // We need to wait a tick since the cleanup is run in a setTimeout to\n    // prevent strict mode bugs.\n    await wait(0);\n\n    expect(client.getObservableQueries().size).toBe(0);\n    expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n  });\n\n  it(\"tears down all queries when rendering with multiple variable sets\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    const { rerenderAsync, result, unmount } = await renderSuspenseHook(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { client, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() =>\n      expect(result.current.data).toEqual(mocks[0].result.data)\n    );\n\n    await rerenderAsync({ id: \"2\" });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[1].result.data);\n    });\n\n    unmount();\n\n    // We need to wait a tick since the cleanup is run in a setTimeout to\n    // prevent strict mode bugs.\n    await wait(0);\n\n    expect(client.getObservableQueries().size).toBe(0);\n\n    expect(client).not.toHaveSuspenseCacheEntryUsing(query, {\n      variables: { id: \"1\" },\n    });\n    expect(client).not.toHaveSuspenseCacheEntryUsing(query, {\n      variables: { id: \"2\" },\n    });\n  });\n\n  it(\"tears down all queries when multiple clients are used\", async () => {\n    const { query } = useVariablesQueryCase();\n\n    const client1 = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query, variables: { id: \"1\" } },\n          result: { data: { character: { id: \"1\", name: \"Client 1\" } } },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const client2 = new ApolloClient({\n      link: new MockLink([\n        {\n          request: { query, variables: { id: \"1\" } },\n          result: { data: { character: { id: \"1\", name: \"Client 2\" } } },\n        },\n      ]),\n      cache: new InMemoryCache(),\n    });\n\n    const { rerenderAsync, result, unmount } = await renderSuspenseHook(\n      ({ client }) =>\n        useSuspenseQuery(query, { client, variables: { id: \"1\" } }),\n      { initialProps: { client: client1 } }\n    );\n\n    await waitFor(() =>\n      expect(result.current.data).toEqual({\n        character: { id: \"1\", name: \"Client 1\" },\n      })\n    );\n\n    await rerenderAsync({ client: client2 });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual({\n        character: { id: \"1\", name: \"Client 2\" },\n      });\n    });\n\n    const variables = { id: \"1\" };\n\n    unmount();\n\n    // We need to wait a tick since the cleanup is run in a setTimeout to\n    // prevent strict mode bugs.\n    await wait(0);\n\n    expect(client1.getObservableQueries().size).toBe(0);\n    expect(client2.getObservableQueries().size).toBe(0);\n    expect(client1).not.toHaveSuspenseCacheEntryUsing(query, {\n      variables,\n    });\n    expect(client2).not.toHaveSuspenseCacheEntryUsing(query, {\n      variables,\n    });\n  });\n\n  it(\"tears down the query if the component never renders again after suspending\", async () => {\n    jest.useFakeTimers();\n    const { query } = useSimpleQueryCase();\n    const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const [showGreeting, setShowGreeting] = React.useState(true);\n\n      return (\n        <ApolloProvider client={client}>\n          <button onClick={() => setShowGreeting(false)}>Hide greeting</button>\n          {showGreeting && (\n            <Suspense fallback=\"Loading greeting...\">\n              <Greeting />\n            </Suspense>\n          )}\n        </ApolloProvider>\n      );\n    }\n\n    function Greeting() {\n      const { data } = useSuspenseQuery(query);\n\n      return <span>{data.greeting}</span>;\n    }\n\n    await renderAsync(<App />);\n\n    // Ensure <Greeting /> suspends immediately\n    expect(screen.getByText(\"Loading greeting...\")).toBeInTheDocument();\n\n    // Hide the greeting before it finishes loading data\n    await act(() => user.click(screen.getByText(\"Hide greeting\")));\n\n    expect(screen.queryByText(\"Loading greeting...\")).not.toBeInTheDocument();\n\n    await act(() => {\n      link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n      // Ensure simulateResult will deliver the result since its wrapped with\n      // setTimeout\n      jest.advanceTimersByTime(10);\n    });\n\n    expect(client.getObservableQueries().size).toBe(1);\n    expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n    jest.advanceTimersByTime(30_000);\n\n    expect(client.getObservableQueries().size).toBe(0);\n    expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n    jest.useRealTimers();\n  });\n\n  it(\"has configurable auto dispose timer if the component never renders again after suspending\", async () => {\n    jest.useFakeTimers();\n    const { query } = useSimpleQueryCase();\n    const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      defaultOptions: {\n        react: {\n          suspense: {\n            autoDisposeTimeoutMs: 5000,\n          },\n        },\n      },\n    });\n\n    function App() {\n      const [showGreeting, setShowGreeting] = React.useState(true);\n\n      return (\n        <ApolloProvider client={client}>\n          <button onClick={() => setShowGreeting(false)}>Hide greeting</button>\n          {showGreeting && (\n            <Suspense fallback=\"Loading greeting...\">\n              <Greeting />\n            </Suspense>\n          )}\n        </ApolloProvider>\n      );\n    }\n\n    function Greeting() {\n      const { data } = useSuspenseQuery(query);\n\n      return <span>{data.greeting}</span>;\n    }\n\n    await renderAsync(<App />);\n\n    // Ensure <Greeting /> suspends immediately\n    expect(screen.getByText(\"Loading greeting...\")).toBeInTheDocument();\n\n    // Hide the greeting before it finishes loading data\n    await act(() => user.click(screen.getByText(\"Hide greeting\")));\n\n    expect(screen.queryByText(\"Loading greeting...\")).not.toBeInTheDocument();\n\n    await act(() => {\n      link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n      // Ensure simulateResult will deliver the result since its wrapped with\n      // setTimeout\n      jest.advanceTimersByTime(10);\n    });\n\n    expect(client.getObservableQueries().size).toBe(1);\n    expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n    jest.advanceTimersByTime(5_000);\n\n    expect(client.getObservableQueries().size).toBe(0);\n    expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n    jest.useRealTimers();\n  });\n\n  it(\"cancels auto dispose if the component renders before timer finishes\", async () => {\n    jest.useFakeTimers();\n    const { query } = useSimpleQueryCase();\n    const link = new ApolloLink(() => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({ data: { greeting: \"Hello\" } });\n          observer.complete();\n        }, 10);\n      });\n    });\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback=\"Loading greeting...\">\n            <Greeting />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function Greeting() {\n      const { data } = useSuspenseQuery(query);\n\n      return <span>{data.greeting}</span>;\n    }\n\n    await renderAsync(<App />);\n\n    // Ensure <Greeting /> suspends immediately\n    expect(screen.getByText(\"Loading greeting...\")).toBeInTheDocument();\n\n    jest.advanceTimersByTime(10);\n\n    await waitFor(() => {\n      expect(screen.getByText(\"Hello\")).toBeInTheDocument();\n    });\n\n    jest.advanceTimersByTime(30_000);\n\n    expect(client.getObservableQueries().size).toBe(1);\n    expect(client).toHaveSuspenseCacheEntryUsing(query);\n\n    jest.useRealTimers();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11270\n  it(\"does not leave component suspended if query completes if request takes longer than auto dispose timeout\", async () => {\n    jest.useFakeTimers();\n    const { query } = useSimpleQueryCase();\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n      defaultOptions: {\n        react: {\n          suspense: {\n            autoDisposeTimeoutMs: 10,\n          },\n        },\n      },\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback=\"Loading greeting...\">\n            <Greeting />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function Greeting() {\n      const { data } = useSuspenseQuery(query);\n\n      return <span>{data.greeting}</span>;\n    }\n\n    await renderAsync(<App />);\n\n    // Ensure <Greeting /> suspends immediately\n    expect(screen.getByText(\"Loading greeting...\")).toBeInTheDocument();\n\n    jest.advanceTimersByTime(20);\n\n    link.simulateResult({ result: { data: { greeting: \"Hello\" } } }, true);\n\n    await waitFor(() => {\n      expect(screen.queryByText(\"Loading greeting...\")).not.toBeInTheDocument();\n    });\n\n    expect(screen.getByText(\"Hello\")).toBeInTheDocument();\n\n    jest.useRealTimers();\n  });\n\n  it(\"allows the client to be overridden\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const globalClient = new ApolloClient({\n      link: new ApolloLink(() => of({ data: { greeting: \"global hello\" } })),\n      cache: new InMemoryCache(),\n    });\n\n    const localClient = new ApolloClient({\n      link: new ApolloLink(() => of({ data: { greeting: \"local hello\" } })),\n      cache: new InMemoryCache(),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { client: localClient }),\n      { client: globalClient }\n    );\n\n    await waitFor(() =>\n      expect(result.current.data).toEqual({ greeting: \"local hello\" })\n    );\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"local hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"allows the client to be overridden in strict mode\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const globalClient = new ApolloClient({\n      link: new ApolloLink(() => of({ data: { greeting: \"global hello\" } })),\n      cache: new InMemoryCache(),\n    });\n\n    const localClient = new ApolloClient({\n      link: new ApolloLink(() => of({ data: { greeting: \"local hello\" } })),\n      cache: new InMemoryCache(),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { client: localClient }),\n      { strictMode: true, client: globalClient }\n    );\n\n    await waitFor(() =>\n      expect(result.current.data).toEqual({ greeting: \"local hello\" })\n    );\n\n    // React double invokes the render function in strict mode so we expect\n    // to render 2 frames after the initial suspense.\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"local hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"local hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"returns the client used in the result\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const client = new ApolloClient({\n      link: new ApolloLink(() => of({ data: { greeting: \"hello\" } })),\n      cache: new InMemoryCache(),\n    });\n\n    const { result } = await renderSuspenseHook(() => useSuspenseQuery(query), {\n      client,\n    });\n\n    // wait for query to finish suspending to avoid warnings\n    await waitFor(() => {\n      expect(result.current.data).toEqual({ greeting: \"hello\" });\n    });\n\n    expect(result.current.client).toBe(client);\n  });\n\n  it(\"suspends when changing variables\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"suspends and fetches data from new client when changing clients\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const client1 = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data: { greeting: \"Hello client 1\" } },\n        },\n      ]),\n    });\n\n    const client2 = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink([\n        {\n          request: { query },\n          result: { data: { greeting: \"Hello client 2\" } },\n        },\n      ]),\n    });\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ client }) => useSuspenseQuery(query, { client }),\n      { initialProps: { client: client1 } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello client 1\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ client: client2 });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello client 2\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello client 1\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello client 2\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"allows custom query key so two components that share same query and variables do not interfere with each other\", async () => {\n    interface Data {\n      todo: {\n        id: number;\n        name: string;\n        completed: boolean;\n      };\n    }\n\n    interface Variables {\n      id: number;\n    }\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query GetTodo($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: 1 } },\n        result: {\n          data: { todo: { id: 1, name: \"Take out trash\", completed: false } },\n        },\n        delay: 20,\n      },\n      // refetch\n      {\n        request: { query, variables: { id: 1 } },\n        result: {\n          data: { todo: { id: 1, name: \"Take out trash\", completed: true } },\n        },\n        delay: 20,\n      },\n    ];\n\n    const user = userEvent.setup();\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function Spinner({ name }: { name: string }) {\n      return <span>Loading {name}</span>;\n    }\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<Spinner name=\"first\" />}>\n            <Todo name=\"first\" />\n          </Suspense>\n          <Suspense fallback={<Spinner name=\"second\" />}>\n            <Todo name=\"second\" />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function Todo({ name }: { name: string }) {\n      const { data, refetch } = useSuspenseQuery(query, {\n        // intentionally use no-cache to allow us to verify each suspense\n        // component is independent of each other\n        fetchPolicy: \"no-cache\",\n        variables: { id: 1 },\n        queryKey: [name],\n      });\n\n      return (\n        <div>\n          <button onClick={() => refetch()}>Refetch {name}</button>\n          <span data-testid={[name, \"data\"].join(\".\")}>\n            {data.todo.name} {data.todo.completed && \"(completed)\"}\n          </span>\n        </div>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.getByText(\"Loading first\")).toBeInTheDocument();\n    expect(screen.getByText(\"Loading second\")).toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(screen.getByTestId(\"first.data\")).toHaveTextContent(\n        \"Take out trash\"\n      );\n    });\n\n    expect(screen.getByTestId(\"second.data\")).toHaveTextContent(\n      \"Take out trash\"\n    );\n\n    await act(() => user.click(screen.getByText(\"Refetch first\")));\n\n    // Ensure that refetching the first todo does not update the second todo\n    // as well\n    expect(screen.getByText(\"Loading first\")).toBeInTheDocument();\n    expect(screen.queryByText(\"Loading second\")).not.toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(screen.getByTestId(\"first.data\")).toHaveTextContent(\n        \"Take out trash (completed)\"\n      );\n    });\n\n    // Ensure that refetching the first todo did not affect the second\n    expect(screen.getByTestId(\"second.data\")).toHaveTextContent(\n      \"Take out trash\"\n    );\n  });\n\n  it(\"suspends and refetches data when changing query keys\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const mocks = [\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello first fetch\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello second fetch\" } },\n        delay: 20,\n      },\n    ];\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ queryKey }) =>\n        // intentionally use a fetch policy that will execute a network request\n        useSuspenseQuery(query, { queryKey, fetchPolicy: \"network-only\" }),\n      { mocks, initialProps: { queryKey: [\"first\"] } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ queryKey: [\"second\"] });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"suspends and refetches data when part of the query key changes\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const mocks = [\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello first fetch\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello second fetch\" } },\n        delay: 20,\n      },\n    ];\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ queryKey }) =>\n        // intentionally use a fetch policy that will execute a network request\n        useSuspenseQuery(query, { queryKey, fetchPolicy: \"network-only\" }),\n      { mocks, initialProps: { queryKey: [\"greeting\", 1] } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ queryKey: [\"greeting\", 2] });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"suspends and refetches when using plain string query keys\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const mocks = [\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello first fetch\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello second fetch\" } },\n        delay: 20,\n      },\n    ];\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ queryKey }) =>\n        // intentionally use a fetch policy that will execute a network request\n        useSuspenseQuery(query, { queryKey, fetchPolicy: \"network-only\" }),\n      { mocks, initialProps: { queryKey: \"first\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ queryKey: \"second\" });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"suspends and refetches when using numeric query keys\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const mocks = [\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello first fetch\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { greeting: \"Hello second fetch\" } },\n        delay: 20,\n      },\n    ];\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ queryKey }) =>\n        // intentionally use a fetch policy that will execute a network request\n        useSuspenseQuery(query, { queryKey, fetchPolicy: \"network-only\" }),\n      { mocks, initialProps: { queryKey: 1 } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ queryKey: 2 });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello first fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello second fetch\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"responds to cache updates after changing variables\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { wrapper: createClientWrapper(client), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    client.writeQuery({\n      query,\n      variables: { id: \"2\" },\n      data: { character: { id: \"2\", name: \"Cached hero\" } },\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { character: { id: \"2\", name: \"Cached hero\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"uses cached result and does not suspend when switching back to already used variables while using `cache-first` fetch policy\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"cache-first\",\n          variables: { id },\n        }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"1\" });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"uses cached result with network request and does not suspend when switching back to already used variables while using `cache-and-network` fetch policy\", async () => {\n    const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n      gql`\n        query CharacterQuery($id: ID!) {\n          character(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"2\",\n              name: \"Black Widow\",\n            },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetch)\",\n            },\n          },\n        },\n        delay: 200,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"cache-and-network\",\n          variables: { id },\n        }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"1\" });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"refetches and suspends when switching back to already used variables while using `network-only` fetch policy\", async () => {\n    const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n      gql`\n        query CharacterQuery($id: ID!) {\n          character(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"2\",\n              name: \"Black Widow\",\n            },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetch)\",\n            },\n          },\n        },\n        delay: 200,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"network-only\",\n          variables: { id },\n        }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"1\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"refetches and suspends when switching back to already used variables while using `no-cache` fetch policy\", async () => {\n    const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n      gql`\n        query CharacterQuery($id: ID!) {\n          character(id: $id) {\n            id\n            name\n          }\n        }\n      `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"2\",\n              name: \"Black Widow\",\n            },\n          },\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Spider-Man (refetch)\",\n            },\n          },\n        },\n        delay: 200,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"no-cache\",\n          variables: { id },\n        }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"1\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"responds to cache updates after changing back to already fetched variables\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) => useSuspenseQuery(query, { variables: { id } }),\n      { wrapper: createClientWrapper(client), initialProps: { id: \"1\" } }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"1\" });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    client.writeQuery({\n      query,\n      variables: { id: \"1\" },\n      data: { character: { id: \"1\", name: \"Cached hero\" } },\n    });\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { character: { id: \"1\", name: \"Cached hero\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it('does not suspend when data is in the cache and using a \"cache-first\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n      { cache, mocks }\n    );\n\n    expect(result.current).toStrictEqualTyped({\n      data: { greeting: \"hello from cache\" },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    expect(renders.count).toBe(1 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(0);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"hello from cache\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('does not initiate a network request when data is in the cache and using a \"cache-first\" fetch policy', async () => {\n    let fetchCount = 0;\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const link = new ApolloLink(() => {\n      return new Observable((observer) => {\n        fetchCount++;\n\n        const mock = mocks[0];\n\n        observer.next(mock.result);\n        observer.complete();\n      });\n    });\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n      { cache, link, initialProps: { id: \"1\" } }\n    );\n\n    expect(fetchCount).toBe(0);\n  });\n\n  it('suspends when partial data is in the cache and using a \"cache-first\" fetch policy', async () => {\n    const fullQuery = gql`\n      query {\n        character {\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(fullQuery, { fetchPolicy: \"cache-first\" }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('does not suspend when partial data is in the cache and using a \"cache-first\" fetch policy with returnPartialData', async () => {\n    const fullQuery = gql`\n      query {\n        character {\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"cache-first\",\n          returnPartialData: true,\n        }),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(0);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { character: { id: \"1\" } },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('suspends and does not use partial data when changing variables and using a \"cache-first\" fetch policy with returnPartialData', async () => {\n    const { query: fullQuery, mocks } = useVariablesQueryCase();\n\n    const partialQuery = gql`\n      query ($id: ID!) {\n        character(id: $id) {\n          id\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n      variables: { id: \"1\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"cache-first\",\n          returnPartialData: true,\n          variables: { id },\n        }),\n      {\n        wrapper: createMockWrapper({ cache, mocks }),\n        initialProps: { id: \"1\" },\n      }\n    );\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { character: { id: \"1\" } },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it('suspends when data is in the cache and using a \"network-only\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"network-only\" }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('suspends when partial data is in the cache and using a \"network-only\" fetch policy with returnPartialData', async () => {\n    const fullQuery = gql`\n      query {\n        character {\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"network-only\",\n          returnPartialData: true,\n        }),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('suspends and does not overwrite cache when data is in the cache and using a \"no-cache\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"no-cache\" }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    const cachedData = cache.readQuery({ query });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n    expect(cachedData).toEqual({ greeting: \"hello from cache\" });\n  });\n\n  it('maintains results when rerendering a query using a \"no-cache\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"no-cache\" }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n\n    await rerenderAsync();\n\n    expect(result.current).toStrictEqualTyped({\n      ...mocks[0].result,\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('suspends when partial data is in the cache and using a \"no-cache\" fetch policy with returnPartialData', async () => {\n    using _consoleSpy = spyOnConsole(\"warn\");\n\n    const fullQuery = gql`\n      query {\n        character {\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n        }),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('warns when using returnPartialData with a \"no-cache\" fetch policy', async () => {\n    using consoleSpy = spyOnConsole(\"warn\");\n\n    const { query, mocks } = useSimpleQueryCase();\n\n    await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n        }),\n      { mocks }\n    );\n\n    expect(consoleSpy.warn).toHaveBeenCalledTimes(IS_REACT_19 ? 2 : 1);\n    expect(consoleSpy.warn).toHaveBeenCalledWith(\n      \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n    );\n  });\n\n  it('does not suspend when data is in the cache and using a \"cache-and-network\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"cache-and-network\" }),\n      { cache, mocks }\n    );\n\n    expect(result.current).toStrictEqualTyped({\n      data: { greeting: \"hello from cache\" },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(0);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"hello from cache\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('does not suspend when partial data is in the cache and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n    const fullQuery = gql`\n      query {\n        character {\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: { data: { character: { id: \"1\", name: \"Doctor Strange\" } } },\n        delay: 20,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"cache-and-network\",\n          returnPartialData: true,\n        }),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: { character: { id: \"1\" } },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(0);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { character: { id: \"1\" } },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('suspends and does not use partial data when changing variables and using a \"cache-and-network\" fetch policy with returnPartialData', async () => {\n    const { query: fullQuery, mocks } = useVariablesQueryCase();\n\n    const partialQuery = gql`\n      query ($id: ID!) {\n        character(id: $id) {\n          id\n        }\n      }\n    `;\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { id: \"1\" } },\n      variables: { id: \"1\" },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(fullQuery, {\n          fetchPolicy: \"cache-and-network\",\n          returnPartialData: true,\n          variables: { id },\n        }),\n      {\n        wrapper: createMockWrapper({ cache, mocks }),\n        initialProps: { id: \"1\" },\n      }\n    );\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { character: { id: \"1\" } },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"cache-and-network\",\n  ])(\n    'writes to the cache when using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useVariablesQueryCase();\n\n      const cache = new InMemoryCache();\n\n      const { result } = await renderSuspenseHook(\n        ({ id }) => useSuspenseQuery(query, { fetchPolicy, variables: { id } }),\n        { cache, mocks, initialProps: { id: \"1\" } }\n      );\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[0].result.data);\n      });\n\n      const cachedData = cache.readQuery({ query, variables: { id: \"1\" } });\n\n      expect(cachedData).toEqual(mocks[0].result.data);\n    }\n  );\n\n  it('does not write to the cache when using a \"no-cache\" fetch policy', async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result } = await renderSuspenseHook(\n      ({ id }) =>\n        useSuspenseQuery(query, { fetchPolicy: \"no-cache\", variables: { id } }),\n      { cache, mocks, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[0].result.data);\n    });\n\n    const cachedData = cache.readQuery({ query, variables: { id: \"1\" } });\n\n    expect(cachedData).toBeNull();\n  });\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"cache-and-network\",\n  ])(\n    'responds to cache updates when using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useSimpleQueryCase();\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const { result, renders } = await renderSuspenseHook(\n        () => useSuspenseQuery(query, { fetchPolicy }),\n        { client }\n      );\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[0].result.data);\n      });\n\n      act(() => {\n        client.writeQuery({\n          query,\n          data: { greeting: \"Updated hello\" },\n        });\n      });\n\n      await waitFor(() => {\n        expect(result.current).toStrictEqualTyped({\n          data: { greeting: \"Updated hello\" },\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      });\n      expect(renders.suspenseCount).toBe(1);\n      expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n      expect(renders.frames).toStrictEqualTyped([\n        {\n          ...mocks[0].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        },\n        {\n          data: { greeting: \"Updated hello\" },\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        },\n      ]);\n    }\n  );\n\n  it('does not respond to cache updates when using a \"no-cache\" fetch policy', async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"no-cache\" }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[0].result.data);\n    });\n\n    client.writeQuery({\n      query,\n      data: { greeting: \"Updated hello\" },\n    });\n\n    // Wait for a while to ensure no updates happen asynchronously\n    await wait(100);\n\n    expect(result.current).toStrictEqualTyped({\n      ...mocks[0].result,\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"no-cache\",\n    \"cache-and-network\",\n  ])(\n    're-suspends the component when changing variables and using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useVariablesQueryCase();\n\n      using _disabledAct = disableActEnvironment();\n      const { takeRender, rerender } = await renderUseSuspenseQuery(\n        ({ id }) => useSuspenseQuery(query, { fetchPolicy, variables: { id } }),\n        { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n      );\n\n      {\n        const { renderedComponents } = await takeRender();\n\n        expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n      }\n\n      {\n        const { snapshot, renderedComponents } = await takeRender();\n\n        expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n        expect(snapshot).toStrictEqualTyped({\n          ...mocks[0].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      }\n\n      await rerender({ id: \"2\" });\n\n      {\n        const { renderedComponents } = await takeRender();\n\n        expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n      }\n\n      {\n        const { snapshot, renderedComponents } = await takeRender();\n\n        expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n        expect(snapshot).toStrictEqualTyped({\n          ...mocks[1].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      }\n\n      await expect(takeRender).not.toRerender();\n    }\n  );\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"no-cache\",\n    \"cache-and-network\",\n  ])(\n    're-suspends the component when changing queries and using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const query1: TypedDocumentNode<{ hello: string }> = gql`\n        query Query1 {\n          hello\n        }\n      `;\n\n      const query2: TypedDocumentNode<{ world: string }> = gql`\n        query Query2 {\n          world\n        }\n      `;\n\n      const mocks = [\n        {\n          request: { query: query1 },\n          result: { data: { hello: \"query1\" } },\n          delay: 20,\n        },\n        {\n          request: { query: query2 },\n          result: { data: { world: \"query2\" } },\n          delay: 20,\n        },\n      ];\n\n      const { result, rerenderAsync, renders } = await renderSuspenseHook(\n        ({ query }) => useSuspenseQuery(query, { fetchPolicy }),\n        { mocks, initialProps: { query: query1 as DocumentNode } }\n      );\n\n      expect(renders.suspenseCount).toBe(1);\n      await waitFor(() => {\n        expect(result.current).toStrictEqualTyped({\n          ...mocks[0].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      });\n\n      await rerenderAsync({ query: query2 });\n\n      await waitFor(() => {\n        expect(result.current).toStrictEqualTyped({\n          ...mocks[1].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      });\n\n      // Renders:\n      // 1. Initiate fetch and suspend\n      // 2. Unsuspend and return results from initial fetch\n      // 3. Change queries and suspend\n      // 5. Unsuspend and return results from refetch\n      expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n      expect(renders.suspenseCount).toBe(2);\n      expect(renders.frames).toStrictEqualTyped([\n        {\n          ...mocks[0].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        },\n        {\n          ...mocks[1].result,\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        },\n      ]);\n    }\n  );\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"no-cache\",\n    \"cache-and-network\",\n  ])(\n    'ensures data is fetched the correct amount of times when changing variables and using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useVariablesQueryCase();\n\n      let fetchCount = 0;\n\n      const link = new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          fetchCount++;\n\n          const mock = mocks.find(({ request }) =>\n            equal(request.variables, operation.variables)\n          );\n\n          if (!mock) {\n            throw new Error(\"Could not find mock for operation\");\n          }\n\n          observer.next(mock.result);\n          observer.complete();\n        });\n      });\n\n      const { result, rerenderAsync } = await renderSuspenseHook(\n        ({ id }) => useSuspenseQuery(query, { fetchPolicy, variables: { id } }),\n        { link, initialProps: { id: \"1\" } }\n      );\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[0].result.data);\n      });\n\n      expect(fetchCount).toBe(1);\n\n      await rerenderAsync({ id: \"2\" });\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[1].result.data);\n      });\n\n      expect(fetchCount).toBe(2);\n    }\n  );\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"no-cache\",\n    \"cache-and-network\",\n  ])(\n    'ensures data is fetched and suspended the correct amount of times in strict mode while using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useVariablesQueryCase();\n\n      let fetchCount = 0;\n\n      const link = new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          fetchCount++;\n\n          const mock = mocks.find(({ request }) =>\n            equal(request.variables, operation.variables)\n          );\n\n          if (!mock) {\n            throw new Error(\"Could not find mock for operation\");\n          }\n\n          observer.next(mock.result);\n          observer.complete();\n        });\n      });\n\n      const { result, renders } = await renderSuspenseHook(\n        ({ id }) => useSuspenseQuery(query, { fetchPolicy, variables: { id } }),\n        { strictMode: true, link, initialProps: { id: \"1\" } }\n      );\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[0].result.data);\n      });\n\n      expect(fetchCount).toBe(1);\n\n      // React double invokes the render function in strict mode so the suspense\n      // fallback is rendered twice before the promise is resolved\n      // https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects\n      expect(renders.suspenseCount).toBe(2);\n    }\n  );\n\n  it.each<useSuspenseQuery.FetchPolicy>([\n    \"cache-first\",\n    \"network-only\",\n    \"cache-and-network\",\n  ])(\n    'responds to cache updates in strict mode while using a \"%s\" fetch policy',\n    async (fetchPolicy) => {\n      const { query, mocks } = useSimpleQueryCase();\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: new MockLink(mocks),\n      });\n\n      const { result } = await renderSuspenseHook(\n        () => useSuspenseQuery(query, { fetchPolicy }),\n        { strictMode: true, client }\n      );\n\n      await waitFor(() => {\n        expect(result.current.data).toEqual(mocks[0].result.data);\n      });\n\n      act(() => {\n        client.writeQuery({\n          query,\n          data: { greeting: \"Updated hello\" },\n        });\n      });\n\n      await waitFor(() => {\n        expect(result.current).toStrictEqualTyped({\n          data: { greeting: \"Updated hello\" },\n          dataState: \"complete\",\n          networkStatus: NetworkStatus.ready,\n          error: undefined,\n        });\n      });\n    }\n  );\n\n  // https://github.com/apollographql/apollo-client/issues/10478\n  it(\"responds to cache updates when data is already in the cache while using a cache-first fetch policy\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: { greeting: \"Hello from cache\" },\n    });\n\n    const { result } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { fetchPolicy: \"cache-first\" }),\n      { client }\n    );\n\n    expect(result.current.data).toEqual({ greeting: \"Hello from cache\" });\n\n    // Allow time for the subscription in the hook to set itself up since it is\n    // wrapped in a setTimeout (to handle Strict mode bugs). Without this\n    // `wait`, `subscribe` isn't called until after our test updates the cache\n    // via `writeQuery`, which then emits the most recent result, which is the\n    // updated value.\n    await wait(0);\n\n    act(() => {\n      client.writeQuery({\n        query,\n        data: { greeting: \"Updated hello\" },\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Updated hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n  });\n\n  it(\"uses the default fetch policy from the client when none provided in options\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const client = new ApolloClient({\n      cache,\n      link: new MockLink(mocks),\n      defaultOptions: {\n        watchQuery: {\n          fetchPolicy: \"network-only\",\n        },\n      },\n    });\n\n    client.writeQuery({ query, data: { greeting: \"hello from cache\" } });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[0].result.data);\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"uses default variables from the client when none provided in options\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n      defaultOptions: {\n        watchQuery: {\n          variables: { id: \"2\" },\n        },\n      },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      // @ts-expect-error we do not recommend this pattern\n      () => useSuspenseQuery(query),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"uses default variables from the client when none provided in options in strict mode\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n      defaultOptions: {\n        watchQuery: {\n          variables: { id: \"2\" },\n        },\n      },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      // @ts-expect-error we do not recommend this pattern\n      () => useSuspenseQuery(query),\n      { strictMode: true, client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    // React double invokes the render function in strict mode so we expect 2\n    // frames to be rendered here.\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"merges global default variables with local variables\", async () => {\n    const query = gql`\n      query MergedVariablesQuery {\n        vars\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        return of({ data: { vars: operation.variables } }).pipe(delay(200));\n      }),\n      defaultOptions: {\n        watchQuery: {\n          variables: { source: \"global\", globalOnlyVar: true },\n        },\n      },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender, rerender } = await renderUseSuspenseQuery(\n      ({ source }) =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"network-only\",\n          variables: { source, localOnlyVar: true },\n        }),\n      {\n        wrapper: createClientWrapper(client),\n        initialProps: { source: \"local\" },\n      }\n    );\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          vars: { source: \"local\", globalOnlyVar: true, localOnlyVar: true },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender({ source: \"rerender\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: {\n          vars: { source: \"rerender\", globalOnlyVar: true, localOnlyVar: true },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"can unset a globally defined variable\", async () => {\n    const query: TypedDocumentNode<{ vars: Record<string, any> }> = gql`\n      query MergedVariablesQuery {\n        vars\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          observer.next({ data: { vars: operation.variables } });\n          observer.complete();\n        });\n      }),\n      defaultOptions: {\n        watchQuery: {\n          variables: { source: \"global\", globalOnlyVar: true },\n        },\n      },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          variables: { source: \"local\", globalOnlyVar: undefined },\n        }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { vars: { source: \"local\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    // Check to make sure the property itself is not defined, not just set to\n    // undefined. Unfortunately this is not caught by toMatchObject as\n    // toMatchObject only checks a if the subset of options are equal, not if\n    // they have strictly the same keys and values.\n    expect(result.current.data.vars).not.toHaveProperty(\"globalOnlyVar\");\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { vars: { source: \"local\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"passes context to the link\", async () => {\n    const query = gql`\n      query ContextQuery {\n        context\n      }\n    `;\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new ApolloLink((operation) => {\n        return new Observable((observer) => {\n          const { valueA, valueB } = operation.getContext();\n\n          observer.next({ data: { context: { valueA, valueB } } });\n          observer.complete();\n        });\n      }),\n    });\n\n    const { result } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          context: { valueA: \"A\", valueB: \"B\" },\n        }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { context: { valueA: \"A\", valueB: \"B\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n  });\n\n  it(\"throws network errors by default\", async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const { query, mocks } = useErrorCase({\n      networkError: new Error(\"Could not fetch\"),\n    });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      {\n        mocks,\n      }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    expect(renders.errors.length).toBe(1);\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toEqual([]);\n\n    const [error] = renders.errors;\n\n    expect(error).toBeInstanceOf(Error);\n    expect(error).toEqual(new Error(\"Could not fetch\"));\n  });\n\n  it(\"throws graphql errors by default\", async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const { query, mocks } = useErrorCase({\n      graphQLErrors: [new GraphQLError(\"`id` should not be null\")],\n    });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      {\n        mocks,\n      }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    expect(renders.errors.length).toBe(1);\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toEqual([]);\n\n    const [error] = renders.errors;\n\n    expect(error).toBeInstanceOf(CombinedGraphQLErrors);\n    expect(error).toEqual(\n      new CombinedGraphQLErrors({\n        errors: [{ message: \"`id` should not be null\" }],\n      })\n    );\n  });\n\n  it(\"tears down subscription when throwing an error\", async () => {\n    jest.useFakeTimers();\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const { query, mocks } = useErrorCase({\n      networkError: new Error(\"Could not fetch\"),\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      {\n        client,\n      }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    // The query was never retained since the error was thrown before the\n    // useEffect could run. We need to wait for the auto dispose timeout to kick\n    // in before we check whether the observable was cleaned up\n    jest.advanceTimersByTime(30_000);\n\n    expect(client.getObservableQueries().size).toBe(0);\n\n    jest.useRealTimers();\n  });\n\n  it(\"tears down subscription when throwing an error on refetch\", async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch().catch(() => {});\n    });\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n    await waitFor(() => expect(client.getObservableQueries().size).toBe(0));\n  });\n\n  it('throws network errors when errorPolicy is set to \"none\"', async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const { query, mocks } = useErrorCase({\n      networkError: new Error(\"Could not fetch\"),\n    });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"none\" }),\n      { mocks }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    expect(renders.errors.length).toBe(1);\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toEqual([]);\n\n    const [error] = renders.errors;\n\n    expect(error).toBeInstanceOf(Error);\n    expect(error).toEqual(new Error(\"Could not fetch\"));\n  });\n\n  it('throws graphql errors when errorPolicy is set to \"none\"', async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const { query, mocks } = useErrorCase({\n      graphQLErrors: [new GraphQLError(\"`id` should not be null\")],\n    });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"none\" }),\n      { mocks }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    expect(renders.errors.length).toBe(1);\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toEqual([]);\n\n    const [error] = renders.errors;\n\n    expect(error).toBeInstanceOf(CombinedGraphQLErrors);\n    expect(error).toEqual(\n      new CombinedGraphQLErrors({\n        errors: [{ message: \"`id` should not be null\" }],\n      })\n    );\n  });\n\n  it('handles multiple graphql errors when errorPolicy is set to \"none\"', async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const graphQLErrors = [\n      new GraphQLError(\"Fool me once\"),\n      new GraphQLError(\"Fool me twice\"),\n    ];\n\n    const { query, mocks } = useErrorCase({ graphQLErrors });\n\n    const { renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"none\" }),\n      { mocks }\n    );\n\n    await waitFor(() => expect(renders.errorCount).toBe(1));\n\n    expect(renders.errors.length).toBe(1);\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toEqual([]);\n\n    const [error] = renders.errors;\n\n    expect(error).toBeInstanceOf(CombinedGraphQLErrors);\n    expect(error).toEqual(new CombinedGraphQLErrors({ errors: graphQLErrors }));\n  });\n\n  it('does not throw or return network errors when errorPolicy is set to \"ignore\"', async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n    const networkError = new Error(\"Could not fetch\");\n\n    const { query, mocks } = useErrorCase({ networkError });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('does not throw or return graphql errors when errorPolicy is set to \"ignore\"', async () => {\n    const { query, mocks } = useErrorCase({\n      graphQLErrors: [new GraphQLError(\"`id` should not be null\")],\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('returns partial data results and discards GraphQL errors when errorPolicy is set to \"ignore\"', async () => {\n    const { query, mocks } = useErrorCase({\n      data: { currentUser: { id: \"1\", name: null } },\n      graphQLErrors: [new GraphQLError(\"`name` could not be found\")],\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { currentUser: { id: \"1\", name: null } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { currentUser: { id: \"1\", name: null } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('discards multiple graphql errors when errorPolicy is set to \"ignore\"', async () => {\n    const { query, mocks } = useErrorCase({\n      graphQLErrors: [\n        new GraphQLError(\"Fool me once\"),\n        new GraphQLError(\"Fool me twice\"),\n      ],\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('responds to cache updates and clears errors after an error returns when errorPolicy is set to \"ignore\"', async () => {\n    const graphQLError = new GraphQLError(\"`id` should not be null\");\n\n    const { query, mocks } = useErrorCase({ graphQLErrors: [graphQLError] });\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    act(() => {\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            id: \"1\",\n            name: \"Cache User\",\n          },\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            id: \"1\",\n            name: \"Cache User\",\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { currentUser: { id: \"1\", name: \"Cache User\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('does not throw and returns network errors when errorPolicy is set to \"all\"', async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const networkError = new Error(\"Could not fetch\");\n\n    const { query, mocks } = useErrorCase({ networkError });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: networkError,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: networkError,\n      },\n    ]);\n\n    const { error } = result.current;\n\n    expect(error).toBeInstanceOf(Error);\n    expect(error).toEqual(networkError);\n  });\n\n  it('does not throw and returns graphql errors when errorPolicy is set to \"all\"', async () => {\n    const graphQLError = new GraphQLError(\"`id` should not be null\");\n\n    const { query, mocks } = useErrorCase({ graphQLErrors: [graphQLError] });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [graphQLError] }),\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [graphQLError] }),\n      },\n    ]);\n\n    const { error } = result.current;\n\n    expect(error).toBeInstanceOf(CombinedGraphQLErrors);\n    expect(error).toEqual(\n      new CombinedGraphQLErrors({ errors: [graphQLError] })\n    );\n  });\n\n  it('responds to cache updates and clears errors after an error returns when errorPolicy is set to \"all\"', async () => {\n    const graphQLError = new GraphQLError(\"`id` should not be null\");\n\n    const { query, mocks } = useErrorCase({ graphQLErrors: [graphQLError] });\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { client }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [graphQLError] }),\n      });\n    });\n\n    act(() => {\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            id: \"1\",\n            name: \"Cache User\",\n          },\n        },\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: {\n          currentUser: {\n            id: \"1\",\n            name: \"Cache User\",\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [graphQLError] }),\n      },\n      {\n        data: { currentUser: { id: \"1\", name: \"Cache User\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('handles multiple graphql errors when errorPolicy is set to \"all\"', async () => {\n    const graphQLErrors = [\n      new GraphQLError(\"Fool me once\"),\n      new GraphQLError(\"Fool me twice\"),\n    ];\n\n    const { query, mocks } = useErrorCase({ graphQLErrors });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { mocks }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({ errors: graphQLErrors });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      },\n    ]);\n\n    const { error } = result.current;\n\n    expect(error).toBeInstanceOf(CombinedGraphQLErrors);\n    expect(error).toEqual(expectedError);\n  });\n\n  it('returns partial data and keeps errors when errorPolicy is set to \"all\"', async () => {\n    const graphQLError = new GraphQLError(\"`name` could not be found\");\n\n    const { query, mocks } = useErrorCase({\n      data: { currentUser: { id: \"1\", name: null } },\n      graphQLErrors: [graphQLError],\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { mocks }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({\n      data: { currentUser: { id: \"1\", name: null } },\n      errors: [graphQLError],\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { currentUser: { id: \"1\", name: null } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { currentUser: { id: \"1\", name: null } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      },\n    ]);\n  });\n\n  it('persists errors between rerenders when errorPolicy is set to \"all\"', async () => {\n    const graphQLError = new GraphQLError(\"`name` could not be found\");\n\n    const { query, mocks } = useErrorCase({\n      graphQLErrors: [graphQLError],\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"all\" }),\n      { mocks }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({ errors: [graphQLError] });\n\n    await waitFor(() => {\n      expect(result.current.error).toEqual(expectedError);\n    });\n\n    await rerenderAsync();\n\n    expect(result.current.error).toEqual(expectedError);\n  });\n\n  it('clears errors when changing variables and errorPolicy is set to \"all\"', async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const graphQLErrors: GraphQLFormattedError[] = [\n      { message: \"Could not fetch user 1\" },\n    ];\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: graphQLErrors,\n        },\n        delay: 200,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: { user: { id: \"2\", name: \"Captain Marvel\" } },\n        },\n        delay: 200,\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender, takeRender } = await renderUseSuspenseQuery(\n      ({ id }) =>\n        useSuspenseQuery(query, { errorPolicy: \"all\", variables: { id } }),\n      { wrapper: createMockWrapper({ mocks }), initialProps: { id: \"1\" } }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({ errors: graphQLErrors });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    }\n\n    await rerender({ id: \"2\" });\n\n    {\n      const { renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"<Suspense />\"]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await takeRender();\n\n      expect(renderedComponents).toStrictEqual([\"useSuspenseQuery\"]);\n      expect(snapshot).toStrictEqualTyped({\n        data: mocks[1].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(takeRender).not.toRerender();\n  });\n\n  it(\"re-suspends when calling `refetch`\", async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel (updated)\" } },\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { mocks, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(2 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n\n    // TODO check: using actAsync instead of unawaited act changes observed render counts here.\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"properly resolves `refetch` when returning a result that is deeply equal to data in the cache\", async () => {\n    type Variables = {\n      id: string;\n    };\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id=\"1\" />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({ id }: { id: string }) {\n      const { data, refetch } = useSuspenseQuery(query, {\n        variables: { id },\n      });\n\n      const { todo } = data;\n\n      return (\n        <div>\n          <button onClick={() => refetch()}>Refetch</button>\n          <div data-testid=\"todo\">\n            {todo.name}\n            {todo.completed && \" (completed)\"}\n          </div>\n        </div>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(await screen.findByText(\"Loading\")).toBeInTheDocument();\n\n    const todo = await screen.findByTestId(\"todo\");\n\n    expect(todo).toHaveTextContent(\"Clean room\");\n\n    await act(() => user.click(screen.getByText(\"Refetch\")));\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    await waitFor(() => {\n      // Suspense will hide the component until the suspense boundary has\n      // finished loading so it is still in the DOM.\n      expect(todo).toBeVisible();\n    });\n\n    expect(todo).toHaveTextContent(\"Clean room\");\n  });\n\n  it(\"re-suspends when calling `refetch` with new variables\", async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: { user: { id: \"2\", name: \"Captain America\" } },\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch({ id: \"2\" });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n    expect(renders.count).toBe(4 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(2);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"re-suspends multiple times when calling `refetch` multiple times\", async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel (updated)\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel (updated again)\" } },\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { mocks, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(6 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(3);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"throws errors when errors are returned after calling `refetch`\", async () => {\n    using _consoleSpy = spyOnConsole(\"error\");\n\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch().catch(() => {});\n    });\n\n    await waitFor(() => {\n      expect(renders.errorCount).toBe(1);\n    });\n\n    expect(renders.errors).toEqual([\n      new CombinedGraphQLErrors({\n        errors: [{ message: \"Something went wrong\" }],\n      }),\n    ]);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('ignores errors returned after calling `refetch` when errorPolicy is set to \"ignore\"', async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        }),\n      { mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      await result.current.refetch();\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('returns errors after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          errorPolicy: \"all\",\n          variables: { id: \"1\" },\n        }),\n      { mocks }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({\n      errors: [{ message: \"Something went wrong\" }],\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: mocks[0].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      },\n    ]);\n  });\n\n  it('handles partial data results after calling `refetch` when errorPolicy is set to \"all\"', async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: null } },\n          errors: [new GraphQLError(\"Something went wrong\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, renders } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          errorPolicy: \"all\",\n          variables: { id: \"1\" },\n        }),\n      { mocks }\n    );\n\n    const expectedError = new CombinedGraphQLErrors({\n      data: { user: { id: \"1\", name: null } },\n      errors: [{ message: \"Something went wrong\" }],\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: mocks[1].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(renders.errors).toEqual([]);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: mocks[1].result.data,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      },\n    ]);\n  });\n\n  it(\"re-suspends when calling `fetchMore` with different variables\", async () => {\n    const { data, query, link } = usePaginatedCase({ delay: 150 });\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const renderStream = createRenderStream<\n      useSuspenseQuery.Result<\n        usePaginatedCase.QueryData,\n        usePaginatedCase.Variables\n      >\n    >({ skipNonTrackingRenders: true });\n\n    function Component() {\n      useTrackRenders();\n      renderStream.replaceSnapshot(\n        useSuspenseQuery(query, { variables: { limit: 2 } })\n      );\n      return <div />;\n    }\n    function SuspenseFallback() {\n      useTrackRenders();\n      return <p>Loading</p>;\n    }\n    function ErrorFallback() {\n      useTrackRenders();\n      return <p>Error</p>;\n    }\n    function App() {\n      useTrackRenders();\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary fallback={<ErrorFallback />}>\n            <Component />\n          </ErrorBoundary>\n        </Suspense>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(<App />, {\n      wrapper: createClientWrapper(client),\n    });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([Component]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { letters: data.slice(0, 2) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    renderStream\n      .getCurrentRender()\n      .snapshot.fetchMore({ variables: { offset: 2 } });\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([Component]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { letters: data.slice(2, 4) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"properly resolves `fetchMore` when returning a result that is deeply equal to data in the cache\", async () => {\n    const { query, link } = usePaginatedCase();\n\n    const user = userEvent.setup();\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Letters offset={0} />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Letters({ offset }: { offset: number }) {\n      const { data, fetchMore } = useSuspenseQuery(query, {\n        variables: { offset },\n      });\n\n      return (\n        <div>\n          <button onClick={() => fetchMore({ variables: { offset } })}>\n            Fetch more\n          </button>\n          <div data-testid=\"letters\">\n            {data.letters.map(({ letter }) => letter).join(\"\")}\n          </div>\n        </div>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(await screen.findByText(\"Loading\")).toBeInTheDocument();\n\n    const letters = await screen.findByTestId(\"letters\");\n\n    expect(letters).toHaveTextContent(\"AB\");\n\n    await act(() => user.click(screen.getByText(\"Fetch more\")));\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    await waitFor(() => {\n      // Suspense will hide the component until the suspense boundary has\n      // finished loading so it is still in the DOM.\n      expect(letters).toBeVisible();\n    });\n\n    expect(letters).toHaveTextContent(\"AB\");\n  });\n\n  it(\"suspends when refetching after returning cached data for the initial fetch\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: { greeting: \"hello from cache\" },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query),\n      { cache, mocks }\n    );\n\n    expect(result.current).toStrictEqualTyped({\n      data: { greeting: \"hello from cache\" },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"hello from cache\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"properly uses `updateQuery` when calling `fetchMore`\", async () => {\n    const { data, query, link } = usePaginatedCase();\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { limit: 2 } }),\n      { link }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { letters: data.slice(0, 2) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(() => {\n      void result.current.fetchMore({\n        variables: { offset: 2 },\n        updateQuery: (prev, { fetchMoreResult }) => ({\n          letters: prev.letters.concat(fetchMoreResult.letters),\n        }),\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { letters: data.slice(0, 4) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { letters: data.slice(0, 2) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { letters: data.slice(0, 4) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"properly uses cache field policies when calling `fetchMore` without `updateQuery`\", async () => {\n    const { data, query, link } = usePaginatedCase();\n\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            letters: concatPagination(),\n          },\n        },\n      },\n    });\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { limit: 2 } }),\n      { cache, link }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { letters: data.slice(0, 2) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(() => {\n      void result.current.fetchMore({ variables: { offset: 2 } });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { letters: data.slice(0, 4) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { letters: data.slice(0, 2) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { letters: data.slice(0, 4) },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it('honors refetchWritePolicy set to \"overwrite\"', async () => {\n    const query: TypedDocumentNode<\n      { primes: number[] },\n      { min: number; max: number }\n    > = gql`\n      query GetPrimes($min: number, $max: number) {\n        primes(min: $min, max: $max)\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const { result } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          variables: { min: 0, max: 12 },\n          refetchWritePolicy: \"overwrite\",\n        }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n    await actAsync(() => {\n      void result.current.refetch({ min: 12, max: 30 });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [undefined, [13, 17, 19, 23, 29]],\n    ]);\n  });\n\n  it('honors refetchWritePolicy set to \"merge\"', async () => {\n    const query: TypedDocumentNode<\n      { primes: number[] },\n      { min: number; max: number }\n    > = gql`\n      query GetPrimes($min: number, $max: number) {\n        primes(min: $min, max: $max)\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const { result } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          variables: { min: 0, max: 12 },\n          refetchWritePolicy: \"merge\",\n        }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n    await actAsync(() => {\n      void result.current.refetch({ min: 12, max: 30 });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n  });\n\n  it('defaults refetchWritePolicy to \"overwrite\"', async () => {\n    const query: TypedDocumentNode<\n      { primes: number[] },\n      { min: number; max: number }\n    > = gql`\n      query GetPrimes($min: number, $max: number) {\n        primes(min: $min, max: $max)\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const { result } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { min: 0, max: 12 } }),\n      { cache, mocks }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n    await actAsync(() => {\n      void result.current.refetch({ min: 12, max: 30 });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [undefined, [13, 17, 19, 23, 29]],\n    ]);\n  });\n\n  it(\"does not suspend when `skip` is true\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { skip: true }),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  });\n\n  it(\"does not suspend when using `skipToken` token as options\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, skipToken),\n      { cache, mocks }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  });\n\n  it(\"suspends when `skip` becomes `false` after it was `true`\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, renders, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, { skip }),\n      { cache, mocks, initialProps: { skip: true } }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    await rerenderAsync({ skip: false });\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"suspends when switching away from `skipToken` in options\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const { result, renders, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, skip ? skipToken : void 0),\n      { mocks, initialProps: { skip: true } }\n    );\n\n    expect(renders.suspenseCount).toBe(0);\n    expect(result.current).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    await rerenderAsync({ skip: false });\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: undefined,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"renders skip result, does not suspend, and maintains `data` when `skip` becomes `true` after it was `false`\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, renders, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, { skip }),\n      { cache, mocks, initialProps: { skip: false } }\n    );\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true });\n\n    expect(renders.suspenseCount).toBe(1);\n\n    expect(result.current).toStrictEqualTyped({\n      ...mocks[0].result,\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"renders skip result, does not suspend, and maintains `data` when skipping a query with `skipToken` as options after it was enabled\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const cache = new InMemoryCache();\n\n    const { result, renders, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, skip ? skipToken : void 0),\n      { cache, mocks, initialProps: { skip: false } }\n    );\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true });\n\n    expect(renders.suspenseCount).toBe(1);\n\n    expect(result.current).toStrictEqualTyped({\n      ...mocks[0].result,\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.suspenseCount).toBe(1);\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"does not make network requests when `skip` is `true`\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    let fetchCount = 0;\n\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        fetchCount++;\n\n        const mock = mocks.find(({ request }) =>\n          equal(request.variables, operation.variables)\n        );\n\n        if (!mock) {\n          throw new Error(\"Could not find mock for operation\");\n        }\n\n        observer.next(mock.result);\n        observer.complete();\n      });\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip, id }) => useSuspenseQuery(query, { skip, variables: { id } }),\n      { mocks, link, initialProps: { skip: true, id: \"1\" } }\n    );\n\n    expect(fetchCount).toBe(0);\n\n    await rerenderAsync({ skip: false, id: \"1\" });\n\n    expect(fetchCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true, id: \"2\" });\n\n    expect(fetchCount).toBe(1);\n  });\n\n  it(\"does not make network requests when using `skipToken` for options\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    let fetchCount = 0;\n\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        fetchCount++;\n\n        const mock = mocks.find(({ request }) =>\n          equal(request.variables, operation.variables)\n        );\n\n        if (!mock) {\n          throw new Error(\"Could not find mock for operation\");\n        }\n\n        observer.next(mock.result);\n        observer.complete();\n      });\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip, id }) =>\n        useSuspenseQuery(query, skip ? skipToken : { variables: { id } }),\n      { mocks, link, initialProps: { skip: true, id: \"1\" } }\n    );\n\n    expect(fetchCount).toBe(0);\n\n    await rerenderAsync({ skip: false, id: \"1\" });\n\n    expect(fetchCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true, id: \"2\" });\n\n    expect(fetchCount).toBe(1);\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11768\n  it(\"does not make network requests when using `skipToken` with strict mode\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    let fetchCount = 0;\n\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        fetchCount++;\n\n        const mock = mocks.find(({ request }) =>\n          equal(request.variables, operation.variables)\n        );\n\n        if (!mock) {\n          throw new Error(\"Could not find mock for operation\");\n        }\n\n        observer.next(mock.result);\n        observer.complete();\n      });\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip, id }) =>\n        useSuspenseQuery(query, skip ? skipToken : { variables: { id } }),\n      { mocks, link, strictMode: true, initialProps: { skip: true, id: \"1\" } }\n    );\n\n    expect(fetchCount).toBe(0);\n\n    await rerenderAsync({ skip: false, id: \"1\" });\n\n    expect(fetchCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true, id: \"2\" });\n\n    expect(fetchCount).toBe(1);\n  });\n\n  it(\"does not make network requests when using `skip` with strict mode\", async () => {\n    const { query, mocks } = useVariablesQueryCase();\n\n    let fetchCount = 0;\n\n    const link = new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        fetchCount++;\n\n        const mock = mocks.find(({ request }) =>\n          equal(request.variables, operation.variables)\n        );\n\n        if (!mock) {\n          throw new Error(\"Could not find mock for operation\");\n        }\n\n        observer.next(mock.result);\n        observer.complete();\n      });\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip, id }) => useSuspenseQuery(query, { skip, variables: { id } }),\n      { mocks, link, strictMode: true, initialProps: { skip: true, id: \"1\" } }\n    );\n\n    expect(fetchCount).toBe(0);\n\n    await rerenderAsync({ skip: false, id: \"1\" });\n\n    expect(fetchCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ skip: true, id: \"2\" });\n\n    expect(fetchCount).toBe(1);\n  });\n\n  it(\"`skip` result is referentially stable\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, { skip }),\n      { mocks, initialProps: { skip: true } }\n    );\n\n    const skipResult = result.current;\n\n    await rerenderAsync({ skip: true });\n\n    expect(result.current).toBe(skipResult);\n\n    await rerenderAsync({ skip: false });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[0].result.data);\n    });\n\n    const fetchedSkipResult = result.current;\n\n    await rerenderAsync({ skip: false });\n\n    expect(fetchedSkipResult).toBe(fetchedSkipResult);\n  });\n\n  it(\"`skip` result is referentially stable when using `skipToken` as options\", async () => {\n    const { query, mocks } = useSimpleQueryCase();\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ skip }) => useSuspenseQuery(query, skip ? skipToken : void 0),\n      { mocks, initialProps: { skip: true } }\n    );\n\n    const skipResult = result.current;\n\n    await rerenderAsync({ skip: true });\n\n    expect(result.current).toBe(skipResult);\n\n    await rerenderAsync({ skip: false });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual(mocks[0].result.data);\n    });\n\n    const fetchedSkipResult = result.current;\n\n    await rerenderAsync({ skip: false });\n\n    expect(fetchedSkipResult).toBe(fetchedSkipResult);\n  });\n\n  it(\"properly resolves when `skip` becomes false when returning a result that is deeply equal to data in the cache\", async () => {\n    type Variables = {\n      id: string;\n    };\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id=\"1\" />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({ id }: { id: string }) {\n      const [skip, setSkip] = React.useState(false);\n      const { data } = useSuspenseQuery(query, {\n        // Force a network request that returns the same data from the cache\n        fetchPolicy: \"network-only\",\n        skip,\n        variables: { id },\n      });\n\n      const todo = data?.todo;\n\n      return (\n        <>\n          <button onClick={() => setSkip((skip) => !skip)}>Toggle skip</button>\n          {todo && (\n            <div data-testid=\"todo\">\n              {todo.name}\n              {todo.completed && \" (completed)\"}\n            </div>\n          )}\n        </>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    const todo = await screen.findByTestId(\"todo\");\n    expect(todo).toHaveTextContent(\"Clean room\");\n\n    // skip false -> true\n    await act(() => user.click(screen.getByText(\"Toggle skip\")));\n    expect(todo).toHaveTextContent(\"Clean room\");\n\n    // skip true -> false\n    await act(() => user.click(screen.getByText(\"Toggle skip\")));\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    await waitFor(() => {\n      expect(todo).toBeVisible();\n    });\n\n    expect(todo).toHaveTextContent(\"Clean room\");\n  });\n\n  it(\"`skip` option works with `startTransition`\", async () => {\n    type Variables = {\n      id: string;\n    };\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const [id, setId] = React.useState<string | null>(null);\n      const [isPending, startTransition] = React.useTransition();\n\n      return (\n        <ApolloProvider client={client}>\n          <button\n            disabled={isPending}\n            onClick={() => {\n              startTransition(() => {\n                setId(\"1\");\n              });\n            }}\n          >\n            Fetch to-do 1\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id={id} />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({ id }: { id: string | null }) {\n      const { data } = useSuspenseQuery(query, {\n        skip: !id,\n        variables: { id: id ?? \"0\" },\n      });\n\n      const todo = data?.todo;\n\n      return todo ?\n          <div data-testid=\"todo\">\n            {todo.name}\n            {todo.completed && \" (completed)\"}\n          </div>\n        : null;\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.queryByTestId(\"todo\")).not.toBeInTheDocument();\n\n    const button = screen.getByText(\"Fetch to-do 1\");\n    await act(() => user.click(button));\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n    // We can ensure this works with isPending from useTransition in the process\n    expect(button).toBeDisabled();\n    // Eventually we should see the updated todo content once its done\n    // suspending.\n    expect(await screen.findByTestId(\"todo\")).toHaveTextContent(\"Clean room\");\n  });\n\n  it(\"`skipToken` works with `startTransition` when used for options\", async () => {\n    type Variables = {\n      id: string;\n    };\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const [id, setId] = React.useState<string | null>(null);\n      const [isPending, startTransition] = React.useTransition();\n\n      return (\n        <ApolloProvider client={client}>\n          <button\n            disabled={isPending}\n            onClick={() => {\n              startTransition(() => {\n                setId(\"1\");\n              });\n            }}\n          >\n            Fetch to-do 1\n          </button>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id={id} />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({ id }: { id: string | null }) {\n      const { data } = useSuspenseQuery(\n        query,\n        id ? { variables: { id } } : skipToken\n      );\n\n      const todo = data?.todo;\n\n      return todo ?\n          <div data-testid=\"todo\">\n            {todo.name}\n            {todo.completed && \" (completed)\"}\n          </div>\n        : null;\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.queryByTestId(\"todo\")).not.toBeInTheDocument();\n\n    const button = screen.getByText(\"Fetch to-do 1\");\n    await act(() => user.click(button));\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n    // We can ensure this works with isPending from useTransition in the process\n    expect(button).toBeDisabled();\n    // Eventually we should see the updated todo content once its done\n    // suspending.\n    expect(await screen.findByTestId(\"todo\")).toHaveTextContent(\"Clean room\");\n  });\n\n  it(\"applies `errorPolicy` on next fetch when it changes between renders\", async () => {\n    const { query, mocks: simpleMocks } = useSimpleQueryCase();\n\n    const successMock = simpleMocks[0];\n\n    const mocks = [\n      successMock,\n      {\n        request: { query },\n        result: {\n          errors: [new GraphQLError(\"oops\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ errorPolicy }) => useSuspenseQuery(query, { errorPolicy }),\n      { mocks, initialProps: { errorPolicy: \"none\" as ErrorPolicy } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...successMock.result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ errorPolicy: \"all\" });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...successMock.result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"oops\" }] }),\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n    expect(\n      renders.frames.map((f) => ({\n        data: f.data,\n        error: f.error,\n        networkStatus: f.networkStatus,\n      }))\n    ).toStrictEqualTyped([\n      {\n        ...successMock.result,\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...successMock.result,\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        ...successMock.result,\n        networkStatus: NetworkStatus.error,\n        error: new CombinedGraphQLErrors({ errors: [{ message: \"oops\" }] }),\n      },\n    ]);\n  });\n\n  it(\"applies `context` on next fetch when it changes between renders\", async () => {\n    const query = gql`\n      query {\n        context\n      }\n    `;\n\n    const link = new ApolloLink((operation) => {\n      return of({\n        data: {\n          context: {\n            // Only apply serialized value to prevent comparing against object\n            // with additional client properties\n            phase: operation.getContext().phase,\n          },\n        },\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    const { result, rerenderAsync, renders } = await renderSuspenseHook(\n      ({ context }) => useSuspenseQuery(query, { context }),\n      { client, initialProps: { context: { phase: \"initialValue\" } } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { context: { phase: \"initialValue\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ context: { phase: \"rerender\" } });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: {\n          context: { phase: \"rerender\" },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { context: { phase: \"initialValue\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { context: { phase: \"initialValue\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { context: { phase: \"rerender\" } },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"applies changed `refetchWritePolicy` to next fetch when changing between renders\", async () => {\n    const query: TypedDocumentNode<\n      { primes: number[] },\n      { min: number; max: number }\n    > = gql`\n      query GetPrimes($min: number, $max: number) {\n        primes(min: $min, max: $max)\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { min: 0, max: 12 } },\n        result: { data: { primes: [2, 3, 5, 7, 11] } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { min: 12, max: 30 } },\n        result: { data: { primes: [13, 17, 19, 23, 29] } },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { min: 30, max: 50 } },\n        result: { data: { primes: [31, 37, 41, 43, 47] } },\n        delay: 10,\n      },\n    ];\n\n    const mergeParams: [number[] | undefined, number[]][] = [];\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            primes: {\n              keyArgs: false,\n              merge(existing: number[] | undefined, incoming: number[]) {\n                mergeParams.push([existing, incoming]);\n                return existing ? existing.concat(incoming) : incoming;\n              },\n            },\n          },\n        },\n      },\n    });\n\n    const { result, rerenderAsync } = await renderSuspenseHook(\n      ({ refetchWritePolicy }) =>\n        useSuspenseQuery(query, {\n          variables: { min: 0, max: 12 },\n          refetchWritePolicy,\n        }),\n      {\n        cache,\n        mocks,\n        initialProps: { refetchWritePolicy: \"merge\" as RefetchWritePolicy },\n      }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([[undefined, [2, 3, 5, 7, 11]]]);\n\n    await actAsync(async () => {\n      void result.current.refetch({ min: 12, max: 30 });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: { primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n    ]);\n\n    await rerenderAsync({ refetchWritePolicy: \"overwrite\" });\n\n    await actAsync(async () => {\n      void result.current.refetch({ min: 30, max: 50 });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(mergeParams).toEqual([\n      [undefined, [2, 3, 5, 7, 11]],\n      [\n        [2, 3, 5, 7, 11],\n        [13, 17, 19, 23, 29],\n      ],\n      [undefined, [31, 37, 41, 43, 47]],\n    ]);\n  });\n\n  it(\"applies `returnPartialData` on next fetch when it changes between renders\", async () => {\n    const fullQuery = gql`\n      query {\n        character {\n          __typename\n          id\n          name\n        }\n      }\n    `;\n\n    const partialQuery = gql`\n      query {\n        character {\n          __typename\n          id\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query: fullQuery },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Doctor Strange\",\n            },\n          },\n        },\n        delay: 20,\n      },\n      {\n        request: { query: fullQuery },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Doctor Strange (refetched)\",\n            },\n          },\n        },\n        delay: 100,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: partialQuery,\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n    });\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache,\n    });\n\n    const renderStream = createRenderStream<useSuspenseQuery.Result>();\n\n    function Component({ returnPartialData }: { returnPartialData: boolean }) {\n      useTrackRenders();\n      renderStream.replaceSnapshot(\n        useSuspenseQuery(fullQuery, { returnPartialData })\n      );\n      return <div />;\n    }\n    function SuspenseFallback() {\n      useTrackRenders();\n      return <p>Loading</p>;\n    }\n    function ErrorFallback() {\n      useTrackRenders();\n      return <p>Error</p>;\n    }\n    function App({ returnPartialData }: { returnPartialData: boolean }) {\n      useTrackRenders();\n      return (\n        <Suspense fallback={<SuspenseFallback />}>\n          <ErrorBoundary fallback={<ErrorFallback />}>\n            <Component returnPartialData={returnPartialData} />\n          </ErrorBoundary>\n        </Suspense>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const { rerender } = await renderStream.render(\n      <App returnPartialData={false} />,\n      {\n        wrapper: createClientWrapper(client),\n      }\n    );\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n    }\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([Component]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    await rerender(<App returnPartialData={true} />);\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([App, Component]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n\n    cache.modify({\n      id: cache.identify({ __typename: \"Character\", id: \"1\" }),\n      fields: {\n        name: (_, { DELETE }) => DELETE,\n      },\n    });\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([Component]);\n      expect(snapshot).toStrictEqualTyped({\n        data: { character: { __typename: \"Character\", id: \"1\" } },\n        dataState: \"partial\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    }\n\n    {\n      const { renderedComponents, snapshot } = await renderStream.takeRender();\n      expect(renderedComponents).toStrictEqual([Component]);\n      expect(snapshot).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    }\n  });\n\n  it(\"applies updated `fetchPolicy` on next fetch when it changes between renders\", async () => {\n    const query = gql`\n      query {\n        character {\n          __typename\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"1\",\n              name: \"Doctor Strange\",\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strangecache\",\n        },\n      },\n    });\n\n    const { result, /* renders, */ rerenderAsync } = await renderSuspenseHook(\n      ({ fetchPolicy }) => useSuspenseQuery(query, { fetchPolicy }),\n      {\n        cache,\n        mocks,\n        initialProps: {\n          fetchPolicy: \"cache-first\" as useSuspenseQuery.FetchPolicy,\n        },\n      }\n    );\n\n    expect(result.current).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strangecache\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    await rerenderAsync({ fetchPolicy: \"no-cache\" });\n\n    const cacheKey = cache.identify({ __typename: \"Character\", id: \"1\" })!;\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual({\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strange\",\n        },\n      });\n    });\n\n    // Because we switched to a `no-cache` fetch policy, we should not see the\n    // newly fetched data in the cache after the fetch occurred.\n    expect(cache.extract()[cacheKey]).toEqual({\n      __typename: \"Character\",\n      id: \"1\",\n      name: \"Doctor Strangecache\",\n    });\n\n    // TODO: Determine why there is an extra render. Unfortunately this is hard\n    // to track down because the test passes if I run only this test or add a\n    // `console.log` statement to the `handleNext` function in `QueryReference`.\n    // expect(renders.count).toBe(4);\n    // expect(renders.suspenseCount).toBe(1);\n    // expect(renders.frames).toStrictEqualTyped([\n    //   {\n    //     data: {\n    //       character: {\n    //         __typename: 'Character',\n    //         id: '1',\n    //         name: 'Doctor Strangecache',\n    //       },\n    //     },\n    //     networkStatus: NetworkStatus.ready,\n    //     error: undefined,\n    //   },\n    //   {\n    //     data: {\n    //       character: {\n    //         __typename: 'Character',\n    //         id: '1',\n    //         name: 'Doctor Strangecache',\n    //       },\n    //     },\n    //     networkStatus: NetworkStatus.ready,\n    //     error: undefined,\n    //   },\n    //   {\n    //     ...mocks[0].result,\n    //     networkStatus: NetworkStatus.ready,\n    //     error: undefined,\n    //   },\n    // ]);\n  });\n\n  it(\"properly handles changing options along with changing `variables`\", async () => {\n    const query = gql`\n      query ($id: ID!) {\n        character(id: $id) {\n          __typename\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          errors: [new GraphQLError(\"oops\")],\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: {\n            character: {\n              __typename: \"Character\",\n              id: \"2\",\n              name: \"Hulk\",\n            },\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query,\n      variables: {\n        id: \"1\",\n      },\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strangecache\",\n        },\n      },\n    });\n\n    const { result, renders, rerenderAsync } = await renderSuspenseHook(\n      ({ errorPolicy, variables }) =>\n        useSuspenseQuery(query, { errorPolicy, variables }),\n      {\n        cache,\n        mocks,\n        initialProps: {\n          errorPolicy: \"none\" as ErrorPolicy,\n          variables: { id: \"1\" },\n        },\n      }\n    );\n\n    expect(result.current).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Doctor Strangecache\",\n        },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n\n    await rerenderAsync({ errorPolicy: \"none\", variables: { id: \"2\" } });\n\n    expect(renders.suspenseCount).toBe(1);\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"2\",\n            name: \"Hulk\",\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await rerenderAsync({ errorPolicy: \"all\", variables: { id: \"1\" } });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    const expectedError = new CombinedGraphQLErrors({\n      errors: [{ message: \"oops\" }],\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        data: {\n          character: {\n            __typename: \"Character\",\n            id: \"1\",\n            name: \"Doctor Strangecache\",\n          },\n        },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.error,\n        error: expectedError,\n      });\n    });\n\n    expect(renders.errorCount).toBe(0);\n  });\n\n  it(\"does not oversubscribe when suspending multiple times\", async () => {\n    const query = gql`\n      query UserQuery($id: String!) {\n        user(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel (updated)\" } },\n        },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { user: { id: \"1\", name: \"Captain Marvel (updated again)\" } },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const { result } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { variables: { id: \"1\" } }),\n      { client, initialProps: { id: \"1\" } }\n    );\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[0].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[1].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    await actAsync(async () => {\n      void result.current.refetch();\n    });\n\n    await waitFor(() => {\n      expect(result.current).toStrictEqualTyped({\n        ...mocks[2].result,\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n\n    expect(client.getObservableQueries().size).toBe(1);\n  });\n\n  it(\"can subscribe to subscriptions and react to cache updates via `subscribeToMore`\", async () => {\n    interface SubscriptionData {\n      greetingUpdated: string;\n    }\n\n    interface QueryData {\n      greeting: string;\n    }\n\n    type UpdateQueryFn = NonNullable<\n      ObservableQuery.SubscribeToMoreOptions<\n        QueryData | undefined,\n        OperationVariables,\n        SubscriptionData\n      >[\"updateQuery\"]\n    >;\n\n    const { mocks, query } = useSimpleQueryCase();\n\n    const wsLink = new MockSubscriptionLink();\n    const mockLink = new MockLink(mocks);\n\n    const link = ApolloLink.split(\n      ({ query }) => {\n        const definition = getMainDefinition(query);\n\n        return (\n          definition.kind === \"OperationDefinition\" &&\n          definition.operation === \"subscription\"\n        );\n      },\n      wsLink,\n      mockLink\n    );\n\n    const { result, renders } = await renderSuspenseHook(\n      () => useSuspenseQuery(query, { errorPolicy: \"ignore\" }),\n      { link }\n    );\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual({ greeting: \"Hello\" });\n    });\n\n    const updateQuery = jest.fn<\n      ReturnType<UpdateQueryFn>,\n      Parameters<UpdateQueryFn>\n    >((_, { subscriptionData: { data } }) => {\n      return { greeting: data.greetingUpdated };\n    });\n\n    result.current.subscribeToMore<SubscriptionData>({\n      document: gql`\n        subscription {\n          greetingUpdated\n        }\n      `,\n      updateQuery,\n    });\n\n    wsLink.simulateResult({\n      result: {\n        data: {\n          greetingUpdated: \"Subscription hello\",\n        },\n      },\n    });\n\n    await waitFor(() => {\n      expect(result.current.data).toEqual({\n        greeting: \"Subscription hello\",\n      });\n    });\n\n    expect(updateQuery).toHaveBeenCalledTimes(1);\n    expect(updateQuery).toHaveBeenCalledWith(\n      { greeting: \"Hello\" },\n      {\n        complete: true,\n        previousData: { greeting: \"Hello\" },\n        subscriptionData: {\n          data: { greetingUpdated: \"Subscription hello\" },\n        },\n        variables: {},\n      }\n    );\n\n    expect(renders.count).toBe(3 + (IS_REACT_19 ? renders.suspenseCount : 0));\n    expect(renders.frames).toStrictEqualTyped([\n      {\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n      {\n        data: { greeting: \"Subscription hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      },\n    ]);\n  });\n\n  it(\"works with useDeferredValue\", async () => {\n    const user = userEvent.setup();\n\n    interface Variables {\n      query: string;\n    }\n\n    interface Data {\n      search: { query: string };\n    }\n\n    const QUERY: TypedDocumentNode<Data, Variables> = gql`\n      query SearchQuery($query: String!) {\n        search(query: $query) {\n          query\n        }\n      }\n    `;\n\n    const link = new ApolloLink(({ variables }) => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({\n            data: { search: { query: variables.query } },\n          });\n          observer.complete();\n        }, 10);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const [query, setValue] = React.useState(\"\");\n      const deferredQuery = React.useDeferredValue(query);\n\n      return (\n        <ApolloProvider client={client}>\n          <label htmlFor=\"searchInput\">Search</label>\n          <input\n            id=\"searchInput\"\n            type=\"text\"\n            value={query}\n            onChange={(e) => setValue(e.target.value)}\n          />\n          <Suspense fallback={<SuspenseFallback />}>\n            <Results query={deferredQuery} />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Results({ query }: { query: string }) {\n      const { data } = useSuspenseQuery(QUERY, { variables: { query } });\n\n      return <div data-testid=\"result\">{data.search.query}</div>;\n    }\n\n    await renderAsync(<App />);\n\n    const input = screen.getByLabelText(\"Search\");\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    expect(await screen.findByTestId(\"result\")).toBeInTheDocument();\n\n    await act(() => user.type(input, \"ab\"));\n\n    await waitFor(\n      () => {\n        expect(screen.getByTestId(\"result\")).toHaveTextContent(\"ab\");\n      },\n      {\n        timeout: 10000,\n      }\n    );\n\n    await act(() => user.type(input, \"c\"));\n\n    // useDeferredValue will try rerendering the component with the new value\n    // in the background. If it suspends with the new value, React will show the\n    // stale UI until the component is done suspending.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the search finishes loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n    expect(screen.getByTestId(\"result\")).toHaveTextContent(\"ab\");\n\n    // Eventually we should see the updated text content once its done\n    // suspending.\n    await waitFor(() => {\n      expect(screen.getByTestId(\"result\")).toHaveTextContent(\"abc\");\n    });\n  }, 10000);\n\n  it(\"works with startTransition to change variables\", async () => {\n    type Variables = {\n      id: string;\n    };\n\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"2\" } },\n        result: {\n          data: { todo: { id: \"2\", name: \"Take out trash\", completed: true } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      const [id, setId] = React.useState(\"1\");\n\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id={id} onChange={setId} />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({\n      id,\n      onChange,\n    }: {\n      id: string;\n      onChange: (id: string) => void;\n    }) {\n      const { data } = useSuspenseQuery(query, { variables: { id } });\n      const [isPending, startTransition] = React.useTransition();\n      const { todo } = data;\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                onChange(\"2\");\n              });\n            }}\n          >\n            Refresh\n          </button>\n          <div data-testid=\"todo\" aria-busy={isPending}>\n            {todo.name}\n            {todo.completed && \" (completed)\"}\n          </div>\n        </>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    const { takeRender, render } = await createRenderStream({\n      snapshotDOM: true,\n    });\n    await render(<App />);\n\n    {\n      const { withinDOM } = await takeRender();\n      expect(withinDOM().getByText(\"Loading\")).toBeInTheDocument();\n    }\n\n    {\n      const { withinDOM } = await takeRender();\n\n      const todo = withinDOM().getByTestId(\"todo\");\n      expect(todo).toBeInTheDocument();\n      expect(todo).toHaveTextContent(\"Clean room\");\n      expect(todo).toHaveAttribute(\"aria-busy\", \"false\");\n    }\n    const el = screen.getByText(\"Refresh\");\n    await user.click(el);\n\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    {\n      const { withinDOM } = await takeRender();\n      const todo = withinDOM().getByTestId(\"todo\");\n\n      expect(withinDOM().queryByText(\"Loading\")).not.toBeInTheDocument();\n\n      // We can ensure this works with isPending from useTransition in the process\n      expect(todo).toHaveAttribute(\"aria-busy\", \"true\");\n\n      // Ensure we are showing the stale UI until the new todo has loaded\n      expect(todo).toHaveTextContent(\"Clean room\");\n    }\n\n    // Eventually we should see the updated todo content once its done\n    // suspending.\n    {\n      const { withinDOM } = await takeRender();\n      const todo = withinDOM().getByTestId(\"todo\");\n      expect(todo).toHaveTextContent(\"Take out trash (completed)\");\n    }\n  });\n\n  it(\"`refetch` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n    type Variables = {\n      id: string;\n    };\n\n    interface Data {\n      todo: {\n        id: string;\n        name: string;\n        completed: boolean;\n      };\n    }\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodoItemQuery($id: ID!) {\n        todo(id: $id) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: false } },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { id: \"1\" } },\n        result: {\n          data: { todo: { id: \"1\", name: \"Clean room\", completed: true } },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache(),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todo id=\"1\" />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todo({ id }: { id: string }) {\n      const { data, refetch } = useSuspenseQuery(query, { variables: { id } });\n      const [isPending, startTransition] = React.useTransition();\n      const { todo } = data;\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                void refetch();\n              });\n            }}\n          >\n            Refresh\n          </button>\n          <div data-testid=\"todo\" aria-busy={isPending}>\n            {todo.name}\n            {todo.completed && \" (completed)\"}\n          </div>\n        </>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    expect(await screen.findByTestId(\"todo\")).toBeInTheDocument();\n\n    const todo = screen.getByTestId(\"todo\");\n    const button = screen.getByText(\"Refresh\");\n\n    expect(todo).toHaveTextContent(\"Clean room\");\n\n    await act(() => user.click(button));\n\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n\n    // We can ensure this works with isPending from useTransition in the process\n    expect(todo).toHaveAttribute(\"aria-busy\", \"true\");\n\n    // Ensure we are showing the stale UI until the new todo has loaded\n    expect(todo).toHaveTextContent(\"Clean room\");\n\n    // Eventually we should see the updated todo content once its done\n    // suspending.\n    await waitFor(() => {\n      expect(todo).toHaveTextContent(\"Clean room (completed)\");\n    });\n  });\n\n  it(\"`fetchMore` works with startTransition to allow React to show stale UI until finished suspending\", async () => {\n    type Variables = {\n      offset: number;\n    };\n\n    interface Todo {\n      __typename: \"Todo\";\n      id: string;\n      name: string;\n      completed: boolean;\n    }\n\n    interface Data {\n      todos: Todo[];\n    }\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodosQuery($offset: Int!) {\n        todos(offset: $offset) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { offset: 0 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { offset: 1 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              todos: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n    });\n\n    function App() {\n      return (\n        <ApolloProvider client={client}>\n          <Suspense fallback={<SuspenseFallback />}>\n            <Todos />\n          </Suspense>\n        </ApolloProvider>\n      );\n    }\n\n    function SuspenseFallback() {\n      return <p>Loading</p>;\n    }\n\n    function Todos() {\n      const { data, fetchMore } = useSuspenseQuery(query, {\n        variables: { offset: 0 },\n      });\n      const [isPending, startTransition] = React.useTransition();\n      const { todos } = data;\n\n      return (\n        <>\n          <button\n            onClick={() => {\n              startTransition(() => {\n                void fetchMore({ variables: { offset: 1 } });\n              });\n            }}\n          >\n            Load more\n          </button>\n          <div data-testid=\"todos\" aria-busy={isPending}>\n            {todos.map((todo) => (\n              <div data-testid={`todo:${todo.id}`} key={todo.id}>\n                {todo.name}\n                {todo.completed && \" (completed)\"}\n              </div>\n            ))}\n          </div>\n        </>\n      );\n    }\n\n    await renderAsync(<App />);\n\n    expect(screen.getByText(\"Loading\")).toBeInTheDocument();\n\n    expect(await screen.findByTestId(\"todos\")).toBeInTheDocument();\n\n    const todos = screen.getByTestId(\"todos\");\n    const todo1 = screen.getByTestId(\"todo:1\");\n    const button = screen.getByText(\"Load more\");\n\n    expect(todo1).toBeInTheDocument();\n\n    await act(() => user.click(button));\n\n    // startTransition will avoid rendering the suspense fallback for already\n    // revealed content if the state update inside the transition causes the\n    // component to suspend.\n    //\n    // Here we should not see the suspense fallback while the component suspends\n    // until the todo is finished loading. Seeing the suspense fallback is an\n    // indication that we are suspending the component too late in the process.\n    expect(screen.queryByText(\"Loading\")).not.toBeInTheDocument();\n\n    // We can ensure this works with isPending from useTransition in the process\n    expect(todos).toHaveAttribute(\"aria-busy\", \"true\");\n\n    // Ensure we are showing the stale UI until the new todo has loaded\n    expect(todo1).toHaveTextContent(\"Clean room\");\n\n    // Eventually we should see the updated todos content once its done\n    // suspending.\n    await waitFor(() => {\n      expect(screen.getByTestId(\"todo:2\")).toHaveTextContent(\n        \"Take out trash (completed)\"\n      );\n      expect(todo1).toHaveTextContent(\"Clean room\");\n    });\n  });\n\n  it(\"updates networkStatus when a network request returns the same cached data with 'cache-and-network' fetchPolicy\", async () => {\n    const { query } = useSimpleQueryCase();\n\n    const link = new ApolloLink(() => {\n      return new Observable((observer) => {\n        setTimeout(() => {\n          observer.next({ data: { greeting: \"Hello\" } });\n          observer.complete();\n        }, 10);\n      });\n    });\n\n    const client = new ApolloClient({\n      link,\n      cache: new InMemoryCache(),\n    });\n\n    // preloaded cache\n    await client.writeQuery({ query, data: { greeting: \"Hello\" } });\n\n    const { result } = await renderSuspenseHook(\n      () =>\n        useSuspenseQuery(query, {\n          fetchPolicy: \"cache-and-network\",\n        }),\n      { client }\n    );\n\n    await waitFor(() => {\n      // We should see the cached greeting while the network request is in flight\n      // and the network status should be set to `loading`.\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.loading,\n        error: undefined,\n      });\n    });\n\n    await waitFor(() => {\n      // We should see the updated greeting once the network request finishes\n      // and the network status should be set to `ready`.\n      expect(result.current).toStrictEqualTyped({\n        data: { greeting: \"Hello\" },\n        dataState: \"complete\",\n        networkStatus: NetworkStatus.ready,\n        error: undefined,\n      });\n    });\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11315\n  it(\"fetchMore does not cause extra render\", async () => {\n    const { query, link } = setupPaginatedCase();\n\n    const user = userEvent.setup();\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              letters: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n      link,\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          PaginatedCaseData,\n          PaginatedCaseVariables\n        > | null,\n      },\n    });\n\n    function SuspenseFallback() {\n      useTrackRenders();\n\n      return <div>Loading...</div>;\n    }\n\n    function App() {\n      useTrackRenders();\n      const [isPending, startTransition] = useTransition();\n      const result = useSuspenseQuery(query, {\n        variables: { offset: 0, limit: 2 },\n      });\n      const { data, fetchMore } = result;\n\n      renderStream.mergeSnapshot({ result });\n\n      return (\n        <button\n          disabled={isPending}\n          onClick={() =>\n            startTransition(() => {\n              void fetchMore({\n                variables: {\n                  offset: data.letters.length,\n                  limit: data.letters.length + 1,\n                },\n              });\n            })\n          }\n        >\n          Fetch next\n        </button>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback={<SuspenseFallback />}>\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch next\"));\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(screen.getByText(\"Fetch next\")).toBeDisabled();\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n          { __typename: \"Letter\", letter: \"E\", position: 5 },\n        ],\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11708\n  it(\"`fetchMore` works with startTransition when setting errorPolicy as default option in ApolloClient constructor\", async () => {\n    type Variables = {\n      offset: number;\n    };\n\n    interface Todo {\n      __typename: \"Todo\";\n      id: string;\n      name: string;\n      completed: boolean;\n    }\n    interface Data {\n      todos: Todo[];\n    }\n    const user = userEvent.setup();\n\n    const query: TypedDocumentNode<Data, Variables> = gql`\n      query TodosQuery($offset: Int!) {\n        todos(offset: $offset) {\n          id\n          name\n          completed\n        }\n      }\n    `;\n\n    const mocks: MockLink.MockedResponse<Data, Variables>[] = [\n      {\n        request: { query, variables: { offset: 0 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n      {\n        request: { query, variables: { offset: 1 } },\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n        },\n        delay: 10,\n      },\n    ];\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        isPending: false,\n        result: null as Pick<\n          useSuspenseQuery.Result<Data>,\n          \"data\" | \"error\" | \"networkStatus\"\n        > | null,\n      },\n    });\n\n    function SuspenseFallback() {\n      useTrackRenders();\n\n      return <div>Loading...</div>;\n    }\n\n    const client = new ApolloClient({\n      link: new MockLink(mocks),\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              todos: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n      defaultOptions: {\n        watchQuery: {\n          errorPolicy: \"all\",\n        },\n      },\n    });\n\n    function App() {\n      useTrackRenders();\n      const [isPending, startTransition] = React.useTransition();\n      const { data, error, networkStatus, fetchMore } = useSuspenseQuery(\n        query,\n        {\n          variables: { offset: 0 },\n        }\n      );\n\n      renderStream.mergeSnapshot({\n        isPending,\n        result: { data, error, networkStatus },\n      });\n\n      return (\n        <button\n          onClick={() => {\n            startTransition(() => {\n              void fetchMore({ variables: { offset: 1 } });\n            });\n          }}\n        >\n          Load more\n        </button>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback={<SuspenseFallback />}>\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot).toEqual({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await user.click(screen.getByText(\"Load more\"));\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot).toEqual({\n        isPending: true,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n            ],\n          },\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot).toEqual({\n        isPending: false,\n        result: {\n          data: {\n            todos: [\n              {\n                __typename: \"Todo\",\n                id: \"1\",\n                name: \"Clean room\",\n                completed: false,\n              },\n              {\n                __typename: \"Todo\",\n                id: \"2\",\n                name: \"Take out trash\",\n                completed: true,\n              },\n            ],\n          },\n          error: undefined,\n          networkStatus: NetworkStatus.ready,\n        },\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/11642\n  it(\"returns merged array when `fetchMore` returns empty array of results\", async () => {\n    const query: TypedDocumentNode<PaginatedCaseData, PaginatedCaseVariables> =\n      gql`\n        query LettersQuery($limit: Int, $offset: Int) {\n          letters(limit: $limit, offset: $offset) {\n            letter\n            position\n          }\n        }\n      `;\n\n    const data = \"ABCD\".split(\"\").map((letter, index) => ({\n      __typename: \"Letter\",\n      letter,\n      position: index + 1,\n    }));\n\n    const link = new MockLink([\n      {\n        request: { query, variables: { offset: 0, limit: 2 } },\n        result: { data: { letters: data.slice(0, 2) } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { offset: 2, limit: 2 } },\n        result: { data: { letters: data.slice(2, 4) } },\n        delay: 20,\n      },\n      {\n        request: { query, variables: { offset: 4, limit: 2 } },\n        result: { data: { letters: [] } },\n        delay: 20,\n      },\n    ]);\n\n    const user = userEvent.setup();\n    const client = new ApolloClient({\n      cache: new InMemoryCache({\n        typePolicies: {\n          Query: {\n            fields: {\n              letters: offsetLimitPagination(),\n            },\n          },\n        },\n      }),\n      link,\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          PaginatedCaseData,\n          PaginatedCaseVariables\n        > | null,\n      },\n    });\n\n    function App() {\n      useTrackRenders();\n      const result = useSuspenseQuery(query, {\n        variables: { offset: 0, limit: 2 },\n      });\n      const { data, fetchMore } = result;\n\n      renderStream.mergeSnapshot({ result });\n\n      return (\n        <button\n          onClick={() =>\n            fetchMore({\n              variables: {\n                offset: data.letters.length,\n                limit: 2,\n              },\n            })\n          }\n        >\n          Fetch next\n        </button>\n      );\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback={<div>Loading...</div>}>\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // initial suspended render\n    await renderStream.takeRender();\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch next\"));\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      });\n    }\n\n    await user.click(screen.getByText(\"Fetch next\"));\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n          { __typename: \"Letter\", letter: \"C\", position: 3 },\n          { __typename: \"Letter\", letter: \"D\", position: 4 },\n        ],\n      });\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  // https://github.com/apollographql/apollo-client/issues/12103\n  it(\"does not get stuck pending when `fetchMore` rejects with an error\", async () => {\n    using _ = spyOnConsole(\"error\");\n    const { query, data } = setupPaginatedCase();\n\n    const link = new ApolloLink((operation) => {\n      const { offset = 0, limit = 2 } = operation.variables;\n      const letters = data.slice(offset, offset + limit);\n\n      return new Observable((observer) => {\n        setTimeout(() => {\n          if (offset === 2) {\n            observer.next({\n              data: null,\n              errors: [{ message: \"Could not fetch letters\" }],\n            });\n          } else {\n            observer.next({ data: { letters } });\n          }\n          observer.complete();\n        }, 150);\n      });\n    });\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          PaginatedCaseData,\n          PaginatedCaseVariables\n        > | null,\n        error: null as Error | null,\n      },\n    });\n\n    function SuspenseFallback() {\n      useTrackRenders();\n\n      return <div>Loading...</div>;\n    }\n\n    function ErrorFallback({ error }: FallbackProps) {\n      useTrackRenders();\n      renderStream.mergeSnapshot({ error });\n\n      return <div>Error</div>;\n    }\n\n    function App() {\n      useTrackRenders();\n      const result = useSuspenseQuery(query, {\n        variables: { offset: 0, limit: 2 },\n      });\n\n      renderStream.mergeSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback={<SuspenseFallback />}>\n        <ErrorBoundary FallbackComponent={ErrorFallback}>\n          <App />\n        </ErrorBoundary>\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([App]);\n      expect(snapshot.result?.data).toEqual({\n        letters: [\n          { __typename: \"Letter\", letter: \"A\", position: 1 },\n          { __typename: \"Letter\", letter: \"B\", position: 2 },\n        ],\n      });\n    }\n\n    const { snapshot } = renderStream.getCurrentRender();\n\n    snapshot.result!.fetchMore({ variables: { offset: 2 } }).catch(() => {});\n\n    {\n      const { renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([SuspenseFallback]);\n    }\n\n    {\n      const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n      expect(renderedComponents).toStrictEqual([ErrorFallback]);\n      expect(snapshot.error).toEqual(\n        new CombinedGraphQLErrors({\n          data: null,\n          errors: [{ message: \"Could not fetch letters\" }],\n        })\n      );\n    }\n\n    await expect(renderStream).not.toRerender();\n  });\n\n  it(\"masks queries when dataMasking is `true`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query);\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback={<div>Loading...</div>}>\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      const { result } = snapshot;\n\n      expect(result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n  });\n\n  it(\"does not mask query when dataMasking is `false`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: false,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query);\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result?.data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  it(\"does not mask query by default\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query);\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result?.data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 30,\n      },\n    });\n  });\n\n  it(\"masks queries updated by the cache\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query);\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    setTimeout(() => {\n      client.writeQuery({\n        query,\n        data: {\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            name: \"Test User (updated)\",\n            // @ts-ignore TODO: Determine how to handle cache writes with masked\n            // query type\n            age: 35,\n          },\n        },\n      });\n    });\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (updated)\",\n        },\n      });\n    }\n  });\n\n  it(\"does not rerender when updating field in named fragment\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query);\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          // @ts-ignore TODO: Determine how to handle cache writes with masked\n          // query type\n          age: 35,\n        },\n      },\n    });\n\n    await expect(renderStream).not.toRerender();\n\n    expect(client.readQuery({ query })).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n        age: 35,\n      },\n    });\n  });\n\n  it(\"masks result from cache when using with cache-first fetch policy\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User\",\n              age: 30,\n            },\n          },\n        },\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 30,\n        },\n      },\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query, { fetchPolicy: \"cache-first\" });\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result?.data).toEqual({\n      currentUser: {\n        __typename: \"User\",\n        id: 1,\n        name: \"Test User\",\n      },\n    });\n  });\n\n  it(\"masks cache and network result when using cache-and-network fetch policy\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n              age: 35,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    client.writeQuery({\n      query,\n      data: {\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n          age: 34,\n        },\n      },\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query, {\n        fetchPolicy: \"cache-and-network\",\n      });\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User\",\n        },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      });\n    }\n  });\n\n  it(\"masks partial cache data when returnPartialData is `true`\", async () => {\n    type UserFieldsFragment = {\n      __typename: \"User\";\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: \"Test User (server)\",\n              age: 35,\n            },\n          },\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    {\n      using _ = spyOnConsole(\"error\");\n      client.writeQuery({\n        query,\n        data: {\n          // @ts-expect-error writing partial cache data\n          currentUser: {\n            __typename: \"User\",\n            id: 1,\n            age: 34,\n          },\n        },\n      });\n    }\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>,\n          \"complete\" | \"streaming\" | \"partial\"\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query, { returnPartialData: true });\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n        },\n      });\n    }\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n\n      expect(snapshot.result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: \"Test User (server)\",\n        },\n      });\n    }\n  });\n\n  it(\"masks partial data returned from data on errors with errorPolicy `all`\", async () => {\n    type UserFieldsFragment = {\n      age: number;\n    } & { \" $fragmentName\"?: \"UserFieldsFragment\" };\n\n    interface Query {\n      currentUser: {\n        __typename: \"User\";\n        id: number;\n        name: string;\n      } & { \" $fragmentRefs\"?: { UserFieldsFragment: UserFieldsFragment } };\n    }\n\n    const query: TypedDocumentNode<Query, Record<string, never>> = gql`\n      query MaskedQuery {\n        currentUser {\n          id\n          name\n          ...UserFields\n        }\n      }\n\n      fragment UserFields on User {\n        age\n      }\n    `;\n\n    const mocks = [\n      {\n        request: { query },\n        result: {\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: null,\n              age: 34,\n            },\n          },\n          errors: [new GraphQLError(\"Couldn't get name\")],\n        },\n        delay: 20,\n      },\n    ];\n\n    const client = new ApolloClient({\n      dataMasking: true,\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n\n    const renderStream = createRenderStream({\n      initialSnapshot: {\n        result: null as useSuspenseQuery.Result<\n          Query,\n          Record<string, never>,\n          \"complete\" | \"streaming\" | \"empty\"\n        > | null,\n      },\n    });\n\n    function App() {\n      const result = useSuspenseQuery(query, { errorPolicy: \"all\" });\n\n      renderStream.replaceSnapshot({ result });\n\n      return null;\n    }\n\n    using _disabledAct = disableActEnvironment();\n    await renderStream.render(\n      <Suspense fallback=\"Loading\">\n        <App />\n      </Suspense>,\n      {\n        wrapper: ({ children }) => (\n          <ApolloProvider client={client}>{children}</ApolloProvider>\n        ),\n      }\n    );\n\n    // loading\n    await renderStream.takeRender();\n\n    {\n      const { snapshot } = await renderStream.takeRender();\n      const { result } = snapshot;\n\n      expect(result?.data).toEqual({\n        currentUser: {\n          __typename: \"User\",\n          id: 1,\n          name: null,\n        },\n      });\n\n      expect(result?.error).toEqual(\n        new CombinedGraphQLErrors({\n          data: {\n            currentUser: {\n              __typename: \"User\",\n              id: 1,\n              name: null,\n              age: 34,\n            },\n          },\n          errors: [{ message: \"Couldn't get name\" }],\n        })\n      );\n    }\n  });\n\n  {\n    interface Query {\n      hello?: string | null;\n    }\n    interface QueryVariables {\n      skipHello: boolean;\n    }\n    type Result = Pick<\n      useSuspenseQuery.Result<Query, QueryVariables>,\n      \"data\" | \"dataState\" | \"networkStatus\" | \"error\"\n    >;\n    it.each<[useSuspenseQuery.Options[\"fetchPolicy\"], ...Array<Result | null>]>(\n      [\n        [\n          \"cache-and-network\",\n          {\n            data: {},\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.loading,\n            error: undefined,\n          },\n          {\n            data: {},\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            error: undefined,\n          },\n        ],\n        [\n          \"cache-first\",\n          {\n            data: {},\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            error: undefined,\n          },\n        ],\n        [\n          \"network-only\",\n          null,\n          {\n            data: {},\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            error: undefined,\n          },\n        ],\n        [\n          \"no-cache\",\n          null,\n          {\n            data: {},\n            dataState: \"complete\",\n            networkStatus: NetworkStatus.ready,\n            error: undefined,\n          },\n        ],\n      ]\n    )(\n      \"unsuspends with `data: {}` and `dataState: 'complete'` when all fields are skipped (using fetchPolicy: %s)\",\n      async (fetchPolicy, ...expectedResults) => {\n        const query: TypedDocumentNode<Query, QueryVariables> = gql`\n          query SkipQuery($skipHello: Boolean!) {\n            hello @skip(if: $skipHello)\n          }\n        `;\n\n        const link = new MockLink([\n          {\n            request: { query, variables: { skipHello: true } },\n            result: { data: {} },\n            delay: 20,\n          },\n        ]);\n\n        const client = new ApolloClient({\n          cache: new InMemoryCache(),\n          link,\n        });\n\n        const renderStream = createRenderStream({\n          initialSnapshot: {\n            result: null as Result | null,\n          },\n        });\n\n        function App() {\n          const result = useSuspenseQuery(query, {\n            variables: { skipHello: true },\n            fetchPolicy,\n          });\n\n          renderStream.replaceSnapshot({ result });\n\n          return null;\n        }\n\n        using _disabledAct = disableActEnvironment();\n        await renderStream.render(\n          <Suspense fallback=\"Loading\">\n            <App />\n          </Suspense>,\n          {\n            wrapper: ({ children }) => (\n              <ApolloProvider client={client}>{children}</ApolloProvider>\n            ),\n          }\n        );\n\n        for (const expectedResult of expectedResults) {\n          const { snapshot } = await renderStream.takeRender();\n          const { result } = snapshot;\n          expect(result).toStrictEqualTyped(expectedResult);\n        }\n\n        await expect(renderStream).not.toRerender();\n      }\n    );\n  }\n\n  describe.skip(\"type tests\", () => {\n    it(\"returns unknown when TData cannot be inferred\", () => {\n      const query = gql`\n        query {\n          hello\n        }\n      `;\n\n      const { data, dataState } = useSuspenseQuery(query);\n\n      expectTypeOf(data).toEqualTypeOf<unknown>();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n    });\n\n    it(\"disallows wider variables type than specified\", () => {\n      const { query } = useVariablesQueryCase();\n\n      useSuspenseQuery(query, {\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variable\n          foo: \"bar\",\n        },\n      });\n    });\n\n    it(\"returns TData in default case\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it('returns TData | undefined with errorPolicy: \"ignore\"', () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { errorPolicy: \"ignore\", variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it('returns TData | undefined with errorPolicy: \"all\"', () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          errorPolicy: \"all\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          errorPolicy: \"all\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          errorPolicy: \"all\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { errorPolicy: \"all\", variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it('returns TData with errorPolicy: \"none\"', () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { errorPolicy: \"none\", variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it(\"returns DeepPartial<TData> with returnPartialData: true\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          returnPartialData: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          returnPartialData: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          returnPartialData: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | DeepPartial<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { returnPartialData: true, variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it(\"returns TData with returnPartialData: false\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          returnPartialData: false,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          returnPartialData: false,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          returnPartialData: false,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { returnPartialData: false, variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it(\"returns TData | undefined when skip is present\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          skip: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          skip: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      // TypeScript is too smart and using a `const` or `let` boolean variable\n      // for the `skip` option results in a false positive. Using an options\n      // object allows us to properly check for a dynamic case.\n      const options = {\n        skip: true,\n      };\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          skip: options.skip,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          skip: true,\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { skip: true, variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const options = {\n          skip: true,\n        };\n\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { skip: options.skip, variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it(\"returns TData | undefined when using `skipToken` as options\", () => {\n      const { query } = useVariablesQueryCase();\n      const options = {\n        skip: true,\n      };\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          query,\n          options.skip ? skipToken : { variables: { id: \"1\" } }\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          maskedQuery,\n          options.skip ? skipToken : { variables: { id: \"1\" } }\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it(\"returns TData | undefined when using `skipToken` with undefined options\", () => {\n      const { query } = useVariablesQueryCase();\n      const options = {\n        skip: true,\n      };\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          query,\n          options.skip ? skipToken : { variables: { id: \"1\" } }\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          maskedQuery,\n          options.skip ? skipToken : { variables: { id: \"1\" } }\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, options.skip ? skipToken : { variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it(\"returns DeepPartial<TData> | undefined when using `skipToken` as options with `returnPartialData`\", () => {\n      const { query } = useVariablesQueryCase();\n      const options = {\n        skip: true,\n      };\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          query,\n          options.skip ? skipToken : (\n            { returnPartialData: true, variables: { id: \"1\" } }\n          )\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(\n          query,\n          options.skip ? skipToken : (\n            { returnPartialData: true, variables: { id: \"id\" } }\n          )\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(\n          maskedQuery,\n          options.skip ? skipToken : (\n            { returnPartialData: true, variables: { id: \"1\" } }\n          )\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(\n          maskedQuery,\n          options.skip ? skipToken : (\n            { returnPartialData: true, variables: { id: \"1\" } }\n          )\n        );\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it(\"returns TData when passing an option that does not affect TData\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          fetchPolicy: \"no-cache\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          fetchPolicy: \"no-cache\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          fetchPolicy: \"no-cache\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, { fetchPolicy: \"no-cache\", variables: { id: \"1\" } });\n\n        expectTypeOf(data).toEqualTypeOf<\n          MaskedVariablesCaseData | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it(\"handles combinations of options\", () => {\n      // TypeScript is too smart and using a `const` or `let` boolean variable\n      // for the `skip` option results in a false positive. Using an options\n      // object allows us to properly check for a dynamic case which is the\n      // typical usage of this option.\n      const options = {\n        skip: true,\n      };\n\n      const { query } = useVariablesQueryCase();\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          returnPartialData: true,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          returnPartialData: true,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          returnPartialData: true,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          returnPartialData: true,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          skip: options.skip,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          skip: options.skip,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          skip: options.skip,\n          errorPolicy: \"ignore\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          skip: options.skip,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          skip: options.skip,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          VariablesCaseData | DataValue.Streaming<VariablesCaseData> | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          skip: options.skip,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          skip: options.skip,\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          skip: options.skip,\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          skip: options.skip,\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n          | undefined\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"empty\") {\n          expectTypeOf(data).toEqualTypeOf<undefined>();\n        }\n      }\n    });\n\n    it(\"returns correct TData type when combined options that do not affect TData\", () => {\n      const { query } = useVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(query, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          VariablesCaseData,\n          VariablesCaseVariables\n        >(query, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | VariablesCaseData\n          | DeepPartial<VariablesCaseData>\n          | DataValue.Streaming<VariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<VariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<VariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<DeepPartial<VariablesCaseData>>();\n        }\n      }\n\n      const { query: maskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { data, dataState } = useSuspenseQuery(maskedQuery, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n      }\n\n      {\n        const { data, dataState } = useSuspenseQuery<\n          MaskedVariablesCaseData,\n          VariablesCaseVariables\n        >(maskedQuery, {\n          fetchPolicy: \"no-cache\",\n          returnPartialData: true,\n          errorPolicy: \"none\",\n          variables: { id: \"1\" },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<\n          | MaskedVariablesCaseData\n          | DeepPartial<MaskedVariablesCaseData>\n          | DataValue.Streaming<MaskedVariablesCaseData>\n        >();\n        expectTypeOf(dataState).toEqualTypeOf<\n          \"complete\" | \"streaming\" | \"partial\"\n        >();\n\n        if (dataState === \"complete\") {\n          expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData>();\n        }\n\n        if (dataState === \"streaming\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DataValue.Streaming<MaskedVariablesCaseData>\n          >();\n        }\n\n        if (dataState === \"partial\") {\n          expectTypeOf(data).toEqualTypeOf<\n            DeepPartial<MaskedVariablesCaseData>\n          >();\n        }\n      }\n    });\n\n    it(\"uses proper masked types for refetch\", async () => {\n      const { query, unmaskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { refetch } = useSuspenseQuery(query, { variables: { id: \"1\" } });\n        const { data } = await refetch();\n\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n      }\n\n      {\n        const { refetch } = useSuspenseQuery(unmaskedQuery, {\n          variables: { id: \"1\" },\n        });\n        const { data } = await refetch();\n\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n      }\n    });\n\n    it(\"uses proper masked types for fetchMore\", async () => {\n      const { query, unmaskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { fetchMore } = useSuspenseQuery(query, {\n          variables: { id: \"1\" },\n        });\n\n        const { data } = await fetchMore({\n          updateQuery: (queryData, { fetchMoreResult }) => {\n            expectTypeOf(queryData).toEqualTypeOf<UnmaskedVariablesCaseData>();\n            expectTypeOf(\n              fetchMoreResult\n            ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n\n            return {} as UnmaskedVariablesCaseData;\n          },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n      }\n\n      {\n        const { fetchMore } = useSuspenseQuery(unmaskedQuery, {\n          variables: { id: \"1\" },\n        });\n\n        const { data } = await fetchMore({\n          updateQuery: (queryData, { fetchMoreResult }) => {\n            expectTypeOf(queryData).toEqualTypeOf<UnmaskedVariablesCaseData>();\n\n            expectTypeOf(\n              fetchMoreResult\n            ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n\n            return {} as UnmaskedVariablesCaseData;\n          },\n        });\n\n        expectTypeOf(data).toEqualTypeOf<MaskedVariablesCaseData | undefined>();\n      }\n    });\n\n    it(\"uses proper masked types for subscribeToMore\", async () => {\n      type CharacterFragment = {\n        __typename: \"Character\";\n        name: string;\n      } & { \" $fragmentName\": \"CharacterFragment\" };\n\n      type Subscription = {\n        pushLetter: {\n          __typename: \"Character\";\n          id: number;\n        } & { \" $fragmentRefs\": { CharacterFragment: CharacterFragment } };\n      };\n\n      type UnmaskedSubscription = {\n        pushLetter: {\n          __typename: \"Character\";\n          id: number;\n          name: string;\n        };\n      };\n\n      const { query, unmaskedQuery } = useMaskedVariablesQueryCase();\n\n      {\n        const { subscribeToMore } = useSuspenseQuery(query, {\n          variables: { id: \"1\" },\n        });\n\n        const subscription: TypedDocumentNode<\n          Subscription,\n          Record<string, never>\n        > = gql`\n          subscription {\n            pushLetter {\n              id\n              ...CharacterFragment\n            }\n          }\n\n          fragment CharacterFragment on Character {\n            name\n          }\n        `;\n\n        subscribeToMore({\n          document: subscription,\n          updateQuery: (queryData, { subscriptionData }) => {\n            expectTypeOf(queryData).toEqualTypeOf<\n              DeepPartial<UnmaskedVariablesCaseData>\n            >();\n\n            expectTypeOf(\n              subscriptionData.data\n            ).toEqualTypeOf<UnmaskedSubscription>();\n\n            return {} as UnmaskedVariablesCaseData;\n          },\n        });\n      }\n\n      {\n        const { subscribeToMore } = useSuspenseQuery(unmaskedQuery, {\n          variables: { id: \"1\" },\n        });\n\n        const subscription: TypedDocumentNode<\n          Subscription,\n          Record<string, never>\n        > = gql`\n          subscription {\n            pushLetter {\n              id\n              ...CharacterFragment\n            }\n          }\n\n          fragment CharacterFragment on Character {\n            name\n          }\n        `;\n\n        subscribeToMore({\n          document: subscription,\n          updateQuery: (\n            queryData,\n            { subscriptionData, complete, previousData }\n          ) => {\n            expectTypeOf(queryData).toEqualTypeOf<\n              DeepPartial<UnmaskedVariablesCaseData>\n            >();\n\n            expectTypeOf(complete).toEqualTypeOf<boolean>();\n            expectTypeOf(previousData).toEqualTypeOf<\n              | UnmaskedVariablesCaseData\n              | DeepPartial<UnmaskedVariablesCaseData>\n              | undefined\n            >();\n\n            if (complete) {\n              expectTypeOf(\n                previousData\n              ).toEqualTypeOf<UnmaskedVariablesCaseData>();\n            } else {\n              expectTypeOf(previousData).toEqualTypeOf<\n                DeepPartial<UnmaskedVariablesCaseData> | undefined\n              >();\n            }\n\n            expectTypeOf(\n              subscriptionData.data\n            ).toEqualTypeOf<UnmaskedSubscription>();\n\n            return {} as UnmaskedVariablesCaseData;\n          },\n        });\n      }\n    });\n\n    test(\"variables are optional and can be anything with an DocumentNode\", () => {\n      const query = gql``;\n\n      useSuspenseQuery(query);\n      useSuspenseQuery(query, {});\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, { variables: { foo: \"bar\" } });\n      useSuspenseQuery(query, { variables: { bar: \"baz\" } });\n\n      let skip!: boolean;\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(query, skip ? skipToken : {});\n      useSuspenseQuery(query, skip ? skipToken : { variables: {} });\n      useSuspenseQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n      useSuspenseQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n    });\n\n    test(\"variables are optional and can be anything with unspecified TVariables on a TypedDocumentNode\", () => {\n      const query: TypedDocumentNode<{ greeting: string }> = gql``;\n\n      useSuspenseQuery(query);\n      useSuspenseQuery(query, {});\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, { variables: { foo: \"bar\" } });\n      useSuspenseQuery(query, { variables: { bar: \"baz\" } });\n\n      let skip!: boolean;\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(query, skip ? skipToken : {});\n      useSuspenseQuery(query, skip ? skipToken : { variables: {} });\n      useSuspenseQuery(query, skip ? skipToken : { variables: { foo: \"bar\" } });\n      useSuspenseQuery(query, skip ? skipToken : { variables: { bar: \"baz\" } });\n    });\n\n    test(\"variables are optional when TVariables are empty\", () => {\n      const query: TypedDocumentNode<\n        { greeting: string },\n        Record<string, never>\n      > = gql``;\n\n      useSuspenseQuery(query);\n      useSuspenseQuery(query, {});\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n\n      let skip!: boolean;\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(query, skip ? skipToken : {});\n      useSuspenseQuery(query, skip ? skipToken : { variables: {} });\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error unknown variables\n        skip ? skipToken : { variables: { foo: \"bar\" } }\n      );\n    });\n\n    test(\"is invalid when TVariables is `never`\", () => {\n      const query: TypedDocumentNode<{ greeting: string }, never> = gql``;\n\n      // @ts-expect-error\n      useSuspenseQuery(query);\n      // @ts-expect-error\n      useSuspenseQuery(query, {});\n      useSuspenseQuery(query, {\n        // @ts-expect-error\n        variables: {},\n      });\n      useSuspenseQuery(query, {\n        // @ts-expect-error\n        variables: undefined,\n      });\n      useSuspenseQuery(query, {\n        // @ts-expect-error\n        variables: {\n          foo: \"bar\",\n        },\n      });\n\n      let skip!: boolean;\n      // @ts-expect-error\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error\n        skip ? skipToken : {}\n      );\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error\n        skip ? skipToken : { variables: {} }\n      );\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error\n        skip ? skipToken : { variables: undefined }\n      );\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error unknown variables\n        skip ? skipToken : { variables: { foo: \"bar\" } }\n      );\n    });\n\n    test(\"optional variables are optional\", () => {\n      const query: TypedDocumentNode<{ posts: string[] }, { limit?: number }> =\n        gql``;\n\n      useSuspenseQuery(query);\n      useSuspenseQuery(query, {});\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, { variables: { limit: 10 } });\n      useSuspenseQuery(query, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      useSuspenseQuery(query, {\n        variables: {\n          limit: 10,\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n\n      let skip!: boolean;\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(query, skip ? skipToken : {});\n      useSuspenseQuery(query, skip ? skipToken : { variables: {} });\n      useSuspenseQuery(query, skip ? skipToken : { variables: { limit: 10 } });\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              limit: 10,\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n    });\n\n    test(\"enforces required variables when TVariables includes required variables\", () => {\n      const query: TypedDocumentNode<{ character: string }, { id: string }> =\n        gql``;\n\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query);\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query, {});\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, { variables: { id: \"1\" } });\n      useSuspenseQuery(query, {\n        variables: {\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      useSuspenseQuery(query, {\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n\n      let skip!: boolean;\n      // @ts-expect-error missing variables option\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error missing variables option\n        skip ? skipToken : {}\n      );\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error missing required variables\n        skip ? skipToken : { variables: {} }\n      );\n      useSuspenseQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              id: \"1\",\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n    });\n\n    test(\"requires variables with mixed TVariables\", () => {\n      const query: TypedDocumentNode<\n        { character: string },\n        { id: string; language?: string }\n      > = gql``;\n\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query);\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query, {});\n      // @ts-expect-error empty variables\n      useSuspenseQuery(query, { variables: {} });\n      useSuspenseQuery(query, { variables: { id: \"1\" } });\n      useSuspenseQuery(query, {\n        // @ts-expect-error missing required variables\n        variables: { language: \"en\" },\n      });\n      useSuspenseQuery(query, { variables: { id: \"1\", language: \"en\" } });\n      useSuspenseQuery(query, {\n        variables: {\n          id: \"1\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n      useSuspenseQuery(query, {\n        variables: {\n          id: \"1\",\n          language: \"en\",\n          // @ts-expect-error unknown variables\n          foo: \"bar\",\n        },\n      });\n\n      let skip!: boolean;\n      // @ts-expect-error missing variables option\n      useSuspenseQuery(query, skip ? skipToken : undefined);\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error missing variables option\n        skip ? skipToken : {}\n      );\n      useSuspenseQuery(\n        query,\n        // @ts-expect-error missing required variables\n        skip ? skipToken : { variables: {} }\n      );\n      useSuspenseQuery(query, skip ? skipToken : { variables: { id: \"1\" } });\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : { variables: { id: \"1\", language: \"en\" } }\n      );\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              id: \"1\",\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n      useSuspenseQuery(\n        query,\n        skip ? skipToken : (\n          {\n            variables: {\n              id: \"1\",\n              language: \"en\",\n              // @ts-expect-error unknown variables\n              foo: \"bar\",\n            },\n          }\n        )\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/constants.ts",
    "content": "export const skipToken = Symbol.for(\"apollo.skipToken\");\nexport type SkipToken = typeof skipToken;\n"
  },
  {
    "path": "src/react/hooks/internal/__tests__/useDeepMemo.test.ts",
    "content": "import { renderHook } from \"@testing-library/react\";\n\n//not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { useDeepMemo } from \"../useDeepMemo.js\";\n\ndescribe(\"useDeepMemo\", () => {\n  it(\"ensures the value is initialized\", () => {\n    const { result } = renderHook(() =>\n      useDeepMemo(() => ({ test: true }), [])\n    );\n\n    expect(result.current).toEqual({ test: true });\n  });\n\n  it(\"returns memoized value when its dependencies are deeply equal\", () => {\n    const { result, rerender } = renderHook(\n      ({ active, items, user }) => {\n        useDeepMemo(() => ({ active, items, user }), [items, name, active]);\n      },\n      {\n        initialProps: {\n          active: true,\n          items: [1, 2],\n          user: { name: \"John Doe\" },\n        },\n      }\n    );\n\n    const previousResult = result.current;\n\n    rerender({ active: true, items: [1, 2], user: { name: \"John Doe\" } });\n\n    expect(result.current).toBe(previousResult);\n  });\n\n  it(\"returns updated value if a dependency changes\", () => {\n    const { result, rerender } = renderHook(\n      ({ items }) => useDeepMemo(() => ({ items }), [items]),\n      { initialProps: { items: [1] } }\n    );\n\n    const previousResult = result.current;\n\n    rerender({ items: [1, 2] });\n\n    expect(result.current).not.toBe(previousResult);\n    expect(result.current).toEqual({ items: [1, 2] });\n  });\n});\n"
  },
  {
    "path": "src/react/hooks/internal/__tests__/useRenderGuard.test.tsx",
    "content": "/* eslint-disable testing-library/render-result-naming-convention */\nimport { render, waitFor } from \"@testing-library/react\";\nimport * as React from \"react\";\n\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { useRenderGuard } from \"../useRenderGuard.js\";\n\nconst UNDEF = {};\nconst IS_REACT_19 = React.version.startsWith(\"19\");\n\nit(\"returns a function that returns `true` if called during render\", () => {\n  // We don't provide this functionality with React 19 anymore since it requires internals access\n  if (IS_REACT_19) return;\n  let result: boolean | typeof UNDEF = UNDEF;\n  function TestComponent() {\n    const calledDuringRender = useRenderGuard();\n    result = calledDuringRender();\n    return <>Test</>;\n  }\n  render(<TestComponent />);\n  expect(result).toBe(true);\n});\n\nit(\"returns a function that returns `false` if called after render\", async () => {\n  let result: boolean | typeof UNDEF = UNDEF;\n  function TestComponent() {\n    const calledDuringRender = useRenderGuard();\n    React.useEffect(() => {\n      result = calledDuringRender();\n    });\n    return <>Test</>;\n  }\n  render(<TestComponent />);\n  await waitFor(() => {\n    expect(result).not.toBe(UNDEF);\n  });\n  expect(result).toBe(false);\n});\n"
  },
  {
    "path": "src/react/hooks/internal/__use.ts",
    "content": "import * as React from \"react\";\n\nimport { decoratePromise } from \"@apollo/client/utilities/internal\";\n\ntype Use = <T>(promise: Promise<T>) => T;\n// Prevent webpack from complaining about our feature detection of the\n// use property of the React namespace, which is expected not\n// to exist when using current stable versions, and that's fine.\nconst useKey = \"use\" as keyof typeof React;\nconst realHook = React[useKey] as Use | undefined;\n\n// This is named with two underscores to allow this hook to evade typical rules of\n// hooks (i.e. it can be used conditionally)\nexport const __use =\n  realHook ||\n  function __use<TValue>(promise: Promise<TValue>) {\n    const decoratedPromise = decoratePromise(promise);\n\n    switch (decoratedPromise.status) {\n      case \"pending\":\n        throw decoratedPromise;\n      case \"rejected\":\n        throw decoratedPromise.reason;\n      case \"fulfilled\":\n        return decoratedPromise.value;\n    }\n  };\n"
  },
  {
    "path": "src/react/hooks/internal/index.ts",
    "content": "// These hooks are used internally and are not exported publicly by the library\nexport { useDeepMemo } from \"./useDeepMemo.js\";\nexport { useRenderGuard } from \"./useRenderGuard.js\";\nexport { useSuspenseHookCacheKey } from \"./useSuspenseHookCacheKey.js\";\nexport { __use } from \"./__use.js\";\nexport { wrapHook } from \"./wrapHook.js\";\n"
  },
  {
    "path": "src/react/hooks/internal/useDeepMemo.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { DependencyList } from \"react\";\nimport * as React from \"react\";\n\nexport function useDeepMemo<TValue>(\n  memoFn: () => TValue,\n  deps: DependencyList\n) {\n  const ref = React.useRef<{ deps: DependencyList; value: TValue }>(void 0);\n  // eslint-disable-next-line react-hooks/refs\n  if (!ref.current || !equal(ref.current.deps, deps)) {\n    ref.current = { value: memoFn(), deps };\n  }\n  // eslint-disable-next-line react-hooks/refs\n  return ref.current.value;\n}\n"
  },
  {
    "path": "src/react/hooks/internal/useIsomorphicLayoutEffect.ts",
    "content": "import * as React from \"react\";\n\nimport { canUseDOM } from \"@apollo/client/utilities/internal\";\n\n// use canUseDOM here instead of canUseLayoutEffect because we want to be able\n// to use useLayoutEffect in our jest tests. useLayoutEffect seems to work fine\n// in useSuspenseQuery tests, but to honor the original comment about the\n// warnings for useSyncExternalStore implementation, canUseLayoutEffect is left\n// alone.\nexport const useIsomorphicLayoutEffect =\n  canUseDOM ? React.useLayoutEffect : React.useEffect;\n"
  },
  {
    "path": "src/react/hooks/internal/useRenderGuard.ts",
    "content": "import * as React from \"react\";\n\nlet Ctx: React.Context<null>;\n\nfunction noop() {}\nexport function useRenderGuard() {\n  if (!Ctx) {\n    // we want the initialization to be lazy because `createContext` would error on import in a RSC\n    Ctx = React.createContext(null);\n  }\n\n  return React.useCallback(\n    /**\n     * @returns true if the hook was called during render\n     */ () => {\n      const orig = console.error;\n      try {\n        console.error = noop;\n\n        /**\n         * `useContext` can be called conditionally during render, so this is safe.\n         * (Also, during render we would want to throw as a reaction to this anyways, so it\n         * wouldn't even matter if we got the order of hooks mixed up...)\n         *\n         * They cannot however be called outside of Render, and that's what we're testing here.\n         *\n         * Different versions of React have different behaviour on an invalid hook call:\n         *\n         * React 16.8 - 17: throws an error\n         * https://github.com/facebook/react/blob/2b93d686e359c7afa299e2ec5cf63160a32a1155/packages/react/src/ReactHooks.js#L18-L26\n         *\n         * React 18 & 19: `console.error` in development, then `resolveDispatcher` returns `null` and a member access on `null` throws.\n         * https://github.com/facebook/react/blob/58e8304483ebfadd02a295339b5e9a989ac98c6e/packages/react/src/ReactHooks.js#L28-L35\n         */\n        React[\"useContext\" /* hide this from the linter */](Ctx);\n        return true;\n      } catch (e) {\n        return false;\n      } finally {\n        console.error = orig;\n      }\n    },\n    []\n  );\n}\n"
  },
  {
    "path": "src/react/hooks/internal/useSuspenseHookCacheKey.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport * as React from \"react\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport type { CacheKey } from \"@apollo/client/react/internal\";\nimport { canonicalStringify } from \"@apollo/client/utilities\";\n\nimport type { SkipToken } from \"../constants.js\";\nimport { skipToken } from \"../constants.js\";\n\nexport declare namespace useSuspenseHookCacheKey {\n  export interface Options {\n    variables?: OperationVariables;\n    queryKey?: string | number | any[];\n  }\n}\n\nexport function useSuspenseHookCacheKey(\n  query: DocumentNode,\n  options:\n    | (SkipToken & Partial<useSuspenseHookCacheKey.Options>)\n    | useSuspenseHookCacheKey.Options\n) {\n  const { queryKey = [], variables } = options;\n  const canonicalVariables = canonicalStringify(variables);\n\n  // This state value let's us maintain the variables used for the cache key\n  // when `skipToken` is used to skip a query after its been executed.\n  // Since options aren't provided when using `skipToken`, `variables` would\n  // otherwise disappear which means we'd return a new cache key without a\n  // variables value which creates a new `ObservableQuery` instance. This was\n  // particularly problematic when `refetchQueries` was used because it meant\n  // refetching against an `ObservableQuery` instance that had no variables.\n  let [cacheKeyVariables, setCacheKeyVariables] =\n    React.useState(canonicalVariables);\n\n  if (options !== skipToken && cacheKeyVariables !== canonicalVariables) {\n    setCacheKeyVariables((cacheKeyVariables = canonicalVariables));\n  }\n\n  return [\n    query,\n    cacheKeyVariables,\n    ...([] as any[]).concat(queryKey),\n  ] satisfies CacheKey;\n}\n"
  },
  {
    "path": "src/react/hooks/internal/validateSuspenseHookOptions.ts",
    "content": "import type {\n  ApolloClient,\n  OperationVariables,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nexport function validateSuspenseHookOptions<\n  TData,\n  TVariables extends OperationVariables,\n>(options: ApolloClient.WatchQueryOptions<TData, TVariables>) {\n  const { fetchPolicy, returnPartialData } = options;\n\n  validateFetchPolicy(fetchPolicy);\n  validatePartialDataReturn(fetchPolicy, returnPartialData);\n}\n\nfunction validateFetchPolicy(\n  fetchPolicy: WatchQueryFetchPolicy = \"cache-first\"\n) {\n  const supportedFetchPolicies: WatchQueryFetchPolicy[] = [\n    \"cache-first\",\n    \"network-only\",\n    \"no-cache\",\n    \"cache-and-network\",\n  ];\n\n  invariant(\n    supportedFetchPolicies.includes(fetchPolicy),\n    `The fetch policy \\`%s\\` is not supported with suspense.`,\n    fetchPolicy\n  );\n}\n\nfunction validatePartialDataReturn(\n  fetchPolicy: WatchQueryFetchPolicy | undefined,\n  returnPartialData: boolean | undefined\n) {\n  if (fetchPolicy === \"no-cache\" && returnPartialData) {\n    invariant.warn(\n      \"Using `returnPartialData` with a `no-cache` fetch policy has no effect. To read partial data from the cache, consider using an alternate fetch policy.\"\n    );\n  }\n}\n"
  },
  {
    "path": "src/react/hooks/internal/wrapHook.ts",
    "content": "import * as React from \"react\";\n\nimport type { ApolloClient, InternalTypes } from \"@apollo/client\";\nimport type { ObservableQuery } from \"@apollo/client\";\nimport type { createQueryPreloader } from \"@apollo/client/react\";\nimport type {\n  useBackgroundQuery,\n  useFragment,\n  useQuery,\n  useQueryRefHandlers,\n  useReadQuery,\n  useSuspenseFragment,\n  useSuspenseQuery,\n} from \"@apollo/client/react\";\nimport { wrapperSymbol } from \"@apollo/client/react/internal\";\n\n// direct import to avoid circular dependency\nimport { getApolloContext } from \"../../context/ApolloContext.js\";\n\ntype FunctionSignature<T> =\n  T extends (...args: infer A) => infer R ? (...args: A) => R : never;\n\ninterface WrappableHooks {\n  createQueryPreloader: FunctionSignature<typeof createQueryPreloader>;\n  useQuery: FunctionSignature<typeof useQuery>;\n  useSuspenseQuery: FunctionSignature<typeof useSuspenseQuery>;\n  useSuspenseFragment: FunctionSignature<typeof useSuspenseFragment>;\n  useBackgroundQuery: FunctionSignature<typeof useBackgroundQuery>;\n  useReadQuery: FunctionSignature<typeof useReadQuery>;\n  useFragment: FunctionSignature<typeof useFragment>;\n  useQueryRefHandlers: FunctionSignature<typeof useQueryRefHandlers>;\n}\n\n/**\n * @internal\n * Can be used to correctly type the [Symbol.for(\"apollo.hook.wrappers\")] property of\n * `QueryManager`, to override/wrap hook functionality.\n */\nexport type HookWrappers = {\n  [K in keyof WrappableHooks]?: (\n    originalHook: WrappableHooks[K]\n  ) => WrappableHooks[K];\n};\n\ninterface QueryManagerWithWrappers extends InternalTypes.QueryManager {\n  [wrapperSymbol]?: HookWrappers;\n}\n\n/**\n * @internal\n *\n * Makes an Apollo Client hook \"wrappable\".\n * That means that the Apollo Client instance can expose a \"wrapper\" that will be\n * used to wrap the original hook implementation with additional logic.\n * @example\n *\n * ```tsx\n * // this is already done in `@apollo/client` for all wrappable hooks (see `WrappableHooks`)\n * // following this pattern\n * function useQuery() {\n *   return wrapHook('useQuery', _useQuery, options.client)(query, options);\n * }\n * function _useQuery(query, options) {\n *   // original implementation\n * }\n *\n * // this is what a library like `@apollo/client-react-streaming` would do\n * class ApolloClientWithStreaming extends ApolloClient {\n *   constructor(options) {\n *     super(options);\n *     this.queryManager[Symbol.for(\"apollo.hook.wrappers\")] = {\n *       useQuery: (original) => (query, options) => {\n *         console.log(\"useQuery was called with options\", options);\n *         return original(query, options);\n *       }\n *     }\n *   }\n * }\n *\n * // this will now log the options and then call the original `useQuery`\n * const client = new ApolloClientWithStreaming({ ... });\n * useQuery(query, { client });\n * ```\n */\nexport function wrapHook<Hook extends (...args: any[]) => any>(\n  hookName: keyof WrappableHooks,\n  useHook: Hook,\n  clientOrObsQuery: ObservableQuery<any> | ApolloClient\n): Hook {\n  // Priority-wise, the later entries in this array wrap\n  // previous entries and could prevent them (and in the end,\n  // even the original hook) from running\n  const wrapperSources = [\n    (\n      clientOrObsQuery as unknown as {\n        // both `ApolloClient` and `ObservableQuery` have a `queryManager` property\n        // but they're both `private`, so we have to cast around for a bit here.\n        queryManager: QueryManagerWithWrappers;\n      }\n    )[\"queryManager\"],\n    // if we are a hook (not `preloadQuery`), we are guaranteed to be inside of\n    // a React render and can use context\n    hookName.startsWith(\"use\") ?\n      // eslint-disable-next-line react-hooks/rules-of-hooks\n      React.useContext(getApolloContext())\n    : undefined,\n  ];\n\n  let wrapped = useHook;\n  for (const source of wrapperSources) {\n    const wrapper = source?.[wrapperSymbol]?.[hookName];\n    if (wrapper) {\n      wrapped = wrapper(wrapped) as Hook;\n    }\n  }\n\n  return wrapped;\n}\n"
  },
  {
    "path": "src/react/hooks/useApolloClient.ts",
    "content": "import * as React from \"react\";\n\nimport type { ApolloClient } from \"@apollo/client\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { getApolloContext } from \"../context/ApolloContext.js\";\n\n/**\n * @example\n *\n * ```jsx\n * import { useApolloClient } from \"@apollo/client/react\";\n *\n * function SomeComponent() {\n *   const client = useApolloClient();\n *   // `client` is now set to the `ApolloClient` instance being used by the\n *   // application (that was configured using something like `ApolloProvider`)\n * }\n * ```\n *\n * @returns The `ApolloClient` instance being used by the application.\n */\nexport function useApolloClient(override?: ApolloClient): ApolloClient {\n  const context = React.useContext(getApolloContext());\n  const client = override || context.client;\n  invariant(\n    !!client,\n    'Could not find \"client\" in the context or passed in as an option. ' +\n      \"Wrap the root component in an <ApolloProvider>, or pass an ApolloClient \" +\n      \"instance in via options.\"\n  );\n\n  return client;\n}\n"
  },
  {
    "path": "src/react/hooks/useBackgroundQuery.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  DefaultContext,\n  DocumentNode,\n  ErrorPolicy,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport type { SubscribeToMoreFunction } from \"@apollo/client\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport type {\n  FetchMoreFunction,\n  RefetchFunction,\n} from \"@apollo/client/react/internal\";\nimport {\n  getSuspenseCache,\n  unwrapQueryRef,\n  updateWrappedQueryRef,\n  wrapQueryRef,\n} from \"@apollo/client/react/internal\";\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { SkipToken } from \"./constants.js\";\nimport { useSuspenseHookCacheKey, wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useWatchQueryOptions } from \"./useSuspenseQuery.js\";\n\nexport declare namespace useBackgroundQuery {\n  import _self = useBackgroundQuery;\n  export type FetchPolicy = Extract<\n    WatchQueryFetchPolicy,\n    \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n  >;\n\n  export namespace Base {\n    export interface Options {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n      client?: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy_suspense:member} */\n      refetchWritePolicy?: RefetchWritePolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n      errorPolicy?: ErrorPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n      context?: DefaultContext;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n      returnPartialData?: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n      fetchPolicy?: FetchPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#queryKey:member} */\n      queryKey?: string | number | any[];\n\n      /**\n       * {@inheritDoc @apollo/client!QueryOptionsDocumentation#skip_deprecated:member}\n       *\n       * @example Recommended usage of `skipToken`:\n       *\n       * ```ts\n       * import { skipToken, useBackgroundQuery } from \"@apollo/client\";\n       *\n       * const [queryRef] = useBackgroundQuery(\n       *   query,\n       *   id ? { variables: { id } } : skipToken\n       * );\n       * ```\n       */\n      skip?: boolean;\n    }\n  }\n\n  export type Options<\n    TVariables extends OperationVariables = OperationVariables,\n  > = Base.Options & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    namespace useBackgroundQuery {\n      export interface Options<\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Options,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n    }\n  }\n\n  export interface Result<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n    subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n\n    /**\n     * {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)}\n     *\n     * @remarks\n     * Calling this function will cause the component to re-suspend, unless the call site is wrapped in [`startTransition`](https://react.dev/reference/react/startTransition).\n     */\n    fetchMore: FetchMoreFunction<TData, TVariables>;\n\n    /**\n     * {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member}\n     *\n     * @remarks\n     * Calling this function will cause the component to re-suspend, unless the call site is wrapped in [`startTransition`](https://react.dev/reference/react/startTransition).\n     */\n    refetch: RefetchFunction<TData, TVariables>;\n  }\n\n  namespace DocumentationTypes {\n    namespace useBackgroundQuery {\n      export interface Result<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends _self.Result<TData, TVariables> {}\n    }\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\n    export function useBackgroundQuery<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options: SkipToken | useBackgroundQuery.Options<TVariables>\n    ): [\n      QueryRef<TData, TVariables> | undefined,\n      useBackgroundQuery.Result<TData, TVariables>,\n    ];\n  }\n}\n\n/**\n * For a detailed explanation of useBackgroundQuery, see the [fetching with Suspense reference](https://www.apollographql.com/docs/react/data/suspense).\n *\n * @returns A tuple containing:\n *\n * 1.  A `QueryRef` that can be passed to `useReadQuery` to read the query result. The `queryRef` is `undefined` if the query is skipped.\n * 2.  An object containing helper functions for the query:\n *     - `refetch`: A function to re-execute the query\n *     - `fetchMore`: A function to fetch more results for pagination\n *     - `subscribeToMore`: A function to subscribe to updates\n *\n * @example\n *\n * ```jsx\n * import { Suspense } from \"react\";\n * import { ApolloClient, InMemoryCache, HttpLink } from \"@apollo/client\";\n * import { useBackgroundQuery, useReadQuery } from \"@apollo/client/react\";\n *\n * const query = gql`\n *   foo {\n *     bar\n *   }\n * `;\n *\n * const client = new ApolloClient({\n *   link: new HttpLink({ uri: \"http://localhost:4000/graphql\" }),\n *   cache: new InMemoryCache(),\n * });\n *\n * function SuspenseFallback() {\n *   return <div>Loading...</div>;\n * }\n *\n * function Child({ queryRef }) {\n *   const { data } = useReadQuery(queryRef);\n *\n *   return <div>{data.foo.bar}</div>;\n * }\n *\n * function Parent() {\n *   const [queryRef] = useBackgroundQuery(query);\n *\n *   return (\n *     <Suspense fallback={<SuspenseFallback />}>\n *       <Child queryRef={queryRef} />\n *     </Suspense>\n *   );\n * }\n *\n * function App() {\n *   return (\n *     <ApolloProvider client={client}>\n *       <Parent />\n *     </ApolloProvider>\n *   );\n * }\n * ```\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - An optional object containing options for the query. Instead of passing a `useBackgroundQuery.Options` object into the hook, you can also pass a [`skipToken`](#skiptoken) to prevent the `useBackgroundQuery` hook from executing the query or suspending.\n */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    /** @deprecated `returnPartialData` has no effect on `no-cache` queries */\n    returnPartialData: boolean;\n    fetchPolicy: \"no-cache\";\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: false;\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: boolean;\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\" | \"empty\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    skip: boolean;\n    returnPartialData: false;\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    skip: boolean;\n    returnPartialData: boolean;\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: false;\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: boolean;\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useBackgroundQuery.Options<NoInfer<TVariables>> & {\n    skip: boolean;\n  }\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: SkipToken\n): [undefined, useBackgroundQuery.Result<TData, TVariables>];\n\n/** {@inheritDoc @apollo/client/react!useBackgroundQuery:function(1)} */\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | (useBackgroundQuery.Options<NoInfer<TVariables>> & {\n        returnPartialData: false;\n      })\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | (useBackgroundQuery.Options<NoInfer<TVariables>> & {\n        returnPartialData: boolean;\n      })\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [options?: useBackgroundQuery.Options<NoInfer<TVariables>>]\n  : [options: useBackgroundQuery.Options<NoInfer<TVariables>>]\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\">,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [options?: SkipToken | useBackgroundQuery.Options<NoInfer<TVariables>>]\n  : [options: SkipToken | useBackgroundQuery.Options<NoInfer<TVariables>>]\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: SkipToken | useBackgroundQuery.Options<NoInfer<TVariables>>\n): [\n  QueryRef<TData, TVariables, \"complete\" | \"streaming\"> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n];\n\nexport function useBackgroundQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: SkipToken | useBackgroundQuery.Options<NoInfer<TVariables>>\n): [\n  QueryRef<TData, TVariables, DataState<TData>[\"dataState\"]> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n] {\n  \"use no memo\";\n  return wrapHook(\n    \"useBackgroundQuery\",\n    useBackgroundQuery_,\n    useApolloClient(typeof options === \"object\" ? options.client : undefined)\n  )(query, options ?? ({} as any));\n}\n\nfunction useBackgroundQuery_<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | (SkipToken & Partial<useBackgroundQuery.Options<NoInfer<TVariables>>>)\n    | useBackgroundQuery.Options<NoInfer<TVariables>>\n): [\n  QueryRef<TData, TVariables, TStates> | undefined,\n  useBackgroundQuery.Result<TData, TVariables>,\n] {\n  const client = useApolloClient(options.client);\n  const suspenseCache = getSuspenseCache(client);\n  const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n  const { fetchPolicy } = watchQueryOptions;\n  const cacheKey = useSuspenseHookCacheKey(query, options);\n\n  // This ref tracks the first time query execution is enabled to determine\n  // whether to return a query ref or `undefined`. When initialized\n  // in a skipped state (either via `skip: true` or `skipToken`) we return\n  // `undefined` for the `queryRef` until the query has been enabled. Once\n  // enabled, a query ref is always returned regardless of whether the query is\n  // skipped again later.\n  const didFetchResult = React.useRef(fetchPolicy !== \"standby\");\n  didFetchResult.current ||= fetchPolicy !== \"standby\";\n\n  const queryRef = suspenseCache.getQueryRef<TData, TStates>(cacheKey, () =>\n    client.watchQuery(\n      watchQueryOptions as ApolloClient.WatchQueryOptions<any, any>\n    )\n  );\n\n  const [wrappedQueryRef, setWrappedQueryRef] = React.useState(\n    wrapQueryRef(queryRef)\n  );\n  if (unwrapQueryRef(wrappedQueryRef) !== queryRef) {\n    setWrappedQueryRef(wrapQueryRef(queryRef));\n  }\n  if (queryRef.didChangeOptions(watchQueryOptions)) {\n    const promise = queryRef.applyOptions(watchQueryOptions);\n    updateWrappedQueryRef(wrappedQueryRef, promise);\n  }\n\n  // This prevents issues where rerendering useBackgroundQuery after the\n  // queryRef has been disposed would cause the hook to return a new queryRef\n  // instance since disposal also removes it from the suspense cache. We add\n  // the queryRef back in the suspense cache so that the next render will reuse\n  // this queryRef rather than initializing a new instance.\n  React.useEffect(() => {\n    // Since the queryRef is disposed async via `setTimeout`, we have to wait a\n    // tick before checking it and adding back to the suspense cache.\n    const id = setTimeout(() => {\n      if (queryRef.disposed) {\n        suspenseCache.add(cacheKey, queryRef);\n      }\n    });\n\n    return () => clearTimeout(id);\n    // Omitting the deps is intentional. This avoids stale closures and the\n    // conditional ensures we aren't running the logic on each render.\n  });\n\n  const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(\n    (options) => {\n      const promise = queryRef.fetchMore(options);\n\n      setWrappedQueryRef(wrapQueryRef(queryRef));\n\n      return promise;\n    },\n    [queryRef]\n  );\n\n  const refetch: RefetchFunction<TData, TVariables> = React.useCallback(\n    (variables) => {\n      const promise = queryRef.refetch(variables);\n\n      setWrappedQueryRef(wrapQueryRef(queryRef));\n\n      return promise;\n    },\n    [queryRef]\n  );\n\n  React.useEffect(() => queryRef.softRetain(), [queryRef]);\n\n  return [\n    didFetchResult.current ? wrappedQueryRef : void 0,\n    {\n      fetchMore,\n      refetch,\n      // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n      subscribeToMore: queryRef.observable\n        .subscribeToMore as SubscribeToMoreFunction<TData, TVariables>,\n    },\n  ];\n}\n"
  },
  {
    "path": "src/react/hooks/useFragment.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataValue,\n  DocumentNode,\n  GetDataState,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport type { ApolloCache, MissingTree } from \"@apollo/client/cache\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { NoInfer } from \"@apollo/client/utilities/internal\";\n\nimport { useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\nexport declare namespace useFragment {\n  import _self = useFragment;\n\n  export interface Options<TData, TVariables extends OperationVariables> {\n    /**\n     * A GraphQL document created using the `gql` template string tag from\n     * `graphql-tag` with one or more fragments which will be used to determine\n     * the shape of data to read. If you provide more than one fragment in this\n     * document then you must also specify `fragmentName` to select a single.\n     */\n    fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n    /**\n     * The name of the fragment in your GraphQL document to be used. If you do\n     * not provide a `fragmentName` and there is only one fragment in your\n     * `fragment` document then that fragment will be used.\n     */\n    fragmentName?: string;\n\n    /**\n     * Any variables that the GraphQL query may depend on.\n     */\n    variables?: NoInfer<TVariables>;\n\n    /**\n     * An object or array containing a `__typename` and primary key fields\n     * (such as `id`) identifying the entity object from which the fragment will\n     * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID (uncommon).\n     */\n    from:\n      | useFragment.FromOptionValue<TData>\n      | Array<useFragment.FromOptionValue<TData> | null>\n      | null;\n\n    /**\n     * Whether to read from optimistic or non-optimistic cache data. If\n     * this named option is provided, the optimistic parameter of the\n     * readQuery method can be omitted.\n     *\n     * @defaultValue true\n     */\n    optimistic?: boolean;\n\n    /**\n     * The instance of `ApolloClient` to use to look up the fragment.\n     *\n     * By default, the instance that's passed down via context is used, but you\n     * can provide a different instance here.\n     *\n     * @docGroup 1. Operation options\n     */\n    client?: ApolloClient;\n  }\n\n  namespace DocumentationTypes {\n    namespace useFragment {\n      export interface Options<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends _self.Options<TData, TVariables> {}\n    }\n  }\n\n  /**\n   * Acceptable values provided to the `from` option.\n   */\n  export type FromOptionValue<TData> = ApolloCache.FromOptionValue<TData>;\n\n  // TODO: Update this to return `null` when there is no data returned from the\n  // fragment.\n  export type Result<TData> =\n    | ({\n        /** {@inheritDoc @apollo/client/react!useFragment.DocumentationTypes.useFragment.Result#complete:member} */\n        complete: true;\n        /** {@inheritDoc @apollo/client/react!useFragment.DocumentationTypes.useFragment.Result#missing:member} */\n        missing?: never;\n      } & GetDataState<MaybeMasked<TData>, \"complete\">)\n    | {\n        /** {@inheritDoc @apollo/client/react!useFragment.DocumentationTypes.useFragment.Result#complete:member} */\n        complete: false;\n        /** {@inheritDoc @apollo/client/react!useFragment.DocumentationTypes.useFragment.Result#missing:member} */\n        missing?: MissingTree;\n        /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n        data: TData extends Array<infer TItem> ?\n          Array<DataValue.Partial<TItem> | null>\n        : DataValue.Partial<TData>;\n        /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n        dataState: \"partial\";\n      };\n\n  export namespace DocumentationTypes {\n    namespace useFragment {\n      export interface Result<TData> {\n        data: MaybeMasked<TData> | DataValue.Partial<MaybeMasked<TData>>;\n        complete: boolean;\n        /**\n         * A tree of all `MissingFieldError` messages reported during fragment reading, where the branches of the tree indicate the paths of the errors within the query result.\n         */\n        missing?: MissingTree;\n      }\n    }\n  }\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useFragment:function(1)} */\n    export function useFragment<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >({\n      fragment,\n      from,\n      fragmentName,\n      variables,\n      optimistic,\n      client,\n    }: useFragment.Options<TData, TVariables>): useFragment.Result<TData>;\n  }\n}\n\n/**\n * `useFragment` represents a lightweight live binding into the Apollo Client Cache and enables Apollo Client to broadcast very specific fragment results to individual components. This hook returns an always-up-to-date view of whatever data the cache currently contains for a given fragment. `useFragment` never triggers network requests of its own.\n *\n * Note that the `useQuery` hook remains the primary hook responsible for querying and populating data in the cache ([see the API reference](./hooks#usequery)). As a result, the component reading the fragment data via `useFragment` is still subscribed to all changes in the query data, but receives updates only when that fragment's specific data change.\n *\n * To view a `useFragment` example, see the [Fragments](https://www.apollographql.com/docs/react/data/fragments#usefragment) page.\n */\nexport function useFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useFragment.Options<TData, TVariables> & {\n    from: Array<useFragment.FromOptionValue<TData>>;\n  }\n): useFragment.Result<Array<TData>>;\n\n/** {@inheritDoc @apollo/client/react!useFragment:function(1)} */\nexport function useFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useFragment.Options<TData, TVariables> & {\n    from: Array<null>;\n  }\n): useFragment.Result<Array<null>>;\n\n/** {@inheritDoc @apollo/client/react!useFragment:function(1)} */\nexport function useFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useFragment.Options<TData, TVariables> & {\n    from: Array<useFragment.FromOptionValue<TData> | null>;\n  }\n): useFragment.Result<Array<TData | null>>;\n\n/** {@inheritDoc @apollo/client/react!useFragment:function(1)} */\nexport function useFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(options: useFragment.Options<TData, TVariables>): useFragment.Result<TData>;\n\nexport function useFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useFragment.Options<TData, TVariables>\n): useFragment.Result<TData> | useFragment.Result<Array<TData | null>> {\n  \"use no memo\";\n  return wrapHook(\n    \"useFragment\",\n    useFragment_,\n    useApolloClient(options.client)\n  )(options);\n}\n\nfunction useFragment_<TData, TVariables extends OperationVariables>(\n  options: useFragment.Options<TData, TVariables>\n): useFragment.Result<TData> | useFragment.Result<Array<TData | null>> {\n  const client = useApolloClient(options.client);\n  const { from, ...rest } = options;\n  const { cache } = client;\n\n  // We calculate the cache id seperately because we don't want changes to non\n  // key fields in the `from` property to recreate the observable. If the cache\n  // identifier stays the same between renders, we want to reuse the existing\n  // subscription.\n  const ids = useDeepMemo(() => {\n    const fromArray = Array.isArray(from) ? from : [from];\n\n    const ids = fromArray.map((value) =>\n      typeof value === \"string\" ? value\n      : value === null ? null\n      : cache.identify(value)\n    );\n\n    return Array.isArray(from) ? ids : ids[0];\n  }, [cache, from]);\n\n  const stableOptions = useDeepMemo(\n    () => ({ ...rest, from: ids as any }),\n    [rest, ids]\n  );\n\n  const observable = React.useMemo(\n    () => client.watchFragment(stableOptions),\n    [client, stableOptions]\n  );\n\n  // Unfortunately we forgot to update the use case of `from: null` on\n  // useFragment in 4.0 to match `useSuspenseFragment`. As such, we need to\n  // fallback to data: {} with complete: false when `from` is `null` to maintain\n  // backwards compatibility. We should plan to change this in v5.\n  const getSnapshot = React.useCallback(\n    () => (from === null ? nullResult : observable.getCurrentResult()),\n    [from, observable]\n  );\n\n  return useSyncExternalStore(\n    React.useCallback(\n      (update) => {\n        let lastTimeout = 0;\n        const subscription = observable.subscribe({\n          next: () => {\n            // If we get another update before we've re-rendered, bail out of\n            // the update and try again. This ensures that the relative timing\n            // between useQuery and useFragment stays roughly the same as\n            // fixed in https://github.com/apollographql/apollo-client/pull/11083\n            clearTimeout(lastTimeout);\n            lastTimeout = setTimeout(update) as any;\n          },\n        });\n\n        return () => {\n          subscription.unsubscribe();\n          clearTimeout(lastTimeout);\n        };\n      },\n      [observable]\n    ),\n    getSnapshot,\n    getSnapshot\n  );\n}\n\nconst nullResult = Object.freeze({\n  data: {},\n  dataState: \"partial\",\n  complete: false,\n}) as useFragment.Result<any>;\n"
  },
  {
    "path": "src/react/hooks/useLazyQuery.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\nimport type { DocumentNode } from \"graphql\";\nimport * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  DefaultContext,\n  ErrorLike,\n  ErrorPolicy,\n  GetDataState,\n  InternalTypes,\n  MaybeMasked,\n  ObservableQuery,\n  OperationVariables,\n  RefetchWritePolicy,\n  SubscribeToMoreFunction,\n  UpdateQueryMapFn,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport { NetworkStatus } from \"@apollo/client\";\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  maybeDeepFreeze,\n  variablesUnknownSymbol,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { useRenderGuard } from \"./internal/index.js\";\nimport { useDeepMemo } from \"./internal/useDeepMemo.js\";\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nexport declare namespace useLazyQuery {\n  import _self = useLazyQuery;\n  export interface Options<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: WatchQueryFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */\n    nextFetchPolicy?:\n      | WatchQueryFetchPolicy\n      | ((\n          this: ApolloClient.WatchQueryOptions<TData, TVariables>,\n          currentFetchPolicy: WatchQueryFetchPolicy,\n          context: InternalTypes.NextFetchPolicyContext<TData, TVariables>\n        ) => WatchQueryFetchPolicy);\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n    refetchWritePolicy?: RefetchWritePolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */\n    pollInterval?: number;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */\n    notifyOnNetworkStatusChange?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n    returnPartialData?: boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */\n    skipPollAttempt?: () => boolean;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n    client?: ApolloClient;\n  }\n  namespace DocumentationTypes {\n    namespace useLazyQuery {\n      export interface Options<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends _self.Options<TData, TVariables> {}\n    }\n  }\n\n  namespace Base {\n    export interface Result<TData, TVariables extends OperationVariables> {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#startPolling:member} */\n      startPolling: (pollInterval: number) => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#stopPolling:member} */\n      stopPolling: () => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#subscribeToMore:member} */\n      subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#updateQuery:member} */\n      updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */\n      refetch: (\n        variables?: Partial<TVariables>\n      ) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */\n      fetchMore: <\n        TFetchData = TData,\n        TFetchVars extends OperationVariables = TVariables,\n      >(\n        fetchMoreOptions: ObservableQuery.FetchMoreOptions<\n          TData,\n          TVariables,\n          TFetchData,\n          TFetchVars\n        >\n      ) => Promise<ApolloClient.QueryResult<MaybeMasked<TFetchData>>>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#client:member} */\n      client: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#observable:member} */\n      observable: ObservableQuery<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#previousData:member} */\n      previousData?: MaybeMasked<TData>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n      error?: ErrorLike;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */\n      loading: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n      networkStatus: NetworkStatus;\n    }\n  }\n\n  export type Result<\n    TData,\n    TVariables extends OperationVariables,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = Base.Result<TData, TVariables> &\n    (\n      | ({\n          /**\n           * If `true`, the associated lazy query has been executed.\n           *\n           * @docGroup 2. Network info\n           */\n          called: true;\n\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#variables:member} */\n          variables: TVariables;\n        } & GetDataState<MaybeMasked<TData>, TStates>)\n      | {\n          /**\n           * If `true`, the associated lazy query has been executed.\n           *\n           * @docGroup 2. Network info\n           */\n          called: false;\n\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#variables:member} */\n          variables: Partial<TVariables>;\n\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n          data: undefined;\n          /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n          dataState: \"empty\";\n        }\n    );\n\n  namespace DocumentationTypes {\n    namespace useLazyQuery {\n      export interface Result<TData, TVariables extends OperationVariables>\n        extends Base.Result<TData, TVariables>,\n          UtilityDocumentationTypes.DataState<TData>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {\n        /**\n         * If `true`, the associated lazy query has been executed.\n         *\n         * @docGroup 2. Network info\n         */\n        called: boolean;\n      }\n    }\n  }\n\n  export type ExecOptions<\n    TVariables extends OperationVariables = OperationVariables,\n  > = {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n  } & VariablesOption<TVariables>;\n\n  namespace DocumentationTypes {\n    namespace useLazyQuery {\n      export interface ExecOptions<TVariables extends OperationVariables>\n        extends UtilityDocumentationTypes.VariableOptions<TVariables> {\n        /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n        context?: DefaultContext;\n      }\n    }\n  }\n\n  export type ResultTuple<\n    TData,\n    TVariables extends OperationVariables,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = [\n    execute: ExecFunction<TData, TVariables>,\n    result: useLazyQuery.Result<TData, TVariables, TStates>,\n  ];\n\n  export type ExecFunction<TData, TVariables extends OperationVariables> = (\n    ...args: {} extends TVariables ?\n      [options?: useLazyQuery.ExecOptions<TVariables>]\n    : [options: useLazyQuery.ExecOptions<TVariables>]\n  ) => ObservableQuery.ResultPromise<ApolloClient.QueryResult<TData>>;\n\n  namespace DocumentationTypes {\n    namespace useLazyQuery {\n      export import ResultTuple = _self.ResultTuple;\n    }\n  }\n\n  namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useLazyQuery:function(1)} */\n    export function useLazyQuery<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options: useLazyQuery.Options<TData, TVariables>\n    ): useLazyQuery.ResultTuple<TData, TVariables>;\n  }\n}\n\n// The following methods, when called will execute the query, regardless of\n// whether the useLazyQuery execute function was called before.\nconst EAGER_METHODS = [\n  \"refetch\",\n  \"fetchMore\",\n  \"updateQuery\",\n  \"startPolling\",\n  \"stopPolling\",\n  \"subscribeToMore\",\n] as const;\n\n/**\n * A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.\n *\n * > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.\n *\n * @example\n *\n * ```jsx\n * import { gql } from \"@apollo/client\";\n * import { useLazyQuery } from \"@apollo/client/react\";\n *\n * const GET_GREETING = gql`\n *   query GetGreeting($language: String!) {\n *     greeting(language: $language) {\n *       message\n *     }\n *   }\n * `;\n *\n * function Hello() {\n *   const [loadGreeting, { called, loading, data }] = useLazyQuery(GET_GREETING, {\n *     variables: { language: \"english\" },\n *   });\n *   if (called && loading) return <p>Loading ...</p>;\n *   if (!called) {\n *     return <button onClick={() => loadGreeting()}>Load greeting</button>;\n *   }\n *   return <h1>Hello {data.greeting.message}!</h1>;\n * }\n * ```\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Default options to control how the query is executed.\n * @returns A tuple in the form of `[execute, result]`\n */\nexport function useLazyQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n    returnPartialData: true;\n  }\n): useLazyQuery.ResultTuple<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useLazyQuery:function(1)} */\nexport function useLazyQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n    returnPartialData: boolean;\n  }\n): useLazyQuery.ResultTuple<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useLazyQuery:function(1)} */\nexport function useLazyQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>>\n): useLazyQuery.ResultTuple<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\"\n>;\n\nexport function useLazyQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: useLazyQuery.Options<NoInfer<TData>, NoInfer<TVariables>>\n): useLazyQuery.ResultTuple<TData, TVariables, TStates> {\n  const client = useApolloClient(options?.client);\n  const previousDataRef = React.useRef<TData>(undefined);\n  const resultRef = React.useRef<ObservableQuery.Result<TData>>(undefined);\n  const stableOptions = useDeepMemo(() => options, [options]);\n  const calledDuringRender = useRenderGuard();\n\n  function createObservable() {\n    return client.watchQuery({\n      ...options,\n      query,\n      initialFetchPolicy: options?.fetchPolicy,\n      fetchPolicy: \"standby\",\n      [variablesUnknownSymbol]: true,\n    } as ApolloClient.WatchQueryOptions<TData, TVariables>);\n  }\n\n  const [currentClient, setCurrentClient] = React.useState(client);\n  const [observable, setObservable] = React.useState(createObservable);\n\n  if (currentClient !== client) {\n    setCurrentClient(client);\n    setObservable(createObservable());\n  }\n\n  // TODO: Revisit after we have RxJS in place. We should be able to use\n  // observable.getCurrentResult() (or equivalent) to get these values which\n  // will hopefully alleviate the need for us to use refs to track these values.\n  const updateResult = React.useCallback(\n    (result: ObservableQuery.Result<TData>, forceUpdate: () => void) => {\n      const previousData = resultRef.current?.data;\n\n      if (previousData && !equal(previousData, result.data)) {\n        previousDataRef.current = previousData as TData;\n      }\n\n      resultRef.current = result;\n\n      forceUpdate();\n    },\n    []\n  );\n\n  const observableResult = useSyncExternalStore(\n    React.useCallback(\n      (forceUpdate) => {\n        const subscription = observable.subscribe((result) => {\n          if (!equal(resultRef.current, result)) {\n            updateResult(result, forceUpdate);\n          }\n        });\n\n        return () => {\n          subscription.unsubscribe();\n        };\n      },\n      [observable, updateResult]\n    ),\n    () => resultRef.current || initialResult,\n    () => initialResult\n  );\n\n  // We use useMemo here to make sure the eager methods have a stable identity.\n  const eagerMethods = React.useMemo(() => {\n    const eagerMethods: Record<string, any> = {};\n    for (const key of EAGER_METHODS) {\n      eagerMethods[key] = function (...args: any[]) {\n        invariant(\n          resultRef.current,\n          \"useLazyQuery: '%s' cannot be called before executing the query.\",\n          key\n        );\n\n        // @ts-expect-error this is just to generic to type\n        return observable[key](...args);\n      };\n    }\n\n    return eagerMethods as Pick<\n      useLazyQuery.Result<TData, TVariables>,\n      (typeof EAGER_METHODS)[number]\n    >;\n  }, [observable]);\n\n  React.useEffect(() => {\n    const updatedOptions: Partial<ObservableQuery.Options<TData, TVariables>> =\n      {\n        query,\n        errorPolicy: stableOptions?.errorPolicy,\n        refetchWritePolicy: stableOptions?.refetchWritePolicy,\n        returnPartialData: stableOptions?.returnPartialData,\n        notifyOnNetworkStatusChange: stableOptions?.notifyOnNetworkStatusChange,\n        nextFetchPolicy: options?.nextFetchPolicy,\n        skipPollAttempt: options?.skipPollAttempt,\n      };\n\n    // Wait to apply the changed fetch policy until after the execute\n    // function has been called. The execute function will handle setting the\n    // the fetch policy away from standby for us when called for the first time.\n    if (\n      observable.options.fetchPolicy !== \"standby\" &&\n      stableOptions?.fetchPolicy\n    ) {\n      updatedOptions.fetchPolicy = stableOptions.fetchPolicy;\n    }\n\n    observable.applyOptions(updatedOptions);\n  }, [\n    query,\n    observable,\n    stableOptions,\n    // Ensure inline functions don't suffer from stale closures by checking for\n    // these deps separately. @wry/equality doesn't compare function identity\n    // so `stableOptions` isn't updated when using inline functions.\n    options?.nextFetchPolicy,\n    options?.skipPollAttempt,\n  ]);\n\n  const execute: useLazyQuery.ExecFunction<TData, TVariables> =\n    React.useCallback(\n      (...args) => {\n        invariant(\n          !calledDuringRender(),\n          \"useLazyQuery: 'execute' should not be called during render. To start a query during render, use the 'useQuery' hook.\"\n        );\n\n        const [executeOptions] = args;\n\n        let fetchPolicy = observable.options.fetchPolicy;\n\n        if (fetchPolicy === \"standby\") {\n          fetchPolicy = observable.options.initialFetchPolicy;\n        }\n\n        return observable.reobserve({\n          fetchPolicy,\n          // If `variables` is not given, reset back to empty variables by\n          // ensuring the key exists in options\n          variables: executeOptions?.variables,\n          context: executeOptions?.context ?? {},\n        });\n      },\n      [observable, calledDuringRender]\n    );\n\n  const executeRef = React.useRef(execute);\n  useIsomorphicLayoutEffect(() => {\n    executeRef.current = execute;\n  });\n\n  const stableExecute = React.useCallback<typeof execute>(\n    (...args) => executeRef.current(...args),\n    []\n  );\n\n  const result = React.useMemo(() => {\n    const { partial, ...result } = observableResult;\n\n    return {\n      ...eagerMethods,\n      ...result,\n      client,\n      // eslint-disable-next-line react-hooks/refs\n      previousData: previousDataRef.current,\n      variables: observable.variables,\n      observable,\n      // eslint-disable-next-line react-hooks/refs\n      called: !!resultRef.current,\n    };\n  }, [client, observableResult, eagerMethods, observable]);\n\n  return [stableExecute, result as any];\n}\n\nconst initialResult: ObservableQuery.Result<any> = maybeDeepFreeze({\n  data: undefined,\n  dataState: \"empty\",\n  loading: false,\n  networkStatus: NetworkStatus.ready,\n  partial: true,\n});\n"
  },
  {
    "path": "src/react/hooks/useLoadableQuery.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  DefaultContext,\n  DocumentNode,\n  ErrorPolicy,\n  ObservableQuery,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport type { SubscribeToMoreFunction } from \"@apollo/client\";\nimport { canonicalStringify } from \"@apollo/client/cache\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport type {\n  CacheKey,\n  FetchMoreFunction,\n  RefetchFunction,\n} from \"@apollo/client/react/internal\";\nimport {\n  assertWrappedQueryRef,\n  getSuspenseCache,\n  unwrapQueryRef,\n  updateWrappedQueryRef,\n  wrapQueryRef,\n} from \"@apollo/client/react/internal\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { __use, useDeepMemo, useRenderGuard } from \"./internal/index.js\";\nimport { validateSuspenseHookOptions } from \"./internal/validateSuspenseHookOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\ntype ResetFunction = () => void;\n\nexport declare namespace useLoadableQuery {\n  export type LoadQueryFunction<TVariables extends OperationVariables> = (\n    // Use variadic args to handle cases where TVariables is type `never`, in\n    // which case we don't want to allow a variables argument. In other\n    // words, we don't want to allow variables to be passed as an argument to this\n    // function if the query does not expect variables in the document.\n    ...args: {} extends TVariables ? [variables?: TVariables]\n    : [variables: TVariables]\n  ) => void;\n\n  export type Result<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = [\n    loadQuery: LoadQueryFunction<TVariables>,\n    queryRef: QueryRef<TData, TVariables, TStates> | null,\n    handlers: Handlers<TData, TVariables>,\n  ];\n  export interface Handlers<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */\n    fetchMore: FetchMoreFunction<TData, TVariables>;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */\n    refetch: RefetchFunction<TData, TVariables>;\n    /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n    subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    /**\n     * A function that resets the `queryRef` back to `null`.\n     */\n    reset: ResetFunction;\n  }\n\n  export type FetchPolicy = Extract<\n    WatchQueryFetchPolicy,\n    \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n  >;\n\n  export interface Options {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n    client?: ApolloClient;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: FetchPolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#queryKey:member} */\n    queryKey?: string | number | any[];\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n    refetchWritePolicy?: RefetchWritePolicy;\n\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n    returnPartialData?: boolean;\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useLoadableQuery:function(1)} */\n    export function useLoadableQuery<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options: useLoadableQuery.Options\n    ): useLoadableQuery.Result<TData, TVariables>;\n  }\n}\n\n/**\n * A hook for imperatively loading a query, such as responding to a user\n * interaction.\n *\n * > Refer to the [Suspense - Fetching in response to user interaction](https://www.apollographql.com/docs/react/data/suspense#fetching-in-response-to-user-interaction) section for a more in-depth overview of `useLoadableQuery`.\n *\n * @example\n *\n * ```jsx\n * import { gql, useLoadableQuery } from \"@apollo/client\";\n *\n * const GET_GREETING = gql`\n *   query GetGreeting($language: String!) {\n *     greeting(language: $language) {\n *       message\n *     }\n *   }\n * `;\n *\n * function App() {\n *   const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);\n *\n *   return (\n *     <>\n *       <button onClick={() => loadGreeting({ language: \"english\" })}>\n *         Load greeting\n *       </button>\n *       <Suspense fallback={<div>Loading...</div>}>\n *         {queryRef && <Hello queryRef={queryRef} />}\n *       </Suspense>\n *     </>\n *   );\n * }\n *\n * function Hello({ queryRef }) {\n *   const { data } = useReadQuery(queryRef);\n *\n *   return <div>{data.greeting.message}</div>;\n * }\n * ```\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Options to control how the query is executed.\n * @returns A tuple in the form of `[loadQuery, queryRef, handlers]`\n */\nexport function useLoadableQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLoadableQuery.Options & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): useLoadableQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useLoadableQuery:function(1)} */\nexport function useLoadableQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLoadableQuery.Options & {\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): useLoadableQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useLoadableQuery:function(1)} */\nexport function useLoadableQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLoadableQuery.Options & {\n    returnPartialData: true;\n  }\n): useLoadableQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useLoadableQuery:function(1)} */\nexport function useLoadableQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: useLoadableQuery.Options\n): useLoadableQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\nexport function useLoadableQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useLoadableQuery.Options = {}\n): useLoadableQuery.Result<TData, TVariables> {\n  const client = useApolloClient(options.client);\n  const suspenseCache = getSuspenseCache(client);\n  const watchQueryOptions = useWatchQueryOptions({ client, query, options });\n  const { queryKey = [] } = options;\n\n  const [queryRef, setQueryRef] = React.useState<QueryRef<\n    TData,\n    TVariables,\n    DataState<TData>[\"dataState\"]\n  > | null>(null);\n\n  assertWrappedQueryRef(queryRef);\n\n  const internalQueryRef = queryRef && unwrapQueryRef(queryRef);\n\n  if (queryRef && internalQueryRef?.didChangeOptions(watchQueryOptions)) {\n    const promise = internalQueryRef.applyOptions(watchQueryOptions);\n    updateWrappedQueryRef(queryRef, promise);\n  }\n\n  const calledDuringRender = useRenderGuard();\n\n  const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(\n    (options) => {\n      if (!internalQueryRef) {\n        throw new Error(\n          \"The query has not been loaded. Please load the query.\"\n        );\n      }\n\n      const promise = internalQueryRef.fetchMore(options);\n\n      setQueryRef(wrapQueryRef(internalQueryRef));\n\n      return promise;\n    },\n    [internalQueryRef]\n  );\n\n  const refetch: RefetchFunction<TData, TVariables> = React.useCallback(\n    (options) => {\n      if (!internalQueryRef) {\n        throw new Error(\n          \"The query has not been loaded. Please load the query.\"\n        );\n      }\n\n      const promise = internalQueryRef.refetch(options);\n\n      setQueryRef(wrapQueryRef(internalQueryRef));\n\n      return promise;\n    },\n    [internalQueryRef]\n  );\n\n  const loadQuery: useLoadableQuery.LoadQueryFunction<TVariables> =\n    React.useCallback(\n      (...args) => {\n        invariant(\n          !calledDuringRender(),\n          \"useLoadableQuery: 'loadQuery' should not be called during render. To start a query during render, use the 'useBackgroundQuery' hook.\"\n        );\n\n        const [variables] = args;\n\n        const cacheKey: CacheKey = [\n          query,\n          canonicalStringify(variables),\n          ...([] as any[]).concat(queryKey),\n        ];\n\n        const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n          client.watchQuery({\n            ...watchQueryOptions,\n            variables,\n          } as ApolloClient.WatchQueryOptions<any, any>)\n        );\n\n        setQueryRef(wrapQueryRef(queryRef));\n      },\n      [\n        query,\n        queryKey,\n        suspenseCache,\n        watchQueryOptions,\n        calledDuringRender,\n        client,\n      ]\n    );\n\n  const subscribeToMore: SubscribeToMoreFunction<TData, TVariables> =\n    React.useCallback(\n      (options) => {\n        invariant(\n          internalQueryRef,\n          \"The query has not been loaded. Please load the query.\"\n        );\n\n        return internalQueryRef.observable.subscribeToMore(\n          // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n          options as any as ObservableQuery.SubscribeToMoreOptions<\n            TData,\n            OperationVariables\n          >\n        );\n      },\n      [internalQueryRef]\n    );\n\n  const reset: ResetFunction = React.useCallback(() => {\n    setQueryRef(null);\n  }, []);\n\n  return [loadQuery, queryRef, { fetchMore, refetch, reset, subscribeToMore }];\n}\n\nfunction useWatchQueryOptions<TData, TVariables extends OperationVariables>({\n  client,\n  query,\n  options,\n}: {\n  client: ApolloClient;\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  options: useLoadableQuery.Options;\n}): ApolloClient.WatchQueryOptions<TData, TVariables> {\n  return useDeepMemo<ApolloClient.WatchQueryOptions<TData, TVariables>>(() => {\n    const fetchPolicy =\n      options.fetchPolicy ||\n      client.defaultOptions.watchQuery?.fetchPolicy ||\n      \"cache-first\";\n\n    const watchQueryOptions = {\n      ...options,\n      fetchPolicy,\n      query,\n      notifyOnNetworkStatusChange: false,\n      nextFetchPolicy: void 0,\n    };\n\n    if (__DEV__) {\n      validateSuspenseHookOptions(watchQueryOptions as any);\n    }\n\n    return watchQueryOptions as ApolloClient.WatchQueryOptions<\n      TData,\n      TVariables\n    >;\n  }, [client, options, query]);\n}\n"
  },
  {
    "path": "src/react/hooks/useMutation.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\nimport * as React from \"react\";\n\nimport type {\n  ApolloCache,\n  ApolloClient,\n  DefaultContext,\n  DocumentNode,\n  ErrorLike,\n  ErrorPolicy,\n  InternalRefetchQueriesInclude,\n  MaybeMasked,\n  MutationFetchPolicy,\n  MutationQueryReducersMap,\n  MutationUpdaterFunction,\n  NormalizedExecutionResult,\n  OnQueryUpdated,\n  OperationVariables,\n  Unmasked,\n} from \"@apollo/client\";\nimport type { IgnoreModifier } from \"@apollo/client/cache\";\nimport type { NoInfer, Prettify } from \"@apollo/client/utilities/internal\";\nimport {\n  mergeOptions,\n  preventUnhandledRejection,\n} from \"@apollo/client/utilities/internal\";\n\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\ntype MakeRequiredVariablesOptional<\n  TVariables extends OperationVariables,\n  TConfiguredVariables extends Partial<TVariables>,\n> = Prettify<\n  {\n    [K in keyof TVariables as K extends keyof TConfiguredVariables ? K\n    : never]?: TVariables[K];\n  } & Omit<TVariables, keyof TConfiguredVariables>\n>;\n\nexport declare namespace useMutation {\n  export interface Options<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n    TConfiguredVariables extends Partial<TVariables> = Partial<TVariables>,\n  > {\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#optimisticResponse:member} */\n    optimisticResponse?:\n      | Unmasked<NoInfer<TData>>\n      | ((\n          vars: TVariables,\n          { IGNORE }: { IGNORE: IgnoreModifier }\n        ) => Unmasked<NoInfer<TData>> | IgnoreModifier);\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#updateQueries:member} */\n    updateQueries?: MutationQueryReducersMap<TData>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#refetchQueries:member} */\n    refetchQueries?:\n      | ((\n          result: NormalizedExecutionResult<Unmasked<TData>>\n        ) => InternalRefetchQueriesInclude)\n      | InternalRefetchQueriesInclude;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#awaitRefetchQueries:member} */\n    awaitRefetchQueries?: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#update:member} */\n    update?: MutationUpdaterFunction<TData, TVariables, TCache>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#onQueryUpdated:member} */\n    onQueryUpdated?: OnQueryUpdated<any>;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#errorPolicy:member} */\n    errorPolicy?: ErrorPolicy;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#variables:member} */\n    variables?: Partial<TVariables> & TConfiguredVariables;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#context:member} */\n    context?: DefaultContext;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#fetchPolicy:member} */\n    fetchPolicy?: MutationFetchPolicy;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#keepRootFields:member} */\n    keepRootFields?: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#client:member} */\n    client?: ApolloClient;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#notifyOnNetworkStatusChange:member} */\n    notifyOnNetworkStatusChange?: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#onCompleted:member} */\n    onCompleted?: (\n      data: MaybeMasked<TData>,\n      clientOptions?: Options<TData, TVariables, TCache>\n    ) => void;\n\n    /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#onError:member} */\n    onError?: (\n      error: ErrorLike,\n      clientOptions?: Options<TData, TVariables, TCache>\n    ) => void;\n  }\n\n  export interface Result<TData = unknown> {\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#data:member} */\n    data: MaybeMasked<TData> | null | undefined;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#error:member} */\n    error: ErrorLike | undefined;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#loading:member} */\n    loading: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#called:member} */\n    called: boolean;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#client:member} */\n    client: ApolloClient;\n\n    /** {@inheritDoc @apollo/client!MutationResultDocumentation#reset:member} */\n    reset: () => void;\n  }\n\n  export type ResultTuple<\n    TData,\n    TVariables extends OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n  > = [\n    mutate: MutationFunction<TData, TVariables, TCache>,\n    result: Result<TData>,\n  ];\n\n  export type MutationFunction<\n    TData,\n    TVariables extends OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n  > = (\n    ...[options]: {} extends TVariables ?\n      [\n        options?: MutationFunctionOptions<TData, TVariables, TCache> & {\n          /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#variables:member} */\n          variables?: TVariables;\n        },\n      ]\n    : [\n        options: MutationFunctionOptions<TData, TVariables, TCache> & {\n          /** {@inheritDoc @apollo/client!MutationOptionsDocumentation#variables:member} */\n          variables: TVariables;\n        },\n      ]\n  ) => Promise<ApolloClient.MutateResult<MaybeMasked<TData>>>;\n\n  export type MutationFunctionOptions<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TCache extends ApolloCache = ApolloCache,\n  > = Options<TData, TVariables, TCache> & {\n    /**\n     * {@inheritDoc @apollo/client!MutationOptionsDocumentation#context:member}\n     *\n     * @remarks\n     * When provided as a callback function, the function is called with the\n     * value of `context` provided to the `useMutation` hook.\n     */\n    context?:\n      | DefaultContext\n      | ((hookContext: DefaultContext | undefined) => DefaultContext);\n  };\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useMutation:function(1)} */\n    export function useMutation<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options?: useMutation.Options<TData, TVariables>\n    ): useMutation.ResultTuple<TData, TVariables>;\n  }\n}\n\n/**\n * > Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of `useMutation`.\n *\n * @example\n *\n * ```jsx\n * import { gql, useMutation } from \"@apollo/client\";\n *\n * const ADD_TODO = gql`\n *   mutation AddTodo($type: String!) {\n *     addTodo(type: $type) {\n *       id\n *       type\n *     }\n *   }\n * `;\n *\n * function AddTodo() {\n *   let input;\n *   const [addTodo, { data }] = useMutation(ADD_TODO);\n *\n *   return (\n *     <div>\n *       <form\n *         onSubmit={(e) => {\n *           e.preventDefault();\n *           addTodo({ variables: { type: input.value } });\n *           input.value = \"\";\n *         }}\n *       >\n *         <input\n *           ref={(node) => {\n *             input = node;\n *           }}\n *         />\n *         <button type=\"submit\">Add Todo</button>\n *       </form>\n *     </div>\n *   );\n * }\n * ```\n *\n * @param mutation - A GraphQL mutation document parsed into an AST by `gql`.\n * @param options - Options to control how the mutation is executed.\n * @returns A tuple in the form of `[mutate, result]`\n */\nexport function useMutation<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TCache extends ApolloCache = ApolloCache,\n  TConfiguredVariables extends Partial<TVariables> = {},\n>(\n  mutation: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: useMutation.Options<\n    NoInfer<TData>,\n    NoInfer<TVariables>,\n    TCache,\n    {\n      [K in keyof TConfiguredVariables]: K extends keyof TVariables ?\n        TConfiguredVariables[K]\n      : never;\n    }\n  >\n): useMutation.ResultTuple<\n  TData,\n  MakeRequiredVariablesOptional<TVariables, TConfiguredVariables>,\n  TCache\n> {\n  const client = useApolloClient(options?.client);\n  const [result, setResult] = React.useState<\n    Omit<useMutation.Result<TData>, \"reset\">\n  >(() => createInitialResult(client));\n\n  const ref = React.useRef({\n    result,\n    mutationId: 0,\n    isMounted: true,\n    client,\n    mutation,\n    options,\n  });\n\n  useIsomorphicLayoutEffect(() => {\n    Object.assign(ref.current, { client, options, mutation });\n  });\n\n  const execute = React.useCallback(\n    (\n      executeOptions: useMutation.MutationFunctionOptions<\n        TData,\n        TVariables,\n        TCache\n      > = {} as useMutation.MutationFunctionOptions<TData, TVariables, TCache>\n    ) => {\n      const { options, mutation } = ref.current;\n      const baseOptions = { ...options, mutation };\n      const client = executeOptions.client || ref.current.client;\n      const context =\n        typeof executeOptions.context === \"function\" ?\n          executeOptions.context(options?.context)\n        : executeOptions.context;\n\n      if (!ref.current.result.loading && ref.current.isMounted) {\n        setResult(\n          (ref.current.result = {\n            loading: true,\n            error: undefined,\n            data: undefined,\n            called: true,\n            client,\n          })\n        );\n      }\n\n      const mutationId = ++ref.current.mutationId;\n      const clientOptions = mergeOptions(baseOptions, {\n        ...executeOptions,\n        context,\n      } as any);\n\n      return preventUnhandledRejection(\n        client\n          .mutate(\n            clientOptions as ApolloClient.MutateOptions<\n              TData,\n              OperationVariables\n            >\n          )\n          .then(\n            (response) => {\n              const { data, error } = response;\n\n              const onError =\n                executeOptions.onError || ref.current.options?.onError;\n\n              if (error && onError) {\n                onError(error, clientOptions);\n              }\n\n              if (mutationId === ref.current.mutationId) {\n                const result = {\n                  called: true,\n                  loading: false,\n                  data,\n                  error,\n                  client,\n                };\n\n                if (\n                  ref.current.isMounted &&\n                  !equal(ref.current.result, result)\n                ) {\n                  setResult((ref.current.result = result));\n                }\n              }\n\n              const onCompleted =\n                executeOptions.onCompleted || ref.current.options?.onCompleted;\n\n              if (!error) {\n                onCompleted?.(response.data!, clientOptions);\n              }\n\n              return response;\n            },\n            (error) => {\n              if (\n                mutationId === ref.current.mutationId &&\n                ref.current.isMounted\n              ) {\n                const result = {\n                  loading: false,\n                  error,\n                  data: void 0,\n                  called: true,\n                  client,\n                };\n\n                if (!equal(ref.current.result, result)) {\n                  setResult((ref.current.result = result));\n                }\n              }\n\n              const onError =\n                executeOptions.onError || ref.current.options?.onError;\n\n              if (onError) {\n                onError(error, clientOptions);\n              }\n\n              throw error;\n            }\n          )\n      );\n    },\n    []\n  );\n\n  const reset = React.useCallback(() => {\n    if (ref.current.isMounted) {\n      const result = createInitialResult(ref.current.client);\n      Object.assign(ref.current, { mutationId: 0, result });\n      setResult(result);\n    }\n  }, []);\n\n  React.useEffect(() => {\n    const current = ref.current;\n    current.isMounted = true;\n\n    return () => {\n      current.isMounted = false;\n    };\n  }, []);\n\n  return [execute as any, { reset, ...result }];\n}\n\nfunction createInitialResult(client: ApolloClient) {\n  return {\n    data: undefined,\n    error: undefined,\n    called: false,\n    loading: false,\n    client,\n  };\n}\n"
  },
  {
    "path": "src/react/hooks/useQuery.ts",
    "content": "/**\n * Function parameters in this file try to follow a common order for the sake of\n * readability and consistency. The order is as follows:\n *\n * resultData\n * observable\n * client\n * query\n * options\n * watchQueryOptions\n * makeWatchQueryOptions\n */\n/**  */\nimport { equal } from \"@wry/equality\";\nimport * as React from \"react\";\nimport { asapScheduler, observeOn } from \"rxjs\";\n\nimport type {\n  DataState,\n  DefaultContext,\n  DocumentNode,\n  ErrorLike,\n  ErrorPolicy,\n  GetDataState,\n  InternalTypes,\n  ObservableQuery,\n  OperationVariables,\n  RefetchWritePolicy,\n  SubscribeToMoreFunction,\n  TypedDocumentNode,\n  UpdateQueryMapFn,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport type { ApolloClient } from \"@apollo/client\";\nimport { NetworkStatus } from \"@apollo/client\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\nimport {\n  maybeDeepFreeze,\n  mergeOptions,\n  variablesUnknownSymbol,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { SkipToken } from \"./constants.js\";\nimport { skipToken } from \"./constants.js\";\nimport { useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\nexport declare namespace useQuery {\n  import _self = useQuery;\n  export namespace Base {\n    export interface Options<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    > {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n      fetchPolicy?: WatchQueryFetchPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#nextFetchPolicy:member} */\n      nextFetchPolicy?:\n        | WatchQueryFetchPolicy\n        | ((\n            this: ApolloClient.WatchQueryOptions<TData, TVariables>,\n            currentFetchPolicy: WatchQueryFetchPolicy,\n            context: InternalTypes.NextFetchPolicyContext<TData, TVariables>\n          ) => WatchQueryFetchPolicy);\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#initialFetchPolicy:member} */\n\n      initialFetchPolicy?: WatchQueryFetchPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n      refetchWritePolicy?: RefetchWritePolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n      errorPolicy?: ErrorPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#pollInterval:member} */\n      pollInterval?: number;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#notifyOnNetworkStatusChange:member} */\n      notifyOnNetworkStatusChange?: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n      returnPartialData?: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skipPollAttempt:member} */\n      skipPollAttempt?: () => boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#ssr:member} */\n      ssr?: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n      client?: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n      context?: DefaultContext;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#skip:member} */\n      skip?: boolean;\n    }\n  }\n  export type Options<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    namespace useQuery {\n      export interface Options<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Options<TData, TVariables>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n    }\n  }\n\n  export namespace Base {\n    export interface Result<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n      TReturnVariables extends OperationVariables = TVariables,\n    > {\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#client:member} */\n      client: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#observable:member} */\n      observable: ObservableQuery<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#previousData:member} */\n      previousData?: MaybeMasked<TData>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n      error?: ErrorLike;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */\n      loading: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n      networkStatus: NetworkStatus;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#startPolling:member} */\n      startPolling: (pollInterval: number) => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#stopPolling:member} */\n      stopPolling: () => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#subscribeToMore:member} */\n      subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#updateQuery:member} */\n      updateQuery: (mapFn: UpdateQueryMapFn<TData, TVariables>) => void;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member} */\n      refetch: (\n        variables?: Partial<TVariables>\n      ) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#variables:member} */\n      variables: TReturnVariables;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member} */\n      fetchMore: <\n        TFetchData = TData,\n        TFetchVars extends OperationVariables = TVariables,\n      >(\n        fetchMoreOptions: ObservableQuery.FetchMoreOptions<\n          TData,\n          TVariables,\n          TFetchData,\n          TFetchVars\n        >\n      ) => Promise<ApolloClient.QueryResult<MaybeMasked<TFetchData>>>;\n    }\n  }\n  export type Result<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n    TReturnVariables extends OperationVariables = TVariables,\n  > = Base.Result<TData, TVariables, TReturnVariables> &\n    GetDataState<MaybeMasked<TData>, TStates>;\n\n  export namespace DocumentationTypes {\n    namespace useQuery {\n      export interface Result<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Result<TData, TVariables>,\n          UtilityDocumentationTypes.DataState<TData> {}\n    }\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\n    export function useQuery<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options: useQuery.Options<TData, TVariables>\n    ): useQuery.Result<TData, TVariables>;\n  }\n}\n\nconst lastWatchOptions = Symbol();\n\ninterface ObsQueryWithMeta<TData, TVariables extends OperationVariables>\n  extends ObservableQuery<TData, TVariables> {\n  [lastWatchOptions]?: Readonly<\n    ApolloClient.WatchQueryOptions<TData, TVariables>\n  >;\n}\n\ninterface InternalResult<TData> {\n  // These members are populated by getCurrentResult and setResult, and it's\n  // okay/normal for them to be initially undefined.\n  current: ObservableQuery.Result<TData>;\n  previousData?: undefined | MaybeMasked<TData>;\n\n  // Track current variables separately in case a call to e.g. `refetch(newVars)`\n  // causes an emit that is deeply equal to the current result. This lets us\n  // compare if we should force rerender due to changed variables\n  variables: OperationVariables;\n}\n\ninterface InternalState<TData, TVariables extends OperationVariables> {\n  client: ReturnType<typeof useApolloClient>;\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  observable: ObsQueryWithMeta<TData, TVariables>;\n  resultData: InternalResult<TData>;\n}\n\n/**\n * A hook for executing queries in an Apollo application.\n *\n * To run a query within a React component, call `useQuery` and pass it a GraphQL query document.\n *\n * When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, `dataState`, and `data` properties you can use to render your UI.\n *\n * > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.\n *\n * @example\n *\n * ```jsx\n * import { gql } from \"@apollo/client\";\n * import { useQuery } from \"@apollo/client/react\";\n *\n * const GET_GREETING = gql`\n *   query GetGreeting($language: String!) {\n *     greeting(language: $language) {\n *       message\n *     }\n *   }\n * `;\n *\n * function Hello() {\n *   const { loading, error, data } = useQuery(GET_GREETING, {\n *     variables: { language: \"english\" },\n *   });\n *   if (loading) return <p>Loading ...</p>;\n *   return <h1>Hello {data.greeting.message}!</h1>;\n * }\n * ```\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - Options to control how the query is executed.\n * @returns Query result object\n */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n    returnPartialData: true;\n  }\n): useQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: SkipToken\n): useQuery.Result<TData, TVariables, \"empty\", Record<string, never>>;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n        returnPartialData: true;\n      })\n): useQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\",\n  Partial<TVariables>\n>;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n    returnPartialData: boolean;\n  }\n): useQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | (useQuery.Options<NoInfer<TData>, NoInfer<TVariables>> & {\n        returnPartialData: boolean;\n      })\n): useQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\" | \"partial\",\n  Partial<TVariables>\n>;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [options?: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]\n  : [options: useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]\n): useQuery.Result<TData, TVariables, \"empty\" | \"complete\" | \"streaming\">;\n\n/** {@inheritDoc @apollo/client/react!useQuery:function(1)} */\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [\n      options?:\n        | SkipToken\n        | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,\n    ]\n  : [options: SkipToken | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]\n): useQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"complete\" | \"streaming\",\n  Partial<TVariables>\n>;\n\nexport function useQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [\n      options?:\n        | SkipToken\n        | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,\n    ]\n  : [options: SkipToken | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>]\n): useQuery.Result<TData, TVariables> {\n  \"use no memo\";\n  return wrapHook(\n    \"useQuery\",\n    useQuery_,\n    useApolloClient(typeof options === \"object\" ? options.client : undefined)\n  )(query, options);\n}\n\nfunction useQuery_<TData, TVariables extends OperationVariables>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | useQuery.Options<\n        NoInfer<TData>,\n        NoInfer<TVariables>\n      > = {} as useQuery.Options<TData, TVariables>\n): useQuery.Result<TData, TVariables> {\n  const client = useApolloClient(\n    typeof options === \"object\" ? options.client : undefined\n  );\n  const { ssr } = typeof options === \"object\" ? options : {};\n\n  const watchQueryOptions = useOptions(\n    query,\n    options,\n    client.defaultOptions.watchQuery\n  );\n\n  function createState(\n    previous?: InternalState<TData, TVariables>\n  ): InternalState<TData, TVariables> {\n    const observable = client.watchQuery(watchQueryOptions);\n\n    return {\n      client,\n      query,\n      observable,\n      resultData: {\n        current: observable.getCurrentResult(),\n        // Reuse previousData from previous InternalState (if any) to provide\n        // continuity of previousData even if/when the query or client changes.\n        previousData: previous?.resultData.current.data as TData,\n        variables: observable.variables,\n      },\n    };\n  }\n\n  let [state, setState] = React.useState(createState);\n\n  if (client !== state.client || query !== state.query) {\n    // If the client or query have changed, we need to create a new InternalState.\n    // This will trigger a re-render with the new state, but it will also continue\n    // to run the current render function to completion.\n    // Since we sometimes trigger some side-effects in the render function, we\n    // re-assign `state` to the new state to ensure that those side-effects are\n    // triggered with the new state.\n    setState((state = createState(state)));\n  }\n\n  const { observable, resultData } = state;\n\n  useInitialFetchPolicyIfNecessary<TData, TVariables>(\n    watchQueryOptions,\n    observable\n  );\n\n  useResubscribeIfNecessary<TData, TVariables>(\n    resultData, // might get mutated during render\n    observable, // might get mutated during render\n    watchQueryOptions\n  );\n\n  const result = useResult<TData, TVariables>(observable, resultData, ssr);\n\n  const obsQueryFields = React.useMemo(\n    () => ({\n      refetch: observable.refetch.bind(observable),\n      fetchMore: observable.fetchMore.bind(observable),\n      updateQuery: observable.updateQuery.bind(observable),\n      startPolling: observable.startPolling.bind(observable),\n      stopPolling: observable.stopPolling.bind(observable),\n      subscribeToMore: observable.subscribeToMore.bind(observable),\n    }),\n    [observable]\n  );\n\n  const previousData = resultData.previousData;\n  return React.useMemo(() => {\n    const { partial, ...rest } = result;\n\n    return {\n      ...rest,\n      client,\n      observable,\n      variables: observable.variables,\n      previousData,\n      ...obsQueryFields,\n    };\n  }, [result, client, observable, previousData, obsQueryFields]);\n}\n\nconst fromSkipToken = Symbol();\n\nfunction useOptions<TData, TVariables extends OperationVariables>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: SkipToken | useQuery.Options<NoInfer<TData>, NoInfer<TVariables>>,\n  defaultOptions: Partial<ApolloClient.WatchQueryOptions<any, any>> | undefined\n): ApolloClient.WatchQueryOptions<TData, TVariables> {\n  return useDeepMemo<ApolloClient.WatchQueryOptions<TData, TVariables>>(() => {\n    if (options === skipToken) {\n      const opts: ApolloClient.WatchQueryOptions<TData, TVariables> = {\n        ...mergeOptions(defaultOptions as any, {\n          query,\n          fetchPolicy: \"standby\",\n        }),\n        [variablesUnknownSymbol]: true,\n      };\n      (opts as any)[fromSkipToken] = true;\n\n      return opts;\n    }\n\n    const watchQueryOptions: ApolloClient.WatchQueryOptions<TData, TVariables> =\n      mergeOptions(defaultOptions as any, { ...options, query });\n\n    if (options.skip) {\n      watchQueryOptions.initialFetchPolicy =\n        options.initialFetchPolicy || options.fetchPolicy;\n      watchQueryOptions.fetchPolicy = \"standby\";\n    }\n\n    return watchQueryOptions;\n  }, [query, options, defaultOptions]);\n}\n\nfunction useInitialFetchPolicyIfNecessary<\n  TData,\n  TVariables extends OperationVariables,\n>(\n  watchQueryOptions: ApolloClient.WatchQueryOptions<TData, TVariables>,\n  observable: ObsQueryWithMeta<TData, TVariables>\n) {\n  \"use no memo\";\n  if (!watchQueryOptions.fetchPolicy) {\n    watchQueryOptions.fetchPolicy = observable.options.initialFetchPolicy;\n  }\n}\n\nfunction useResult<TData, TVariables extends OperationVariables>(\n  observable: ObsQueryWithMeta<TData, TVariables>,\n  resultData: InternalResult<TData>,\n  ssr: boolean | undefined\n) {\n  \"use no memo\";\n  const fetchPolicy = observable.options.fetchPolicy;\n  return useSyncExternalStore(\n    React.useCallback(\n      (handleStoreChange) => {\n        const subscription = observable\n          // We use the asapScheduler here to prevent issues with trying to\n          // update in the middle of a render. `reobserve` is kicked off in the\n          // middle of a render and because RxJS emits values synchronously,\n          // its possible for this `handleStoreChange` to be called in that same\n          // render. This allows the render to complete before trying to emit a\n          // new value.\n          .pipe(observeOn(asapScheduler))\n          .subscribe((result) => {\n            const previous = resultData.current;\n\n            if (\n              // Avoid rerendering if the result is the same\n              equal(previous, result) &&\n              // Force rerender if the value was emitted because variables\n              // changed, such as when calling `refetch(newVars)` which returns\n              // the same data when `notifyOnNetworkStatusChange` is `false`.\n              equal(resultData.variables, observable.variables)\n            ) {\n              return;\n            }\n\n            resultData.variables = observable.variables;\n\n            if (previous.data && !equal(previous.data, result.data)) {\n              resultData.previousData = previous.data as TData;\n            }\n\n            resultData.current = result;\n            handleStoreChange();\n          });\n\n        // Do the \"unsubscribe\" with a short delay.\n        // This way, an existing subscription can be reused without an additional\n        // request if \"unsubscribe\"  and \"resubscribe\" to the same ObservableQuery\n        // happen in very fast succession.\n        return () => {\n          setTimeout(() => subscription.unsubscribe());\n        };\n      },\n\n      [observable, resultData]\n    ),\n    () => resultData.current,\n    () =>\n      (\n        (fetchPolicy !== \"standby\" && ssr === false) ||\n        fetchPolicy === \"no-cache\"\n      ) ?\n        useQuery.ssrDisabledResult\n      : resultData.current\n  );\n}\n\n// this hook is not compatible with any rules of React, and there's no good way to rewrite it.\n// it should stay a separate hook that will not be optimized by the compiler\nfunction useResubscribeIfNecessary<\n  TData,\n  TVariables extends OperationVariables,\n>(\n  /** this hook will mutate properties on `resultData` */\n  resultData: InternalResult<TData>,\n  /** this hook will mutate properties on `observable` */\n  observable: ObsQueryWithMeta<TData, TVariables>,\n  watchQueryOptions: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>\n) {\n  \"use no memo\";\n  if (\n    observable[lastWatchOptions] &&\n    !equal(observable[lastWatchOptions], watchQueryOptions)\n  ) {\n    // If skipToken was used to generate options, we won't know the correct\n    // initialFetchPolicy until the hook is rerendered with real options, so we\n    // set it the next time we get real options\n    if (\n      (observable[lastWatchOptions] as any)[fromSkipToken] &&\n      !watchQueryOptions.initialFetchPolicy\n    ) {\n      (watchQueryOptions.initialFetchPolicy as any) =\n        watchQueryOptions.fetchPolicy;\n    }\n    // Though it might be tempting to postpone this reobserve call to the\n    // useEffect block, we need getCurrentResult to return an appropriate\n    // loading:true result synchronously (later within the same call to\n    // useQuery). Since we already have this.observable here (not true for\n    // the very first call to useQuery), we are not initiating any new\n    // subscriptions, though it does feel less than ideal that reobserve\n    // (potentially) kicks off a network request (for example, when the\n    // variables have changed), which is technically a side-effect.\n    if (shouldReobserve(observable[lastWatchOptions], watchQueryOptions)) {\n      observable.reobserve(watchQueryOptions);\n    } else {\n      observable.applyOptions(watchQueryOptions);\n    }\n\n    // Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,\n    // but save the current data as this.previousData, just like setResult\n    // usually does.\n    const result = observable.getCurrentResult();\n\n    if (!equal(result.data, resultData.current.data)) {\n      resultData.previousData = (resultData.current.data ||\n        (resultData.previousData as TData)) as TData;\n    }\n    resultData.current = result;\n    resultData.variables = observable.variables;\n  }\n  observable[lastWatchOptions] = watchQueryOptions;\n}\n\nfunction shouldReobserve<TData, TVariables extends OperationVariables>(\n  previousOptions: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>,\n  options: Readonly<ApolloClient.WatchQueryOptions<TData, TVariables>>\n) {\n  return (\n    previousOptions.query !== options.query ||\n    !equal(previousOptions.variables, options.variables) ||\n    (previousOptions.fetchPolicy !== options.fetchPolicy &&\n      (options.fetchPolicy === \"standby\" ||\n        previousOptions.fetchPolicy === \"standby\"))\n  );\n}\n\nuseQuery.ssrDisabledResult = maybeDeepFreeze({\n  loading: true,\n  data: void 0 as any,\n  dataState: \"empty\",\n  error: void 0,\n  networkStatus: NetworkStatus.loading,\n  partial: true,\n}) satisfies ObservableQuery.Result<any> as ObservableQuery.Result<any>;\n"
  },
  {
    "path": "src/react/hooks/useQueryRefHandlers.ts",
    "content": "import * as React from \"react\";\n\nimport type { DataState, OperationVariables } from \"@apollo/client\";\nimport type { SubscribeToMoreFunction } from \"@apollo/client\";\nimport type { ApolloClient } from \"@apollo/client\";\nimport type { ObservableQuery } from \"@apollo/client\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport type {\n  FetchMoreFunction,\n  RefetchFunction,\n} from \"@apollo/client/react/internal\";\nimport {\n  assertWrappedQueryRef,\n  getWrappedPromise,\n  unwrapQueryRef,\n  updateWrappedQueryRef,\n  wrapQueryRef,\n} from \"@apollo/client/react/internal\";\n\nimport { wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\nexport declare namespace useQueryRefHandlers {\n  export interface Result<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    /** {@inheritDoc @apollo/client!ObservableQuery#refetch:member(1)} */\n    refetch: RefetchFunction<TData, TVariables>;\n    /** {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)} */\n    fetchMore: FetchMoreFunction<TData, TVariables>;\n    /** {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)} */\n    subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useQueryRefHandlers:function(1)} */\n    export function useQueryRefHandlers<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      queryRef: QueryRef<TData, TVariables>\n    ): useQueryRefHandlers.Result<TData, TVariables>;\n  }\n}\n\n/**\n * A React hook that returns a `refetch` and `fetchMore` function for a given\n * `queryRef`.\n *\n * This is useful to get access to handlers for a `queryRef` that was created by\n * `createQueryPreloader` or when the handlers for a `queryRef` produced in\n * a different component are inaccessible.\n *\n * @example\n *\n * ```tsx\n * const MyComponent({ queryRef }) {\n *   const { refetch, fetchMore } = useQueryRefHandlers(queryRef);\n *\n *   // ...\n * }\n * ```\n *\n * @param queryRef - A `QueryRef` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.\n */\nexport function useQueryRefHandlers<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  queryRef: QueryRef<TData, TVariables, DataState<TData>[\"dataState\"]>\n): useQueryRefHandlers.Result<TData, TVariables> {\n  \"use no memo\";\n  const unwrapped = unwrapQueryRef(queryRef);\n  const clientOrObsQuery = useApolloClient(\n    unwrapped ?\n      // passing an `ObservableQuery` is not supported by the types, but it will\n      // return any truthy value that is passed in as an override so we cast the result\n      (unwrapped[\"observable\"] as any)\n    : undefined\n  ) as ApolloClient | ObservableQuery<TData>;\n\n  return wrapHook(\n    \"useQueryRefHandlers\",\n    useQueryRefHandlers_,\n    clientOrObsQuery\n  )(queryRef);\n}\n\nfunction useQueryRefHandlers_<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  queryRef: QueryRef<TData, TVariables, DataState<TData>[\"dataState\"]>\n): useQueryRefHandlers.Result<TData, TVariables> {\n  assertWrappedQueryRef(queryRef);\n  const [previousQueryRef, setPreviousQueryRef] = React.useState(queryRef);\n  const [wrappedQueryRef, setWrappedQueryRef] = React.useState(queryRef);\n  const internalQueryRef = unwrapQueryRef(queryRef);\n\n  // To ensure we can support React transitions, this hook needs to manage the\n  // queryRef state and apply React's state value immediately to the existing\n  // queryRef since this hook doesn't return the queryRef directly\n  if (previousQueryRef !== queryRef) {\n    setPreviousQueryRef(queryRef);\n    setWrappedQueryRef(queryRef);\n  } else {\n    updateWrappedQueryRef(queryRef, getWrappedPromise(wrappedQueryRef));\n  }\n\n  const refetch: RefetchFunction<TData, TVariables> = React.useCallback(\n    (variables) => {\n      const promise = internalQueryRef.refetch(variables);\n\n      setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n      return promise;\n    },\n    [internalQueryRef]\n  );\n\n  const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(\n    (options) => {\n      const promise = internalQueryRef.fetchMore(\n        options as ObservableQuery.FetchMoreOptions<any, any>\n      );\n\n      setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n      return promise;\n    },\n    [internalQueryRef]\n  );\n\n  return {\n    refetch,\n    fetchMore,\n    // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n    subscribeToMore: internalQueryRef.observable\n      .subscribeToMore as SubscribeToMoreFunction<TData, TVariables>,\n  };\n}\n"
  },
  {
    "path": "src/react/hooks/useReactiveVar.ts",
    "content": "import * as React from \"react\";\n\nimport type { ReactiveVar } from \"@apollo/client\";\n\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\n/**\n * Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.\n *\n * @example\n *\n * ```jsx\n * import { makeVar } from \"@apollo/client\";\n * import { useReactiveVar } from \"@apollo/client/react\";\n * export const cartItemsVar = makeVar([]);\n *\n * export function Cart() {\n *   const cartItems = useReactiveVar(cartItemsVar);\n *   // ...\n * }\n * ```\n *\n * @param rv - A reactive variable.\n * @returns The current value of the reactive variable.\n */\nexport function useReactiveVar<T>(rv: ReactiveVar<T>): T {\n  return useSyncExternalStore(\n    React.useCallback(\n      (update) => {\n        // By reusing the same onNext function in the nested call to\n        // rv.onNextChange(onNext), we can keep using the initial clean-up function\n        // returned by rv.onNextChange(function onNext(v){...}), without having to\n        // register the new clean-up function (returned by the nested\n        // rv.onNextChange(onNext)) with yet another callback.\n        return rv.onNextChange(function onNext() {\n          update();\n          rv.onNextChange(onNext);\n        });\n      },\n      [rv]\n    ),\n    rv,\n    rv\n  );\n}\n"
  },
  {
    "path": "src/react/hooks/useReadQuery.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  ErrorLike,\n  GetDataState,\n  NetworkStatus,\n  ObservableQuery,\n} from \"@apollo/client\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  assertWrappedQueryRef,\n  getWrappedPromise,\n  unwrapQueryRef,\n  updateWrappedQueryRef,\n} from \"@apollo/client/react/internal\";\nimport type { DocumentationTypes as UtilityDocumentationTypes } from \"@apollo/client/utilities/internal\";\n\nimport { __use, wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\nexport declare namespace useReadQuery {\n  export namespace Base {\n    export interface Result<TData = unknown> {\n      /**\n       * {@inheritDoc @apollo/client!QueryResultDocumentation#error:member}\n       *\n       * This property can be ignored when using the default `errorPolicy` or an\n       * `errorPolicy` of `none`. The hook will throw the error instead of setting\n       * this property.\n       */\n      error: ErrorLike | undefined;\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n      networkStatus: NetworkStatus;\n    }\n  }\n  export type Result<\n    TData = unknown,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = Base.Result<TData> & GetDataState<MaybeMasked<TData>, TStates>;\n\n  export namespace DocumentationTypes {\n    namespace useReadQuery {\n      export interface Result<TData = unknown>\n        extends Base.Result<TData>,\n          UtilityDocumentationTypes.DataState<TData> {}\n    }\n\n    /** {@inheritDoc @apollo/client/react!useReadQuery:function(1)} */\n    export function useReadQuery<TData>(\n      queryRef: QueryRef<TData>\n    ): useReadQuery.Result<TData>;\n  }\n}\n\n/**\n * For a detailed explanation of `useReadQuery`, see the [fetching with Suspense reference](https://www.apollographql.com/docs/react/data/suspense#avoiding-request-waterfalls).\n *\n * @param queryRef - The `QueryRef` that was generated via `useBackgroundQuery`.\n * @returns An object containing the query result data, error, and network status.\n *\n * @example\n *\n * ```jsx\n * import { Suspense } from \"react\";\n * import { useBackgroundQuery, useReadQuery } from \"@apollo/client\";\n *\n * function Parent() {\n *   const [queryRef] = useBackgroundQuery(query);\n *\n *   return (\n *     <Suspense fallback={<div>Loading...</div>}>\n *       <Child queryRef={queryRef} />\n *     </Suspense>\n *   );\n * }\n *\n * function Child({ queryRef }) {\n *   const { data } = useReadQuery(queryRef);\n *\n *   return <div>{data.name}</div>;\n * }\n * ```\n */\nexport function useReadQuery<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: QueryRef<TData, any, TStates>\n): useReadQuery.Result<TData, TStates> {\n  \"use no memo\";\n  const unwrapped = unwrapQueryRef(queryRef);\n  const clientOrObsQuery = useApolloClient(\n    unwrapped ?\n      // passing an `ObservableQuery` is not supported by the types, but it will\n      // return any truthy value that is passed in as an override so we cast the result\n      (unwrapped[\"observable\"] as any)\n    : undefined\n  ) as ApolloClient | ObservableQuery<TData>;\n\n  return wrapHook(\"useReadQuery\", useReadQuery_, clientOrObsQuery)(queryRef);\n}\n\nfunction useReadQuery_<TData, TStates extends DataState<TData>[\"dataState\"]>(\n  queryRef: QueryRef<TData, any, TStates>\n): useReadQuery.Result<TData, TStates> {\n  assertWrappedQueryRef(queryRef);\n  const internalQueryRef = React.useMemo(\n    () => unwrapQueryRef(queryRef),\n    [queryRef]\n  );\n\n  const getPromise = React.useCallback(\n    () => getWrappedPromise(queryRef),\n    [queryRef]\n  );\n\n  if (internalQueryRef.disposed) {\n    internalQueryRef.reinitialize();\n    updateWrappedQueryRef(queryRef, internalQueryRef.promise);\n  }\n\n  React.useEffect(() => internalQueryRef.retain(), [internalQueryRef]);\n\n  const promise = useSyncExternalStore(\n    React.useCallback(\n      (forceUpdate) => {\n        return internalQueryRef.listen((promise) => {\n          updateWrappedQueryRef(queryRef, promise);\n          forceUpdate();\n        });\n      },\n      [internalQueryRef, queryRef]\n    ),\n    getPromise,\n    getPromise\n  );\n\n  const result = __use(promise);\n\n  return React.useMemo(() => {\n    return {\n      data: result.data,\n      dataState: result.dataState,\n      networkStatus: result.networkStatus,\n      error: result.error,\n    } as useReadQuery.Result<TData, TStates>;\n  }, [result]);\n}\n"
  },
  {
    "path": "src/react/hooks/useSubscription.ts",
    "content": "import type { TypedDocumentNode } from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\nimport type { DocumentNode } from \"graphql\";\nimport * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DefaultContext,\n  ErrorLike,\n  ErrorPolicy,\n  FetchPolicy,\n  OperationVariables,\n} from \"@apollo/client\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { DocumentationTypes as UtilityDocumentationTypes } from \"@apollo/client/utilities/internal\";\nimport type {\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { useDeepMemo } from \"./internal/useDeepMemo.js\";\nimport { useIsomorphicLayoutEffect } from \"./internal/useIsomorphicLayoutEffect.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\nexport declare namespace useSubscription {\n  import _self = useSubscription;\n  export namespace Base {\n    export interface Options<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    > {\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#fetchPolicy:member} */\n      fetchPolicy?: FetchPolicy;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#errorPolicy:member} */\n      errorPolicy?: ErrorPolicy;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#shouldResubscribe:member} */\n      shouldResubscribe?:\n        | boolean\n        | ((options: Options<TData, TVariables>) => boolean);\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#client:member} */\n      client?: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#skip:member} */\n      skip?: boolean;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#context:member} */\n      context?: DefaultContext;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#extensions:member} */\n      extensions?: Record<string, any>;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#onComplete:member} */\n      onComplete?: () => void;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#onData:member} */\n      onData?: (options: OnDataOptions<TData>) => any;\n\n      /** {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#onError:member} */\n      onError?: (error: ErrorLike) => void;\n\n      /**\n       * {@inheritDoc @apollo/client!SubscriptionOptionsDocumentation#ignoreResults:member}\n       * @defaultValue `false`\n       */\n      ignoreResults?: boolean;\n    }\n  }\n\n  export type Options<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  > = Base.Options<TData, TVariables> & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    namespace useSubscription {\n      export interface Options<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Options<TData, TVariables>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n    }\n  }\n\n  export interface Result<TData = unknown> {\n    /** {@inheritDoc @apollo/client!SubscriptionResultDocumentation#loading:member} */\n    loading: boolean;\n\n    /** {@inheritDoc @apollo/client!SubscriptionResultDocumentation#data:member} */\n    data?: MaybeMasked<TData>;\n\n    /** {@inheritDoc @apollo/client!SubscriptionResultDocumentation#error:member} */\n    error?: ErrorLike;\n\n    /**\n     * A function that when called will disconnect and reconnect the connection\n     * to the subscription. If the subscription is deduplicated, this will\n     * restart the connection for all deduplicated subscriptions.\n     */\n    restart: () => void;\n  }\n\n  export namespace DocumentationTypes {\n    namespace useSubscription {\n      export interface Result<TData = unknown> extends _self.Result<TData> {}\n    }\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useSubscription:function(1)} */\n    export function useSubscription<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      options?: useSubscription.Options<TData, TVariables>\n    ): useSubscription.Result<TData>;\n  }\n\n  export type OnDataResult<TData = unknown> = Omit<Result<TData>, \"restart\">;\n\n  export interface OnDataOptions<TData = unknown> {\n    client: ApolloClient;\n    data: OnDataResult<TData>;\n  }\n\n  export interface OnSubscriptionDataOptions<TData = unknown> {\n    client: ApolloClient;\n    subscriptionData: OnDataResult<TData>;\n  }\n}\n\n/**\n * > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.\n *\n * @example\n *\n * ```jsx\n * const COMMENTS_SUBSCRIPTION = gql`\n *   subscription OnCommentAdded($repoFullName: String!) {\n *     commentAdded(repoFullName: $repoFullName) {\n *       id\n *       content\n *     }\n *   }\n * `;\n *\n * function DontReadTheComments({ repoFullName }) {\n *   const {\n *     data: { commentAdded },\n *     loading,\n *   } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });\n *   return <h4>New comment: {!loading && commentAdded.content}</h4>;\n * }\n * ```\n *\n * @remarks\n *\n * #### Consider using `onData` instead of `useEffect`\n *\n * If you want to react to incoming data, please use the `onData` option instead of `useEffect`.\n * State updates you make inside a `useEffect` hook might cause additional rerenders, and `useEffect` is mostly meant for side effects of rendering, not as an event handler.\n * State updates made in an event handler like `onData` might - depending on the React version - be batched and cause only a single rerender.\n *\n * Consider the following component:\n *\n * ```jsx\n * export function Subscriptions() {\n *   const { data, error, loading } = useSubscription(query);\n *   const [accumulatedData, setAccumulatedData] = useState([]);\n *\n *   useEffect(() => {\n *     setAccumulatedData((prev) => [...prev, data]);\n *   }, [data]);\n *\n *   return (\n *     <>\n *       {loading && <p>Loading...</p>}\n *       {JSON.stringify(accumulatedData, undefined, 2)}\n *     </>\n *   );\n * }\n * ```\n *\n * Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:\n *\n * ```jsx\n * export function Subscriptions() {\n *   const [accumulatedData, setAccumulatedData] = useState([]);\n *   const { data, error, loading } = useSubscription(query, {\n *     onData({ data }) {\n *       setAccumulatedData((prev) => [...prev, data]);\n *     },\n *   });\n *\n *   return (\n *     <>\n *       {loading && <p>Loading...</p>}\n *       {JSON.stringify(accumulatedData, undefined, 2)}\n *     </>\n *   );\n * }\n * ```\n *\n * > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.\n *\n * Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.\n *\n * @param subscription - A GraphQL subscription document parsed into an AST by `gql`.\n * @param options - Options to control how the subscription is executed.\n * @returns Query result object\n */\nexport function useSubscription<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  subscription: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options = {} as useSubscription.Options<TData, TVariables>]: {} extends (\n    TVariables\n  ) ?\n    [options?: useSubscription.Options<NoInfer<TData>, NoInfer<TVariables>>]\n  : [options: useSubscription.Options<NoInfer<TData>, NoInfer<TVariables>>]\n): useSubscription.Result<TData> {\n  const client = useApolloClient(options.client);\n\n  const {\n    skip,\n    fetchPolicy,\n    errorPolicy,\n    shouldResubscribe,\n    context,\n    extensions,\n    ignoreResults,\n  } = options;\n  const variables = useDeepMemo(() => options.variables, [options.variables]);\n\n  const recreate = () =>\n    createSubscription(\n      client,\n      subscription,\n      variables,\n      fetchPolicy,\n      errorPolicy,\n      context,\n      extensions\n    );\n\n  let [observable, setObservable] = React.useState(\n    options.skip ? null : recreate\n  );\n\n  const recreateRef = React.useRef(recreate);\n  useIsomorphicLayoutEffect(() => {\n    recreateRef.current = recreate;\n  });\n\n  if (skip) {\n    if (observable) {\n      setObservable((observable = null));\n    }\n  } else if (\n    !observable ||\n    ((client !== observable.__.client ||\n      subscription !== observable.__.query ||\n      fetchPolicy !== observable.__.fetchPolicy ||\n      errorPolicy !== observable.__.errorPolicy ||\n      !equal(variables, observable.__.variables)) &&\n      (typeof shouldResubscribe === \"function\" ?\n        !!shouldResubscribe(options!)\n      : shouldResubscribe) !== false)\n  ) {\n    setObservable((observable = recreate()));\n  }\n\n  const optionsRef = React.useRef(options);\n  React.useEffect(() => {\n    optionsRef.current = options;\n  });\n\n  const fallbackLoading = !skip && !ignoreResults;\n  const fallbackResult = React.useMemo(\n    () => ({\n      loading: fallbackLoading,\n      error: void 0,\n      data: void 0,\n    }),\n    [fallbackLoading]\n  );\n\n  const ignoreResultsRef = React.useRef(ignoreResults);\n  useIsomorphicLayoutEffect(() => {\n    // We cannot reference `ignoreResults` directly in the effect below\n    // it would add a dependency to the `useEffect` deps array, which means the\n    // subscription would be recreated if `ignoreResults` changes\n    // As a result, on resubscription, the last result would be re-delivered,\n    // rendering the component one additional time, and re-triggering `onData`.\n    // The same applies to `fetchPolicy`, which results in a new `observable`\n    // being created. We cannot really avoid it in that case, but we can at least\n    // avoid it for `ignoreResults`.\n    ignoreResultsRef.current = ignoreResults;\n  });\n\n  const ret = useSyncExternalStore(\n    React.useCallback(\n      (update) => {\n        if (!observable) {\n          return () => {};\n        }\n\n        let subscriptionStopped = false;\n        const client = observable.__.client;\n        const subscription = observable.subscribe({\n          next(value) {\n            if (subscriptionStopped) {\n              return;\n            }\n\n            const result = {\n              loading: false,\n              data: value.data,\n              error: value.error,\n            };\n\n            observable.__.setResult(result);\n            if (!ignoreResultsRef.current) update();\n\n            if (result.error) {\n              optionsRef.current.onError?.(result.error);\n            } else if (optionsRef.current.onData) {\n              optionsRef.current.onData({\n                client,\n                data: result,\n              });\n            }\n          },\n          complete() {\n            observable.__.completed = true;\n            if (!subscriptionStopped && optionsRef.current.onComplete) {\n              optionsRef.current.onComplete();\n            }\n          },\n        });\n\n        return () => {\n          // immediately stop receiving subscription values, but do not unsubscribe\n          // until after a short delay in case another useSubscription hook is\n          // reusing the same underlying observable and is about to subscribe\n          subscriptionStopped = true;\n\n          setTimeout(() => subscription.unsubscribe());\n        };\n      },\n      [observable]\n    ),\n    () =>\n      observable && !skip && !ignoreResults ?\n        observable.__.result\n      : fallbackResult,\n    () => fallbackResult\n  );\n\n  const restart = React.useCallback(() => {\n    invariant(\n      !optionsRef.current.skip,\n      \"A subscription that is skipped cannot be restarted.\"\n    );\n    if (observable?.__.completed) {\n      setObservable(recreateRef.current());\n    } else {\n      observable?.restart();\n    }\n  }, [observable, setObservable, optionsRef, recreateRef]);\n\n  return React.useMemo(() => ({ ...ret, restart }), [ret, restart]);\n}\n\ntype SubscriptionResult<TData> = Omit<useSubscription.Result<TData>, \"restart\">;\n\nfunction createSubscription<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  client: ApolloClient,\n  query: TypedDocumentNode<TData, TVariables>,\n  variables: TVariables | undefined,\n  fetchPolicy: FetchPolicy | undefined,\n  errorPolicy: ErrorPolicy | undefined,\n  context: DefaultContext | undefined,\n  extensions: Record<string, any> | undefined\n) {\n  const options = {\n    query,\n    variables,\n    fetchPolicy,\n    errorPolicy,\n    context,\n    extensions,\n  } as ApolloClient.SubscribeOptions<TData, TVariables>;\n  const __ = {\n    ...options,\n    client,\n    completed: false,\n    result: {\n      loading: true,\n      data: void 0,\n      error: void 0,\n    } as SubscriptionResult<TData>,\n    setResult(result: SubscriptionResult<TData>) {\n      __.result = result;\n    },\n  };\n\n  return Object.assign(client.subscribe(options), {\n    /**\n     * A tracking object to store details about the observable and the latest result of the subscription.\n     */\n    __,\n  });\n}\n"
  },
  {
    "path": "src/react/hooks/useSuspenseFragment.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataValue,\n  DocumentNode,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport type { ApolloCache } from \"@apollo/client/cache\";\nimport { canonicalStringify } from \"@apollo/client/cache\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { FragmentKey } from \"@apollo/client/react/internal\";\nimport { getSuspenseCache } from \"@apollo/client/react/internal\";\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\n\nimport { __use } from \"./internal/__use.js\";\nimport { useDeepMemo, wrapHook } from \"./internal/index.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\nexport declare namespace useSuspenseFragment {\n  import _self = useSuspenseFragment;\n  export namespace Base {\n    export type Options<TData, TVariables extends OperationVariables> = {\n      /**\n       * A GraphQL document created using the `gql` template string tag from\n       * `graphql-tag` with one or more fragments which will be used to determine\n       * the shape of data to read. If you provide more than one fragment in this\n       * document then you must also specify `fragmentName` to select a single.\n       */\n      fragment: DocumentNode | TypedDocumentNode<TData, TVariables>;\n\n      /**\n       * The name of the fragment in your GraphQL document to be used. If you do\n       * not provide a `fragmentName` and there is only one fragment in your\n       * `fragment` document then that fragment will be used.\n       */\n      fragmentName?: string;\n\n      /**\n       * An object or array containing a `__typename` and primary key fields\n       * (such as `id`) identifying the entity object from which the fragment will\n       * be retrieved, or a `{ __ref: \"...\" }` reference, or a `string` ID (uncommon).\n       */\n      from:\n        | useSuspenseFragment.FromOptionValue<TData>\n        | Array<useSuspenseFragment.FromOptionValue<TData> | null>\n        | null;\n\n      // Override this field to make it optional (default: true).\n      optimistic?: boolean;\n      /**\n       * The instance of `ApolloClient` to use to look up the fragment.\n       *\n       * By default, the instance that's passed down via context is used, but you\n       * can provide a different instance here.\n       *\n       * @docGroup 1. Operation options\n       */\n      client?: ApolloClient;\n    };\n  }\n  export type Options<\n    TData,\n    TVariables extends OperationVariables,\n  > = Base.Options<TData, TVariables> & VariablesOption<NoInfer<TVariables>>;\n\n  export namespace DocumentationTypes {\n    export namespace useSuspenseFragment {\n      export interface Options<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Options<TData, TVariables>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n    }\n  }\n\n  /**\n   * Acceptable values provided to the `from` option.\n   */\n  export type FromOptionValue<TData> = ApolloCache.FromOptionValue<TData>;\n\n  export interface Result<TData> {\n    data: DataValue.Complete<MaybeMasked<TData>>;\n  }\n  export namespace DocumentationTypes {\n    export namespace useSuspenseFragment {\n      export interface Result<TData = unknown> extends _self.Result<TData> {}\n    }\n  }\n\n  export namespace DocumentationTypes {\n    /** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\n    export function useSuspenseFragment<\n      TData,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      options: useSuspenseFragment.Options<TData, TVariables>\n    ): useSuspenseFragment.Result<TData>;\n  }\n}\n\n/** #TODO documentation */\nexport function useSuspenseFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<useSuspenseFragment.FromOptionValue<TData>>;\n  }\n): useSuspenseFragment.Result<Array<TData>>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<null>;\n  }\n): useSuspenseFragment.Result<Array<null>>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: Array<useSuspenseFragment.FromOptionValue<TData> | null>;\n  }\n): useSuspenseFragment.Result<Array<TData | null>>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: useSuspenseFragment.FromOptionValue<TData>;\n  }\n): useSuspenseFragment.Result<TData>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: null;\n  }\n): useSuspenseFragment.Result<null>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables> & {\n    from: useSuspenseFragment.FromOptionValue<TData> | null;\n  }\n): useSuspenseFragment.Result<TData | null>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseFragment:function(1)} */\nexport function useSuspenseFragment<\n  TData,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables>\n): useSuspenseFragment.Result<TData>;\n\nexport function useSuspenseFragment<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables>\n): useSuspenseFragment.Result<TData | null> {\n  \"use no memo\";\n  return wrapHook(\n    \"useSuspenseFragment\",\n    useSuspenseFragment_,\n    useApolloClient(typeof options === \"object\" ? options.client : undefined)\n  )(options);\n}\n\nfunction useSuspenseFragment_<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  options: useSuspenseFragment.Options<TData, TVariables>\n): useSuspenseFragment.Result<TData | null> {\n  const client = useApolloClient(options.client);\n  const { from, variables } = options;\n  const { cache } = client;\n\n  const ids = useDeepMemo(() => {\n    return Array.isArray(from) ?\n        from.map((id) => toStringId(cache, id))\n      : toStringId(cache, from);\n  }, [cache, from]);\n  const idString = React.useMemo(\n    () => (Array.isArray(ids) ? ids.join(\",\") : ids),\n    [ids]\n  );\n\n  const fragmentRef = getSuspenseCache(client).getFragmentRef(\n    [options.fragment, canonicalStringify(variables), idString],\n    client,\n    { ...options, variables: variables as TVariables, from: ids }\n  );\n\n  let [current, setPromise] = React.useState<\n    [FragmentKey, Promise<MaybeMasked<TData> | null>]\n  >([fragmentRef.key, fragmentRef.promise]);\n\n  React.useEffect(() => {\n    const dispose = fragmentRef.retain();\n    const removeListener = fragmentRef.listen((promise) => {\n      setPromise([fragmentRef.key, promise]);\n    });\n\n    return () => {\n      dispose();\n      removeListener();\n    };\n  }, [fragmentRef]);\n\n  if (current[0] !== fragmentRef.key) {\n    // eslint-disable-next-line react-hooks/immutability\n    current[0] = fragmentRef.key;\n    // eslint-disable-next-line react-hooks/immutability\n    current[1] = fragmentRef.promise;\n  }\n\n  const data = __use(current[1]);\n\n  return { data };\n}\n\nfunction toStringId(\n  cache: ApolloCache,\n  from: useSuspenseFragment.FromOptionValue<any> | null\n) {\n  return (\n    typeof from === \"string\" ? from\n    : from === null ? null\n    : cache.identify(from)) as string | null;\n}\n"
  },
  {
    "path": "src/react/hooks/useSuspenseQuery.ts",
    "content": "import * as React from \"react\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  DefaultContext,\n  DocumentNode,\n  ErrorLike,\n  ErrorPolicy,\n  GetDataState,\n  MaybeMasked,\n  ObservableQuery,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport type { SubscribeToMoreFunction } from \"@apollo/client\";\nimport { NetworkStatus } from \"@apollo/client\";\nimport type {\n  FetchMoreFunction,\n  QueryKey,\n  RefetchFunction,\n} from \"@apollo/client/react/internal\";\nimport { getSuspenseCache } from \"@apollo/client/react/internal\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport type {\n  DocumentationTypes as UtilityDocumentationTypes,\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\nimport { variablesUnknownSymbol } from \"@apollo/client/utilities/internal\";\n\nimport type { SkipToken } from \"./constants.js\";\nimport { skipToken } from \"./constants.js\";\nimport {\n  __use,\n  useDeepMemo,\n  useSuspenseHookCacheKey,\n  wrapHook,\n} from \"./internal/index.js\";\nimport { validateSuspenseHookOptions } from \"./internal/validateSuspenseHookOptions.js\";\nimport { useApolloClient } from \"./useApolloClient.js\";\n\nexport declare namespace useSuspenseQuery {\n  export type FetchPolicy = Extract<\n    WatchQueryFetchPolicy,\n    \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n  >;\n\n  export namespace Base {\n    export interface Options<\n      TVariables extends OperationVariables = OperationVariables,\n    > {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n      client?: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n      context?: DefaultContext;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n      errorPolicy?: ErrorPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n      returnPartialData?: boolean;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy_suspense:member} */\n      refetchWritePolicy?: RefetchWritePolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n      fetchPolicy?: FetchPolicy;\n\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#queryKey:member} */\n      queryKey?: string | number | any[];\n\n      /**\n       * {@inheritDoc @apollo/client!QueryOptionsDocumentation#skip_deprecated:member}\n       *\n       * @example Recommended usage of `skipToken`:\n       *\n       * ```ts\n       * import { skipToken, useSuspenseQuery } from \"@apollo/client\";\n       *\n       * const { data } = useSuspenseQuery(\n       *   query,\n       *   id ? { variables: { id } } : skipToken\n       * );\n       * ```\n       */\n      skip?: boolean;\n    }\n  }\n  export type Options<\n    TVariables extends OperationVariables = OperationVariables,\n  > = Base.Options<TVariables> & VariablesOption<TVariables>;\n\n  export namespace DocumentationTypes {\n    namespace useSuspenseQuery {\n      export interface Options<\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Options<TVariables>,\n          UtilityDocumentationTypes.VariableOptions<TVariables> {}\n    }\n  }\n\n  export namespace Base {\n    export interface Result<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    > {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#client:member} */\n      client: ApolloClient;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n      error: ErrorLike | undefined;\n\n      /**\n       * {@inheritDoc @apollo/client!QueryResultDocumentation#fetchMore:member}\n       *\n       * @remarks\n       * Calling this function will cause the component to re-suspend, unless the call site is wrapped in [`startTransition`](https://react.dev/reference/react/startTransition).\n       */\n      fetchMore: FetchMoreFunction<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n      networkStatus: NetworkStatus;\n\n      /**\n       * {@inheritDoc @apollo/client!QueryResultDocumentation#refetch:member}\n       *\n       * @remarks\n       * Calling this function will cause the component to re-suspend, unless the call site is wrapped in [`startTransition`](https://react.dev/reference/react/startTransition).\n       */\n      refetch: RefetchFunction<TData, TVariables>;\n\n      /** {@inheritDoc @apollo/client!QueryResultDocumentation#subscribeToMore:member} */\n      subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;\n    }\n  }\n  export type Result<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  > = Base.Result<TData, TVariables> &\n    GetDataState<MaybeMasked<TData>, TStates>;\n\n  export namespace DocumentationTypes {\n    namespace useSuspenseQuery {\n      export interface Result<\n        TData = unknown,\n        TVariables extends OperationVariables = OperationVariables,\n      > extends Base.Result<TData, TVariables>,\n          UtilityDocumentationTypes.DataState<TData> {}\n    }\n  }\n  export namespace DocumentationTypes {\n    /** Test {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\n    export function useSuspenseQuery<\n      TData = unknown,\n      TVariables extends OperationVariables = OperationVariables,\n    >(\n      query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n      options?: useSuspenseQuery.Options<TVariables>\n    ): useSuspenseQuery.Result<TData, TVariables>;\n  }\n}\n\n/**\n * For a detailed explanation of `useSuspenseQuery`, see the [fetching with Suspense reference](https://www.apollographql.com/docs/react/data/suspense).\n *\n * @example\n *\n * ```jsx\n * import { Suspense } from \"react\";\n * import { useSuspenseQuery } from \"@apollo/client\";\n *\n * const listQuery = gql`\n *   query {\n *     list {\n *       id\n *     }\n *   }\n * `;\n *\n * function App() {\n *   return (\n *     <Suspense fallback={<Spinner />}>\n *       <List />\n *     </Suspense>\n *   );\n * }\n *\n * function List() {\n *   const { data } = useSuspenseQuery(listQuery);\n *\n *   return (\n *     <ol>\n *       {data.list.map((item) => (\n *         <Item key={item.id} id={item.id} />\n *       ))}\n *     </ol>\n *   );\n * }\n * ```\n *\n * @param query - A GraphQL query document parsed into an AST by `gql`.\n * @param options - An optional object containing options for the query. Instead of passing a `useSuspenseQuery.Options` object into the hook, you can also pass a [`skipToken`](#skiptoken) to prevent the `useSuspenseQuery` hook from executing the query or suspending.\n */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useSuspenseQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: true;\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useSuspenseQuery.Options<NoInfer<TVariables>> & {\n    errorPolicy: \"ignore\" | \"all\";\n  }\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useSuspenseQuery.Options<NoInfer<TVariables>> & {\n    skip: boolean;\n    returnPartialData: true;\n  }\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"empty\" | \"streaming\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useSuspenseQuery.Options<NoInfer<TVariables>> & {\n    returnPartialData: true;\n  }\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"partial\" | \"streaming\" | \"complete\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: useSuspenseQuery.Options<NoInfer<TVariables>> & {\n    skip: boolean;\n  }\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | SkipToken\n    | (useSuspenseQuery.Options<NoInfer<TVariables>> & {\n        returnPartialData: true;\n      })\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"streaming\" | \"complete\" | \"partial\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [options?: useSuspenseQuery.Options<NoInfer<TVariables>>]\n  : [options: useSuspenseQuery.Options<NoInfer<TVariables>>]\n): useSuspenseQuery.Result<TData, TVariables, \"complete\" | \"streaming\">;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  ...[options]: {} extends TVariables ?\n    [options?: SkipToken | useSuspenseQuery.Options<NoInfer<TVariables>>]\n  : [options: SkipToken | useSuspenseQuery.Options<NoInfer<TVariables>>]\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"empty\"\n>;\n\n/** {@inheritDoc @apollo/client/react!useSuspenseQuery:function(1)} */\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options: SkipToken | useSuspenseQuery.Options<NoInfer<TVariables>>\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"complete\" | \"streaming\" | \"empty\"\n>;\n\nexport function useSuspenseQuery<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options?: SkipToken | useSuspenseQuery.Options<NoInfer<TVariables>>\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"empty\" | \"streaming\" | \"complete\" | \"partial\"\n> {\n  \"use no memo\";\n  return wrapHook(\n    \"useSuspenseQuery\",\n    useSuspenseQuery_,\n    useApolloClient(typeof options === \"object\" ? options.client : undefined)\n  )(query, options ?? ({} as any));\n}\n\nfunction useSuspenseQuery_<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n>(\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n  options:\n    | (SkipToken & Partial<useSuspenseQuery.Options<TVariables>>)\n    | useSuspenseQuery.Options<TVariables>\n): useSuspenseQuery.Result<\n  TData,\n  TVariables,\n  \"partial\" | \"complete\" | \"streaming\" | \"empty\"\n> {\n  const client = useApolloClient(options.client);\n  const suspenseCache = getSuspenseCache(client);\n  const watchQueryOptions = useWatchQueryOptions<any, any>({\n    client,\n    query,\n    options,\n  });\n  const { fetchPolicy } = watchQueryOptions;\n  const cacheKey = useSuspenseHookCacheKey(query, options);\n\n  const queryRef = suspenseCache.getQueryRef(cacheKey, () =>\n    client.watchQuery(watchQueryOptions)\n  );\n\n  let [current, setPromise] = React.useState<\n    [QueryKey, Promise<ObservableQuery.Result<any>>]\n  >([queryRef.key, queryRef.promise]);\n\n  // This saves us a re-execution of the render function when a variable changed.\n  if (current[0] !== queryRef.key) {\n    // eslint-disable-next-line react-hooks/immutability\n    current[0] = queryRef.key;\n    // eslint-disable-next-line react-hooks/immutability\n    current[1] = queryRef.promise;\n  }\n  let promise = current[1];\n\n  if (queryRef.didChangeOptions(watchQueryOptions)) {\n    // eslint-disable-next-line react-hooks/immutability\n    current[1] = promise = queryRef.applyOptions(watchQueryOptions);\n  }\n\n  React.useEffect(() => {\n    const dispose = queryRef.retain();\n\n    const removeListener = queryRef.listen((promise) => {\n      setPromise([queryRef.key, promise]);\n    });\n\n    return () => {\n      removeListener();\n      dispose();\n    };\n  }, [queryRef]);\n\n  const skipResult = React.useMemo<ObservableQuery.Result<TData>>(() => {\n    const error = queryRef.result.error;\n    const complete = !!queryRef.result.data;\n\n    return {\n      loading: false,\n      data: queryRef.result.data,\n      dataState: queryRef.result.dataState,\n      networkStatus: error ? NetworkStatus.error : NetworkStatus.ready,\n      error,\n      complete,\n      partial: !complete,\n    };\n  }, [queryRef.result]);\n\n  const result = fetchPolicy === \"standby\" ? skipResult : __use(promise);\n\n  const fetchMore = React.useCallback<\n    FetchMoreFunction<unknown, OperationVariables>\n  >(\n    (options) => {\n      const promise = queryRef.fetchMore(options);\n      setPromise([queryRef.key, queryRef.promise]);\n\n      return promise;\n    },\n    [queryRef]\n  ) as FetchMoreFunction<TData | undefined, TVariables>;\n\n  const refetch: RefetchFunction<TData, TVariables> = React.useCallback(\n    (variables) => {\n      const promise = queryRef.refetch(variables);\n      setPromise([queryRef.key, queryRef.promise]);\n\n      return promise;\n    },\n    [queryRef]\n  );\n\n  // TODO: The internalQueryRef doesn't have TVariables' type information so we have to cast it here\n  const subscribeToMore = queryRef.observable\n    .subscribeToMore as SubscribeToMoreFunction<TData | undefined, TVariables>;\n\n  return React.useMemo<\n    useSuspenseQuery.Result<TData, TVariables, DataState<TData>[\"dataState\"]>\n  >(() => {\n    return {\n      client,\n      data: result.data,\n      dataState: result.dataState,\n      error: result.error,\n      networkStatus: result.networkStatus,\n      fetchMore,\n      refetch,\n      subscribeToMore,\n    } as useSuspenseQuery.Result<\n      TData,\n      TVariables,\n      DataState<TData>[\"dataState\"]\n    >;\n  }, [client, fetchMore, refetch, result, subscribeToMore]);\n}\n\ninterface UseWatchQueryOptionsHookOptions<\n  TData,\n  TVariables extends OperationVariables,\n> {\n  client: ApolloClient;\n  query: DocumentNode | TypedDocumentNode<TData, TVariables>;\n  options: SkipToken | useSuspenseQuery.Options<TVariables>;\n}\n\nexport function useWatchQueryOptions<\n  TData,\n  TVariables extends OperationVariables,\n>({\n  client,\n  query,\n  options,\n}: UseWatchQueryOptionsHookOptions<\n  TData,\n  TVariables\n>): ApolloClient.WatchQueryOptions<TData, TVariables> {\n  return useDeepMemo<ApolloClient.WatchQueryOptions<TData, TVariables>>(() => {\n    if (options === skipToken) {\n      return {\n        query,\n        fetchPolicy: \"standby\",\n        [variablesUnknownSymbol]: true,\n      } as ApolloClient.WatchQueryOptions<TData, TVariables>;\n    }\n\n    const fetchPolicy =\n      options.fetchPolicy ||\n      client.defaultOptions.watchQuery?.fetchPolicy ||\n      \"cache-first\";\n\n    const watchQueryOptions: ApolloClient.WatchQueryOptions<TData, TVariables> =\n      {\n        ...options,\n        fetchPolicy,\n        query,\n        notifyOnNetworkStatusChange: false,\n        nextFetchPolicy: void 0,\n      };\n\n    if (__DEV__) {\n      validateSuspenseHookOptions(watchQueryOptions);\n    }\n\n    // Assign the updated fetch policy after our validation since `standby` is\n    // not a supported fetch policy on its own without the use of `skip`.\n    if (options.skip) {\n      watchQueryOptions.fetchPolicy = \"standby\";\n    }\n\n    return watchQueryOptions;\n  }, [client, options, query]);\n}\n"
  },
  {
    "path": "src/react/hooks/useSyncExternalStore.ts",
    "content": "import * as React from \"react\";\n\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { canUseDOM } from \"@apollo/client/utilities/internal\";\nimport { maybe } from \"@apollo/client/utilities/internal/globals\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nlet didWarnUncachedGetSnapshot = false;\n\ntype RealUseSESHookType =\n  // This import depends only on the @types/use-sync-external-store package, not\n  // the actual use-sync-external-store package, which is not installed. It\n  // might be nice to get this type from React 18, but it still needs to work\n  // when only React 17 or earlier is installed.\n  typeof import(\"use-sync-external-store\").useSyncExternalStore;\n\n// Prevent webpack from complaining about our feature detection of the\n// useSyncExternalStore property of the React namespace, which is expected not\n// to exist when using React 17 and earlier, and that's fine.\nconst uSESKey = \"useSyncExternalStore\" as keyof typeof React;\nconst realHook = React[uSESKey] as RealUseSESHookType | undefined;\n\nconst isReactNative = maybe(() => navigator.product) == \"ReactNative\";\nconst usingJSDOM: boolean =\n  // Following advice found in this comment from @domenic (maintainer of jsdom):\n  // https://github.com/jsdom/jsdom/issues/1537#issuecomment-229405327\n  //\n  // Since we control the version of Jest and jsdom used when running Apollo\n  // Client tests, and that version is recent enough to include \" jsdom/x.y.z\"\n  // at the end of the user agent string, I believe this case is all we need to\n  // check. Testing for \"Node.js\" was recommended for backwards compatibility\n  // with older version of jsdom, but we don't have that problem.\n  maybe(() => navigator.userAgent.indexOf(\"jsdom\") >= 0) || false;\n\n// Our tests should all continue to pass if we remove this !usingJSDOM\n// condition, thereby allowing useLayoutEffect when using jsdom. Unfortunately,\n// if we allow useLayoutEffect, then useSyncExternalStore generates many\n// warnings about useLayoutEffect doing nothing on the server. While these\n// warnings are harmless, this !usingJSDOM condition seems to be the best way to\n// prevent them (i.e. skipping useLayoutEffect when using jsdom).\nconst canUseLayoutEffect = (canUseDOM || isReactNative) && !usingJSDOM;\n\n// Adapted from https://www.npmjs.com/package/use-sync-external-store, with\n// Apollo Client deviations called out by \"// DEVIATION ...\" comments.\n\n// When/if React.useSyncExternalStore is defined, delegate fully to it.\nexport const useSyncExternalStore: RealUseSESHookType =\n  realHook ||\n  ((subscribe, getSnapshot, getServerSnapshot) => {\n    // Read the current snapshot from the store on every render. Again, this\n    // breaks the rules of React, and only works here because of specific\n    // implementation details, most importantly that updates are\n    // always synchronous.\n    const value = getSnapshot();\n    if (\n      // DEVIATION: Using __DEV__\n      __DEV__ &&\n      !didWarnUncachedGetSnapshot &&\n      // DEVIATION: Not using Object.is because we know our snapshots will never\n      // be exotic primitive values like NaN, which is !== itself.\n      value !== getSnapshot()\n    ) {\n      didWarnUncachedGetSnapshot = true;\n      // DEVIATION: Using invariant.error instead of console.error directly.\n      invariant.error(\n        \"The result of getSnapshot should be cached to avoid an infinite loop\"\n      );\n    }\n\n    // Because updates are synchronous, we don't queue them. Instead we force a\n    // re-render whenever the subscribed state changes by updating an some\n    // arbitrary useState hook. Then, during render, we call getSnapshot to read\n    // the current value.\n    //\n    // Because we don't actually use the state returned by the useState hook, we\n    // can save a bit of memory by storing other stuff in that slot.\n    //\n    // To implement the early bailout, we need to track some things on a mutable\n    // object. Usually, we would put that in a useRef hook, but we can stash it in\n    // our useState hook instead.\n    //\n    // To force a re-render, we call forceUpdate({inst}). That works because the\n    // new object always fails an equality check.\n    const [{ inst }, forceUpdate] = React.useState({\n      inst: { value, getSnapshot },\n    });\n\n    // Track the latest getSnapshot function with a ref. This needs to be updated\n    // in the layout phase so we can access it during the tearing check that\n    // happens on subscribe.\n    if (canUseLayoutEffect) {\n      // DEVIATION: We avoid calling useLayoutEffect when !canUseLayoutEffect,\n      // which may seem like a conditional hook, but this code ends up behaving\n      // unconditionally (one way or the other) because canUseLayoutEffect is\n      // constant.\n      React.useLayoutEffect(() => {\n        Object.assign(inst, { value, getSnapshot });\n        // Whenever getSnapshot or subscribe changes, we need to check in the\n        // commit phase if there was an interleaved mutation. In concurrent mode\n        // this can happen all the time, but even in synchronous mode, an earlier\n        // effect may have mutated the store.\n        if (checkIfSnapshotChanged(inst)) {\n          // Force a re-render.\n          forceUpdate({ inst });\n        }\n        // React Hook React.useLayoutEffect has a missing dependency: 'inst'. Either include it or remove the dependency array.\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n      }, [subscribe, value, getSnapshot]);\n    } else {\n      Object.assign(inst, { value, getSnapshot });\n    }\n\n    React.useEffect(() => {\n      // Check for changes right before subscribing. Subsequent changes will be\n      // detected in the subscription handler.\n      if (checkIfSnapshotChanged(inst)) {\n        // Force a re-render.\n        forceUpdate({ inst });\n      }\n\n      // Subscribe to the store and return a clean-up function.\n      return subscribe(function handleStoreChange() {\n        // TODO: Because there is no cross-renderer API for batching updates, it's\n        // up to the consumer of this library to wrap their subscription event\n        // with unstable_batchedUpdates. Should we try to detect when this isn't\n        // the case and print a warning in development?\n\n        // The store changed. Check if the snapshot changed since the last time we\n        // read from the store.\n        if (checkIfSnapshotChanged(inst)) {\n          // Force a re-render.\n          forceUpdate({ inst });\n        }\n      });\n      // React Hook React.useEffect has a missing dependency: 'inst'. Either include it or remove the dependency array.\n      // eslint-disable-next-line react-hooks/exhaustive-deps\n    }, [subscribe]);\n\n    return value;\n  });\n\nfunction checkIfSnapshotChanged<Snapshot>({\n  value,\n  getSnapshot,\n}: {\n  value: Snapshot;\n  getSnapshot: () => Snapshot;\n}): boolean {\n  try {\n    return value !== getSnapshot();\n  } catch {\n    return true;\n  }\n}\n"
  },
  {
    "path": "src/react/index.react-server.ts",
    "content": "type Exported = typeof import(\"./index.js\");\ntype ExportedFunctions = {\n  [K in keyof Exported]: Exported[K] extends (...args: any[]) => any ? K\n  : never;\n}[keyof Exported];\n\nfunction missingFeatureWarning(\n  feature: string,\n  name: ExportedFunctions\n): () => never {\n  return {\n    [name]() {\n      throw new Error(\n        `The ${feature} ${name} is not supported in React Server Components, but only in Client Components.`\n      );\n    },\n  }[name];\n}\n\n// eslint-disable-next-line no-restricted-syntax\nexport type * from \"./index.js\";\n\n// prettier-ignore\nexport const ApolloProvider = missingFeatureWarning(\"component\", \"ApolloProvider\");\n// prettier-ignore\nexport const getApolloContext = missingFeatureWarning(\"function\",  \"getApolloContext\");\n// prettier-ignore\nexport const createQueryPreloader = missingFeatureWarning(\"function\",\"createQueryPreloader\");\n// prettier-ignore\nexport const useApolloClient = missingFeatureWarning(\"hook\", \"useApolloClient\");\n// prettier-ignore\nexport const useBackgroundQuery = missingFeatureWarning(\"hook\",\"useBackgroundQuery\");\n// prettier-ignore\nexport const useFragment = missingFeatureWarning(\"hook\", \"useFragment\");\n// prettier-ignore\nexport const useLazyQuery = missingFeatureWarning(\"hook\", \"useLazyQuery\");\n// prettier-ignore\nexport const useLoadableQuery = missingFeatureWarning(\"hook\",\"useLoadableQuery\");\n// prettier-ignore\nexport const useMutation = missingFeatureWarning(\"hook\", \"useMutation\");\n// prettier-ignore\nexport const useQuery = missingFeatureWarning(\"hook\", \"useQuery\");\n// prettier-ignore\nexport const useQueryRefHandlers = missingFeatureWarning(\"hook\",\"useQueryRefHandlers\");\n// prettier-ignore\nexport const useReactiveVar = missingFeatureWarning(\"hook\", \"useReactiveVar\");\n// prettier-ignore\nexport const useReadQuery = missingFeatureWarning(\"hook\", \"useReadQuery\");\n// prettier-ignore\nexport const useSubscription = missingFeatureWarning(\"hook\", \"useSubscription\");\n// prettier-ignore\nexport const useSuspenseFragment = missingFeatureWarning(\"hook\",\"useSuspenseFragment\");\n// prettier-ignore\nexport const useSuspenseQuery = missingFeatureWarning(\"hook\",\"useSuspenseQuery\");\n\n// We cannot warn on import of `skipToken`, and there is nothing to \"execute\" giving us a moment to warn,\n// so we can only fully omit it from the bundle, leading to a bundling time error.\n// export const skipToken = {};\n"
  },
  {
    "path": "src/react/index.ts",
    "content": "export type { ApolloContextValue } from \"./context/ApolloContext.js\";\nexport { getApolloContext } from \"./context/ApolloContext.js\";\nexport { ApolloProvider } from \"./context/ApolloProvider.js\";\n\nexport { useApolloClient } from \"./hooks/useApolloClient.js\";\nexport { useLazyQuery } from \"./hooks/useLazyQuery.js\";\nexport { useMutation } from \"./hooks/useMutation.js\";\nexport { useQuery } from \"./hooks/useQuery.js\";\nexport { useSubscription } from \"./hooks/useSubscription.js\";\nexport { useReactiveVar } from \"./hooks/useReactiveVar.js\";\nexport { useFragment } from \"./hooks/useFragment.js\";\nexport { useSuspenseQuery } from \"./hooks/useSuspenseQuery.js\";\nexport { useBackgroundQuery } from \"./hooks/useBackgroundQuery.js\";\nexport { useSuspenseFragment } from \"./hooks/useSuspenseFragment.js\";\nexport { useLoadableQuery } from \"./hooks/useLoadableQuery.js\";\nexport { useQueryRefHandlers } from \"./hooks/useQueryRefHandlers.js\";\nexport { useReadQuery } from \"./hooks/useReadQuery.js\";\nexport { skipToken } from \"./hooks/constants.js\";\nexport type { SkipToken } from \"./hooks/constants.js\";\n\nexport type {\n  PreloadQueryFetchPolicy,\n  PreloadQueryFunction,\n  PreloadQueryOptions,\n} from \"./query-preloader/createQueryPreloader.js\";\nexport { createQueryPreloader } from \"./query-preloader/createQueryPreloader.js\";\n\nexport type {\n  PreloadedQueryRef,\n  QueryRef,\n} from \"@apollo/client/react/internal\";\n\n// These types will be removed with v5\nexport type {\n  BackgroundQueryHookFetchPolicy,\n  BackgroundQueryHookOptions,\n  LazyQueryExecFunction,\n  LazyQueryHookExecOptions,\n  LazyQueryHookOptions,\n  LazyQueryResult,\n  LazyQueryResultTuple,\n  LoadableQueryFetchPolicy,\n  LoadableQueryHookOptions,\n  LoadQueryFunction,\n  MutationFunctionOptions,\n  MutationHookOptions,\n  MutationResult,\n  MutationTuple,\n  OnDataOptions,\n  OnSubscriptionDataOptions,\n  QueryHookOptions,\n  QueryResult,\n  SubscriptionHookOptions,\n  SubscriptionResult,\n  SuspenseQueryHookFetchPolicy,\n  SuspenseQueryHookOptions,\n  UseBackgroundQueryResult,\n  UseFragmentOptions,\n  UseFragmentResult,\n  UseLoadableQueryResult,\n  UseQueryRefHandlersResult,\n  UseReadQueryResult,\n  UseSuspenseFragmentOptions,\n  UseSuspenseFragmentResult,\n  UseSuspenseQueryResult,\n} from \"./types/deprecated.js\";\n\n// internal types\nimport type { HookWrappers } from \"./hooks/internal/wrapHook.js\";\n/** @internal */\nexport declare namespace InternalTypes {\n  export type { HookWrappers };\n}\n\nexport const reactCompilerVersion = \"uncompiled\" as string;\n"
  },
  {
    "path": "src/react/internal/cache/FragmentReference.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { Subscription } from \"rxjs\";\n\nimport type { ApolloClient, OperationVariables } from \"@apollo/client\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { DecoratedPromise } from \"@apollo/client/utilities/internal\";\nimport {\n  createFulfilledPromise,\n  decoratePromise,\n} from \"@apollo/client/utilities/internal\";\n\nimport type { FragmentKey } from \"./types.js\";\n\ntype FragmentRefPromise<TData> = DecoratedPromise<TData>;\ntype Listener<TData> = (promise: FragmentRefPromise<TData>) => void;\n\ninterface FragmentReferenceOptions {\n  autoDisposeTimeoutMs?: number;\n  onDispose?: () => void;\n}\n\nexport class FragmentReference<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> {\n  public readonly observable: ApolloClient.ObservableFragment<TData | null>;\n  public readonly key: FragmentKey = {};\n  public promise!: FragmentRefPromise<MaybeMasked<TData>>;\n\n  private resolve: ((result: MaybeMasked<TData>) => void) | undefined;\n  private reject: ((error: unknown) => void) | undefined;\n\n  private subscription!: Subscription;\n  private listeners = new Set<Listener<MaybeMasked<TData>>>();\n  private autoDisposeTimeoutId?: NodeJS.Timeout;\n\n  private references = 0;\n\n  constructor(\n    client: ApolloClient,\n    watchFragmentOptions: ApolloClient.WatchFragmentOptions<\n      TData,\n      TVariables\n    > & {\n      from: string | null | Array<string | null>;\n    },\n    options: FragmentReferenceOptions\n  ) {\n    this.dispose = this.dispose.bind(this);\n    this.handleNext = this.handleNext.bind(this);\n    this.handleError = this.handleError.bind(this);\n\n    this.observable = client.watchFragment(watchFragmentOptions);\n\n    if (options.onDispose) {\n      this.onDispose = options.onDispose;\n    }\n\n    const result = this.observable.getCurrentResult();\n\n    // Start a timer that will automatically dispose of the query if the\n    // suspended resource does not use this fragmentRef in the given time. This\n    // helps prevent memory leaks when a component has unmounted before the\n    // query has finished loading.\n    const startDisposeTimer = () => {\n      if (!this.references) {\n        this.autoDisposeTimeoutId = setTimeout(\n          this.dispose,\n          options.autoDisposeTimeoutMs ?? 30_000\n        );\n      }\n    };\n\n    this.promise =\n      result.complete ?\n        createFulfilledPromise(result.data)\n      : this.createPendingPromise();\n    this.subscribeToFragment();\n\n    this.promise.then(startDisposeTimer, startDisposeTimer);\n  }\n\n  listen(listener: Listener<MaybeMasked<TData>>) {\n    this.listeners.add(listener);\n\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n\n  retain() {\n    this.references++;\n    clearTimeout(this.autoDisposeTimeoutId);\n    let disposed = false;\n\n    return () => {\n      if (disposed) {\n        return;\n      }\n\n      disposed = true;\n      this.references--;\n\n      setTimeout(() => {\n        if (!this.references) {\n          this.dispose();\n        }\n      });\n    };\n  }\n\n  private dispose() {\n    this.subscription.unsubscribe();\n  }\n\n  private onDispose() {\n    // noop. overridable by options\n  }\n\n  private subscribeToFragment() {\n    this.subscription = this.observable.subscribe(\n      this.handleNext.bind(this),\n      this.handleError.bind(this)\n    );\n    // call `onDispose` when the subscription is finalized, either because it is\n    // unsubscribed as a consequence of a `dispose` call or because the\n    // ObservableQuery completes because of a `ApolloClient.stop()` call.\n    this.subscription.add(this.onDispose);\n  }\n\n  private handleNext(result: ApolloClient.WatchFragmentResult<TData | null>) {\n    switch (this.promise.status) {\n      case \"pending\": {\n        if (result.complete) {\n          return this.resolve?.(result.data);\n        }\n\n        this.deliver(this.promise);\n        break;\n      }\n      case \"fulfilled\": {\n        // This can occur when we already have a result written to the cache and\n        // we subscribe for the first time. We create a fulfilled promise in the\n        // constructor with a value that is the same as the first emitted value\n        // so we want to skip delivering it.\n        if (equal(this.promise.value, result.data)) {\n          return;\n        }\n\n        this.promise =\n          result.complete ?\n            createFulfilledPromise(result.data)\n          : this.createPendingPromise();\n\n        this.deliver(this.promise);\n      }\n    }\n  }\n\n  private handleError(error: unknown) {\n    this.reject?.(error);\n  }\n\n  private deliver(promise: FragmentRefPromise<MaybeMasked<TData>>) {\n    this.listeners.forEach((listener) => listener(promise));\n  }\n\n  private createPendingPromise() {\n    return decoratePromise(\n      new Promise<MaybeMasked<TData>>((resolve, reject) => {\n        this.resolve = resolve;\n        this.reject = reject;\n      })\n    );\n  }\n}\n"
  },
  {
    "path": "src/react/internal/cache/QueryReference.ts",
    "content": "import type {\n  DocumentTypeDecoration,\n  ResultOf,\n  VariablesOf,\n} from \"@graphql-typed-document-node/core\";\nimport { equal } from \"@wry/equality\";\nimport type { Subscription } from \"rxjs\";\nimport { filter } from \"rxjs\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\nimport type { MaybeMasked } from \"@apollo/client/masking\";\nimport type { DecoratedPromise } from \"@apollo/client/utilities/internal\";\nimport {\n  createFulfilledPromise,\n  createRejectedPromise,\n  decoratePromise,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { QueryKey } from \"./types.js\";\n\ntype QueryRefPromise<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n> = DecoratedPromise<ObservableQuery.Result<MaybeMasked<TData>, TStates>>;\n\ntype Listener<TData, TStates extends DataState<TData>[\"dataState\"]> = (\n  promise: QueryRefPromise<TData, TStates>\n) => void;\n\nconst QUERY_REFERENCE_SYMBOL: unique symbol = Symbol.for(\n  \"apollo.internal.queryRef\"\n);\nconst PROMISE_SYMBOL: unique symbol = Symbol.for(\"apollo.internal.refPromise\");\ndeclare const QUERY_REF_BRAND: unique symbol;\ndeclare const PRELOADED_QUERY_REF_BRAND: unique symbol;\n/**\n * A `QueryReference` is an opaque object returned by `useBackgroundQuery`.\n * A child component reading the `QueryReference` via `useReadQuery` will\n * suspend until the promise resolves.\n */\nexport interface QueryRef<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n> {\n  /** @internal */\n  [QUERY_REF_BRAND]?(variables: TVariables): { data: TData; states: TStates };\n}\n\nexport declare namespace QueryRef {\n  export type ForQuery<\n    Document extends DocumentTypeDecoration<any, any>,\n    TStates extends DataState<ResultOf<Document>>[\"dataState\"] =\n      | \"complete\"\n      | \"streaming\",\n  > = QueryRef<ResultOf<Document>, VariablesOf<Document>, TStates>;\n}\n\n/**\n * @internal\n * For usage in internal helpers only.\n */\ninterface WrappedQueryRef<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n> extends QueryRef<TData, TVariables, TStates> {\n  /** @internal */\n  readonly [QUERY_REFERENCE_SYMBOL]: InternalQueryReference<TData, TStates>;\n  /** @internal */\n  [PROMISE_SYMBOL]: QueryRefPromise<TData, TStates>;\n}\n\n/**\n * {@inheritDoc @apollo/client/react!QueryRef:interface}\n */\nexport interface PreloadedQueryRef<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n> extends QueryRef<TData, TVariables, TStates> {\n  /** @internal */\n  [PRELOADED_QUERY_REF_BRAND]: typeof PRELOADED_QUERY_REF_BRAND;\n}\n\ninterface InternalQueryReferenceOptions {\n  onDispose?: () => void;\n  autoDisposeTimeoutMs?: number;\n}\n\nexport function wrapQueryRef<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"],\n>(internalQueryRef: InternalQueryReference<TData, TStates>) {\n  return {\n    [QUERY_REFERENCE_SYMBOL]: internalQueryRef,\n    [PROMISE_SYMBOL]: internalQueryRef.promise,\n  } as WrappedQueryRef<TData, TVariables, TStates>;\n}\n\nexport function assertWrappedQueryRef<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: QueryRef<TData, TVariables, TStates>\n): asserts queryRef is WrappedQueryRef<TData, TVariables, TStates>;\n\nexport function assertWrappedQueryRef<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: QueryRef<TData, TVariables, TStates> | undefined | null\n): asserts queryRef is\n  | WrappedQueryRef<TData, TVariables, TStates>\n  | undefined\n  | null;\n\nexport function assertWrappedQueryRef<\n  TData,\n  TVariables extends OperationVariables,\n  TStates extends DataState<TData>[\"dataState\"],\n>(queryRef: QueryRef<TData, TVariables, TStates> | undefined | null) {\n  invariant(\n    !queryRef || QUERY_REFERENCE_SYMBOL in queryRef,\n    \"Expected a QueryRef object, but got something else instead.\"\n  );\n}\n\nexport function getWrappedPromise<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(queryRef: WrappedQueryRef<TData, any, TStates>) {\n  const internalQueryRef = unwrapQueryRef(queryRef);\n\n  return internalQueryRef.promise.status === \"fulfilled\" ?\n      internalQueryRef.promise\n    : queryRef[PROMISE_SYMBOL];\n}\n\nexport function unwrapQueryRef<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: WrappedQueryRef<TData, any, TStates>\n): InternalQueryReference<TData, TStates>;\n\nexport function unwrapQueryRef<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: Partial<WrappedQueryRef<TData, any, TStates>>\n): undefined | InternalQueryReference<TData, TStates>;\n\nexport function unwrapQueryRef<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(queryRef: Partial<WrappedQueryRef<TData, any, TStates>>) {\n  return queryRef[QUERY_REFERENCE_SYMBOL];\n}\n\nexport function updateWrappedQueryRef<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"],\n>(\n  queryRef: WrappedQueryRef<TData, any, TStates>,\n  promise: QueryRefPromise<TData, TStates>\n) {\n  queryRef[PROMISE_SYMBOL] = promise;\n}\n\nconst OBSERVED_CHANGED_OPTIONS = [\n  \"context\",\n  \"errorPolicy\",\n  \"fetchPolicy\",\n  \"refetchWritePolicy\",\n  \"returnPartialData\",\n] as const;\n\ntype ObservedOptions = Pick<\n  ApolloClient.WatchQueryOptions,\n  (typeof OBSERVED_CHANGED_OPTIONS)[number]\n>;\n\nexport class InternalQueryReference<\n  TData = unknown,\n  TStates extends DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n> {\n  public result!: ObservableQuery.Result<MaybeMasked<TData>, TStates>;\n  public readonly key: QueryKey = {};\n  public readonly observable: ObservableQuery<TData>;\n\n  public promise!: QueryRefPromise<TData, TStates>;\n\n  private queue: QueryRefPromise<TData, TStates> | undefined;\n  private subscription!: Subscription;\n  private listeners = new Set<Listener<TData, TStates>>();\n  private autoDisposeTimeoutId?: NodeJS.Timeout;\n\n  private resolve:\n    | ((result: ObservableQuery.Result<MaybeMasked<TData>, TStates>) => void)\n    | undefined;\n  private reject: ((error: unknown) => void) | undefined;\n\n  private references = 0;\n  private softReferences = 0;\n\n  constructor(\n    observable: ObservableQuery<TData, any>,\n    options: InternalQueryReferenceOptions\n  ) {\n    this.handleNext = this.handleNext.bind(this);\n    this.dispose = this.dispose.bind(this);\n    this.observable = observable;\n\n    if (options.onDispose) {\n      this.onDispose = options.onDispose;\n    }\n\n    this.setResult();\n    this.subscribeToQuery();\n\n    // Start a timer that will automatically dispose of the query if the\n    // suspended resource does not use this queryRef in the given time. This\n    // helps prevent memory leaks when a component has unmounted before the\n    // query has finished loading.\n    const startDisposeTimer = () => {\n      if (!this.references) {\n        this.autoDisposeTimeoutId = setTimeout(\n          this.dispose,\n          options.autoDisposeTimeoutMs ?? 30_000\n        );\n      }\n    };\n\n    // We wait until the request has settled to ensure we don't dispose of the\n    // query ref before the request finishes, otherwise we would leave the\n    // promise in a pending state rendering the suspense boundary indefinitely.\n    this.promise.then(startDisposeTimer, startDisposeTimer);\n  }\n\n  get disposed() {\n    return this.subscription.closed;\n  }\n\n  get watchQueryOptions() {\n    return this.observable.options;\n  }\n\n  reinitialize() {\n    const { observable } = this;\n\n    const originalFetchPolicy = this.watchQueryOptions.fetchPolicy;\n    const avoidNetworkRequests =\n      originalFetchPolicy === \"no-cache\" || originalFetchPolicy === \"standby\";\n\n    try {\n      if (avoidNetworkRequests) {\n        observable.applyOptions({ fetchPolicy: \"standby\" });\n      } else {\n        observable.reset();\n        observable.applyOptions({ fetchPolicy: \"cache-first\" });\n      }\n\n      if (!avoidNetworkRequests) {\n        this.setResult();\n      }\n      this.subscribeToQuery();\n    } finally {\n      observable.applyOptions({ fetchPolicy: originalFetchPolicy });\n    }\n  }\n\n  retain() {\n    this.references++;\n    clearTimeout(this.autoDisposeTimeoutId);\n    let disposed = false;\n\n    return () => {\n      if (disposed) {\n        return;\n      }\n\n      disposed = true;\n      this.references--;\n\n      setTimeout(() => {\n        if (!this.references) {\n          this.dispose();\n        }\n      });\n    };\n  }\n\n  softRetain() {\n    this.softReferences++;\n    let disposed = false;\n\n    return () => {\n      // Tracking if this has already been called helps ensure that\n      // multiple calls to this function won't decrement the reference\n      // counter more than it should. Subsequent calls just result in a noop.\n      if (disposed) {\n        return;\n      }\n\n      disposed = true;\n      this.softReferences--;\n      setTimeout(() => {\n        if (!this.softReferences && !this.references) {\n          this.dispose();\n        }\n      });\n    };\n  }\n\n  didChangeOptions(watchQueryOptions: ObservedOptions) {\n    return OBSERVED_CHANGED_OPTIONS.some(\n      (option) =>\n        option in watchQueryOptions &&\n        !equal(this.watchQueryOptions[option], watchQueryOptions[option])\n    );\n  }\n\n  applyOptions(watchQueryOptions: ObservedOptions) {\n    const { fetchPolicy: currentFetchPolicy } = this.watchQueryOptions;\n\n    // \"standby\" is used when `skip` is set to `true`. Detect when we've\n    // enabled the query (i.e. `skip` is `false`) to execute a network request.\n    if (\n      currentFetchPolicy === \"standby\" &&\n      currentFetchPolicy !== watchQueryOptions.fetchPolicy\n    ) {\n      this.initiateFetch(this.observable.reobserve(watchQueryOptions));\n    } else {\n      this.observable.applyOptions(watchQueryOptions);\n    }\n\n    return this.promise;\n  }\n\n  listen(listener: Listener<TData, TStates>) {\n    this.listeners.add(listener);\n\n    if (this.queue) {\n      this.deliver(this.queue);\n      this.queue = undefined;\n    }\n\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n\n  refetch(variables: OperationVariables | undefined) {\n    return this.initiateFetch(this.observable.refetch(variables));\n  }\n\n  fetchMore(options: ObservableQuery.FetchMoreOptions<TData, any, any, any>) {\n    return this.initiateFetch(this.observable.fetchMore<TData>(options));\n  }\n\n  private dispose() {\n    this.subscription.unsubscribe();\n  }\n\n  private onDispose() {\n    // noop. overridable by options\n  }\n\n  private handleNext(\n    result: ObservableQuery.Result<MaybeMasked<TData>, TStates>\n  ) {\n    switch (this.promise.status) {\n      case \"pending\": {\n        // Maintain the last successful `data` value if the next result does not\n        // have one.\n        // TODO: This can likely be removed once\n        // https://github.com/apollographql/apollo-client/issues/12667 is fixed\n        if (result.data === void 0) {\n          result.data = this.result.data;\n\n          if (result.data) {\n            result.dataState = \"complete\" as any;\n          }\n        }\n\n        if (this.shouldReject(result)) {\n          this.reject?.(result.error);\n        } else {\n          this.result = result;\n          this.resolve?.(result);\n        }\n        break;\n      }\n      default: {\n        // This occurs when switching to a result that is fully cached when this\n        // class is instantiated. ObservableQuery will run reobserve when\n        // subscribing, which delivers a result from the cache.\n        if (\n          result.data === this.result.data &&\n          result.networkStatus === this.result.networkStatus\n        ) {\n          return;\n        }\n\n        // Maintain the last successful `data` value if the next result does not\n        // have one.\n        if (result.data === void 0) {\n          result.data = this.result.data;\n        }\n\n        if (this.shouldReject(result)) {\n          this.promise = createRejectedPromise(result.error);\n          this.deliver(this.promise);\n        } else {\n          this.result = result;\n          this.promise = createFulfilledPromise(result);\n          this.deliver(this.promise);\n        }\n        break;\n      }\n    }\n  }\n\n  private deliver(promise: QueryRefPromise<TData, TStates>) {\n    // Maintain a queue of the last item we tried to deliver so that we can\n    // deliver it as soon as we get the first listener. This helps in cases such\n    // as `@stream` where React may render a component and incremental results\n    // are loaded in between when the component renders and effects are run. If\n    // effects are run after the incremntal chunks are delivered, we'll have\n    // rendered a stale value. The queue ensures we can deliver the most\n    // up-to-date value as soon as the component is ready to listen for new\n    // values.\n    if (this.listeners.size === 0) {\n      this.queue = promise;\n    }\n\n    this.listeners.forEach((listener) => listener(promise));\n  }\n\n  private initiateFetch(\n    returnedPromise: Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>\n  ) {\n    this.promise = this.createPendingPromise();\n    this.promise.catch(() => {});\n\n    // If the data returned from the fetch is deeply equal to the data already\n    // in the cache, `handleNext` will not be triggered leaving the promise we\n    // created in a pending state forever. To avoid this situation, we attempt\n    // to resolve the promise if `handleNext` hasn't been run to ensure the\n    // promise is resolved correctly.\n    returnedPromise\n      .then(() => {\n        // In the case of `fetchMore`, this promise is resolved before a cache\n        // result is emitted due to the fact that `fetchMore` sets a `no-cache`\n        // fetch policy and runs `cache.batch` in its `.then` handler. Because\n        // the timing is different, we accidentally run this update twice\n        // causing an additional re-render with the `fetchMore` result by\n        // itself. By wrapping in `setTimeout`, this should provide a short\n        // delay to allow the `QueryInfo.notify` handler to run before this\n        // promise is checked.\n        // See https://github.com/apollographql/apollo-client/issues/11315 for\n        // more information\n        setTimeout(() => {\n          if (this.promise.status === \"pending\") {\n            // Use the current result from the observable instead of the value\n            // resolved from the promise. This avoids issues in some cases where\n            // the raw resolved value should not be the emitted value, such as\n            // when a `fetchMore` call returns an empty array after it has\n            // reached the end of the list.\n            //\n            // See the following for more information:\n            // https://github.com/apollographql/apollo-client/issues/11642\n            this.result =\n              this.observable.getCurrentResult() as ObservableQuery.Result<\n                TData,\n                TStates\n              >;\n            this.resolve?.(this.result);\n          }\n        });\n      })\n      .catch((error) => this.reject?.(error));\n\n    return returnedPromise;\n  }\n\n  private subscribeToQuery() {\n    this.subscription = this.observable\n      .pipe(filter((result) => !equal(result, this.result)))\n      .subscribe(this.handleNext as any);\n    // call `onDispose` when the subscription is finalized, either because it is\n    // unsubscribed as a consequence of a `dispose` call or because the\n    // ObservableQuery completes because of a `ApolloClient.stop()` call.\n    this.subscription.add(this.onDispose);\n  }\n\n  private setResult() {\n    const result = this.observable.getCurrentResult() as ObservableQuery.Result<\n      TData,\n      TStates\n    >;\n\n    if (equal(result, this.result)) {\n      return;\n    }\n\n    this.result = result;\n    this.promise =\n      result.data ?\n        createFulfilledPromise(result)\n      : this.createPendingPromise();\n  }\n\n  private shouldReject(result: ObservableQuery.Result<any>) {\n    const { errorPolicy = \"none\" } = this.watchQueryOptions;\n\n    return result.error && errorPolicy === \"none\";\n  }\n\n  private createPendingPromise() {\n    return decoratePromise(\n      new Promise<ObservableQuery.Result<MaybeMasked<TData>, TStates>>(\n        (resolve, reject) => {\n          this.resolve = resolve;\n          this.reject = reject;\n        }\n      )\n    );\n  }\n}\n"
  },
  {
    "path": "src/react/internal/cache/SuspenseCache.ts",
    "content": "import { Trie } from \"@wry/trie\";\n\nimport type {\n  ApolloClient,\n  DataState,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\n\nimport { FragmentReference } from \"./FragmentReference.js\";\nimport { InternalQueryReference } from \"./QueryReference.js\";\nimport type { CacheKey, FragmentCacheKey } from \"./types.js\";\n\nexport interface SuspenseCacheOptions {\n  /**\n   * Specifies the amount of time, in milliseconds, the suspense cache will wait\n   * for a suspended component to read from the suspense cache before it\n   * automatically disposes of the query. This prevents memory leaks when a\n   * component unmounts before a suspended resource finishes loading. Increase\n   * the timeout if your queries take longer than than the specified time to\n   * prevent your queries from suspending over and over.\n   *\n   * Defaults to 30 seconds.\n   */\n  autoDisposeTimeoutMs?: number;\n}\n\nexport class SuspenseCache {\n  private queryRefs = new Trie<{ current?: InternalQueryReference }>();\n  private fragmentRefs = new Trie<{ current?: FragmentReference }>();\n\n  private options: SuspenseCacheOptions;\n\n  constructor(options: SuspenseCacheOptions = {}) {\n    this.options = options;\n  }\n\n  getQueryRef<\n    TData = unknown,\n    TStates extends\n      DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n  >(cacheKey: CacheKey, createObservable: () => ObservableQuery<TData>) {\n    const ref = this.queryRefs.lookupArray(cacheKey) as {\n      current?: InternalQueryReference<TData, TStates>;\n    };\n\n    if (!ref.current) {\n      ref.current = new InternalQueryReference(createObservable(), {\n        autoDisposeTimeoutMs: this.options.autoDisposeTimeoutMs,\n        onDispose: () => {\n          delete ref.current;\n        },\n      });\n    }\n\n    return ref.current;\n  }\n\n  getFragmentRef<TData, TVariables extends OperationVariables>(\n    cacheKey: FragmentCacheKey,\n    client: ApolloClient,\n    options: ApolloClient.WatchFragmentOptions<TData, TVariables> & {\n      from: string | null | Array<string | null>;\n    }\n  ) {\n    const ref = this.fragmentRefs.lookupArray(cacheKey) as {\n      current?: FragmentReference<TData, TVariables>;\n    };\n\n    if (!ref.current) {\n      ref.current = new FragmentReference(client, options, {\n        autoDisposeTimeoutMs: this.options.autoDisposeTimeoutMs,\n        onDispose: () => {\n          delete ref.current;\n        },\n      });\n    }\n\n    return ref.current;\n  }\n\n  add(cacheKey: CacheKey, queryRef: InternalQueryReference<any, any>) {\n    const ref = this.queryRefs.lookupArray(cacheKey);\n    ref.current = queryRef;\n  }\n}\n"
  },
  {
    "path": "src/react/internal/cache/__tests__/QueryReference.test.tsx",
    "content": "import { expectTypeOf } from \"expect-type\";\nimport React from \"react\";\nimport { of } from \"rxjs\";\n\nimport type {\n  DataState,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { InternalQueryReference } from \"@apollo/client/react/internal\";\nimport { setupSimpleCase } from \"@apollo/client/testing/internal\";\n\nimport type { PreloadedQueryRef, QueryRef } from \"../QueryReference.js\";\n\ntest(\"kicks off request immediately when created\", async () => {\n  const { query } = setupSimpleCase();\n  let fetchCount = 0;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      fetchCount++;\n      return of({ data: { greeting: \"Hello\" } });\n    }),\n  });\n\n  const observable = client.watchQuery({ query });\n\n  expect(fetchCount).toBe(0);\n  new InternalQueryReference(observable, {});\n  expect(fetchCount).toBe(1);\n});\n\ntest.skip(\"type tests\", () => {\n  test(\"passing as prop\", () => {\n    const ANY: any = {};\n\n    interface Data {\n      foo: string;\n    }\n    type Vars = {\n      bar: string;\n    };\n    function ComponentWithQueryRefProp<\n      TData = unknown,\n      TVariables extends OperationVariables = Record<string, unknown>,\n      TStates extends\n        DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n    >({}: { queryRef: QueryRef<TData, TVariables, TStates> }) {\n      return null;\n    }\n    function ComponentWithPreloadedQueryRefProp<\n      TData = unknown,\n      TVariables extends OperationVariables = Record<string, unknown>,\n      TStates extends\n        DataState<TData>[\"dataState\"] = DataState<TData>[\"dataState\"],\n    >({}: { queryRef: PreloadedQueryRef<TData, TVariables, TStates> }) {\n      return null;\n    }\n\n    {\n      const withoutTypes: QueryRef = ANY;\n      const withData: QueryRef<Data> = ANY;\n      const withDataAndVariables: QueryRef<Data, Vars> = ANY;\n      const withDataAndVariablesAndStates: QueryRef<\n        Data,\n        Vars,\n        \"complete\" | \"streaming\"\n      > = ANY;\n      const withDataAndVariablesAndPartialStates: QueryRef<\n        Data,\n        Vars,\n        \"complete\" | \"streaming\" | \"partial\"\n      > = ANY;\n\n      <>\n        {/* passing queryRef into components that expect queryRef */}\n        <>\n          <ComponentWithQueryRefProp queryRef={withoutTypes} />\n          <ComponentWithQueryRefProp queryRef={withData} />\n          <ComponentWithQueryRefProp queryRef={withDataAndVariables} />\n          <ComponentWithQueryRefProp queryRef={withDataAndVariablesAndStates} />\n          <ComponentWithQueryRefProp\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n\n          <ComponentWithQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithQueryRefProp<Data> queryRef={withData} />\n          <ComponentWithQueryRefProp<Data> queryRef={withDataAndVariables} />\n          <ComponentWithQueryRefProp<Data>\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithQueryRefProp<Data>\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n\n          <ComponentWithQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithQueryRefProp<Data, Vars> queryRef={withData} />\n          <ComponentWithQueryRefProp<Data, Vars>\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithQueryRefProp<Data, Vars>\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithQueryRefProp<Data, Vars>\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n\n          <ComponentWithQueryRefProp<\n            Data,\n            Vars,\n            \"complete\" | \"streaming\"\n          > /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithQueryRefProp<Data, Vars, \"complete\" | \"streaming\">\n            queryRef={withData}\n          />\n          <ComponentWithQueryRefProp<Data, Vars, \"complete\" | \"streaming\">\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithQueryRefProp<Data, Vars, \"complete\" | \"streaming\">\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithQueryRefProp<\n            Data,\n            Vars,\n            \"complete\" | \"streaming\"\n          > /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n          <ComponentWithQueryRefProp<\n            Data,\n            Vars,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithQueryRefProp<\n            Data,\n            Vars,\n            \"complete\" | \"streaming\" | \"partial\"\n          >\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n        </>\n        {/* passing queryRef into components that expect preloadedQueryRef */}\n        <>\n          <ComponentWithPreloadedQueryRefProp /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithPreloadedQueryRefProp /* @ts-expect-error */\n            queryRef={withData}\n          />\n          <ComponentWithPreloadedQueryRefProp /* @ts-expect-error */\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithPreloadedQueryRefProp /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithPreloadedQueryRefProp /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withData}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withData}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndStates}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withDataAndVariablesAndPartialStates}\n          />\n        </>\n      </>;\n    }\n    {\n      const withoutTypes: PreloadedQueryRef = ANY;\n      const withData: PreloadedQueryRef<Data> = ANY;\n      const withDataAndVariables: PreloadedQueryRef<Data, Vars> = ANY;\n      <>\n        {/* passing preloadedQueryRef into components that expect queryRef */}\n        <>\n          <ComponentWithQueryRefProp queryRef={withoutTypes} />\n          <ComponentWithQueryRefProp queryRef={withData} />\n          <ComponentWithQueryRefProp queryRef={withDataAndVariables} />\n          <ComponentWithQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithQueryRefProp<Data> queryRef={withData} />\n          <ComponentWithQueryRefProp<Data> queryRef={withDataAndVariables} />\n          <ComponentWithQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithQueryRefProp<Data, Vars> queryRef={withData} />\n          <ComponentWithQueryRefProp<Data, Vars>\n            queryRef={withDataAndVariables}\n          />\n        </>\n        {/* passing preloadedQueryRef into components that expect preloadedQueryRef */}\n        <>\n          <ComponentWithPreloadedQueryRefProp queryRef={withoutTypes} />\n          <ComponentWithPreloadedQueryRefProp queryRef={withData} />\n          <ComponentWithPreloadedQueryRefProp queryRef={withDataAndVariables} />\n          <ComponentWithPreloadedQueryRefProp<Data> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data> queryRef={withData} />\n          <ComponentWithPreloadedQueryRefProp<Data>\n            queryRef={withDataAndVariables}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> /* @ts-expect-error */\n            queryRef={withoutTypes}\n          />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars> queryRef={withData} />\n          <ComponentWithPreloadedQueryRefProp<Data, Vars>\n            queryRef={withDataAndVariables}\n          />\n        </>\n      </>;\n    }\n  });\n\n  test(\"QueryRef.ForQuery\", () => {\n    const ANY: any = {};\n\n    interface Data {\n      foo: string;\n    }\n    type Vars = {\n      bar: string;\n    };\n    const query: TypedDocumentNode<Data, Vars> = ANY;\n\n    expectTypeOf<QueryRef.ForQuery<typeof query>>().toEqualTypeOf<\n      QueryRef<Data, Vars>\n    >();\n\n    expectTypeOf<QueryRef.ForQuery<typeof query, \"complete\">>().toEqualTypeOf<\n      QueryRef<Data, Vars, \"complete\">\n    >();\n\n    expectTypeOf<\n      QueryRef.ForQuery<typeof query, \"empty\" | \"partial\" | \"complete\">\n    >().toEqualTypeOf<QueryRef<Data, Vars, \"empty\" | \"partial\" | \"complete\">>();\n  });\n});\n"
  },
  {
    "path": "src/react/internal/cache/__tests__/SuspenseCache.ts",
    "content": "import { of } from \"rxjs\";\n\nimport { ApolloClient, ApolloLink, InMemoryCache } from \"@apollo/client\";\nimport { getSuspenseCache } from \"@apollo/client/react/internal\";\nimport { setupSimpleCase } from \"@apollo/client/testing/internal\";\n\ntest(\"QueryRef is removed from SuspenseCache on store reset\", () => {\n  const { query } = setupSimpleCase();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      return of({ data: { greeting: \"Hello\" } });\n    }),\n  });\n  const cache = getSuspenseCache(client);\n  const get = () =>\n    cache.getQueryRef([query, \"{}\"], () =>\n      client.watchQuery<any, any>({ query })\n    );\n  const queryRef = get();\n\n  // should return the same `queryRef` from the cache\n  expect(get()).toBe(queryRef);\n\n  client.stop();\n  // queryRef should have been removed from the cache so we get a new one\n  expect(get()).not.toBe(queryRef);\n});\n"
  },
  {
    "path": "src/react/internal/cache/getSuspenseCache.ts",
    "content": "import type { ApolloClient } from \"@apollo/client\";\nimport type { SuspenseCacheOptions } from \"@apollo/client/react/internal\";\n\nimport { SuspenseCache } from \"./SuspenseCache.js\";\n\ndeclare module \"@apollo/client\" {\n  namespace ApolloClient {\n    interface DefaultOptions {\n      react?: {\n        suspense?: Readonly<SuspenseCacheOptions>;\n      };\n    }\n  }\n}\n\nconst suspenseCacheSymbol = Symbol.for(\"apollo.suspenseCache\");\n\nexport function getSuspenseCache(\n  client: ApolloClient & {\n    [suspenseCacheSymbol]?: SuspenseCache;\n  }\n) {\n  if (!client[suspenseCacheSymbol]) {\n    client[suspenseCacheSymbol] = new SuspenseCache(\n      client.defaultOptions.react?.suspense\n    );\n  }\n\n  return client[suspenseCacheSymbol];\n}\n"
  },
  {
    "path": "src/react/internal/cache/types.ts",
    "content": "import type { DocumentNode } from \"graphql\";\n\nexport type CacheKey = [\n  query: DocumentNode,\n  stringifiedVariables: string,\n  ...queryKey: any[],\n];\n\nexport type FragmentCacheKey = [\n  fragment: DocumentNode,\n  stringifiedVariables: string,\n  cacheId: string | null,\n];\n\nexport interface QueryKey {\n  __queryKey?: string;\n}\n\nexport interface FragmentKey {\n  __fragmentKey?: string;\n}\n"
  },
  {
    "path": "src/react/internal/compiler-runtime/LICENSE",
    "content": "MIT License\n\nCopyright (c) Meta Platforms, Inc. and affiliates.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "src/react/internal/compiler-runtime/index.ts",
    "content": "/**\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in this directory.\n */\n/* eslint-disable */\n\nimport * as React from \"react\";\n\nconst $empty = Symbol.for(\"react.memo_cache_sentinel\");\n\n// Re-export React.c if present, otherwise fallback to the userspace polyfill for versions of React\n// < 19.\nexport const c =\n  (\n    \"__COMPILER_RUNTIME\" in React &&\n    typeof Object(React).__COMPILER_RUNTIME?.c === \"function\"\n  ) ?\n    Object(React).__COMPILER_RUNTIME.c\n  : function c(size: number) {\n      return React.useMemo<Array<unknown>>(() => {\n        const $ = new Array(size);\n        for (let ii = 0; ii < size; ii++) {\n          $[ii] = $empty;\n        }\n        // This symbol is added to tell the react devtools that this array is from\n        // useMemoCache.\n        // @ts-ignore\n        $[$empty] = true;\n        return $;\n      }, []);\n    };\n"
  },
  {
    "path": "src/react/internal/index.ts",
    "content": "import type { InternalTypes as ReactInternalTypes } from \"@apollo/client/react\";\nexport { getSuspenseCache } from \"./cache/getSuspenseCache.js\";\nexport type { CacheKey, FragmentKey, QueryKey } from \"./cache/types.js\";\nexport type { PreloadedQueryRef, QueryRef } from \"./cache/QueryReference.js\";\nexport {\n  assertWrappedQueryRef,\n  getWrappedPromise,\n  InternalQueryReference,\n  unwrapQueryRef,\n  updateWrappedQueryRef,\n  wrapQueryRef,\n} from \"./cache/QueryReference.js\";\nexport type { SuspenseCacheOptions } from \"./cache/SuspenseCache.js\";\nexport type HookWrappers = ReactInternalTypes.HookWrappers;\nexport const wrapperSymbol = Symbol.for(\"apollo.hook.wrappers\");\nexport type { FetchMoreFunction, RefetchFunction } from \"./types.js\";\n"
  },
  {
    "path": "src/react/internal/types.ts",
    "content": "import type {\n  ApolloClient,\n  MaybeMasked,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\n\nexport type RefetchFunction<TData, TVariables extends OperationVariables> = (\n  variables?: Partial<TVariables>\n) => Promise<ApolloClient.QueryResult<TData>>;\n\nexport type FetchMoreFunction<TData, TVariables extends OperationVariables> = <\n  TFetchData = TData,\n  TFetchVars extends OperationVariables = TVariables,\n>(\n  fetchMoreOptions: ObservableQuery.FetchMoreOptions<\n    TData,\n    TVariables,\n    TFetchData,\n    TFetchVars\n  >\n) => Promise<ApolloClient.QueryResult<MaybeMasked<TData>>>;\n"
  },
  {
    "path": "src/react/query-preloader/__tests__/createQueryPreloader/defer20220824.test.tsx",
    "content": "import {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type { DataState } from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  createQueryPreloader,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport {\n  markAsStreaming,\n  mockDefer20220824,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderDefaultTestApp<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n>({\n  client,\n  queryRef,\n}: {\n  client: ApolloClient;\n  queryRef: QueryRef<TData, any, TStates>;\n}) {\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<TData, TStates> | null,\n      error: null as Error | null,\n    },\n  });\n\n  function ReadQueryHook() {\n    useTrackRenders({ name: \"ReadQueryHook\" });\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n    return <p>Loading</p>;\n  }\n\n  function ErrorFallback({ error }: { error: Error }) {\n    useTrackRenders({ name: \"ErrorFallback\" });\n    renderStream.mergeSnapshot({ error });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders({ name: \"App\" });\n\n    return (\n      <ErrorBoundary FallbackComponent={ErrorFallback}>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </ErrorBoundary>\n    );\n  }\n\n  const utils = await renderStream.render(<App />, {\n    wrapper: ({ children }) => (\n      <ApolloProvider client={client}>{children}</ApolloProvider>\n    ),\n  });\n\n  function rerender() {\n    return utils.rerender(<App />);\n  }\n\n  return { ...utils, rerender, renderStream };\n}\n\ntest(\"suspends deferred queries until initial chunk loads then rerenders with deferred data\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDefer20220824();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new Defer20220824Handler(),\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        path: [\"greeting\"],\n      },\n    ],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n"
  },
  {
    "path": "src/react/query-preloader/__tests__/createQueryPreloader/deferGraphQL17Alpha9.test.tsx",
    "content": "import {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\n\nimport type { DataState } from \"@apollo/client\";\nimport { ApolloClient, gql, NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { GraphQL17Alpha9Handler } from \"@apollo/client/incremental\";\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  createQueryPreloader,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport {\n  markAsStreaming,\n  mockDeferStreamGraphQL17Alpha9,\n} from \"@apollo/client/testing/internal\";\n\nasync function renderDefaultTestApp<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n>({\n  client,\n  queryRef,\n}: {\n  client: ApolloClient;\n  queryRef: QueryRef<TData, any, TStates>;\n}) {\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<TData, TStates> | null,\n      error: null as Error | null,\n    },\n  });\n\n  function ReadQueryHook() {\n    useTrackRenders({ name: \"ReadQueryHook\" });\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n    return <p>Loading</p>;\n  }\n\n  function ErrorFallback({ error }: { error: Error }) {\n    useTrackRenders({ name: \"ErrorFallback\" });\n    renderStream.mergeSnapshot({ error });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders({ name: \"App\" });\n\n    return (\n      <ErrorBoundary FallbackComponent={ErrorFallback}>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </ErrorBoundary>\n    );\n  }\n\n  const utils = await renderStream.render(<App />, {\n    wrapper: ({ children }) => (\n      <ApolloProvider client={client}>{children}</ApolloProvider>\n    ),\n  });\n\n  function rerender() {\n    return utils.rerender(<App />);\n  }\n\n  return { ...utils, rerender, renderStream };\n}\n\ntest(\"suspends deferred queries until initial chunk loads then rerenders with deferred data\", async () => {\n  const query = gql`\n    query {\n      greeting {\n        message\n        ... on Greeting @defer {\n          recipient {\n            name\n          }\n        }\n      }\n    }\n  `;\n\n  const { httpLink, enqueueInitialChunk, enqueueSubsequentChunk } =\n    mockDeferStreamGraphQL17Alpha9();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: httpLink,\n    incrementalHandler: new GraphQL17Alpha9Handler(),\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  enqueueInitialChunk({\n    data: { greeting: { message: \"Hello world\", __typename: \"Greeting\" } },\n    pending: [{ id: \"0\", path: [\"greeting\"] }],\n    hasNext: true,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: markAsStreaming({\n        greeting: { message: \"Hello world\", __typename: \"Greeting\" },\n      }),\n      dataState: \"streaming\",\n      error: undefined,\n      networkStatus: NetworkStatus.streaming,\n    });\n  }\n\n  enqueueSubsequentChunk({\n    incremental: [\n      {\n        data: {\n          recipient: { name: \"Alice\", __typename: \"Person\" },\n          __typename: \"Greeting\",\n        },\n        id: \"0\",\n      },\n    ],\n    completed: [{ id: \"0\" }],\n    hasNext: false,\n  });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        greeting: {\n          __typename: \"Greeting\",\n          message: \"Hello world\",\n          recipient: { __typename: \"Person\", name: \"Alice\" },\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n"
  },
  {
    "path": "src/react/query-preloader/__tests__/createQueryPreloader.test.tsx",
    "content": "import { act, screen, waitFor } from \"@testing-library/react\";\nimport {\n  createRenderStream,\n  disableActEnvironment,\n  useTrackRenders,\n} from \"@testing-library/react-render-stream\";\nimport { userEvent } from \"@testing-library/user-event\";\nimport { expectTypeOf } from \"expect-type\";\nimport { GraphQLError } from \"graphql\";\nimport React, { Suspense } from \"react\";\nimport { ErrorBoundary } from \"react-error-boundary\";\nimport { Observable } from \"rxjs\";\n\nimport type {\n  DataState,\n  DataValue,\n  OperationVariables,\n  TypedDocumentNode,\n} from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport type { PreloadedQueryRef, QueryRef } from \"@apollo/client/react\";\nimport {\n  ApolloProvider,\n  createQueryPreloader,\n  useReadQuery,\n} from \"@apollo/client/react\";\nimport { unwrapQueryRef } from \"@apollo/client/react/internal\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport type {\n  MaskedVariablesCaseData,\n  SimpleCaseData,\n  VariablesCaseData,\n} from \"@apollo/client/testing/internal\";\nimport {\n  createClientWrapper,\n  renderHookAsync,\n  setupMaskedVariablesCase,\n  setupSimpleCase,\n  setupVariablesCase,\n  spyOnConsole,\n  wait,\n} from \"@apollo/client/testing/internal\";\nimport type { DeepPartial } from \"@apollo/client/utilities\";\n\nfunction createDefaultClient(mocks: MockLink.MockedResponse[]) {\n  return new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n}\n\nasync function renderDefaultTestApp<\n  TData,\n  TStates extends DataState<TData>[\"dataState\"] = \"complete\" | \"streaming\",\n>({\n  client,\n  queryRef,\n}: {\n  client: ApolloClient;\n  queryRef: QueryRef<TData, any, TStates>;\n}) {\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<TData, TStates> | null,\n      error: null as Error | null,\n    },\n  });\n\n  function ReadQueryHook() {\n    useTrackRenders({ name: \"ReadQueryHook\" });\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  function SuspenseFallback() {\n    useTrackRenders({ name: \"SuspenseFallback\" });\n    return <p>Loading</p>;\n  }\n\n  function ErrorFallback({ error }: { error: Error }) {\n    useTrackRenders({ name: \"ErrorFallback\" });\n    renderStream.mergeSnapshot({ error });\n\n    return null;\n  }\n\n  function App() {\n    useTrackRenders({ name: \"App\" });\n\n    return (\n      <ErrorBoundary FallbackComponent={ErrorFallback}>\n        <Suspense fallback={<SuspenseFallback />}>\n          <ReadQueryHook />\n        </Suspense>\n      </ErrorBoundary>\n    );\n  }\n\n  const utils = await renderStream.render(<App />, {\n    wrapper: ({ children }) => (\n      <ApolloProvider client={client}>{children}</ApolloProvider>\n    ),\n  });\n\n  function rerender() {\n    return utils.rerender(<App />);\n  }\n\n  return { ...utils, rerender, renderStream };\n}\n\ntest(\"loads a query and suspends when passed to useReadQuery\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = createDefaultClient(mocks);\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"loads a query with variables and suspends when passed to useReadQuery\", async () => {\n  const { query, mocks } = setupVariablesCase();\n  const client = createDefaultClient(mocks);\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, {\n    variables: { id: \"1\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"Auto disposes of the query ref if not retained within the given time\", async () => {\n  jest.useFakeTimers();\n  const { query, mocks } = setupSimpleCase();\n  const client = createDefaultClient(mocks);\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query);\n\n  // We don't start the dispose timer until the promise is initially resolved\n  // so we need to wait for it\n  jest.advanceTimersByTime(20);\n  await preloadQuery.toPromise(queryRef);\n  jest.advanceTimersByTime(30_000);\n\n  expect(queryRef).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  jest.useRealTimers();\n});\n\ntest(\"Honors configured auto dispose timer on the client\", async () => {\n  jest.useFakeTimers();\n  const { query, mocks } = setupSimpleCase();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n    defaultOptions: {\n      react: {\n        suspense: {\n          autoDisposeTimeoutMs: 5000,\n        },\n      },\n    },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query);\n\n  // We don't start the dispose timer until the promise is initially resolved\n  // so we need to wait for it\n  jest.advanceTimersByTime(20);\n  await preloadQuery.toPromise(queryRef);\n  jest.advanceTimersByTime(5_000);\n\n  expect(queryRef).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n\n  jest.useRealTimers();\n});\n\ntest(\"useReadQuery auto-retains the queryRef and disposes of it when unmounted\", async () => {\n  jest.useFakeTimers();\n  const { query, mocks } = setupSimpleCase();\n\n  const client = createDefaultClient(mocks);\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query);\n\n  const { unmount } = await renderHookAsync(() => useReadQuery(queryRef));\n\n  // We don't start the dispose timer until the promise is initially resolved\n  // so we need to wait for it\n  jest.advanceTimersByTime(20);\n  await act(() => preloadQuery.toPromise(queryRef));\n  jest.advanceTimersByTime(30_000);\n\n  expect(queryRef).not.toBeDisposed();\n\n  jest.useRealTimers();\n\n  unmount();\n\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n  expect(client.getObservableQueries().size).toBe(0);\n  expect(client).not.toHaveSuspenseCacheEntryUsing(query);\n});\n\ntest(\"useReadQuery auto-resubscribes the query after its disposed\", async () => {\n  const { query } = setupSimpleCase();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    let count = ++fetchCount;\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { greeting: `Hello ${count}` } });\n        observer.complete();\n      }, 100);\n    });\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const user = userEvent.setup();\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query);\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await wait(0);\n  await renderStream.takeRender();\n\n  expect(queryRef).toBeDisposed();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // Ensure we aren't refetching the data by checking we still render the same\n  // cache result\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  client.writeQuery({ query, data: { greeting: \"Hello (cached)\" } });\n\n  // Ensure we can get cache updates again after remounting\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello (cached)\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Write a cache result to ensure that remounting will read this result\n  // instead of the old one\n  client.writeQuery({ query, data: { greeting: \"While you were away\" } });\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we read the newest cache result changed while this queryRef was\n  // disposed\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"While you were away\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Remove cached data to ensure remounting will refetch the data\n  client.cache.modify({\n    fields: {\n      greeting: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  // we wait a moment to ensure no network request is triggered\n  // by the `cache.modify` (even with a slight delay)\n  await wait(10);\n  expect(fetchCount).toBe(1);\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // this should now trigger a network request\n  expect(fetchCount).toBe(2);\n  expect(queryRef).not.toBeDisposed();\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 2\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"useReadQuery handles auto-resubscribe with returnPartialData\", async () => {\n  const { query, mocks } = setupVariablesCase();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    fetchCount++;\n    const mock = mocks.find(\n      (mock) =>\n        typeof mock.request.variables === \"object\" &&\n        mock.request.variables?.id === operation.variables.id\n    );\n\n    if (!mock) {\n      throw new Error(\"Could not find mock for variables\");\n    }\n\n    const result = mock.result as Record<string, any>;\n\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: result.data });\n        observer.complete();\n      }, 100);\n    });\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<\n        VariablesCaseData,\n        \"complete\" | \"streaming\" | \"partial\"\n      > | null,\n    },\n  });\n  const user = userEvent.setup();\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, {\n    returnPartialData: true,\n    variables: { id: \"1\" },\n  });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await wait(0);\n  await renderStream.takeRender();\n\n  expect(queryRef).toBeDisposed();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // Ensure we aren't refetching the data by checking we still render the same\n  // cache result\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  client.writeQuery({\n    query,\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Spider-Man (cached)\",\n      },\n    },\n    variables: { id: \"1\" },\n  });\n\n  // Ensure we can get cache updates again after remounting\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Spider-Man (cached)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Write a cache result to ensure that remounting will read this result\n  // instead of the old one\n  client.writeQuery({\n    query,\n    data: {\n      character: {\n        __typename: \"Character\",\n        id: \"1\",\n        name: \"Spider-Man (Away)\",\n      },\n    },\n    variables: { id: \"1\" },\n  });\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we read the newest cache result changed while this queryRef was\n  // disposed\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: {\n          __typename: \"Character\",\n          id: \"1\",\n          name: \"Spider-Man (Away)\",\n        },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Remove cached data to ensure remounting will refetch the data\n  client.cache.modify({\n    id: \"Character:1\",\n    fields: {\n      name: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  // we wait a moment to ensure no network request is triggered\n  // by the `cache.modify` (even with a slight delay)\n  await wait(10);\n  expect(fetchCount).toBe(1);\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // this should now trigger a network request\n  expect(fetchCount).toBe(2);\n  expect(queryRef).not.toBeDisposed();\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  // Ensure that remounting without data in the cache will fetch and suspend\n  void client.clearStore();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(fetchCount).toBe(3);\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"useReadQuery handles auto-resubscribe on network-only fetch policy\", async () => {\n  const { query } = setupSimpleCase();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    let count = ++fetchCount;\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { greeting: `Hello ${count}` } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const user = userEvent.setup();\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { fetchPolicy: \"network-only\" });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await wait(0);\n  await renderStream.takeRender();\n\n  expect(queryRef).toBeDisposed();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // Ensure we aren't refetching the data by checking we still render the same\n  // cache result\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  client.writeQuery({ query, data: { greeting: \"Hello (cached)\" } });\n\n  // Ensure we can get cache updates again after remounting\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello (cached)\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Write a cache result to ensure that remounting will read this result\n  // instead of the old one\n  client.writeQuery({ query, data: { greeting: \"While you were away\" } });\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we read the newest cache result changed while this queryRef was\n  // disposed\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"While you were away\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Remove cached data to ensure remounting will refetch the data\n  client.cache.modify({\n    fields: {\n      greeting: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  // Ensure the delete doesn't immediately fetch\n  await wait(10);\n  expect(fetchCount).toBe(1);\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(fetchCount).toBe(2);\n  expect(queryRef).not.toBeDisposed();\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 2\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"useReadQuery handles auto-resubscribe on cache-and-network fetch policy\", async () => {\n  const { query } = setupSimpleCase();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    let count = ++fetchCount;\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { greeting: `Hello ${count}` } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const user = userEvent.setup();\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { fetchPolicy: \"cache-and-network\" });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await wait(0);\n  await renderStream.takeRender();\n\n  expect(queryRef).toBeDisposed();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // Ensure we aren't refetching the data by checking we still render the same\n  // cache result\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  client.writeQuery({ query, data: { greeting: \"Hello (cached)\" } });\n\n  // Ensure we can get cache updates again after remounting\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello (cached)\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Write a cache result to ensure that remounting will read this result\n  // instead of the old one\n  client.writeQuery({ query, data: { greeting: \"While you were away\" } });\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we read the newest cache result changed while this queryRef was\n  // disposed\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"While you were away\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Remove cached data to ensure remounting will refetch the data\n  client.cache.modify({\n    fields: {\n      greeting: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  // Ensure delete doesn't refetch immediately\n  await wait(10);\n  expect(fetchCount).toBe(1);\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(fetchCount).toBe(2);\n  expect(queryRef).not.toBeDisposed();\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, SuspenseFallback]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 2\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"useReadQuery handles auto-resubscribe on no-cache fetch policy\", async () => {\n  const { query } = setupSimpleCase();\n\n  let fetchCount = 0;\n  const link = new ApolloLink((operation) => {\n    let count = ++fetchCount;\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { greeting: `Hello ${count}` } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const renderStream = createRenderStream({\n    initialSnapshot: {\n      result: null as useReadQuery.Result<SimpleCaseData> | null,\n    },\n  });\n  const user = userEvent.setup();\n  const client = new ApolloClient({ cache: new InMemoryCache(), link });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { fetchPolicy: \"no-cache\" });\n\n  function SuspenseFallback() {\n    useTrackRenders();\n    return <div>Loading</div>;\n  }\n\n  function App() {\n    useTrackRenders();\n    const [show, setShow] = React.useState(true);\n\n    return (\n      <>\n        <button onClick={() => setShow((show) => !show)}>Toggle</button>\n        <Suspense fallback={<SuspenseFallback />}>\n          {show && <ReadQueryHook />}\n        </Suspense>\n      </>\n    );\n  }\n\n  function ReadQueryHook() {\n    useTrackRenders();\n    renderStream.mergeSnapshot({ result: useReadQuery(queryRef) });\n\n    return null;\n  }\n\n  await renderStream.render(<App />, { wrapper: createClientWrapper(client) });\n\n  const toggleButton = screen.getByText(\"Toggle\");\n\n  // initial render\n  await renderStream.takeRender();\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await wait(0);\n  await renderStream.takeRender();\n\n  expect(queryRef).toBeDisposed();\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  // Ensure we aren't refetching the data by checking we still render the same\n  // result\n  {\n    const { renderedComponents, snapshot } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure caches writes for the query are ignored by the hook\n  client.writeQuery({ query, data: { greeting: \"Hello (cached)\" } });\n\n  await expect(renderStream).not.toRerender();\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Write a cache result to ensure that remounting will ignore this result\n  client.writeQuery({ query, data: { greeting: \"While you were away\" } });\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we continue to read the same value\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(fetchCount).toBe(1);\n\n  // unmount ReadQueryHook\n  await user.click(toggleButton);\n  await renderStream.takeRender();\n  await wait(0);\n\n  expect(queryRef).toBeDisposed();\n\n  // Remove cached data to verify this type of cache change is also ignored\n  client.cache.modify({\n    fields: {\n      greeting: (_, { DELETE }) => DELETE,\n    },\n  });\n\n  // Ensure delete doesn't fire off request\n  await wait(10);\n  expect(fetchCount).toBe(1);\n\n  // mount ReadQueryHook\n  await user.click(toggleButton);\n\n  expect(fetchCount).toBe(1);\n  expect(queryRef).not.toBeDisposed();\n\n  // Ensure we are still rendering the same result and haven't refetched\n  // anything based on missing cache data\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([App, ReadQueryHook]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello 1\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"reacts to cache updates\", async () => {\n  const { query, mocks } = setupSimpleCase();\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  client.writeQuery({\n    query,\n    data: { greeting: \"Hello (updated)\" },\n  });\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello (updated)\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"ignores cached result and suspends when `fetchPolicy` is network-only\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = createDefaultClient(mocks);\n  client.writeQuery({ query, data: { greeting: \"Cached Hello\" } });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    fetchPolicy: \"network-only\",\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"does not cache results when `fetchPolicy` is no-cache\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    fetchPolicy: \"no-cache\",\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  expect(client.extract()).toEqual({});\n});\n\ntest(\"returns initial cache data followed by network data when `fetchPolicy` is cache-and-network\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = createDefaultClient(mocks);\n  client.writeQuery({ query, data: { greeting: \"Cached Hello\" } });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    fetchPolicy: \"cache-and-network\",\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Cached Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.loading,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"returns cached data when all data is present in the cache\", async () => {\n  const { query, mocks } = setupSimpleCase();\n\n  const client = createDefaultClient(mocks);\n  client.writeQuery({ query, data: { greeting: \"Cached Hello\" } });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { greeting: \"Cached Hello\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"suspends and ignores partial data in the cache\", async () => {\n  const query = gql`\n    query {\n      hello\n      foo\n    }\n  `;\n\n  const mocks = [\n    {\n      request: { query },\n      result: { data: { hello: \"from link\", foo: \"bar\" } },\n      delay: 20,\n    },\n  ];\n\n  const client = createDefaultClient(mocks);\n\n  {\n    // we expect a \"Missing field 'foo' while writing result...\" error\n    // when writing hello to the cache, so we'll silence it\n    using _consoleSpy = spyOnConsole(\"error\");\n    client.writeQuery({ query, data: { hello: \"from cache\" } });\n  }\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { hello: \"from link\", foo: \"bar\" },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n\n  await expect(renderStream).not.toRerender();\n});\n\ntest(\"throws when error is returned\", async () => {\n  // Disable error messages shown by React when an error is thrown to an error\n  // boundary\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query } = setupSimpleCase();\n  const mocks = [\n    {\n      request: { query },\n      result: { errors: [new GraphQLError(\"Oops\")] },\n      delay: 20,\n    },\n  ];\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query);\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ErrorFallback\"]);\n    expect(snapshot.error).toEqual(\n      new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] })\n    );\n  }\n});\n\ntest(\"returns error when error policy is 'all'\", async () => {\n  // Disable error messages shown by React when an error is thrown to an error\n  // boundary\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query } = setupSimpleCase();\n  const mocks = [\n    { request: { query }, result: { errors: [new GraphQLError(\"Oops\")] } },\n  ];\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, { errorPolicy: \"all\" });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new CombinedGraphQLErrors({ errors: [{ message: \"Oops\" }] }),\n      networkStatus: NetworkStatus.error,\n    });\n    expect(snapshot.error).toEqual(null);\n  }\n});\n\ntest(\"returns network error when error policy is 'all'\", async () => {\n  // Disable error messages shown by React when an error is thrown to an error\n  // boundary\n  using _consoleSpy = spyOnConsole(\"error\");\n  const { query } = setupSimpleCase();\n  const mocks = [{ request: { query }, error: new Error(\"Oops\") }];\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, { errorPolicy: \"all\" });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new Error(\"Oops\"),\n      networkStatus: NetworkStatus.error,\n    });\n    expect(snapshot.error).toEqual(null);\n  }\n});\n\ntest(\"discards error when error policy is 'ignore'\", async () => {\n  const { query } = setupSimpleCase();\n  const mocks = [\n    { request: { query }, result: { errors: [new GraphQLError(\"Oops\")] } },\n  ];\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, { errorPolicy: \"ignore\" });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(snapshot.error).toEqual(null);\n  }\n});\n\ntest(\"discards network errors when error policy is 'ignore'\", async () => {\n  const { query } = setupSimpleCase();\n  const mocks = [{ request: { query }, error: new Error(\"Oops\") }];\n  const client = createDefaultClient(mocks);\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, { errorPolicy: \"ignore\" });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n    expect(snapshot.error).toEqual(null);\n  }\n});\n\ntest(\"passes context to the link\", async () => {\n  interface QueryData {\n    context: Record<string, any>;\n  }\n\n  const query: TypedDocumentNode<QueryData, Record<string, never>> = gql`\n    query ContextQuery {\n      context\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new ApolloLink((operation) => {\n      return new Observable((observer) => {\n        const { valueA, valueB } = operation.getContext();\n        setTimeout(() => {\n          observer.next({ data: { context: { valueA, valueB } } });\n          observer.complete();\n        }, 10);\n      });\n    }),\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    context: { valueA: \"A\", valueB: \"B\" },\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  // initial render\n  await renderStream.takeRender();\n\n  const { snapshot } = await renderStream.takeRender();\n\n  expect(snapshot.result).toStrictEqualTyped({\n    data: { context: { valueA: \"A\", valueB: \"B\" } },\n    dataState: \"complete\",\n    networkStatus: NetworkStatus.ready,\n    error: undefined,\n  });\n});\n\ntest(\"creates unique query refs when calling preloadQuery with the same query\", async () => {\n  const { query } = setupSimpleCase();\n\n  const mocks: MockLink.MockedResponse[] = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      maxUsageCount: Infinity,\n    },\n  ];\n\n  const client = createDefaultClient(mocks);\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef1 = preloadQuery(query);\n  const queryRef2 = preloadQuery(query);\n\n  const unwrappedQueryRef1 = unwrapQueryRef(queryRef1);\n  const unwrappedQueryRef2 = unwrapQueryRef(queryRef2);\n\n  // Use Object.is inside expect to prevent circular reference errors on toBe\n  expect(Object.is(queryRef1, queryRef2)).toBe(false);\n  expect(Object.is(unwrappedQueryRef1, unwrappedQueryRef2)).toBe(false);\n\n  await expect(preloadQuery.toPromise(queryRef1)).resolves.toBe(queryRef1);\n  await expect(preloadQuery.toPromise(queryRef2)).resolves.toBe(queryRef2);\n});\n\ntest(\"does not suspend and returns partial data when `returnPartialData` is `true`\", async () => {\n  const { query, mocks } = setupVariablesCase();\n  const partialQuery = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n      }\n    }\n  `;\n\n  const client = createDefaultClient(mocks);\n\n  client.writeQuery({\n    query: partialQuery,\n    data: { character: { __typename: \"Character\", id: \"1\" } },\n    variables: { id: \"1\" },\n  });\n\n  const preloadQuery = createQueryPreloader(client);\n  const queryRef = preloadQuery(query, {\n    variables: { id: \"1\" },\n    returnPartialData: true,\n  });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp({ client, queryRef });\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: { character: { __typename: \"Character\", id: \"1\" } },\n      dataState: \"partial\",\n      networkStatus: NetworkStatus.loading,\n      error: undefined,\n    });\n  }\n\n  {\n    const { snapshot, renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"ReadQueryHook\"]);\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      networkStatus: NetworkStatus.ready,\n      error: undefined,\n    });\n  }\n});\n\ntest(\"masks result when dataMasking is `true`\", async () => {\n  const { query, mocks } = setupMaskedVariablesCase();\n  const client = new ApolloClient({\n    dataMasking: true,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { variables: { id: \"1\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp<MaskedVariablesCaseData>({\n    client,\n    queryRef,\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"does not mask result when dataMasking is `false`\", async () => {\n  const { query, mocks } = setupVariablesCase();\n  const client = new ApolloClient({\n    dataMasking: false,\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { variables: { id: \"1\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp<VariablesCaseData>({\n    client,\n    queryRef,\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ntest(\"does not mask results by default\", async () => {\n  const { query, mocks } = setupVariablesCase();\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  const queryRef = preloadQuery(query, { variables: { id: \"1\" } });\n\n  using _disabledAct = disableActEnvironment();\n  const { renderStream } = await renderDefaultTestApp<VariablesCaseData>({\n    client,\n    queryRef,\n  });\n\n  {\n    const { renderedComponents } = await renderStream.takeRender();\n\n    expect(renderedComponents).toStrictEqual([\"App\", \"SuspenseFallback\"]);\n  }\n\n  {\n    const { snapshot } = await renderStream.takeRender();\n\n    expect(snapshot.result).toStrictEqualTyped({\n      data: {\n        character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n      },\n      dataState: \"complete\",\n      error: undefined,\n      networkStatus: NetworkStatus.ready,\n    });\n  }\n});\n\ndescribe(\"`PreloadedQueryRef` disposal\", () => {\n  test(\"when the `PreloadedQueryRef` is disposed of, the ObservableQuery is unsubscribed\", async () => {\n    const { query, mocks } = setupVariablesCase();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n    const preloadQuery = createQueryPreloader(client);\n\n    let queryRef: PreloadedQueryRef | null = preloadQuery(query, {\n      variables: { id: \"1\" },\n    });\n    const internalQueryRef = unwrapQueryRef(queryRef)!;\n\n    expect(internalQueryRef.observable.hasObservers()).toBe(true);\n    expect(internalQueryRef[\"softReferences\"]).toBe(1);\n    queryRef = null;\n\n    await waitFor(() => {\n      global.gc!();\n      expect(internalQueryRef.observable.hasObservers()).toBe(false);\n    });\n    expect(internalQueryRef[\"softReferences\"]).toBe(0);\n  });\n\n  test(\"when the `PreloadedQueryRef` is disposed of, while the initial request is still ongoing the ObservableQuery stays subscribed to\", async () => {\n    const { query } = setupVariablesCase();\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n    const preloadQuery = createQueryPreloader(client);\n\n    let queryRef: PreloadedQueryRef | null = preloadQuery(query, {\n      variables: { id: \"1\" },\n    });\n    const internalQueryRef = unwrapQueryRef(queryRef)!;\n\n    expect(internalQueryRef.observable.hasObservers()).toBe(true);\n    expect(internalQueryRef[\"softReferences\"]).toBe(1);\n    queryRef = null;\n\n    await expect(\n      waitFor(() => {\n        global.gc!();\n        expect(internalQueryRef.observable.hasObservers()).toBe(false);\n      })\n    ).rejects.toThrow();\n    expect(internalQueryRef[\"softReferences\"]).toBe(1);\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            character: { __typename: \"Character\", id: \"1\", name: \"Spider-Man\" },\n          },\n        },\n      },\n      true\n    );\n\n    await waitFor(() => {\n      global.gc!();\n      expect(internalQueryRef.observable.hasObservers()).toBe(false);\n    });\n    expect(internalQueryRef[\"softReferences\"]).toBe(0);\n  });\n\n  test(\"when retained by a component, the soft retain lets go\", async () => {\n    const { query, mocks } = setupVariablesCase();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: new MockLink(mocks),\n    });\n    const preloadQuery = createQueryPreloader(client);\n\n    const queryRef = preloadQuery(query, {\n      variables: { id: \"1\" },\n    });\n    const internalQueryRef = unwrapQueryRef(queryRef)!;\n\n    expect(internalQueryRef[\"softReferences\"]).toBe(1);\n\n    using _disabledAct = disableActEnvironment();\n    const { renderStream } = await renderDefaultTestApp<VariablesCaseData>({\n      client,\n      queryRef,\n    });\n    await renderStream.takeRender();\n    await renderStream.takeRender();\n\n    expect(internalQueryRef[\"softReferences\"]).toBe(0);\n  });\n});\n\ndescribe.skip(\"type tests\", () => {\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([]),\n  });\n  const preloadQuery = createQueryPreloader(client);\n\n  test(\"variables are optional and can be anything with untyped DocumentNode\", () => {\n    const query = gql``;\n\n    preloadQuery(query);\n    preloadQuery(query, { variables: {} });\n    preloadQuery(query, { returnPartialData: true, variables: {} });\n    preloadQuery(query, { variables: { foo: \"bar\" } });\n    preloadQuery(query, { variables: { foo: \"bar\", bar: 2 } });\n  });\n\n  test(\"variables are optional and can be anything with unspecified TVariables\", () => {\n    type Data = { greeting: string };\n    const query: TypedDocumentNode<Data> = gql``;\n\n    preloadQuery(query);\n    preloadQuery<Data>(query);\n    preloadQuery(query, { variables: {} });\n    preloadQuery<Data>(query, { variables: {} });\n    preloadQuery(query, { returnPartialData: true, variables: {} });\n    preloadQuery<Data>(query, { returnPartialData: true, variables: {} });\n    preloadQuery(query, { variables: { foo: \"bar\" } });\n    preloadQuery<Data>(query, { variables: { foo: \"bar\" } });\n    preloadQuery(query, { variables: { foo: \"bar\", bar: 2 } });\n    preloadQuery<Data>(query, { variables: { foo: \"bar\", bar: 2 } });\n  });\n\n  test(\"variables are optional when TVariables are empty\", () => {\n    type Data = { greeting: string };\n    type Variables = Record<string, never>;\n    const query: TypedDocumentNode<Data, Variables> = gql``;\n\n    preloadQuery(query);\n    preloadQuery<Data, Variables>(query);\n    preloadQuery(query, { variables: {} });\n    preloadQuery<Data, Variables>(query, { variables: {} });\n    preloadQuery(query, { returnPartialData: true, variables: {} });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {},\n    });\n    preloadQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variables\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"is invalid when TVariables is `never`\", () => {\n    type Data = { greeting: string };\n    const query: TypedDocumentNode<Data, never> = gql``;\n\n    // @ts-expect-error\n    preloadQuery(query);\n    // @ts-expect-error\n    preloadQuery<Data, never>(query);\n    preloadQuery(query, {\n      // @ts-expect-error\n      variables: {},\n    });\n    preloadQuery<Data, never>(query, {\n      // @ts-expect-error\n      variables: {},\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      // @ts-expect-error\n      variables: {},\n    });\n    preloadQuery<Data, never>(query, {\n      returnPartialData: true,\n      // @ts-expect-error\n      variables: {},\n    });\n    preloadQuery(query, {\n      // @ts-expect-error no variables allowed\n      variables: { foo: \"bar\" },\n    });\n    preloadQuery<Data, never>(query, {\n      // @ts-expect-error no variables allowed\n      variables: { foo: \"bar\" },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      // @ts-expect-error no variables allowed\n      variables: {\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, never>(query, {\n      returnPartialData: true,\n      // @ts-expect-error no variables allowed\n      variables: {\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"optional variables are optional\", () => {\n    type Data = { posts: string[] };\n    type Variables = { limit?: number };\n    const query: TypedDocumentNode<Data, Variables> = gql``;\n\n    preloadQuery(query);\n    preloadQuery<Data, Variables>(query);\n    preloadQuery(query, { variables: {} });\n    preloadQuery<Data, Variables>(query, { variables: {} });\n    preloadQuery(query, { returnPartialData: true, variables: {} });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {},\n    });\n    preloadQuery(query, { variables: { limit: 10 } });\n    preloadQuery<Data, Variables>(query, { variables: { limit: 10 } });\n    preloadQuery(query, { returnPartialData: true, variables: { limit: 10 } });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: { limit: 10 },\n    });\n    preloadQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        limit: 10,\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"enforces required variables\", () => {\n    type Data = { character: string };\n    type Variables = { id: string };\n    const query: TypedDocumentNode<Data, Variables> = gql``;\n\n    // @ts-expect-error missing variables option\n    preloadQuery(query);\n    // @ts-expect-error missing variables option\n    preloadQuery<Data, Variables>(query);\n    // @ts-expect-error missing variables option\n    preloadQuery(query, { returnPartialData: true });\n    // @ts-expect-error missing variables option\n    preloadQuery<Data, Variables>(query, { returnPartialData: true });\n    preloadQuery(query, {\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    preloadQuery<Data, Variables>(query, {\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      // @ts-expect-error empty variables\n      variables: {},\n    });\n    preloadQuery(query, { variables: { id: \"1\" } });\n    preloadQuery<Data, Variables>(query, { variables: { id: \"1\" } });\n    preloadQuery(query, { returnPartialData: true, variables: { id: \"1\" } });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: { id: \"1\" },\n    });\n    preloadQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"requires variables with mixed TVariables\", () => {\n    type Data = { character: string };\n    type Variables = { id: string; language?: string };\n    const query: TypedDocumentNode<Data, Variables> = gql``;\n\n    // @ts-expect-error missing variables argument\n    preloadQuery(query);\n    // @ts-expect-error missing variables argument\n    preloadQuery<Data, Variables>(query);\n    // @ts-expect-error missing variables argument\n    preloadQuery(query, {});\n    // @ts-expect-error missing variables argument\n    preloadQuery<Data, Variables>(query, {});\n    // @ts-expect-error missing variables option\n    preloadQuery(query, { returnPartialData: true });\n    // @ts-expect-error missing variables option\n    preloadQuery<Data, Variables>(query, { returnPartialData: true });\n    preloadQuery(query, {\n      // @ts-expect-error missing required variables\n      variables: {},\n    });\n    preloadQuery<Data, Variables>(query, {\n      // @ts-expect-error missing required variables\n      variables: {},\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      // @ts-expect-error missing required variables\n      variables: {},\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      // @ts-expect-error missing required variables\n      variables: {},\n    });\n    preloadQuery(query, { variables: { id: \"1\" } });\n    preloadQuery<Data, Variables>(query, { variables: { id: \"1\" } });\n    preloadQuery(query, {\n      // @ts-expect-error missing required variable\n      variables: { language: \"en\" },\n    });\n    preloadQuery<Data, Variables>(query, {\n      // @ts-expect-error missing required variable\n      variables: { language: \"en\" },\n    });\n    preloadQuery(query, { variables: { id: \"1\", language: \"en\" } });\n    preloadQuery<Data, Variables>(query, {\n      variables: { id: \"1\", language: \"en\" },\n    });\n    preloadQuery(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      returnPartialData: true,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      returnPartialData: true,\n      variables: {\n        id: \"1\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery(query, {\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n    preloadQuery<Data, Variables>(query, {\n      variables: {\n        id: \"1\",\n        language: \"en\",\n        // @ts-expect-error unknown variable\n        foo: \"bar\",\n      },\n    });\n  });\n\n  test(\"returns QueryReference<unknown> when TData cannot be inferred\", () => {\n    const query = gql``;\n\n    const queryRef = preloadQuery(query);\n    const { data, dataState } = useReadQuery(queryRef);\n\n    expectTypeOf(queryRef).toEqualTypeOf<\n      PreloadedQueryRef<unknown, OperationVariables, \"complete\" | \"streaming\">\n    >();\n    expectTypeOf(data).toEqualTypeOf<unknown>();\n    expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n  });\n\n  test(\"returns QueryReference<TData> in default case\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query);\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query);\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          OperationVariables,\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<TData | undefined> with errorPolicy: 'ignore'\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { errorPolicy: \"ignore\" });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        errorPolicy: \"ignore\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<TData | undefined> with errorPolicy: 'all'\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { errorPolicy: \"all\" });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        errorPolicy: \"all\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData> | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<TData> with errorPolicy: 'none'\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { errorPolicy: \"none\" });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        errorPolicy: \"none\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<DeepPartial<TData>> with returnPartialData: true\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { returnPartialData: true });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        returnPartialData: true,\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<DeepPartial<TData>> with returnPartialData: false\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { returnPartialData: false });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        returnPartialData: false,\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"returns QueryReference<TData> when passing an option unrelated to TData\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, { fetchPolicy: \"cache-first\" });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        fetchPolicy: \"cache-first\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        SimpleCaseData | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\"complete\" | \"streaming\">();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"handles combinations of options\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        returnPartialData: true,\n        errorPolicy: \"ignore\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n        | undefined\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n\n      if (dataState === \"empty\") {\n        expectTypeOf(data).toEqualTypeOf<undefined>();\n      }\n    }\n\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n  });\n\n  test(\"returns correct TData type when combined with options unrelated to TData\", () => {\n    {\n      const query: TypedDocumentNode<SimpleCaseData> = gql``;\n      const queryRef = preloadQuery(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n\n    {\n      const query = gql``;\n      const queryRef = preloadQuery<SimpleCaseData>(query, {\n        fetchPolicy: \"cache-first\",\n        returnPartialData: true,\n        errorPolicy: \"none\",\n      });\n      const { data, dataState } = useReadQuery(queryRef);\n\n      expectTypeOf(queryRef).toEqualTypeOf<\n        PreloadedQueryRef<\n          SimpleCaseData,\n          { [key: string]: any },\n          \"complete\" | \"streaming\" | \"partial\"\n        >\n      >();\n      expectTypeOf(data).toEqualTypeOf<\n        | SimpleCaseData\n        | DeepPartial<SimpleCaseData>\n        | DataValue.Streaming<SimpleCaseData>\n      >();\n      expectTypeOf(dataState).toEqualTypeOf<\n        \"complete\" | \"streaming\" | \"partial\"\n      >();\n\n      if (dataState === \"complete\") {\n        expectTypeOf(data).toEqualTypeOf<SimpleCaseData>();\n      }\n\n      if (dataState === \"streaming\") {\n        expectTypeOf(data).toEqualTypeOf<DataValue.Streaming<SimpleCaseData>>();\n      }\n\n      if (dataState === \"partial\") {\n        expectTypeOf(data).toEqualTypeOf<DeepPartial<SimpleCaseData>>();\n      }\n    }\n  });\n});\n"
  },
  {
    "path": "src/react/query-preloader/createQueryPreloader.ts",
    "content": "import type {\n  ApolloClient,\n  DefaultContext,\n  DocumentNode,\n  ErrorPolicy,\n  OperationVariables,\n  RefetchWritePolicy,\n  TypedDocumentNode,\n  WatchQueryFetchPolicy,\n} from \"@apollo/client\";\nimport type { PreloadedQueryRef } from \"@apollo/client/react\";\nimport {\n  assertWrappedQueryRef,\n  getWrappedPromise,\n  InternalQueryReference,\n  wrapQueryRef,\n} from \"@apollo/client/react/internal\";\nimport type {\n  NoInfer,\n  VariablesOption,\n} from \"@apollo/client/utilities/internal\";\nimport { FinalizationRegistry } from \"@apollo/client/utilities/internal/ponyfills\";\n\nimport { wrapHook } from \"../hooks/internal/index.js\";\n\nexport type PreloadQueryFetchPolicy = Extract<\n  WatchQueryFetchPolicy,\n  \"cache-first\" | \"network-only\" | \"no-cache\" | \"cache-and-network\"\n>;\n\nexport type PreloadQueryOptions<\n  TVariables extends OperationVariables = OperationVariables,\n> = {\n  /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#context:member} */\n  context?: DefaultContext;\n  /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#errorPolicy:member} */\n  errorPolicy?: ErrorPolicy;\n  /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#fetchPolicy:member} */\n  fetchPolicy?: PreloadQueryFetchPolicy;\n  /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#returnPartialData:member} */\n  returnPartialData?: boolean;\n  /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#refetchWritePolicy:member} */\n  refetchWritePolicy?: RefetchWritePolicy;\n} & VariablesOption<TVariables>;\n\n/**\n * A function that will begin loading a query when called. It's result can be\n * read by `useReadQuery` which will suspend until the query is loaded.\n * This is useful when you want to start loading a query as early as possible\n * outside of a React component.\n *\n * @example\n *\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * const queryRef = preloadQuery(query, { variables, ...otherOptions });\n *\n * function App() {\n *   return (\n *     <Suspense fallback={<div>Loading</div>}>\n *       <MyQuery />\n *     </Suspense>\n *   );\n * }\n *\n * function MyQuery() {\n *   const { data } = useReadQuery(queryRef);\n *\n *   // do something with `data`\n * }\n * ```\n */\nexport interface PreloadQueryFunction {\n  /** {@inheritDoc @apollo/client/react!PreloadQueryFunction:interface} */\n  <TData = unknown, TVariables extends OperationVariables = OperationVariables>(\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    options: PreloadQueryOptions<NoInfer<TVariables>> & {\n      returnPartialData: true;\n      errorPolicy: \"ignore\" | \"all\";\n    }\n  ): PreloadedQueryRef<\n    TData,\n    TVariables,\n    \"complete\" | \"streaming\" | \"partial\" | \"empty\"\n  >;\n\n  /** {@inheritDoc @apollo/client/react!PreloadQueryFunction:interface} */\n  <TData = unknown, TVariables extends OperationVariables = OperationVariables>(\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    options: PreloadQueryOptions<NoInfer<TVariables>> & {\n      errorPolicy: \"ignore\" | \"all\";\n    }\n  ): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"empty\">;\n\n  /** {@inheritDoc @apollo/client/react!PreloadQueryFunction:interface} */\n  <TData = unknown, TVariables extends OperationVariables = OperationVariables>(\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    options: PreloadQueryOptions<NoInfer<TVariables>> & {\n      returnPartialData: true;\n    }\n  ): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\" | \"partial\">;\n\n  /** {@inheritDoc @apollo/client/react!PreloadQueryFunction:interface} */\n  <TData = unknown, TVariables extends OperationVariables = OperationVariables>(\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    ...[options]: {} extends TVariables ?\n      [options?: PreloadQueryOptions<NoInfer<TVariables>>]\n    : [options: PreloadQueryOptions<NoInfer<TVariables>>]\n  ): PreloadedQueryRef<TData, TVariables, \"complete\" | \"streaming\">;\n\n  /**\n   * A function that returns a promise that resolves when the query has finished\n   * loading. The promise resolves with the `QueryReference` itself.\n   *\n   * @remarks\n   * This method is useful for preloading queries in data loading routers, such\n   * as [React Router](https://reactrouter.com/en/main) or [TanStack Router](https://tanstack.com/router),\n   * to prevent routes from transitioning until the query has finished loading.\n   * `data` is not exposed on the promise to discourage using the data in\n   * `loader` functions and exposing it to your route components. Instead, we\n   * prefer you rely on `useReadQuery` to access the data to ensure your\n   * component can rerender with cache updates. If you need to access raw query\n   * data, use `client.query()` directly.\n   *\n   * @example\n   * Here's an example using React Router's `loader` function:\n   *\n   * ```ts\n   * import { createQueryPreloader } from \"@apollo/client\";\n   *\n   * const preloadQuery = createQueryPreloader(client);\n   *\n   * export async function loader() {\n   *   const queryRef = preloadQuery(GET_DOGS_QUERY);\n   *\n   *   return preloadQuery.toPromise(queryRef);\n   * }\n   *\n   * export function RouteComponent() {\n   *   const queryRef = useLoaderData();\n   *   const { data } = useReadQuery(queryRef);\n   *\n   *   // ...\n   * }\n   * ```\n   */\n  toPromise<TQueryRef extends PreloadedQueryRef<any, any, any>>(\n    queryRef: TQueryRef\n  ): Promise<TQueryRef>;\n}\n\n/**\n * A higher order function that returns a `preloadQuery` function which\n * can be used to begin loading a query with the given `client`. This is useful\n * when you want to start loading a query as early as possible outside of a\n * React component.\n *\n * > Refer to the [Suspense - Initiating queries outside React](https://www.apollographql.com/docs/react/data/suspense#initiating-queries-outside-react) section for a more in-depth overview.\n *\n * @param client - The `ApolloClient` instance that will be used to load queries\n * from the returned `preloadQuery` function.\n * @returns The `preloadQuery` function.\n *\n * @example\n *\n * ```js\n * const preloadQuery = createQueryPreloader(client);\n * ```\n */\nexport function createQueryPreloader(\n  client: ApolloClient\n): PreloadQueryFunction {\n  return wrapHook(\n    \"createQueryPreloader\",\n    _createQueryPreloader,\n    client\n  )(client);\n}\n\nconst _createQueryPreloader: typeof createQueryPreloader = (client) => {\n  function preloadQuery<\n    TData = unknown,\n    TVariables extends OperationVariables = OperationVariables,\n  >(\n    query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n    options: PreloadQueryOptions<NoInfer<TVariables>> &\n      VariablesOption<TVariables> = {} as any\n  ): PreloadedQueryRef<TData, TVariables> {\n    const queryRef = new InternalQueryReference(\n      client.watchQuery({\n        ...options,\n        query,\n        notifyOnNetworkStatusChange: false,\n      } as ApolloClient.WatchQueryOptions<any, any>),\n      {\n        autoDisposeTimeoutMs:\n          client.defaultOptions.react?.suspense?.autoDisposeTimeoutMs,\n      }\n    );\n\n    const wrapped = wrapQueryRef(queryRef) as unknown as PreloadedQueryRef<\n      TData,\n      TVariables\n    >;\n    softRetainWhileReferenced(wrapped, queryRef);\n    return wrapped;\n  }\n\n  return Object.assign(preloadQuery, {\n    toPromise<TQueryRef extends PreloadedQueryRef<any, any, any>>(\n      queryRef: TQueryRef\n    ) {\n      assertWrappedQueryRef(queryRef);\n      return getWrappedPromise(queryRef).then(() => queryRef);\n    },\n  });\n};\n\n/**\n * Soft-retains the underlying `InternalQueryReference` while the `PreloadedQueryRef`\n * is still reachable.\n * When the `PreloadedQueryRef` is garbage collected, the soft retain is\n * disposed of, but only after the initial query has finished loading.\n * Once the `InternalQueryReference` is properly retained, the check for garbage\n * collection is unregistered and the soft retain is disposed of immediately.\n */\n// this is an individual function to avoid closing over any values more than necessary\nfunction softRetainWhileReferenced(\n  wrapped: PreloadedQueryRef<any, any, any>,\n  queryRef: InternalQueryReference\n) {\n  const { softDispose, delayedSoftDispose } = getCleanup(queryRef);\n  registry.register(wrapped, delayedSoftDispose, queryRef);\n  // This will unregister the cleanup from the finalization registry when\n  // the queryRef is properly retained.\n  // This is mostly done to keep the FinalizationRegistry from holding too many\n  // cleanup functions, as our React Native polyfill has to iterate all of them regularly.\n  queryRef.retain = unregisterOnRetain(queryRef.retain, softDispose);\n}\n\ntype RetainFunction = (\n  this: InternalQueryReference,\n  ...args: Parameters<InternalQueryReference[\"retain\"]>\n) => ReturnType<InternalQueryReference[\"retain\"]>;\n\n// this is an individual function to avoid closing over any values more than necessary\nfunction unregisterOnRetain(\n  originalRetain: RetainFunction,\n  softDispose: () => void\n): RetainFunction {\n  return function (...args) {\n    registry.unregister(this);\n    const dispose = originalRetain.apply(this, args);\n    softDispose();\n    return dispose;\n  };\n}\n\n// this is an individual function to avoid closing over any values more than necessary\nfunction getCleanup(queryRef: InternalQueryReference) {\n  const softDispose = queryRef.softRetain();\n  const initialPromise = queryRef.promise;\n\n  return {\n    softDispose,\n    delayedSoftDispose: () =>\n      initialPromise.finally(softDispose).catch(() => {}),\n  };\n}\n\nconst registry = new FinalizationRegistry<() => void>((cleanup) => cleanup());\n"
  },
  {
    "path": "src/react/ssr/__tests__/__snapshots__/prerenderStatic.test.tsx.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`real-life kitchen sink use case with prerender and \\`useSuspenseQuery\\` 1`] = `\"<!DOCTYPE html><html><head><meta charSet=\\\\\"utf-8\\\\\"/><meta name=\\\\\"viewport\\\\\" content=\\\\\"width=device-width, initial-scale=1\\\\\"/><link rel=\\\\\"preload\\\\\" as=\\\\\"script\\\\\" fetchPriority=\\\\\"low\\\\\" href=\\\\\"/main.js\\\\\"/><title>My app</title><link rel=\\\\\"stylesheet\\\\\" href=\\\\\"/styles.css\\\\\"/></head><body><!--$--><div><p>Hello <!-- -->world<!-- -->!</p><!--$--><p>My name is <!-- -->Apollo<!-- -->!</p><!--$--><p>Current time is <!-- -->2025-03-26T14:40:53.118Z<!-- -->!</p><!--/$--><!--/$--></div><!--/$--><script id=\\\\\"_R_\\\\\">window.__APOLLO_CLIENT_INIT__ = {\\\\\"ROOT_QUERY\\\\\":{\\\\\"__typename\\\\\":\\\\\"Query\\\\\",\\\\\"hello\\\\\":\\\\\"world\\\\\",\\\\\"whoami\\\\\":{\\\\\"name\\\\\":\\\\\"Apollo\\\\\"},\\\\\"currentTime\\\\\":\\\\\"2025-03-26T14:40:53.118Z\\\\\"}}</script><script src=\\\\\"/main.js\\\\\" async=\\\\\"\\\\\"></script></body></html>\"`;\n\nexports[`real-life kitchen sink use case with prerender and \\`useSuspenseQuery\\` 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"currentTime\": \"2025-03-26T14:40:53.118Z\",\n    \"hello\": \"world\",\n    \"whoami\": Object {\n      \"name\": \"Apollo\",\n    },\n  },\n}\n`;\n\nexports[`real-life kitchen sink use case with prerenderToNodeStream and \\`useSuspenseQuery\\` 1`] = `\"<!DOCTYPE html><html><head><meta charSet=\\\\\"utf-8\\\\\"/><meta name=\\\\\"viewport\\\\\" content=\\\\\"width=device-width, initial-scale=1\\\\\"/><link rel=\\\\\"preload\\\\\" as=\\\\\"script\\\\\" fetchPriority=\\\\\"low\\\\\" href=\\\\\"/main.js\\\\\"/><title>My app</title><link rel=\\\\\"stylesheet\\\\\" href=\\\\\"/styles.css\\\\\"/></head><body><!--$--><div><p>Hello <!-- -->world<!-- -->!</p><!--$--><p>My name is <!-- -->Apollo<!-- -->!</p><!--$--><p>Current time is <!-- -->2025-03-26T14:40:53.118Z<!-- -->!</p><!--/$--><!--/$--></div><!--/$--><script id=\\\\\"_R_\\\\\">window.__APOLLO_CLIENT_INIT__ = {\\\\\"ROOT_QUERY\\\\\":{\\\\\"__typename\\\\\":\\\\\"Query\\\\\",\\\\\"hello\\\\\":\\\\\"world\\\\\",\\\\\"whoami\\\\\":{\\\\\"name\\\\\":\\\\\"Apollo\\\\\"},\\\\\"currentTime\\\\\":\\\\\"2025-03-26T14:40:53.118Z\\\\\"}}</script><script src=\\\\\"/main.js\\\\\" async=\\\\\"\\\\\"></script></body></html>\"`;\n\nexports[`real-life kitchen sink use case with prerenderToNodeStream and \\`useSuspenseQuery\\` 2`] = `\nObject {\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"currentTime\": \"2025-03-26T14:40:53.118Z\",\n    \"hello\": \"world\",\n    \"whoami\": Object {\n      \"name\": \"Apollo\",\n    },\n  },\n}\n`;\n\nexports[`renderToStaticMarkup: AbortSignal times out during render - stops rerendering, returns partial result 1`] = `\"<div><p>Hello world!</p><p>My name is Apollo!</p><div>loading...</div></div>\"`;\n\nexports[`renderToString: AbortSignal times out during render - stops rerendering, returns partial result 1`] = `\"<div><p>Hello <!-- -->world<!-- -->!</p><p>My name is <!-- -->Apollo<!-- -->!</p><div>loading...</div></div>\"`;\n"
  },
  {
    "path": "src/react/ssr/__tests__/__snapshots__/useQuery.test.tsx.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`useQuery Hook SSR should return data written previously to cache during SSR pass if using cache-only fetchPolicy 1`] = `\nObject {\n  \"Order:{\\\\\"selection\\\\\":\\\\\"RELEVANCE\\\\\"}\": Object {\n    \"__typename\": \"Order\",\n    \"selection\": \"RELEVANCE\",\n  },\n  \"ROOT_QUERY\": Object {\n    \"__typename\": \"Query\",\n    \"getSearchResults\": Object {\n      \"__typename\": \"SearchResults\",\n      \"locale\": \"en-US\",\n      \"order\": Object {\n        \"__ref\": \"Order:{\\\\\"selection\\\\\":\\\\\"RELEVANCE\\\\\"}\",\n      },\n      \"pagination\": Object {\n        \"pageLimit\": 3,\n      },\n      \"results\": Array [\n        Object {\n          \"__ref\": \"SearchResult:1\",\n        },\n        Object {\n          \"__ref\": \"SearchResult:2\",\n        },\n        Object {\n          \"__ref\": \"SearchResult:3\",\n        },\n      ],\n    },\n  },\n  \"SearchResult:1\": Object {\n    \"__typename\": \"SearchResult\",\n    \"id\": 1,\n    \"text\": \"hi\",\n  },\n  \"SearchResult:2\": Object {\n    \"__typename\": \"SearchResult\",\n    \"id\": 2,\n    \"text\": \"hello\",\n  },\n  \"SearchResult:3\": Object {\n    \"__typename\": \"SearchResult\",\n    \"id\": 3,\n    \"text\": \"hey\",\n  },\n}\n`;\n"
  },
  {
    "path": "src/react/ssr/__tests__/getDataFromTree.test.tsx",
    "content": "// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport \"../../../testing/internal/messageChannelPolyfill.js\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  CombinedGraphQLErrors,\n} from \"@apollo/client\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport {\n  ApolloProvider,\n  getApolloContext,\n  useQuery,\n} from \"@apollo/client/react\";\nimport { getDataFromTree } from \"@apollo/client/react/ssr\";\nimport { MockLink } from \"@apollo/client/testing\";\n\ndescribe(\"SSR\", () => {\n  describe(\"`getDataFromTree`\", () => {\n    it(\"should support passing a root context\", async () => {\n      const client = new ApolloClient({\n        clientAwareness: {\n          name: \"oyez\",\n        },\n        cache: new Cache(),\n        link: ApolloLink.empty(),\n      });\n      const ApolloContext = getApolloContext();\n\n      function App() {\n        return (\n          <ApolloContext.Consumer>\n            {(context) => (\n              <div>\n                {\n                  context?.client?.[\"queryManager\"].clientOptions\n                    .clientAwareness?.name\n                }\n              </div>\n            )}\n          </ApolloContext.Consumer>\n        );\n      }\n\n      const html = await getDataFromTree(<App />, {\n        client,\n      });\n\n      expect(html).toEqual(\"<div>oyez</div>\");\n    });\n\n    it(\"should run through all of the queries (also defined via Query component) that want SSR\", async () => {\n      const query: TypedDocumentNode<Data> = gql`\n        {\n          currentUser {\n            firstName\n          }\n        }\n      `;\n      const data1 = { currentUser: { firstName: \"James\" } };\n      const link = new MockLink([\n        {\n          request: { query },\n          result: { data: data1 },\n          delay: 50,\n        },\n      ]);\n      const apolloClient = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      interface Data {\n        currentUser?: {\n          firstName: string;\n        };\n      }\n\n      function App() {\n        const { data, loading } = useQuery(query);\n\n        return (\n          <div>\n            {loading || !data ? \"loading\" : data.currentUser!.firstName}\n          </div>\n        );\n      }\n\n      const app = (\n        <ApolloProvider client={apolloClient}>\n          <App />\n        </ApolloProvider>\n      );\n\n      const markup = await getDataFromTree(app);\n\n      expect(markup).toMatch(/James/);\n    });\n\n    it('should pass any GraphQL errors in props along with data during a SSR when errorPolicy=\"all\"', async () => {\n      expect.assertions(3);\n      const query: DocumentNode = gql`\n        query people {\n          allPeople {\n            people {\n              name\n            }\n          }\n        }\n      `;\n      const link = new MockLink([\n        {\n          request: { query },\n          result: {\n            data: {\n              allPeople: {\n                people: null,\n              },\n            },\n            errors: [{ message: \"this is an error\" }],\n          },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        link,\n        cache: new Cache(),\n      });\n\n      function App() {\n        const { data, loading, error } = useQuery(query, {\n          errorPolicy: \"all\",\n        });\n\n        if (!loading) {\n          expect(data).toMatchObject({ allPeople: { people: null } });\n          expect(error).toBeDefined();\n          expect(error).toEqual(\n            new CombinedGraphQLErrors({\n              data: { allPeople: { people: null } },\n              errors: [{ message: \"this is an error\" }],\n            })\n          );\n        }\n\n        return null;\n      }\n\n      await getDataFromTree(\n        <ApolloProvider client={client}>\n          <App />\n        </ApolloProvider>\n      );\n    });\n  });\n});\n"
  },
  {
    "path": "src/react/ssr/__tests__/polyfillReactDomTypes.d.ts",
    "content": "/* eslint-disable local-rules/no-duplicate-exports */\ndeclare module \"react-dom/static.node\" {\n  export {\n    prerenderToNodeStream,\n    resumeAndPrerenderToNodeStream,\n  } from \"react-dom/static\";\n}\ndeclare module \"react-dom/static.browser\" {\n  export { prerender, resumeAndPrerender } from \"react-dom/static\";\n}\n"
  },
  {
    "path": "src/react/ssr/__tests__/prerenderStatic.test.tsx",
    "content": "/* eslint-disable testing-library/render-result-naming-convention */\n// not exported\n// eslint-disable-next-line local-rules/no-relative-imports\nimport \"../../../testing/internal/messageChannelPolyfill.js\";\n\nimport \"./polyfillReactDomTypes.d.ts\";\n\nimport { expectTypeOf } from \"expect-type\";\nimport { JSDOM } from \"jsdom\";\nimport jsesc from \"jsesc\";\nimport * as React from \"react\";\nimport { renderToStaticMarkup, renderToString } from \"react-dom/server\";\nimport {\n  type PrerenderResult,\n  type PrerenderToNodeStreamResult,\n} from \"react-dom/static\";\nimport { prerender, resumeAndPrerender } from \"react-dom/static.browser\";\nimport {\n  prerenderToNodeStream,\n  resumeAndPrerenderToNodeStream,\n} from \"react-dom/static.node\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport {\n  ApolloClient,\n  ApolloLink,\n  gql,\n  InMemoryCache,\n  NetworkStatus,\n} from \"@apollo/client\";\nimport {\n  ApolloProvider,\n  getApolloContext,\n  type SkipToken,\n  skipToken,\n  useQuery,\n  useSuspenseQuery,\n} from \"@apollo/client/react\";\nimport { prerenderStatic } from \"@apollo/client/react/ssr\";\nimport { MockLink, MockSubscriptionLink } from \"@apollo/client/testing\";\nimport { resetApolloContext, wait } from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\nbeforeEach(() => {\n  // We are running tests with multiple different renderers, and that can result in a warning like\n  // > Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.\n  // This avoids that.\n  resetApolloContext();\n});\n// @ts-ignore\nglobal.setImmediate ||= (fn) => setTimeout(fn, 0);\n\nfunction testSetup() {\n  const query1: TypedDocumentNode<{ hello: string }> = gql`\n    query {\n      hello\n    }\n  `;\n  const query2: TypedDocumentNode<{ whoami: { name: string } }> = gql`\n    query {\n      whoami {\n        name\n      }\n    }\n  `;\n  const query3: TypedDocumentNode<{ currentTime: string }> = gql`\n    query {\n      currentTime\n    }\n  `;\n\n  function Outlet() {\n    const { data } = useSuspenseQuery(query1);\n\n    return (\n      <div>\n        <p>Hello {data.hello}!</p>\n        <React.Suspense>\n          <Parent />\n        </React.Suspense>\n      </div>\n    );\n  }\n\n  function Parent() {\n    const { data } = useSuspenseQuery(query2);\n\n    return (\n      <>\n        <p>My name is {data.whoami.name}!</p>\n        <React.Suspense>\n          <Child />\n        </React.Suspense>\n      </>\n    );\n  }\n  function Child() {\n    const { data } = useSuspenseQuery(query3);\n\n    return (\n      <>\n        <p>Current time is {data.currentTime}!</p>\n      </>\n    );\n  }\n\n  const mocks = [\n    {\n      request: { query: query1 },\n      result: { data: { hello: \"world\" } },\n      maxUsageCount: 1,\n    },\n    {\n      request: { query: query2 },\n      result: { data: { whoami: { name: \"Apollo\" } } },\n      maxUsageCount: 1,\n    },\n    {\n      request: { query: query3 },\n      result: { data: { currentTime: \"2025-03-26T14:40:53.118Z\" } },\n      maxUsageCount: 1,\n    },\n  ];\n  const mockLink = new MockLink(mocks);\n  return {\n    Outlet,\n    mocks,\n    mockLink,\n    query1,\n    query2,\n    query3,\n  };\n}\n\ntest.each([\n  [\"prerender\", prerender satisfies prerenderStatic.PrerenderToWebStream],\n  [\n    \"prerenderToNodeStream\",\n    prerenderToNodeStream satisfies prerenderStatic.PrerenderToNodeStream,\n  ],\n] as const)(\n  \"real-life kitchen sink use case with %s and `useSuspenseQuery`\",\n  async (_, prerender) => {\n    // reset things that might have been set by a previous run of this test with\n    // a different runner\n    (window as any).__APOLLO_CLIENT_INIT__ = undefined;\n    window.document.documentElement.innerHTML = \"<head></head><body></body>\";\n\n    const throwingLink = new ApolloLink(() => {\n      throw new Error(\n        \"This ApolloClient instance should not need to make requests!\"\n      );\n    });\n\n    const { Outlet, mockLink: ssrLink } = testSetup();\n    // from here on it's essentially what a userland app could look like\n\n    function makeClient(link = throwingLink) {\n      return new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n    }\n    function App() {\n      const externalClient = React.useContext(getApolloContext()).client;\n      const [client] = React.useState<ApolloClient>(\n        externalClient || makeClient\n      );\n      if ((window as any).__APOLLO_CLIENT_INIT__) {\n        client.restore((window as any).__APOLLO_CLIENT_INIT__);\n      }\n\n      return (\n        <html>\n          <head>\n            <meta charSet=\"utf-8\" />\n            <meta\n              name=\"viewport\"\n              content=\"width=device-width, initial-scale=1\"\n            />\n            <link rel=\"stylesheet\" href=\"/styles.css\"></link>\n            <title>My app</title>\n          </head>\n          <body>\n            <ApolloProvider client={client}>\n              <React.Suspense fallback=\"Loading...\">\n                <Outlet />\n              </React.Suspense>\n            </ApolloProvider>\n          </body>\n        </html>\n      );\n    }\n\n    async function ssr() {\n      const client = makeClient(ssrLink);\n      const signal = AbortSignal.timeout(2000);\n\n      await prerenderStatic({\n        tree: <App />,\n        renderFunction: (tree) => prerender(tree, { signal }),\n        context: {\n          client,\n        },\n        ignoreResults: true,\n        signal,\n      });\n\n      const extracted = client.extract();\n\n      const { prelude } = await prerender(\n        <ApolloProvider client={client}>\n          <App />\n        </ApolloProvider>,\n        {\n          bootstrapScripts: [\"/main.js\"],\n          bootstrapScriptContent: `window.__APOLLO_CLIENT_INIT__ = ${jsesc(\n            extracted,\n            {\n              isScriptContext: true,\n              wrap: true,\n              json: true,\n            }\n          )}`,\n          signal,\n        }\n      );\n      return new Response(prelude as any, {\n        headers: { \"content-type\": \"text/html\" },\n      });\n    }\n\n    const response = await ssr();\n\n    // We're switching renderer, so we need to reset the context or the value\n    // will carry over from the SSR render to the \"browser\" render\n    resetApolloContext();\n\n    const responseText = await response.text();\n    expect(responseText).toMatchSnapshot();\n\n    // JS isn't executed if we just assign the html to the current JSDOM root,\n    // so we create another JSDOM instance just to extract the `__APOLLO_CLIENT_INIT__`\n    // value and the top-level elements innerHTML\n    const jsdom = new JSDOM(responseText, { runScripts: \"dangerously\" });\n    expect(jsdom.window.__APOLLO_CLIENT_INIT__).toMatchSnapshot();\n    const __APOLLO_CLIENT_INIT__ = jsdom.window.__APOLLO_CLIENT_INIT__;\n    const innerHtml = jsdom.window.document.documentElement.innerHTML;\n    jsdom.window.close();\n\n    // hydrate the app in the \"jest/browser\" JSDOM\n    (window as any).__APOLLO_CLIENT_INIT__ = __APOLLO_CLIENT_INIT__;\n    window.document.documentElement.innerHTML = innerHtml;\n    const reactClient = await import(\"react-dom/client\");\n    const root = reactClient.hydrateRoot(window.document, <App />, {\n      onCaughtError: console.error,\n      onRecoverableError: console.error,\n      onUncaughtError: console.error,\n    });\n\n    // wait a bit - hydration errors would be thrown here\n    await new Promise((resolve) => setTimeout(resolve, 500));\n\n    // no errors, hydration was successful, test is done\n    root.unmount();\n  }\n);\n\ntest.each([\n  [\"renderToString\", renderToString satisfies prerenderStatic.RenderToString],\n  [\n    \"renderToStaticMarkup\",\n    renderToStaticMarkup satisfies prerenderStatic.RenderToString,\n  ],\n])(\n  \"`prerenderStatic` with `%s` and suspense hooks will error\",\n  async (_, renderFunction) => {\n    const { Outlet, mockLink } = testSetup();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: mockLink,\n    });\n\n    const promise = prerenderStatic({\n      tree: <Outlet />,\n      context: { client },\n      renderFunction,\n    });\n\n    await expect(promise).rejects.toEqual(\n      new Error(\n        \"A component suspended while responding to synchronous input. This will cause the UI to be replaced with a loading indicator. To fix, updates that suspend should be wrapped with startTransition.\"\n      )\n    );\n  }\n);\n\ntest.each([\n  [\"prerender\", prerender, resumeAndPrerender],\n  [\n    \"prerenderToNodeStream\",\n    prerenderToNodeStream,\n    resumeAndPrerenderToNodeStream,\n  ],\n])(\n  \"%s: AbortSignal times out during render - can be resumed with `resumeAndPrerender`\",\n  async (_, renderFunction, resumeFunction) => {\n    const { Outlet, query1, query2, query3 } = testSetup();\n    type DataFor<T> = T extends TypedDocumentNode<infer D, any> ? D : never;\n\n    const onError = jest.fn();\n\n    const link = new MockSubscriptionLink();\n\n    const client1 = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    let controller = new AbortController();\n    const promise = prerenderStatic({\n      tree: <Outlet />,\n      context: { client: client1 },\n      renderFunction: (tree) =>\n        renderFunction(tree, {\n          signal: controller.signal,\n          onError,\n        }),\n      signal: controller.signal,\n    });\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            hello: \"world\",\n          } satisfies DataFor<typeof query1>,\n        },\n      },\n      true\n    );\n\n    await wait(10);\n    controller.abort(\"AbortReason\");\n\n    const initialResult = await promise;\n    expect(initialResult).toStrictEqualTyped({\n      aborted: true,\n      result:\n        '<div><p>Hello <!-- -->world<!-- -->!</p><!--$?--><template id=\"B:0\"></template><!--/$--></div><script>requestAnimationFrame(function(){$RT=performance.now()});</script>',\n      renderFnResult: expect.objectContaining<PrerenderResult>({\n        postponed: expect.any(Object),\n        prelude: expect.anything(), // Readable or ReadableStream depending on the renderer\n      }),\n    });\n\n    expect(initialResult.renderFnResult.postponed).not.toBeNull();\n\n    // The different incremental renders usually don't happen within the same JS context.\n    // We just create a new client to simulate that.\n    const client2 = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n    client2.restore(client1.extract());\n    controller = new AbortController();\n    const resumedPromise1 = prerenderStatic({\n      tree: <Outlet />,\n      context: { client: client2 },\n      renderFunction: (tree) =>\n        resumeFunction(tree, initialResult.renderFnResult.postponed, {\n          signal: controller.signal,\n        }),\n      signal: controller.signal,\n    });\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            whoami: { name: \"Apollo\" },\n          } satisfies DataFor<typeof query2>,\n        },\n      },\n      true\n    );\n\n    await wait(10);\n    controller.abort(\"AbortReason2\");\n\n    const resumedResult1 = await resumedPromise1;\n    expect(resumedResult1).toStrictEqualTyped({\n      aborted: true,\n      result:\n        '<div hidden id=\"S:0\"><p>My name is <!-- -->Apollo<!-- -->!</p><!--$?--><template id=\"B:1\"></template><!--/$--></div><script>$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if(\"/$\"===d||\"/&\"===d)if(0===h)break;else h--;else\"$\"!==d&&\"$?\"!==d&&\"$~\"!==d&&\"$!\"!==d&&\"&\"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data=\"$\";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};\\n' +\n        '$RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data=\"$~\",$RB.push(a,b),2===$RB.length&&(\"number\"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};$RC(\"B:0\",\"S:0\")</script>',\n      renderFnResult: expect.objectContaining<PrerenderResult>({\n        postponed: expect.any(Object),\n        prelude: expect.anything(), // Readable or ReadableStream depending on the renderer\n      }),\n    });\n\n    // The different incremental renders usually don't happen within the same JS context.\n    // We just create a new client to simulate that.\n    const client3 = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n    client3.restore(client2.extract());\n    const resumedPromise2 = prerenderStatic({\n      tree: <Outlet />,\n      context: { client: client3 },\n      renderFunction: (tree) =>\n        resumeFunction(tree, resumedResult1.renderFnResult.postponed, {}),\n    });\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            currentTime: \"now\",\n          } satisfies DataFor<typeof query3>,\n        },\n      },\n      true\n    );\n\n    const resumedResult2 = await resumedPromise2;\n    expect(resumedResult2).toStrictEqualTyped({\n      aborted: false,\n      result:\n        '<div hidden id=\"S:1\"><p>Current time is <!-- -->now<!-- -->!</p></div><script>$RC(\"B:1\",\"S:1\")</script>',\n      renderFnResult: expect.objectContaining<PrerenderResult>({\n        postponed: null,\n        prelude: expect.anything(), // Readable or ReadableStream depending on the renderer\n      }),\n    });\n  }\n);\n\ntest.each([\n  [\"renderToString\", renderToString],\n  [\"renderToStaticMarkup\", renderToStaticMarkup],\n])(\n  \"%s: AbortSignal times out during render - stops rerendering, returns partial result\",\n  async (_, renderFunction) => {\n    const { query1, query2, query3 } = testSetup();\n    type DataFor<T> = T extends TypedDocumentNode<infer D, any> ? D : never;\n\n    const link = new MockSubscriptionLink();\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n    });\n\n    const controller = new AbortController();\n\n    function Component() {\n      const { data, loading } = useQuery(query1);\n      if (loading) return <div>loading...</div>;\n      return (\n        <div>\n          <p>Hello {data?.hello}!</p>\n          <Parent />\n        </div>\n      );\n    }\n\n    function Parent() {\n      const { data, loading } = useQuery(query2);\n      if (loading) return <div>loading...</div>;\n\n      return (\n        <>\n          <p>My name is {data?.whoami.name}!</p>\n          <Child />\n        </>\n      );\n    }\n    function Child() {\n      const { data, loading } = useQuery(query3);\n      if (loading) return <div>loading...</div>;\n\n      return (\n        <>\n          <p>Current time is {data?.currentTime}!</p>\n        </>\n      );\n    }\n\n    const promise = prerenderStatic({\n      tree: <Component />,\n      context: { client },\n      renderFunction,\n      signal: controller.signal,\n      diagnostics: true,\n    });\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            hello: \"world\",\n          } satisfies DataFor<typeof query1>,\n        },\n      },\n      true\n    );\n\n    await wait(10);\n\n    link.simulateResult(\n      {\n        result: {\n          data: {\n            whoami: { name: \"Apollo\" },\n          } satisfies DataFor<typeof query2>,\n        },\n      },\n      true\n    );\n\n    await wait(10);\n\n    controller.abort(\"AbortReason\");\n    // the network request here never \"resolves\"\n    // (no call to `simulateResult` for the third query), yet the `abort` call\n    // should finish up the prerendering\n\n    const { result, aborted, diagnostics } = await promise;\n    expect(result).toMatchSnapshot();\n    expect(result).toMatch(/world/);\n    expect(result).toMatch(/Apollo/);\n    expect(result).toMatch(/loading.../);\n    expect(aborted).toBe(true);\n    expect(diagnostics?.renderCount).toBe(3);\n  }\n);\n\ntest(\"cancelled AbortSignal is passed into `prerenderStatic`\", async () => {\n  const { Outlet, mockLink } = testSetup();\n\n  const controller = new AbortController();\n  controller.abort();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: mockLink,\n  });\n\n  const promise = prerenderStatic({\n    tree: <Outlet />,\n    context: { client },\n    renderFunction: prerender,\n    signal: controller.signal,\n  });\n\n  await expect(promise).rejects.toEqual(\n    new Error(\"The operation was aborted before it could be attempted.\")\n  );\n});\n\ntest(\"usage with `useSuspenseQuery`: `diagnostics.renderCount` stays 1\", async () => {\n  const { Outlet, mockLink } = testSetup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: mockLink,\n  });\n\n  const { diagnostics, result } = await prerenderStatic({\n    tree: <Outlet />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n  });\n\n  expect(diagnostics?.renderCount).toBe(1);\n  expect(result).toMatchInlineSnapshot(\n    `\"<div><p>Hello <!-- -->world<!-- -->!</p><!--$--><p>My name is <!-- -->Apollo<!-- -->!</p><!--$--><p>Current time is <!-- -->2025-03-26T14:40:53.118Z<!-- -->!</p><!--/$--><!--/$--></div>\"`\n  );\n});\n\ntest(\"usage with `useQuery`: `diagnostics.renderCount` is 2\", async () => {\n  const { query1, mockLink } = testSetup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: mockLink,\n  });\n\n  function Component() {\n    const { data, loading } = useQuery(query1);\n    if (loading) return <div>loading...</div>;\n    return <div>{data?.hello}</div>;\n  }\n\n  const { diagnostics, result } = await prerenderStatic({\n    tree: <Component />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n  });\n\n  expect(diagnostics?.renderCount).toBe(2);\n  expect(result).toMatchInlineSnapshot(`\"<div>world</div>\"`);\n});\n\ntest(\"usage with a waterfall of `useQuery`: `diagnostics.renderCount` is `n+1`\", async () => {\n  const { query1, query2, query3, mockLink } = testSetup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: mockLink,\n  });\n\n  function Component() {\n    const { data, loading } = useQuery(query1);\n    if (loading) return <div>loading...</div>;\n    return (\n      <div>\n        <p>Hello {data?.hello}!</p>\n        <Parent />\n      </div>\n    );\n  }\n\n  function Parent() {\n    const { data, loading } = useQuery(query2);\n    if (loading) return <div>loading...</div>;\n\n    return (\n      <>\n        <p>My name is {data?.whoami.name}!</p>\n        <Child />\n      </>\n    );\n  }\n  function Child() {\n    const { data, loading } = useQuery(query3);\n    if (loading) return <div>loading...</div>;\n\n    return (\n      <>\n        <p>Current time is {data?.currentTime}!</p>\n      </>\n    );\n  }\n\n  const { diagnostics, result } = await prerenderStatic({\n    tree: <Component />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n  });\n\n  expect(diagnostics?.renderCount).toBe(4);\n  expect(result).toMatchInlineSnapshot(\n    `\"<div><p>Hello <!-- -->world<!-- -->!</p><p>My name is <!-- -->Apollo<!-- -->!</p><p>Current time is <!-- -->2025-03-26T14:40:53.118Z<!-- -->!</p></div>\"`\n  );\n});\n\ntest(\"multiple `useQuery` calls in the same component do not waterfall\", async () => {\n  const { query1, query2, query3, mockLink } = testSetup();\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: mockLink,\n  });\n\n  function Component() {\n    const result1 = useQuery(query1);\n    const result2 = useQuery(query2);\n    const result3 = useQuery(query3);\n    if (result1.loading || result2.loading || result3.loading)\n      return <div>loading...</div>;\n\n    return (\n      <div>\n        {result1.data?.hello}\n        {result2.data?.whoami?.name}\n        {result3.data?.currentTime}\n      </div>\n    );\n  }\n\n  const { result, diagnostics } = await prerenderStatic({\n    tree: <Component />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n  });\n\n  expect(diagnostics?.renderCount).toBe(2);\n  expect(result).toMatchInlineSnapshot(\n    `\"<div>world<!-- -->Apollo<!-- -->2025-03-26T14:40:53.118Z</div>\"`\n  );\n});\n\ntest(\"`maxRerenders` will throw an error if exceeded\", async () => {\n  const query: TypedDocumentNode<{ hello: string }, { depth: number }> = gql`\n    query ($depth: Int!) {\n      hello(depth: $depth)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query, variables: () => true },\n        result: (arg) => ({ data: { hello: \"world\" + arg.depth } }),\n        maxUsageCount: Number.POSITIVE_INFINITY,\n      } satisfies MockLink.MockedResponse<{ hello: string }, { depth: number }>,\n    ]),\n  });\n\n  function Component({ depth }: { depth: number }) {\n    const { loading, data } = useQuery(query, { variables: { depth } });\n\n    if (loading) return <div>loading...</div>;\n\n    return (\n      <div>\n        {data?.hello}\n        <Component depth={depth + 1} />\n      </div>\n    );\n  }\n\n  const promise = prerenderStatic({\n    tree: <Component depth={1} />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n    maxRerenders: 4,\n  });\n  await expect(promise).rejects.toEqual(\n    new InvariantError(`Exceeded maximum rerender count of 4.\nThis either means you have very deep \\`useQuery\\` waterfalls in your application\nand need to increase the \\`maxRerender\\` option to \\`prerenderStatic\\`, or that\nyou have an infinite render loop in your application.`)\n  );\n});\n\ntest(\"`maxRerenders` defaults to 50\", async () => {\n  const query: TypedDocumentNode<{ hello: string }, { depth: number }> = gql`\n    query ($depth: Int!) {\n      hello(depth: $depth)\n    }\n  `;\n\n  const client = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink([\n      {\n        request: { query, variables: () => true },\n        result: (arg) => ({ data: { hello: \"world\" + arg.depth } }),\n        maxUsageCount: Number.POSITIVE_INFINITY,\n      } satisfies MockLink.MockedResponse<{ hello: string }, { depth: number }>,\n    ]),\n  });\n\n  function Component({ depth }: { depth: number }) {\n    const { loading, data } = useQuery(query, { variables: { depth } });\n\n    if (loading) return <div>loading...</div>;\n\n    return (\n      <div>\n        {data?.hello}\n        <Component depth={depth + 1} />\n      </div>\n    );\n  }\n\n  const promise = prerenderStatic({\n    tree: <Component depth={1} />,\n    context: { client },\n    renderFunction: prerender,\n    diagnostics: true,\n  });\n  await expect(promise).rejects.toEqual(\n    new InvariantError(`Exceeded maximum rerender count of 50.\nThis either means you have very deep \\`useQuery\\` waterfalls in your application\nand need to increase the \\`maxRerender\\` option to \\`prerenderStatic\\`, or that\nyou have an infinite render loop in your application.`)\n  );\n}, 10000);\n\ntest.each([\n  [\"renderToString\", renderToString],\n  [\"renderToStaticMarkup\", renderToStaticMarkup],\n  [\"prerender\", prerender],\n  [\"prerenderToNodeStream\", prerenderToNodeStream],\n])(\n  \"`ignoreResults` will result in an empty string to be returned (%s)\",\n  async (_, renderFunction) => {\n    const { mockLink, query1 } = testSetup();\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link: mockLink,\n    });\n    function Component() {\n      const { data, loading } = useQuery(query1);\n      if (loading) return <div>loading...</div>;\n      return <div>{data?.hello}</div>;\n    }\n    const { result } = await prerenderStatic({\n      tree: <Component />,\n      context: { client },\n      renderFunction,\n      ignoreResults: true,\n    });\n\n    expect(result).toBe(\"\");\n  }\n);\n\nit.skip(\"type tests\", async () => {\n  expectTypeOf(\n    await prerenderStatic({\n      tree: <div />,\n      renderFunction: renderToStaticMarkup,\n    })\n  ).toEqualTypeOf<{\n    result: string;\n    renderFnResult: string;\n    aborted: boolean;\n    diagnostics?: { renderCount: number };\n  }>();\n  expectTypeOf(\n    await prerenderStatic({\n      tree: <div />,\n      renderFunction: renderToString,\n    })\n  ).toEqualTypeOf<{\n    result: string;\n    renderFnResult: string;\n    aborted: boolean;\n    diagnostics?: { renderCount: number };\n  }>();\n  if (React.version.startsWith(\"19\")) {\n    const { prerender, prerenderToNodeStream } =\n      require(\"react-dom/static\") as typeof import(\"react-dom/static\");\n\n    expectTypeOf(\n      await prerenderStatic({\n        tree: <div />,\n        renderFunction: prerender,\n      })\n    ).toEqualTypeOf<{\n      result: string;\n      renderFnResult: PrerenderResult;\n      aborted: boolean;\n      diagnostics?: { renderCount: number };\n    }>();\n    expectTypeOf(\n      await prerenderStatic({\n        tree: <div />,\n        renderFunction: prerenderToNodeStream,\n      })\n    ).toEqualTypeOf<{\n      result: string;\n      renderFnResult: PrerenderToNodeStreamResult;\n      aborted: boolean;\n      diagnostics?: { renderCount: number };\n    }>();\n  }\n});\n\ndescribe(\"cases that should skip SSR\", () => {\n  test.each<{\n    options: useQuery.Options<{ hello: string }, any> | SkipToken;\n    populateCache: boolean;\n    expectedResult: {\n      data: unknown;\n      loading: boolean;\n      dataState: \"empty\";\n      networkStatus: NetworkStatus;\n    };\n  }>([\n    // skipToken\n    {\n      options: skipToken,\n      populateCache: false,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n    {\n      options: skipToken,\n      populateCache: true,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n\n    // skip: true\n    {\n      options: { skip: true },\n      populateCache: false,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n    {\n      options: { skip: true },\n      populateCache: true,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n\n    // no-cache\n    {\n      options: { fetchPolicy: \"no-cache\" },\n      populateCache: false,\n      expectedResult: {\n        data: null,\n        loading: true,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.loading,\n      },\n    },\n    {\n      options: { fetchPolicy: \"no-cache\" },\n      populateCache: true,\n      expectedResult: {\n        data: null,\n        loading: true,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.loading,\n      },\n    },\n\n    // standby\n    {\n      options: { fetchPolicy: \"standby\" },\n      populateCache: false,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n    {\n      options: { fetchPolicy: \"standby\" },\n      populateCache: true,\n      expectedResult: {\n        data: null,\n        loading: false,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.ready,\n      },\n    },\n\n    // ssr: false\n    {\n      options: { ssr: false },\n      populateCache: false,\n      expectedResult: {\n        data: null,\n        loading: true,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.loading,\n      },\n    },\n    {\n      options: { ssr: false },\n      populateCache: true,\n      expectedResult: {\n        data: null,\n        loading: true,\n        dataState: \"empty\",\n        networkStatus: NetworkStatus.loading,\n      },\n    },\n  ])(\n    \"options: $options (cache populated: $populateCache)\",\n    async ({ options, populateCache, expectedResult }) => {\n      const query: TypedDocumentNode<{ hello: string }> = gql`\n        {\n          hello\n        }\n      `;\n\n      const mockLink = new MockLink([\n        {\n          request: { query },\n          result: { data: { hello: \"world\" } },\n        },\n      ]);\n      const linkSpy = jest.spyOn(mockLink, \"request\");\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link: mockLink,\n      });\n\n      if (populateCache) {\n        client.writeQuery({\n          query,\n          data: { hello: \"cached\" },\n        });\n      }\n\n      function Component() {\n        const result = useQuery(query, options);\n        return (\n          <div>\n            {JSON.stringify({\n              data: result.data || null,\n              loading: result.loading,\n              dataState: result.dataState,\n              networkStatus: result.networkStatus,\n            })}\n          </div>\n        );\n      }\n\n      const { result } = await prerenderStatic({\n        tree: <Component />,\n        context: { client },\n        renderFunction: prerender,\n      });\n\n      expect(result.replaceAll(\"&quot;\", '\"')).toContain(\n        `${JSON.stringify(expectedResult)}`\n      );\n      expect(linkSpy).toHaveBeenCalledTimes(0);\n    }\n  );\n});\n"
  },
  {
    "path": "src/react/ssr/__tests__/useQuery.test.tsx",
    "content": "/** @jest-environment node */\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\nimport { renderToStaticMarkup, renderToString } from \"react-dom/server\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport {\n  ApolloProvider,\n  useApolloClient,\n  useQuery,\n} from \"@apollo/client/react\";\nimport {\n  prerenderStatic,\n  renderToStringWithData,\n} from \"@apollo/client/react/ssr\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport { resetApolloContext } from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\n\nbeforeEach(() => {\n  // We are running tests with multiple different renderers, and that can result in a warning like\n  // > Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.\n  // This avoids that.\n  resetApolloContext();\n});\n\ndescribe(\"useQuery Hook SSR\", () => {\n  const CAR_QUERY: TypedDocumentNode<typeof CAR_RESULT_DATA> = gql`\n    query {\n      cars {\n        make\n        model\n        vin\n      }\n    }\n  `;\n\n  const CAR_RESULT_DATA = {\n    cars: [\n      {\n        make: \"Audi\",\n        model: \"RS8\",\n        vin: \"DOLLADOLLABILL\",\n        __typename: \"Car\",\n      },\n    ],\n  };\n\n  const CAR_MOCKS = [\n    {\n      request: {\n        query: CAR_QUERY,\n      },\n      result: { data: CAR_RESULT_DATA },\n    },\n  ];\n\n  it(\"should support SSR\", () => {\n    const Component = () => {\n      const { loading, data } = useQuery(CAR_QUERY);\n      if (!loading) {\n        expect(data).toEqual(CAR_RESULT_DATA);\n        const { make, model, vin } = data!.cars[0];\n        return (\n          <div>\n            {make}, {model}, {vin}\n          </div>\n        );\n      }\n      return null;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((markup) => {\n      expect(markup).toMatch(/Audi/);\n    });\n  });\n\n  it(\"should initialize data as `undefined` when loading\", () => {\n    const Component = () => {\n      const { data, loading } = useQuery(CAR_QUERY);\n      if (loading) {\n        expect(data).toBeUndefined();\n      }\n      return null;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app);\n  });\n\n  it(\"should skip SSR tree rendering and return a loading state if `ssr` option is `false`\", async () => {\n    let renderCount = 0;\n    const Component = () => {\n      const { data, loading } = useQuery(CAR_QUERY, { ssr: false });\n      renderCount += 1;\n\n      expect(loading).toBeTruthy();\n\n      if (!loading) {\n        const { make } = data!.cars[0];\n        return <div>{make}</div>;\n      }\n      return null;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((result) => {\n      expect(renderCount).toBe(1);\n      expect(result).toEqual(\"\");\n    });\n  });\n\n  it(\"should skip SSR tree rendering and not return a loading state loading if `ssr` option is `false` and `skip` is `true`\", async () => {\n    let renderCount = 0;\n    const Component = () => {\n      const { data, loading } = useQuery(CAR_QUERY, { ssr: false, skip: true });\n      renderCount += 1;\n\n      expect(loading).toBeFalsy();\n      expect(data).toBeUndefined();\n\n      return null;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((result) => {\n      expect(renderCount).toBe(1);\n      expect(result).toEqual(\"\");\n    });\n  });\n\n  it(\"should skip both SSR tree rendering and SSR component rendering if `ssr` option is `false` and `ssrMode` is `true`\", async () => {\n    const link = new MockLink([\n      {\n        request: { query: CAR_QUERY },\n        result: { data: CAR_RESULT_DATA },\n      },\n    ]);\n\n    const client = new ApolloClient({\n      cache: new InMemoryCache(),\n      link,\n      ssrMode: true,\n    });\n\n    let renderCount = 0;\n    const Component = () => {\n      const { data, loading } = useQuery(CAR_QUERY, { ssr: false });\n\n      let content = null;\n      switch (renderCount) {\n        case 0:\n          expect(loading).toBeTruthy();\n          expect(data).toBeUndefined();\n          break;\n        case 1: // FAIL; should not render a second time\n        default:\n          throw new Error(\"Duplicate render\");\n      }\n\n      renderCount += 1;\n      return content;\n    };\n\n    const app = (\n      <ApolloProvider client={client}>\n        <Component />\n      </ApolloProvider>\n    );\n\n    const view = await renderToStringWithData(app);\n    expect(renderCount).toBe(1);\n    expect(view).toEqual(\"\");\n    await new Promise((resolve) => setTimeout(resolve, 20));\n    expect(renderCount).toBe(1);\n    expect(view).toEqual(\"\");\n  });\n\n  it(\"should skip SSR tree rendering if `skip` option is `true`\", async () => {\n    let renderCount = 0;\n    const Component = () => {\n      const { loading, networkStatus, data } = useQuery(CAR_QUERY, {\n        skip: true,\n      });\n      renderCount += 1;\n\n      expect(loading).toBeFalsy();\n      expect(networkStatus).toBe(7);\n      expect(data).toBeUndefined();\n\n      return null;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((result) => {\n      expect(renderCount).toBe(1);\n      expect(result).toBe(\"\");\n    });\n  });\n\n  it(\"should render SSR tree rendering if `skip` option is `true` for only one instance of the query\", async () => {\n    let renderCount = 0;\n\n    const AnotherComponent = () => {\n      const { loading, data } = useQuery(CAR_QUERY, { skip: false });\n\n      renderCount += 1;\n\n      if (!loading) {\n        expect(data).toEqual(CAR_RESULT_DATA);\n        const { make, model, vin } = data!.cars[0];\n        return (\n          <div>\n            {make}, {model}, {vin}\n          </div>\n        );\n      }\n\n      return null;\n    };\n\n    const Component = () => {\n      const { loading, data } = useQuery(CAR_QUERY, { skip: true });\n      renderCount += 1;\n\n      expect(loading).toBeFalsy();\n      expect(data).toBeUndefined();\n\n      return <AnotherComponent />;\n    };\n\n    const app = (\n      <MockedProvider mocks={CAR_MOCKS}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((result) => {\n      expect(renderCount).toBe(4);\n      expect(result).toMatch(/Audi/);\n      expect(result).toMatch(/RS8/);\n    });\n  });\n\n  it(\"should return data written previously to cache during SSR pass if using cache-only fetchPolicy\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Order: {\n          keyFields: [\"selection\"],\n        },\n      },\n    });\n\n    const query: TypedDocumentNode<typeof initialData> = gql`\n      query GetSearchResults {\n        getSearchResults @client {\n          locale\n          order {\n            selection\n          }\n          pagination {\n            pageLimit\n          }\n          results {\n            id\n            text\n          }\n        }\n      }\n    `;\n\n    const initialData = {\n      getSearchResults: {\n        __typename: \"SearchResults\",\n        locale: \"en-US\",\n        order: {\n          __typename: \"Order\",\n          selection: \"RELEVANCE\",\n        },\n        pagination: {\n          pageLimit: 3,\n        },\n        results: [\n          { __typename: \"SearchResult\", id: 1, text: \"hi\" },\n          { __typename: \"SearchResult\", id: 2, text: \"hello\" },\n          { __typename: \"SearchResult\", id: 3, text: \"hey\" },\n        ],\n      },\n    };\n\n    const spy = jest.fn();\n\n    const Component = () => {\n      useApolloClient().writeQuery({ query, data: initialData });\n\n      const { loading, data } = useQuery(query, {\n        fetchPolicy: \"cache-only\",\n      });\n\n      spy(loading);\n\n      if (!loading) {\n        expect(data).toEqual(initialData);\n\n        const {\n          getSearchResults: {\n            pagination: { pageLimit },\n          },\n        } = data!;\n        return <div>{pageLimit}</div>;\n      }\n      return null;\n    };\n\n    const app = (\n      <MockedProvider cache={cache}>\n        <Component />\n      </MockedProvider>\n    );\n\n    return renderToStringWithData(app).then((markup) => {\n      expect(spy).toHaveBeenNthCalledWith(1, false);\n      expect(markup).toMatch(/<div.*>3<\\/div>/);\n      expect(cache.extract()).toMatchSnapshot();\n    });\n  });\n\n  it(\"should deduplicate `variables` with identical content, but different order\", async () => {\n    const mocks: MockLink.MockedResponse[] = [\n      {\n        request: {\n          query: CAR_QUERY,\n          variables: { foo: \"a\", bar: 1 },\n        },\n        result: { data: CAR_RESULT_DATA },\n        maxUsageCount: 1,\n      },\n    ];\n\n    const Component = ({\n      variables,\n    }: {\n      variables: { foo: string; bar: number };\n    }) => {\n      const { loading, data } = useQuery(CAR_QUERY, { variables, ssr: true });\n      if (!loading) {\n        expect(data).toEqual(CAR_RESULT_DATA);\n        const { make, model, vin } = data!.cars[0];\n        return (\n          <div>\n            {make}, {model}, {vin}\n          </div>\n        );\n      }\n      return null;\n    };\n\n    await renderToStringWithData(\n      <MockedProvider mocks={mocks}>\n        <>\n          <Component variables={{ foo: \"a\", bar: 1 }} />\n          <Component variables={{ bar: 1, foo: \"a\" }} />\n        </>\n      </MockedProvider>\n    );\n  });\n\n  const reactMajor = React.version.split(\".\")[0];\n  it.each(\n    reactMajor == \"19\" ?\n      [\n        [\n          \"renderToStaticMarkup\",\n          renderToStaticMarkup satisfies prerenderStatic.RenderToString,\n        ],\n        [\n          \"renderToString\",\n          renderToString satisfies prerenderStatic.RenderToString,\n        ],\n        [\n          \"prerender\",\n          (\n            require(\"react-dom/static.edge\") as typeof import(\"react-dom/static\")\n          ).prerender satisfies prerenderStatic.PrerenderToWebStream,\n        ],\n        [\n          \"prerenderToNodeStream\",\n          (\n            require(\"react-dom/static.node\") as typeof import(\"react-dom/static\")\n          )\n            .prerenderToNodeStream satisfies prerenderStatic.PrerenderToNodeStream,\n        ],\n      ]\n    : [\n        [\n          \"renderToStaticMarkup\",\n          renderToStaticMarkup satisfies prerenderStatic.RenderToString,\n        ],\n        [\n          \"renderToString\",\n          renderToString satisfies prerenderStatic.RenderToString,\n        ],\n      ]\n  )(\n    `React ${reactMajor}, %s, should render waterfalls by rerendering the tree multiple times`,\n    async (_, renderFunction) => {\n      const query1: TypedDocumentNode<{ hello: string }> = gql`\n        query {\n          hello\n        }\n      `;\n      const query2: TypedDocumentNode<{ whoami: { name: string } }> = gql`\n        query {\n          whoami {\n            name\n          }\n        }\n      `;\n      const query3: TypedDocumentNode<{ currentTime: string }> = gql`\n        query {\n          currentTime\n        }\n      `;\n\n      const link = new MockLink([\n        { request: { query: query1 }, result: { data: { hello: \"world\" } } },\n        {\n          request: { query: query2 },\n          result: { data: { whoami: { name: \"Apollo\" } } },\n        },\n        {\n          request: { query: query3 },\n          result: { data: { currentTime: \"2025-03-26T14:40:53.118Z\" } },\n        },\n      ]);\n\n      const client = new ApolloClient({\n        cache: new InMemoryCache(),\n        link,\n      });\n\n      function App() {\n        const { loading, data } = useQuery(query1);\n\n        if (loading) {\n          return <p>Loading...</p>;\n        }\n        return (\n          <div>\n            <p>Hello {data?.hello}!</p>\n            <Parent />\n          </div>\n        );\n      }\n      function Parent() {\n        const { loading, data } = useQuery(query2);\n\n        if (loading) {\n          return <p>Loading...</p>;\n        }\n        return (\n          <>\n            <p>My name is {data?.whoami.name}!</p>\n            <Child />\n          </>\n        );\n      }\n      function Child() {\n        const { loading, data } = useQuery(query3);\n\n        if (loading) {\n          return <p>Loading...</p>;\n        }\n        return (\n          <>\n            <p>Current time is {data?.currentTime}!</p>\n          </>\n        );\n      }\n      const { result } = await prerenderStatic({\n        tree: (\n          <ApolloProvider client={client}>\n            <App />\n          </ApolloProvider>\n        ),\n        renderFunction,\n      });\n      expect(result).toMatch(/world/);\n      expect(result).toMatch(/Apollo/);\n      expect(result).toMatch(/2025-03-26T14:40:53.118Z/);\n    }\n  );\n});\n"
  },
  {
    "path": "src/react/ssr/__tests__/useQueryEndToEnd.test.tsx",
    "content": "import { screen, waitFor } from \"@testing-library/react\";\nimport React from \"react\";\nimport { hydrateRoot } from \"react-dom/client\";\nimport { renderToString } from \"react-dom/server\";\n\nimport { ApolloClient, gql, InMemoryCache } from \"@apollo/client\";\nimport { ApolloProvider, useQuery } from \"@apollo/client/react\";\nimport { prerenderStatic } from \"@apollo/client/react/ssr\";\nimport { MockLink } from \"@apollo/client/testing\";\n\nit(\"should not cause a hydration mismatch when both ssr: false and skip: true are set\", async () => {\n  const query = gql`\n    {\n      hello\n    }\n  `;\n  const mocks = [\n    {\n      request: { query },\n      result: { data: { hello: \"world\" } },\n    },\n  ];\n\n  const rendered: Array<{\n    loading: boolean;\n    data: unknown;\n    networkStatus: number;\n    hasMounted: boolean;\n  }> = [];\n\n  const Component = () => {\n    const {\n      loading,\n      data = \"<undefined>\",\n      networkStatus,\n    } = useQuery(query, {\n      ssr: false,\n      skip: true,\n    });\n    const [hasMounted, setHasMounted] = React.useState(false);\n    React.useEffect(() => {\n      setHasMounted(true);\n    }, []);\n    rendered.push({ loading, data, networkStatus, hasMounted });\n    return (\n      <div id=\"target\">\n        {JSON.stringify({ loading, data, networkStatus, hasMounted })}\n      </div>\n    );\n  };\n\n  const serverClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const { result } = await prerenderStatic({\n    tree: <Component />,\n    renderFunction: renderToString,\n    context: { client: serverClient },\n  });\n  expect(result).toMatchInlineSnapshot(\n    `\"<div id=\\\\\"target\\\\\">{&quot;loading&quot;:false,&quot;data&quot;:&quot;&lt;undefined&gt;&quot;,&quot;networkStatus&quot;:7,&quot;hasMounted&quot;:false}</div>\"`\n  );\n\n  expect(serverClient.extract()).toEqual({});\n\n  const container = document.createElement(\"div\");\n  container.innerHTML = result;\n  document.body.appendChild(container);\n\n  const clientClient = new ApolloClient({\n    cache: new InMemoryCache(),\n    link: new MockLink(mocks),\n  });\n\n  const hydrationErrors: unknown[] = [];\n  const root = hydrateRoot(\n    container,\n    <ApolloProvider client={clientClient}>\n      <Component />\n    </ApolloProvider>,\n    {\n      onRecoverableError: (err) => hydrationErrors.push(err),\n    }\n  );\n\n  await waitFor(() => {\n    expect(\n      screen.getByText(\n        JSON.stringify({\n          loading: false,\n          data: \"<undefined>\",\n          networkStatus: 7,\n          hasMounted: true,\n        })\n      )\n    ).toBeInTheDocument();\n  });\n\n  expect(hydrationErrors).toHaveLength(0);\n\n  expect(\n    rendered.every(({ data, loading, networkStatus }) => {\n      return data === \"<undefined>\" && loading === false && networkStatus === 7;\n    })\n  ).toBe(true);\n\n  root.unmount();\n  document.body.removeChild(container);\n});\n"
  },
  {
    "path": "src/react/ssr/__tests__/useReactiveVar.test.tsx",
    "content": "/** @jest-environment node */\nimport React from \"react\";\n\nimport { makeVar } from \"@apollo/client\";\nimport { useReactiveVar } from \"@apollo/client/react\";\nimport { renderToStringWithData } from \"@apollo/client/react/ssr\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\n\ndescribe(\"useReactiveVar Hook SSR\", () => {\n  it(\"does not cause warnings\", async () => {\n    using consoleSpy = spyOnConsole(\"error\");\n    const counterVar = makeVar(0);\n    function Component() {\n      const count = useReactiveVar(counterVar);\n      counterVar(1);\n      counterVar(2);\n      return <div>{count}</div>;\n    }\n\n    // eslint-disable-next-line testing-library/render-result-naming-convention\n    const value = await renderToStringWithData(<Component />);\n    expect(value).toEqual(\"<div>0</div>\");\n    expect(consoleSpy.error).toHaveBeenCalledTimes(0);\n  });\n});\n"
  },
  {
    "path": "src/react/ssr/getDataFromTree.ts",
    "content": "import type * as ReactTypes from \"react\";\n\nimport { prerenderStatic } from \"./prerenderStatic.js\";\n\n/**\n * @deprecated This function uses the legacy `renderToStaticMarkup` API from React.\n * Use `prerenderStatic` instead, which can be configured to run with more modern\n * React APIs.\n */\nexport async function getDataFromTree(\n  tree: ReactTypes.ReactNode,\n  context: { [key: string]: any } = {}\n) {\n  return getMarkupFromTree({\n    tree,\n    context,\n    // If you need to configure this renderFunction, call getMarkupFromTree\n    // directly instead of getDataFromTree.\n    renderFunction: (await import(\"react-dom/server\")).renderToStaticMarkup,\n  });\n}\n\ntype GetMarkupFromTreeOptions = {\n  tree: ReactTypes.ReactNode;\n  context?: { [key: string]: any };\n  renderFunction?:\n    | prerenderStatic.RenderToString\n    | prerenderStatic.RenderToStringPromise;\n};\n\n/**\n * @deprecated This function is only compatible with legacy React prerendering APIs.\n * Use `prerenderStatic` instead, which can be configured to run with more modern\n * React APIs.\n */\nexport async function getMarkupFromTree({\n  tree,\n  context = {},\n  // The rendering function is configurable! We use renderToStaticMarkup as\n  // the default, because it's a little less expensive than renderToString,\n  // and legacy usage of getDataFromTree ignores the return value anyway.\n  renderFunction,\n}: GetMarkupFromTreeOptions): Promise<string> {\n  if (!renderFunction) {\n    renderFunction = (await import(\"react-dom/server\")).renderToStaticMarkup;\n  }\n  const { result } = await prerenderStatic({\n    tree,\n    context,\n    renderFunction,\n    maxRerenders: Number.POSITIVE_INFINITY,\n  });\n  return result;\n}\n"
  },
  {
    "path": "src/react/ssr/index.ts",
    "content": "export { getDataFromTree, getMarkupFromTree } from \"./getDataFromTree.js\";\nexport { prerenderStatic } from \"./prerenderStatic.js\";\nexport { renderToStringWithData } from \"./renderToStringWithData.js\";\n"
  },
  {
    "path": "src/react/ssr/prerenderStatic.tsx",
    "content": "import { print } from \"graphql\";\nimport type * as ReactTypes from \"react\";\nimport * as React from \"react\";\nimport type { Observer, Subscription } from \"rxjs\";\nimport { filter, firstValueFrom } from \"rxjs\";\n\nimport type {\n  ApolloClient,\n  DocumentNode,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\nimport { getApolloContext } from \"@apollo/client/react\";\nimport { wrapperSymbol } from \"@apollo/client/react/internal\";\nimport { canonicalStringify } from \"@apollo/client/utilities\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { useSSRQuery } from \"./useSSRQuery.js\";\n\ntype ObservableQueryKey = `${string}|${string}`;\nfunction getObservableQueryKey(\n  query: DocumentNode,\n  variables: Record<string, any> = {}\n): ObservableQueryKey {\n  const queryKey = print(query);\n  const variablesKey = canonicalStringify(variables);\n  return `${queryKey}|${variablesKey}`;\n}\nexport interface PrerenderStaticInternalContext {\n  getObservableQuery(\n    query: DocumentNode,\n    variables?: Record<string, any>\n  ): ObservableQuery | undefined;\n  onCreatedObservableQuery: (\n    observable: ObservableQuery,\n    query: DocumentNode,\n    variables: OperationVariables\n  ) => void;\n}\n\nexport declare namespace prerenderStatic {\n  /** {@inheritDoc @apollo/client!~prerenderStatic~Options#renderFunction:member} */\n  export type PrerenderFunction =\n    | RenderToString\n    | RenderToStringPromise\n    | PrerenderToWebStream\n    | PrerenderToNodeStream\n    | ((\n        reactNode: ReactTypes.ReactNode\n      ) =>\n        | ReturnType<RenderToString>\n        | ReturnType<RenderToStringPromise>\n        | ReturnType<PrerenderToWebStream>\n        | ReturnType<PrerenderToNodeStream>);\n\n  export interface Options<\n    Prerender extends PrerenderFunction = PrerenderFunction,\n  > {\n    /**\n     * The React component tree to prerender\n     */\n    tree: ReactTypes.ReactNode;\n    /**\n     * If your app is not wrapped in an `ApolloProvider`, you can pass a `client` instance in here.\n     */\n    context?: { client?: ApolloClient };\n    /**\n     * An `AbortSignal` that indicates you want to stop the re-render loop, even if not all data is fetched yet.\n     *\n     * Note that if you use an api like `prerender` or `prerenderToNodeStream` that supports `AbortSignal` as an option,\n     * you will still have to pass that `signal` option to that function by wrapping the `renderFunction`, and if that api\n     * throws an exception if the signal is aborted, so will `prerenderStatic`.\n     *\n     * @example\n     *\n     * ```ts\n     * const result = await prerenderStatic({\n     *   tree: <App/>,\n     *   signal,\n     *   renderFunction: (tree) => prerender(tree, { signal }),\n     * })\n     * ```\n     */\n    signal?: AbortSignal;\n    /**\n     * If this is set, this method will return `\"\"` as the `result` property.\n     * Setting this can save CPU time that would otherwise be spent on converting\n     * `Uint8Array` or `Buffer` instances to strings for the result.\n     */\n    ignoreResults?: boolean;\n    /**\n     * The rendering function to use.\n     * These functions are currently supported:\n     *\n     * - `prerender` from `react-dom/static` (https://react.dev/reference/react-dom/static/prerender)\n     *   - recommended if you use Deno or a modern edge runtime with Web Streams\n     * - `prerenderToNodeStream` from `react-dom/static` (https://react.dev/reference/react-dom/static/prerenderToNodeStream)\n     *   - recommended if you use Node.js\n     * - `renderToString` from `react-dom/server` (https://react.dev/reference/react-dom/server/renderToString)\n     *   - this API has no suspense support and will not work with hooks like `useSuspenseQuery`\n     * - `renderToStaticMarkup` from `react-dom/server` (https://react.dev/reference/react-dom/server/renderToStaticMarkup)\n     *   - slightly faster than `renderToString`, but the result cannot be hydrated\n     *   - this API has no suspense support and will not work with hooks like `useSuspenseQuery`\n     */\n    renderFunction: Prerender;\n\n    /**\n     * If this is set to `true`, the result will contain a `diagnostics` property that can help you e.g. detect `useQuery` waterfalls in your application.\n     * @defaultValue false\n     */\n    diagnostics?: boolean;\n\n    /**\n     * The maximum number of times the tree will be rerendered until no more network requests are made.\n     * This is useful to prevent infinite loops in case of a bug in your application.\n     * If you have a lot of waterfalls in your application, you might need to increase this number.\n     *\n     * @defaultValue 50\n     */\n    maxRerenders?: number;\n  }\n\n  export interface Result<\n    Prerender extends PrerenderFunction = PrerenderFunction,\n  > {\n    /**\n     * The result of the last render, or an empty string if `ignoreResults` was set to `true`.\n     */\n    result: string;\n\n    /**\n     * The result of the last execution of the `renderFunction`.\n     */\n    renderFnResult: ReturnType<Prerender> extends PromiseLike<infer U> ? U\n    : ReturnType<Prerender>;\n\n    /**\n     * If the render was aborted early because the `AbortSignal` was cancelled,\n     * this will be `true`.\n     * If you used a hydratable render function (everything except `renderToStaticMarkup`),\n     * the result will still be able to hydrate in the browser, but it might still\n     * contain `loading` states and need additional data fetches in the browser.\n     */\n    aborted: boolean;\n    /**\n     * If `diagnostics` was set to `true`, this will contain an object with diagnostics that can be used to\n     * detect ineffective rendering structures in your app.\n     */\n    diagnostics?: Diagnostics;\n  }\n\n  export interface Diagnostics {\n    /**\n     * The number of times the tree had to be rerendered until no more network requests\n     * were made.\n     * A high number here might indicate that you have a waterfall of `useQuery` calls\n     * in your application and shows potential for optimization, e.g. via fragment colocation.\n     */\n    renderCount: number;\n  }\n\n  export type RenderToString = (element: ReactTypes.ReactNode) => string;\n  export type RenderToStringPromise = (\n    element: ReactTypes.ReactNode\n  ) => PromiseLike<string>;\n\n  export type PrerenderToWebStream = (\n    reactNode: ReactTypes.ReactNode\n  ) => Promise<{\n    prelude: ReadableStream<Uint8Array>; // AsyncIterable<Uint8Array>;\n  }>;\n\n  export type PrerenderToNodeStream = (\n    reactNode: ReactTypes.ReactNode\n  ) => Promise<{\n    prelude: AsyncIterable<string | Buffer>;\n  }>;\n}\n\nconst noopObserver: Partial<Observer<unknown>> = { complete() {} };\n\n/**\n * This function will rerender your React tree until no more network requests need\n * to be made.\n * If you only use suspenseful hooks (and a suspense-ready `renderFunction`), this\n * means that the tree will be rendered once.\n * If you use non-suspenseful hooks like `useQuery`, this function will render all\n * components, wait for all requests started by your rendered\n * hooks to finish, and then render the tree again, until no more requests are made.\n *\n * After executing this function, you can use `client.extract()` to get a full set\n * of the data that was fetched during these renders.\n * You can then transport that data and hydrate your cache via `client.restore(extractedData)`\n * before hydrating your React tree in the browser.\n */\nexport function prerenderStatic<\n  Prerender extends\n    prerenderStatic.PrerenderFunction = prerenderStatic.PrerenderFunction,\n>({\n  tree,\n  context = {},\n  // The rendering function is configurable! We use renderToStaticMarkup as\n  // the default, because it's a little less expensive than renderToString,\n  // and legacy usage of getDataFromTree ignores the return value anyway.\n  renderFunction,\n  signal,\n  ignoreResults,\n  diagnostics,\n  maxRerenders = 50,\n}: prerenderStatic.Options<Prerender>): Promise<\n  prerenderStatic.Result<Prerender>\n> {\n  const availableObservableQueries = new Map<\n    ObservableQueryKey,\n    ObservableQuery\n  >();\n  const subscriptions = new Set<Subscription>();\n  let recentlyCreatedObservableQueries = new Set<ObservableQuery>();\n  let renderCount = 0;\n\n  const internalContext: PrerenderStaticInternalContext = {\n    getObservableQuery(query, variables) {\n      return availableObservableQueries.get(\n        getObservableQueryKey(query, variables)\n      );\n    },\n    onCreatedObservableQuery: (\n      observable: ObservableQuery,\n      query: DocumentNode,\n      variables: OperationVariables\n    ) => {\n      availableObservableQueries.set(\n        getObservableQueryKey(query, variables),\n        observable\n      );\n      // we keep the observable subscribed to until we are done with rendering\n      // otherwise it will be torn down after every render pass\n      subscriptions.add(observable.subscribe(noopObserver));\n      if (observable.options.fetchPolicy !== \"cache-only\") {\n        recentlyCreatedObservableQueries.add(observable);\n      }\n    },\n  };\n\n  async function process(): Promise<prerenderStatic.Result<any>> {\n    renderCount++;\n    invariant(\n      renderCount <= maxRerenders,\n      `Exceeded maximum rerender count of %d.\nThis either means you have very deep \\`useQuery\\` waterfalls in your application\nand need to increase the \\`maxRerender\\` option to \\`prerenderStatic\\`, or that\nyou have an infinite render loop in your application.`,\n      maxRerenders\n    );\n\n    invariant(\n      !signal?.aborted,\n      \"The operation was aborted before it could be attempted.\"\n    );\n\n    // Always re-render from the rootElement, even though it might seem\n    // better to render the children of the component responsible for the\n    // promise, because it is not possible to reconstruct the full context\n    // of the original rendering (including all unknown context provider\n    // elements) for a subtree of the original component tree.\n    const ApolloContext = getApolloContext();\n\n    const element = (\n      <ApolloContext.Provider\n        value={{\n          ...context,\n          [wrapperSymbol]: {\n            useQuery: () => useSSRQuery.bind(internalContext) as any,\n          },\n        }}\n      >\n        {tree}\n      </ApolloContext.Provider>\n    );\n    const renderFnResult = await renderFunction(element);\n    const result = await consume(renderFnResult);\n\n    if (recentlyCreatedObservableQueries.size == 0) {\n      return {\n        result,\n        renderFnResult,\n        aborted: signal?.aborted ?? false,\n      };\n    }\n    if (signal?.aborted) {\n      return {\n        result,\n        renderFnResult,\n        aborted: true,\n      };\n    }\n\n    const dataPromise = Promise.all(\n      Array.from(recentlyCreatedObservableQueries).map(async (observable) => {\n        await firstValueFrom(\n          observable.pipe(filter((result) => result.loading === false))\n        );\n\n        recentlyCreatedObservableQueries.delete(observable);\n      })\n    );\n\n    let resolveAbortPromise!: () => void;\n    const abortPromise = new Promise<void>((resolve) => {\n      resolveAbortPromise = resolve;\n    });\n    signal?.addEventListener(\"abort\", resolveAbortPromise);\n    await Promise.race([abortPromise, dataPromise]);\n    signal?.removeEventListener(\"abort\", resolveAbortPromise);\n\n    if (signal?.aborted) {\n      return {\n        result,\n        renderFnResult,\n        aborted: true,\n      } as prerenderStatic.Result<any>;\n    }\n    return process();\n  }\n\n  return Promise.resolve()\n    .then(process)\n    .then((result) =>\n      diagnostics ?\n        {\n          ...result,\n          diagnostics: {\n            renderCount,\n          },\n        }\n      : result\n    )\n    .finally(() => {\n      availableObservableQueries.clear();\n      recentlyCreatedObservableQueries.clear();\n      subscriptions.forEach((subscription) => subscription.unsubscribe());\n      subscriptions.clear();\n    });\n\n  async function consume(\n    value:\n      | string\n      | {\n          prelude: ReadableStream<Uint8Array>;\n        }\n      | {\n          prelude: AsyncIterable<string | Buffer>;\n        }\n  ): Promise<string> {\n    if (typeof value === \"string\") {\n      return ignoreResults ? \"\" : value;\n    }\n    if (!value.prelude) {\n      throw new Error(\n        \"`getMarkupFromTree` was called with an incompatible render method.\\n\" +\n          'It is compatible with `renderToStaticMarkup` and `renderToString`  from `\"react-dom/server\"`\\n' +\n          'as well as `prerender` and `prerenderToNodeStream` from \"react-dom/static\"'\n      );\n    }\n    const prelude = value.prelude;\n    let result = \"\";\n    if (\"getReader\" in prelude) {\n      /**\n       * The \"web\" `ReadableStream` consuming path.\n       * This could also be done with the `AsyncIterable` branch, but we add this\n       * code for two reasons:\n       *\n       * 1.  potential performance benefits if we don't need to create an `AsyncIterator` on top\n       * 2.  some browsers (looking at Safari) don't support `AsyncIterable` for `ReadableStream` yet\n       *     and we're not 100% sure how good this is covered on edge runtimes\n       *\n       * The extra code here doesn't really matter, since _usually_ this would not\n       * be run in a browser, so we don't have to shave every single byte.\n       */\n      const reader = prelude.getReader();\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) {\n          break;\n        }\n        if (!ignoreResults) {\n          result += Buffer.from(value).toString(\"utf8\");\n        }\n      }\n    } else {\n      for await (const chunk of prelude) {\n        if (!ignoreResults) {\n          result +=\n            typeof chunk === \"string\" ? chunk : (\n              Buffer.from(chunk).toString(\"utf8\")\n            );\n        }\n      }\n    }\n    return result;\n  }\n}\n"
  },
  {
    "path": "src/react/ssr/renderToStringWithData.ts",
    "content": "import type * as ReactTypes from \"react\";\n\nimport { prerenderStatic } from \"./prerenderStatic.js\";\n\n/**\n * @deprecated This function uses the legacy `renderToString` API from React.\n * Use `prerenderStatic` instead, which can be configured to run with more modern\n * React APIs.\n */\nexport async function renderToStringWithData(\n  component: ReactTypes.ReactElement<any>\n): Promise<string> {\n  const { result } = await prerenderStatic({\n    tree: component,\n    renderFunction: (await import(\"react-dom/server\")).renderToString,\n    maxRerenders: Number.POSITIVE_INFINITY,\n  });\n  return result;\n}\n"
  },
  {
    "path": "src/react/ssr/useSSRQuery.ts",
    "content": "import type { DocumentNode } from \"graphql\";\n\nimport type { ObservableQuery } from \"@apollo/client\";\nimport { NetworkStatus } from \"@apollo/client\";\nimport type { SkipToken } from \"@apollo/client/react\";\nimport { skipToken, useApolloClient, useQuery } from \"@apollo/client/react\";\nimport { maybeDeepFreeze } from \"@apollo/client/utilities/internal\";\n\nimport type { PrerenderStaticInternalContext } from \"./prerenderStatic.js\";\n\nconst skipStandbyResult: ObservableQuery.Result<any> = maybeDeepFreeze({\n  loading: false,\n  data: void 0 as any,\n  dataState: \"empty\",\n  error: void 0,\n  networkStatus: NetworkStatus.ready,\n  partial: true,\n});\n\nexport const useSSRQuery = function (\n  // eslint-disable-next-line react-hooks/unsupported-syntax\n  this: PrerenderStaticInternalContext,\n  query: DocumentNode,\n  options: useQuery.Options<any, any> | SkipToken = {}\n): useQuery.Result<any, any> {\n  \"use no memo\";\n  function notAllowed(): never {\n    throw new Error(\"This method cannot be called during SSR.\");\n  }\n  const client = useApolloClient(\n    typeof options === \"object\" ? options.client : undefined\n  );\n\n  const baseResult: Omit<\n    useQuery.Result,\n    \"observable\" | \"data\" | \"error\" | \"loading\" | \"networkStatus\" | \"dataState\"\n  > = {\n    client,\n    refetch: notAllowed,\n    fetchMore: notAllowed,\n    subscribeToMore: notAllowed,\n    updateQuery: notAllowed,\n    startPolling: notAllowed,\n    stopPolling: notAllowed,\n    variables: typeof options === \"object\" ? options?.variables : undefined,\n    previousData: undefined,\n  };\n\n  if (\n    options === skipToken ||\n    options.skip ||\n    options.fetchPolicy === \"standby\"\n  ) {\n    return withoutObservableAccess({\n      ...baseResult,\n      ...skipStandbyResult,\n    });\n  }\n  if (options.ssr === false || options.fetchPolicy === \"no-cache\") {\n    return withoutObservableAccess({\n      ...baseResult,\n      ...useQuery.ssrDisabledResult,\n    });\n  }\n\n  let observable = this.getObservableQuery(query, options.variables);\n  if (!observable) {\n    observable = client.watchQuery({\n      query,\n      ...options,\n      fetchPolicy:\n        (\n          options.fetchPolicy === \"network-only\" ||\n          options.fetchPolicy === \"cache-and-network\"\n        ) ?\n          \"cache-first\"\n        : options.fetchPolicy,\n    });\n    this.onCreatedObservableQuery(observable, query, options.variables);\n  }\n  return {\n    observable,\n    ...observable.getCurrentResult(),\n    ...baseResult,\n  };\n};\n\nfunction withoutObservableAccess<T>(\n  value: T\n): T & { observable: ObservableQuery<any, any> } {\n  Object.defineProperty(value, \"observable\", {\n    get() {\n      throw new Error(\n        '\"observable\" property is not accessible on skipped hooks or hook calls with `ssr: false` during SSR'\n      );\n    },\n  });\n  return value as any;\n}\n"
  },
  {
    "path": "src/react/types/deprecated.ts",
    "content": "import type {\n  ApolloCache,\n  DefaultContext,\n  OperationVariables,\n} from \"@apollo/client\";\n\nimport type { useBackgroundQuery } from \"../hooks/useBackgroundQuery.js\";\nimport type { useFragment } from \"../hooks/useFragment.js\";\nimport type { useLazyQuery } from \"../hooks/useLazyQuery.js\";\nimport type { useLoadableQuery } from \"../hooks/useLoadableQuery.js\";\nimport type { useMutation } from \"../hooks/useMutation.js\";\nimport type { useQuery } from \"../hooks/useQuery.js\";\nimport type { useQueryRefHandlers } from \"../hooks/useQueryRefHandlers.js\";\nimport type { useReadQuery } from \"../hooks/useReadQuery.js\";\nimport type { useSubscription } from \"../hooks/useSubscription.js\";\nimport type { useSuspenseFragment } from \"../hooks/useSuspenseFragment.js\";\nimport type { useSuspenseQuery } from \"../hooks/useSuspenseQuery.js\";\n\n/** @deprecated Use `useQuery.Options` instead */\nexport type QueryHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useQuery.Options<TData, TVariables>;\n\n/** @deprecated Use `useQuery.Result` instead */\nexport type QueryResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useQuery.Result<TData, TVariables>;\n\n/** @deprecated Use `useLazyQuery.Options` instead */\nexport type LazyQueryHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useLazyQuery.Options<TData, TVariables>;\n\n/** @deprecated Use `useLazyQuery.Result` instead */\nexport type LazyQueryResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useLazyQuery.Result<TData, TVariables>;\n\n/** @deprecated Use `useLazyQuery.ResultTuple` instead */\nexport type LazyQueryResultTuple<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useLazyQuery.ResultTuple<TData, TVariables>;\n\n/** @deprecated Use `useLazyQuery.ExecOptions` instead */\nexport type LazyQueryHookExecOptions<\n  TVariables extends OperationVariables = OperationVariables,\n> = useLazyQuery.ExecOptions<TVariables>;\n\n/** @deprecated Use `useLazyQuery.ExecFunction` instead */\nexport type LazyQueryExecFunction<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useLazyQuery.ExecFunction<TData, TVariables>;\n\n/** @deprecated Use `useMutation.Options` instead */\nexport type MutationHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  _TContext = DefaultContext,\n  TCache extends ApolloCache = ApolloCache,\n> = useMutation.Options<TData, TVariables, TCache>;\n\n/** @deprecated Use `useMutation.Result` instead */\nexport type MutationResult<TData = unknown> = useMutation.Result<TData>;\n\n/** @deprecated Use `useMutation.MutationFunctionOptions` instead */\nexport type MutationFunctionOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n  _TContext = DefaultContext,\n  TCache extends ApolloCache = ApolloCache,\n> = useMutation.MutationFunctionOptions<TData, TVariables, TCache>;\n\n/** @deprecated Use `useMutation.ResultTuple` instead */\nexport type MutationTuple<\n  TData,\n  TVariables extends OperationVariables,\n  _TContext = DefaultContext,\n  TCache extends ApolloCache = ApolloCache,\n> = useMutation.ResultTuple<TData, TVariables, TCache>;\n\n/** @deprecated Use `useSubscription.Result` instead */\nexport type SubscriptionResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useSubscription.Result<TData>;\n\n/** @deprecated Use `useSubscription.Options` instead */\nexport type SubscriptionHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useSubscription.Options<TData, TVariables>;\n\n/** @deprecated Use `useSubscription.OnDataOptions` instead */\nexport type OnDataOptions<TData = unknown> =\n  useSubscription.OnDataOptions<TData>;\n\n/** @deprecated Use `useSubscription.OnSubscriptionDataOptions` instead */\nexport type OnSubscriptionDataOptions<TData = unknown> =\n  useSubscription.OnSubscriptionDataOptions<TData>;\n\n/** @deprecated Use `useFragment.Options` instead */\nexport type UseFragmentOptions<\n  TData,\n  TVariables extends OperationVariables,\n> = useFragment.Options<TData, TVariables>;\n\n/** @deprecated Use `useFragment.Result` instead */\nexport type UseFragmentResult<TData> = useFragment.Result<TData>;\n\n/** @deprecated Use `useSuspenseQuery.Options` instead */\nexport type SuspenseQueryHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useSuspenseQuery.Options<TVariables>;\n\n/** @deprecated Use `useSuspenseQuery.Result` instead */\nexport type UseSuspenseQueryResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useSuspenseQuery.Result<TData, TVariables>;\n\n/** @deprecated Use `useSuspenseQuery.FetchPolicy` instead */\nexport type SuspenseQueryHookFetchPolicy = useSuspenseQuery.FetchPolicy;\n\n/** @deprecated Use `useBackgroundQuery.Options` instead */\nexport type BackgroundQueryHookOptions<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useBackgroundQuery.Options<TVariables>;\n\n/** @deprecated Use `useBackgroundQuery.Result` instead */\nexport type UseBackgroundQueryResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useBackgroundQuery.Result<TData, TVariables>;\n\n/** @deprecated Use `useBackgroundQuery.FetchPolicy` instead */\nexport type BackgroundQueryHookFetchPolicy = useBackgroundQuery.FetchPolicy;\n\n/** @deprecated Use `useSuspenseFragment.Options` instead */\nexport type UseSuspenseFragmentOptions<\n  TData,\n  TVariables extends OperationVariables,\n> = useSuspenseFragment.Options<TData, TVariables>;\n\n/** @deprecated Use `useSuspenseFragment.Result` instead */\nexport type UseSuspenseFragmentResult<TData> =\n  useSuspenseFragment.Result<TData>;\n\n/** @deprecated Use `useLoadableQuery.LoadQueryFunction` instead */\nexport type LoadQueryFunction<TVariables extends OperationVariables> =\n  useLoadableQuery.LoadQueryFunction<TVariables>;\n\n/** @deprecated Use `useLoadableQuery.FetchPolicy` instead */\nexport type LoadableQueryFetchPolicy = useLoadableQuery.FetchPolicy;\n\n/** @deprecated Use `useLoadableQuery.Options` instead */\nexport type LoadableQueryHookOptions = useLoadableQuery.Options;\n\n/** @deprecated Use `useLoadableQuery.Result` instead */\nexport type UseLoadableQueryResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useLoadableQuery.Result<TData, TVariables>;\n\n/** @deprecated Use `useQueryRefHandlers.Result` instead */\nexport type UseQueryRefHandlersResult<\n  TData = unknown,\n  TVariables extends OperationVariables = OperationVariables,\n> = useQueryRefHandlers.Result<TData, TVariables>;\n\n/** @deprecated Use `useReadQuery.Result` instead */\nexport type UseReadQueryResult<TData = unknown> = useReadQuery.Result<TData>;\n"
  },
  {
    "path": "src/react/types/types.documentation.ts",
    "content": "export interface QueryOptionsDocumentation {\n  /**\n   * A GraphQL query string parsed into an AST with the gql template literal.\n   *\n   * @docGroup 1. Operation options\n   */\n  query: unknown;\n\n  /**\n   * An object containing all of the GraphQL variables your query requires to execute.\n   *\n   * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.\n   *\n   * @docGroup 1. Operation options\n   */\n  variables: unknown;\n\n  /**\n   * Specifies how the query handles a response that returns both GraphQL errors and partial results.\n   *\n   * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).\n   *\n   * The default value is `none`, meaning that the query result includes error details but not partial results.\n   *\n   * @docGroup 1. Operation options\n   */\n  errorPolicy: unknown;\n\n  /**\n   * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain.\n   *\n   * @docGroup 2. Networking options\n   */\n  context: unknown;\n\n  /**\n   * Specifies how the query interacts with the Apollo Client cache during execution (for example, whether it checks the cache for results before sending a request to the server).\n   *\n   * For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).\n   *\n   * The default value is `cache-first`.\n   *\n   * @docGroup 3. Caching options\n   */\n  fetchPolicy: unknown;\n\n  /**\n   * Specifies the `FetchPolicy` to be used after this query has completed.\n   *\n   * @docGroup 3. Caching options\n   */\n  nextFetchPolicy: unknown;\n\n  /**\n   * Defaults to the initial value of options.fetchPolicy, but can be explicitly\n   * configured to specify the WatchQueryFetchPolicy to revert back to whenever\n   * variables change (unless nextFetchPolicy intervenes).\n   *\n   * @docGroup 3. Caching options\n   */\n  initialFetchPolicy: unknown;\n\n  /**\n   * Specifies the interval (in milliseconds) at which the query polls for updated results.\n   *\n   * The default value is `0` (no polling).\n   *\n   * @docGroup 2. Networking options\n   */\n  pollInterval: unknown;\n\n  /**\n   * If `true`, the in-progress query's associated component re-renders whenever the network status changes or a network error occurs.\n   *\n   * The default value is `true`.\n   *\n   * @docGroup 2. Networking options\n   */\n  notifyOnNetworkStatusChange: unknown;\n\n  /**\n   * If `true`, the query can return partial results from the cache if the cache doesn't contain results for all queried fields.\n   *\n   * The default value is `false`.\n   *\n   * @docGroup 3. Caching options\n   */\n  returnPartialData: unknown;\n\n  /**\n   * Specifies whether a `NetworkStatus.refetch` operation should merge\n   * incoming field data with existing data, or overwrite the existing data.\n   * Overwriting is probably preferable, but merging is currently the default\n   * behavior, for backwards compatibility with Apollo Client 3.x.\n   *\n   * @docGroup 3. Caching options\n   */\n  refetchWritePolicy: unknown;\n\n  /**\n   * Watched queries must opt into overwriting existing data on refetch, by passing refetchWritePolicy: \"overwrite\" in their WatchQueryOptions.\n   *\n   * The default value is \"overwrite\".\n   *\n   * @docGroup 3. Caching options\n   */\n  refetchWritePolicy_suspense: unknown;\n\n  /**\n   * If true, the query is not executed.\n   *\n   * The default value is `false`.\n   *\n   * @docGroup 1. Operation options\n   */\n  skip: unknown;\n\n  /**\n   * If `true`, the query is not executed. The default value is `false`.\n   *\n   * @deprecated We recommend using `skipToken` in place of the `skip` option as\n   * it is more type-safe.\n   *\n   * This option is deprecated and only supported to ease the migration from `useQuery`. It will be removed in a future release.\n   * Please use [`skipToken`](https://www.apollographql.com/docs/react/api/react/hooks#skiptoken) instead of the `skip` option as it is more type-safe.\n   *\n   * @docGroup 1. Operation options\n   */\n  skip_deprecated: unknown;\n\n  /**\n   * The instance of `ApolloClient` to use to execute the query.\n   *\n   * By default, the instance that's passed down via context is used, but you\n   * can provide a different instance here.\n   *\n   * @docGroup 1. Operation options\n   */\n  client: unknown;\n\n  /**\n   * A unique identifier for the query. Each item in the array must be a stable\n   * identifier to prevent infinite fetches.\n   *\n   * This is useful when using the same query and variables combination in more\n   * than one component, otherwise the components may clobber each other. This\n   * can also be used to force the query to re-evaluate fresh.\n   *\n   * @docGroup 1. Operation options\n   */\n  queryKey: unknown;\n\n  /**\n   * Pass `false` to skip executing the query during [server-side rendering](https://www.apollographql.com/docs/react/performance/server-side-rendering/).\n   *\n   * @docGroup 2. Networking options\n   */\n  ssr: unknown;\n\n  /**\n   * A callback function that's called whenever a refetch attempt occurs\n   * while polling. If the function returns `true`, the refetch is\n   * skipped and not reattempted until the next poll interval.\n   *\n   * @docGroup 2. Networking options\n   */\n  skipPollAttempt: unknown;\n}\n\nexport interface QueryResultDocumentation {\n  /**\n   * The instance of Apollo Client that executed the query.\n   * Can be useful for manually executing followup queries or writing data to the cache.\n   *\n   * @docGroup 2. Network info\n   */\n  client: unknown;\n  /**\n   * A reference to the internal `ObservableQuery` used by the hook.\n   */\n  observable: unknown;\n  /**\n   * An object containing the result of your GraphQL query after it completes.\n   *\n   * This value might be `undefined` if a query results in one or more errors (depending on the query's `errorPolicy`).\n   *\n   * @docGroup 1. Operation data\n   */\n  data: unknown;\n  /**\n   * An object containing the result from the most recent _previous_ execution of this query.\n   *\n   * This value is `undefined` if this is the query's first execution.\n   *\n   * @docGroup 1. Operation data\n   */\n  previousData: unknown;\n  /**\n   * A single ErrorLike object describing the error that occurred during the latest\n   * query execution.\n   *\n   * For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).\n   *\n   * @docGroup 1. Operation data\n   */\n  error: unknown;\n  /**\n   * If `true`, the query is still in flight.\n   *\n   * @docGroup 2. Network info\n   */\n  loading: unknown;\n  /**\n   * A number indicating the current network state of the query's associated request. [See possible values.](https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4)\n   *\n   * Used in conjunction with the [`notifyOnNetworkStatusChange`](#notifyonnetworkstatuschange) option.\n   *\n   * @docGroup 2. Network info\n   */\n  networkStatus: unknown;\n  /**\n   * An object containing the variables that were provided for the query.\n   *\n   * @docGroup 1. Operation data\n   */\n  variables: unknown;\n\n  /**\n   * A function that enables you to re-execute the query, optionally passing in new `variables`.\n   *\n   * To guarantee that the refetch performs a network request, its `fetchPolicy` is set to `network-only` (unless the original query's `fetchPolicy` is `no-cache` or `cache-and-network`, which also guarantee a network request).\n   *\n   * See also [Refetching](https://www.apollographql.com/docs/react/data/queries/#refetching).\n   *\n   * Returns a `ResultPromise` with an additional `.retain()` method. Calling\n   * `.retain()` keeps the network operation running even if the `ObservableQuery`\n   * no longer requires the result.\n   *\n   * @docGroup 3. Helper functions\n   */\n  refetch: unknown;\n  /**\n   * {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)}\n   *\n   * @docGroup 3. Helper functions\n   */\n  fetchMore: unknown;\n  /**\n   * {@inheritDoc @apollo/client!ObservableQuery#startPolling:member(1)}\n   *\n   * @docGroup 3. Helper functions\n   */\n  startPolling: unknown;\n  /**\n   * {@inheritDoc @apollo/client!ObservableQuery#stopPolling:member(1)}\n   *\n   * @docGroup 3. Helper functions\n   */\n  stopPolling: unknown;\n  /**\n   * {@inheritDoc @apollo/client!ObservableQuery#subscribeToMore:member(1)}\n   *\n   * @docGroup 3. Helper functions\n   */\n  subscribeToMore: unknown;\n  /**\n   * {@inheritDoc @apollo/client!ObservableQuery#updateQuery:member(1)}\n   *\n   * @docGroup 3. Helper functions\n   */\n  updateQuery: unknown;\n\n  /**\n   * Describes the completeness of `data`.\n   *\n   * - `empty`: No data could be fulfilled from the cache or the result is\n   *   incomplete. `data` is `undefined`.\n   * - `partial`: Some data could be fulfilled from the cache but `data` is\n   *   incomplete. This is only possible when `returnPartialData` is `true`.\n   * - `streaming`: `data` is incomplete as a result of a deferred query and\n   *   the result is still streaming in.\n   * - `complete`: `data` is a fully satisfied query result fulfilled\n   *   either from the cache or network.\n   *\n   * @docGroup 1. Operation data\n   */\n  dataState: unknown;\n\n  /**\n   * Describes whether `data` is a complete or partial result. This flag is only\n   * set when `returnPartialData` is `true` in query options.\n   *\n   * @deprecated This field will be removed in a future version of Apollo Client.\n   * @docGroup 1. Operation data\n   */\n  partial: boolean;\n}\n\nexport interface MutationOptionsDocumentation {\n  /**\n   * A GraphQL document, often created with `gql` from the `graphql-tag`\n   * package, that contains a single mutation inside of it.\n   *\n   * @docGroup 1. Operation options\n   */\n  mutation: unknown;\n\n  /**\n   * Provide `no-cache` if the mutation's result should _not_ be written to the Apollo Client cache.\n   *\n   * The default value is `network-only` (which means the result _is_ written to the cache).\n   *\n   * Unlike queries, mutations _do not_ support [fetch policies](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy) besides `network-only` and `no-cache`.\n   *\n   * @docGroup 3. Caching options\n   */\n  fetchPolicy: unknown;\n\n  /**\n   * To avoid retaining sensitive information from mutation root field\n   * arguments, Apollo Client v3.4+ automatically clears any `ROOT_MUTATION`\n   * fields from the cache after each mutation finishes. If you need this\n   * information to remain in the cache, you can prevent the removal by passing\n   * `keepRootFields: true` to the mutation. `ROOT_MUTATION` result data are\n   * also passed to the mutation `update` function, so we recommend obtaining\n   * the results that way, rather than using this option, if possible.\n   */\n  keepRootFields: unknown;\n\n  /**\n   * By providing either an object or a callback function that, when invoked after\n   * a mutation, allows you to return optimistic data and optionally skip updates\n   * via the `IGNORE` sentinel object, Apollo Client caches this temporary\n   * (and potentially incorrect) response until the mutation completes, enabling\n   * more responsive UI updates.\n   *\n   * For more information, see [Optimistic mutation results](https://www.apollographql.com/docs/react/performance/optimistic-ui/).\n   *\n   * @docGroup 3. Caching options\n   */\n  optimisticResponse: unknown;\n\n  /**\n   * A `MutationQueryReducersMap`, which is map from query names to\n   * mutation query reducers. Briefly, this map defines how to incorporate the\n   * results of the mutation into the results of queries that are currently\n   * being watched by your application.\n   */\n  updateQueries: unknown;\n\n  /**\n   * An array (or a function that _returns_ an array) that specifies which queries you want to refetch after the mutation occurs.\n   *\n   * Each array value can be either:\n   *\n   * - An object containing the `query` to execute, along with any `variables`\n   *\n   * - A string indicating the operation name of the query to refetch\n   *\n   * @docGroup 1. Operation options\n   */\n  refetchQueries: unknown;\n\n  /**\n   * If `true`, makes sure all queries included in `refetchQueries` are completed before the mutation is considered complete.\n   *\n   * The default value is `false` (queries are refetched asynchronously).\n   *\n   * @docGroup 1. Operation options\n   */\n  awaitRefetchQueries: unknown;\n\n  /**\n   * A function used to update the Apollo Client cache after the mutation completes.\n   *\n   * For more information, see [Updating the cache after a mutation](https://www.apollographql.com/docs/react/data/mutations#updating-the-cache-after-a-mutation).\n   *\n   * @docGroup 3. Caching options\n   */\n  update: unknown;\n\n  /**\n   * Optional callback for intercepting queries whose cache data has been updated by the mutation, as well as any queries specified in the `refetchQueries: [...]` list passed to `client.mutate`.\n   *\n   * Returning a `Promise` from `onQueryUpdated` will cause the final mutation `Promise` to await the returned `Promise`. Returning `false` causes the query to be ignored.\n   *\n   * @docGroup 1. Operation options\n   */\n  onQueryUpdated: unknown;\n\n  /**\n   * Specifies how the mutation handles a response that returns both GraphQL errors and partial results.\n   *\n   * For details, see [GraphQL error policies](https://www.apollographql.com/docs/react/data/error-handling/#graphql-error-policies).\n   *\n   * The default value is `none`, meaning that the mutation result includes error details but _not_ partial results.\n   *\n   * @docGroup 1. Operation options\n   */\n  errorPolicy: unknown;\n\n  /**\n   * An object containing all of the GraphQL variables your mutation requires to execute.\n   *\n   * Each key in the object corresponds to a variable name, and that key's value corresponds to the variable value.\n   *\n   * @docGroup 1. Operation options\n   */\n  variables: unknown;\n\n  /**\n   * If you're using [Apollo Link](https://www.apollographql.com/docs/react/api/link/introduction/), this object is the initial value of the `context` object that's passed along your link chain.\n   *\n   * @docGroup 2. Networking options\n   */\n  context: unknown;\n\n  /**\n   * The instance of `ApolloClient` to use to execute the mutation.\n   *\n   * By default, the instance that's passed down via context is used, but you can provide a different instance here.\n   *\n   * @docGroup 2. Networking options\n   */\n  client: unknown;\n  /**\n   * If `true`, the in-progress mutation's associated component re-renders whenever the network status changes or a network error occurs.\n   *\n   * The default value is `true`.\n   *\n   * @docGroup 2. Networking options\n   */\n  notifyOnNetworkStatusChange: unknown;\n  /**\n   * A callback function that's called when your mutation successfully completes with zero errors (or if `errorPolicy` is `ignore` and partial data is returned).\n   *\n   * This function is passed the mutation's result `data` and any options passed to the mutation.\n   *\n   * @docGroup 1. Operation options\n   */\n  onCompleted: unknown;\n  /**\n   * A callback function that's called when the mutation encounters one or more errors (unless `errorPolicy` is `ignore`).\n   *\n   * This function is passed an [`ApolloError`](https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/errors/index.ts#L36-L39) object that contains either a `networkError` object or a `graphQLErrors` array, depending on the error(s) that occurred, as well as any options passed the mutation.\n   *\n   * @docGroup 1. Operation options\n   */\n  onError: unknown;\n}\n\nexport interface MutationResultDocumentation {\n  /**\n   * The data returned from your mutation. Can be `undefined` if the `errorPolicy`\n   * is `all` or `ignore` and the server returns a GraphQL response with `errors`\n   * but not `data` or a network error is returned.\n   */\n  data: unknown;\n  /**\n   * If the mutation produces one or more errors, this object contains either an array of `graphQLErrors` or a single `networkError`. Otherwise, this value is `undefined`.\n   *\n   * For more information, see [Handling operation errors](https://www.apollographql.com/docs/react/data/error-handling/).\n   */\n  error: unknown;\n  /**\n   * If `true`, the mutation is currently in flight.\n   */\n  loading: unknown;\n  /**\n   * If `true`, the mutation's mutate function has been called.\n   */\n  called: unknown;\n  /**\n   * The instance of Apollo Client that executed the mutation.\n   *\n   * Can be useful for manually executing followup operations or writing data to the cache.\n   */\n  client: unknown;\n  /**\n   * A function that you can call to reset the mutation's result to its initial, uncalled state.\n   */\n  reset: unknown;\n  /**\n   * Custom extensions returned from the GraphQL server\n   */\n  extensions: unknown;\n}\n\nexport interface SubscriptionOptionsDocumentation {\n  /**\n   * A GraphQL document, often created with `gql` from the `graphql-tag`\n   * package, that contains a single subscription inside of it.\n   */\n  query: unknown;\n  /**\n   * An object containing all of the variables your subscription needs to execute\n   */\n  variables: unknown;\n\n  /**\n   * Specifies the `ErrorPolicy` to be used for this operation\n   */\n  errorPolicy: unknown;\n\n  /**\n   * How you want your component to interact with the Apollo cache. For details, see [Setting a fetch policy](https://www.apollographql.com/docs/react/data/queries/#setting-a-fetch-policy).\n   */\n  fetchPolicy: unknown;\n\n  /**\n   * Determines if your subscription should be unsubscribed and subscribed again when an input to the hook (such as `subscription` or `variables`) changes.\n   */\n  shouldResubscribe: unknown;\n\n  /**\n   * If `true`, the hook will not cause the component to rerender. This is useful when you want to control the rendering of your component yourself with logic in the `onData` and `onError` callbacks.\n   *\n   * Changing this to `true` when the hook already has `data` will reset the `data` to `undefined`.\n   */\n  ignoreResults: unknown;\n  /**\n   * An `ApolloClient` instance. By default `useSubscription` / `Subscription` uses the client passed down via context, but a different client can be passed in.\n   */\n  client: unknown;\n\n  /**\n   * Determines if the current subscription should be skipped. Useful if, for example, variables depend on previous queries and are not ready yet.\n   */\n  skip: unknown;\n\n  /**\n   * Shared context between your component and your network interface (Apollo Link).\n   */\n  context: unknown;\n\n  /**\n   * Shared context between your component and your network interface (Apollo Link).\n   */\n  extensions: unknown;\n\n  /**\n   * Allows the registration of a callback function that will be triggered each time the `useSubscription` Hook / `Subscription` component completes the subscription.\n   */\n  onComplete: unknown;\n\n  /**\n   * Allows the registration of a callback function that will be triggered each time the `useSubscription` Hook / `Subscription` component receives data. The callback `options` object param consists of the current Apollo Client instance in `client`, and the received subscription data in `data`.\n   */\n  onData: unknown;\n\n  /**\n   * Allows the registration of a callback function that will be triggered each time the `useSubscription` Hook / `Subscription` component receives an error.\n   */\n  onError: unknown;\n}\n\nexport interface SubscriptionResultDocumentation {\n  /**\n   * A boolean that indicates whether any initial data has been returned\n   */\n  loading: unknown;\n  /**\n   * An object containing the result of your GraphQL subscription. Defaults to an empty object.\n   */\n  data: unknown;\n  /**\n   * A runtime error with `graphQLErrors` and `networkError` properties\n   */\n  error: unknown;\n}\n"
  },
  {
    "path": "src/testing/core/mocking/__tests__/__snapshots__/mockLink.ts.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`can use \\`result\\` as callback with \\`maxUsageCount\\` 1`] = `\n\"No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n  }\n}\n\nRequest variables: {\\\\\"username\\\\\":\\\\\"username\\\\\"}\n\"\n`;\n\nexports[`consumes matched mock 1`] = `\n\"No more mocked responses for the query:\n{\n  a\n}\n\nRequest variables: {}\n\"\n`;\n\nexports[`does not show variables in error message if none configured 1`] = `\n\"No more mocked responses for the query:\n{\n  b\n}\n\nRequest variables: {}\n\"\n`;\n\nexports[`fails when variables returns false 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID!) {\n  user(id: $id) {\n    name\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":1}\n\nFailed to match variables against 1 mock for this query. The available mocks had the following variables:\n  <function variables>\n\"\n`;\n\nexports[`mocks is consumed after running \\`result\\` callback function 1`] = `\n\"No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n  }\n}\n\nRequest variables: {\\\\\"username\\\\\":\\\\\"username\\\\\"}\n\"\n`;\n\nexports[`returns error when no mock matches request 1`] = `\n\"No more mocked responses for the query:\n{\n  a\n}\n\nRequest variables: {}\n\"\n`;\n\nexports[`returns error when no mock matches request 2`] = `\n\"No more mocked responses for the query:\n{\n  a\n}\n\nRequest variables: {}\n\"\n`;\n\nexports[`shows <undefined> for mocks with no configured variables 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID!) {\n  user(id: $id) {\n    name\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":3}\n\nFailed to match variables against 2 mocks for this query. The available mocks had the following variables:\n  <undefined>\n  {\\\\\"id\\\\\":2}\n\"\n`;\n\nexports[`shows all configured variables for queries that did not match request 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID!) {\n  user(id: $id) {\n    name\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":4}\n\nFailed to match variables against 3 mocks for this query. The available mocks had the following variables:\n  {\\\\\"id\\\\\":1}\n  {\\\\\"id\\\\\":2}\n  {\\\\\"id\\\\\":3}\n\"\n`;\n\nexports[`shows default variables from query in error message for mocks with no configured variables 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID! = 1) {\n  user(id: $id) {\n    name\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":3}\n\nFailed to match variables against 2 mocks for this query. The available mocks had the following variables:\n  {\\\\\"id\\\\\":1}\n  {\\\\\"id\\\\\":2}\n\"\n`;\n\nexports[`shows empty object for variables when configured with empty vars 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID!) {\n  user(id: $id) {\n    name\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":3}\n\nFailed to match variables against 2 mocks for this query. The available mocks had the following variables:\n  {}\n  {\\\\\"id\\\\\":2}\n\"\n`;\n\nexports[`shows undefined and NaN in debug messages 1`] = `\n\"No more mocked responses for the query:\nquery ($id: ID!, $filter: Boolean) {\n  usersByTestId(id: $id, filter: $filter) {\n    id\n  }\n}\n\nRequest variables: {\\\\\"id\\\\\":NaN,\\\\\"filter\\\\\":<undefined>}\n\nFailed to match variables against 1 mock for this query. The available mocks had the following variables:\n  {\\\\\"id\\\\\":1,\\\\\"filter\\\\\":true}\n\"\n`;\n\nexports[`uses a mock a configured number of times when \\`maxUsageCount\\` is configured 1`] = `\n\"No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n  }\n}\n\nRequest variables: {\\\\\"username\\\\\":\\\\\"username\\\\\"}\n\"\n`;\n\nexports[`uses a mock once when \\`maxUsageCount\\` is not configured 1`] = `\n\"No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n  }\n}\n\nRequest variables: {\\\\\"username\\\\\":\\\\\"username\\\\\"}\n\"\n`;\n"
  },
  {
    "path": "src/testing/core/mocking/__tests__/mockLink.ts",
    "content": "import { gql } from \"graphql-tag\";\n\nimport { MockLink, realisticDelay } from \"@apollo/client/testing\";\nimport {\n  enableFakeTimers,\n  executeWithDefaultContext as execute,\n  ObservableStream,\n  spyOnConsole,\n  withCleanup,\n} from \"@apollo/client/testing/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\n// This isn't a public API and won't be exposed\n// eslint-disable-next-line local-rules/no-relative-imports\nimport { stringifyMockedResponse } from \"../mockLink.js\";\n\nconst withRestoredDefaults = function () {\n  const originalDefaults = MockLink.defaultOptions;\n\n  return withCleanup(originalDefaults, (originalDefaults) => {\n    MockLink.defaultOptions = originalDefaults;\n  });\n};\n\n/*\nWe've chosen this value as the MAXIMUM_DELAY since values that don't fit into a 32-bit signed int cause setTimeout to fire immediately\n*/\nconst MAXIMUM_DELAY = 0x7f_ff_ff_ff;\n\nconst query = gql`\n  query A {\n    a\n  }\n`;\n\ntest(\"should not require a result or error when delay equals Infinity\", async () => {\n  using _fakeTimers = enableFakeTimers();\n\n  const mockLink = new MockLink([\n    {\n      request: {\n        query,\n      },\n      delay: Infinity,\n    },\n  ]);\n\n  const observable = execute(mockLink, { query });\n\n  const subscription = observable.subscribe(\n    () => fail(\"onNext was called\"),\n    () => fail(\"onError was called\"),\n    () => fail(\"onComplete was called\")\n  );\n  jest.advanceTimersByTime(MAXIMUM_DELAY);\n  subscription.unsubscribe();\n});\n\ntest(\"should require result or error when delay is just large\", async () => {\n  const invalidResponse = { request: { query }, delay: MAXIMUM_DELAY };\n  const expectedError = new Error(\n    `Mocked response should contain either \\`result\\`, \\`error\\` or a \\`delay\\` of \\`Infinity\\`:\\n${stringifyMockedResponse(\n      invalidResponse\n    )}`\n  );\n\n  {\n    const link = new MockLink([invalidResponse]);\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(expectedError);\n  }\n\n  {\n    const link = new MockLink([]);\n    link.addMockedResponse(invalidResponse);\n\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitError(expectedError);\n  }\n});\n\ntest(\"waits to return result based on static delay\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { a: \"a\" } },\n      delay: 100,\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).not.toEmitAnything({ timeout: 80 });\n  await expect(stream).toEmitNext({ timeout: 30 });\n  await expect(stream).toComplete();\n});\n\ntest(\"waits to return result based on delay returned from callback function\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const delay = jest.fn().mockReturnValue(100);\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { a: \"a\" } },\n      delay,\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).not.toEmitAnything({ timeout: 95 });\n  await expect(stream).toEmitNext({ timeout: 6 });\n  await expect(stream).toComplete();\n\n  expect(delay).toHaveBeenCalledTimes(1);\n  expect(delay).toHaveBeenCalledWith(expect.objectContaining({ query }));\n});\n\ntest(\"can set min/max for realisticDelay\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink([\n    {\n      request: { query },\n      result: { data: { a: \"a\" } },\n      delay: realisticDelay({ min: 50, max: 100 }),\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).not.toEmitAnything({ timeout: 45 });\n  await expect(stream).toEmitNext({ timeout: 56 });\n  await expect(stream).toComplete();\n});\n\ntest(\"returns matched mock\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink([\n    { request: { query }, result: { data: { a: \"a\" } } },\n    {\n      request: {\n        query: gql`\n          query {\n            b\n          }\n        `,\n      },\n      result: { data: { b: \"b\" } },\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query }));\n\n  await expect(stream).toEmitTypedValue({ data: { a: \"a\" } });\n  await expect(stream).toComplete();\n});\n\ntest(\"allows global default static delay to be defined for all instances of MockLink\", async () => {\n  using _ = withRestoredDefaults();\n\n  MockLink.defaultOptions = {\n    delay: 50,\n  };\n\n  const aQuery = gql`\n    query {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query {\n      b\n    }\n  `;\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).not.toEmitAnything({ timeout: 45 });\n    await expect(streamA).toEmitNext({ timeout: 6 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n    await expect(streamB).not.toEmitAnything({ timeout: 45 });\n    await expect(streamB).toEmitNext({ timeout: 6 });\n    await expect(streamB).toComplete();\n  }\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).not.toEmitAnything({ timeout: 45 });\n    await expect(streamA).toEmitNext({ timeout: 6 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n    await expect(streamB).not.toEmitAnything({ timeout: 45 });\n    await expect(streamB).toEmitNext({ timeout: 6 });\n    await expect(streamB).toComplete();\n  }\n});\n\ntest(\"allows global default dynamic delay to be defined for all instances of MockLink\", async () => {\n  using _ = withRestoredDefaults();\n\n  MockLink.defaultOptions = {\n    delay: (operation) => (operation.operationName === \"A\" ? 50 : 20),\n  };\n\n  const aQuery = gql`\n    query A {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query B {\n      b\n    }\n  `;\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).not.toEmitAnything({ timeout: 45 });\n    await expect(streamA).toEmitNext({ timeout: 6 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n    await expect(streamB).not.toEmitAnything({ timeout: 15 });\n    await expect(streamB).toEmitNext({ timeout: 6 });\n    await expect(streamB).toComplete();\n  }\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).not.toEmitAnything({ timeout: 45 });\n    await expect(streamA).toEmitNext({ timeout: 6 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n    await expect(streamB).not.toEmitAnything({ timeout: 15 });\n    await expect(streamB).toEmitNext({ timeout: 6 });\n    await expect(streamB).toComplete();\n  }\n});\n\ntest(\"can change global defaults between creation of instances\", async () => {\n  using _ = withRestoredDefaults();\n\n  MockLink.defaultOptions = {\n    delay: 50,\n  };\n\n  const aQuery = gql`\n    query {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query {\n      b\n    }\n  `;\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).not.toEmitAnything({ timeout: 45 });\n    await expect(streamA).toEmitNext({ timeout: 6 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n    await expect(streamB).not.toEmitAnything({ timeout: 45 });\n    await expect(streamB).toEmitNext({ timeout: 6 });\n    await expect(streamB).toComplete();\n  }\n\n  MockLink.defaultOptions = {\n    delay: 20,\n  };\n\n  {\n    const link = new MockLink([\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ]);\n\n    const streamA = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(streamA).toEmitNext({ timeout: 25 });\n    await expect(streamA).toComplete();\n\n    const streamB = new ObservableStream(execute(link, { query: bQuery }));\n\n    await expect(streamB).toEmitNext({ timeout: 25 });\n    await expect(streamB).toComplete();\n  }\n});\n\ntest(\"allows per-instance default static delay to be defined for all mocks\", async () => {\n  const aQuery = gql`\n    query {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query {\n      b\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ],\n    { defaultOptions: { delay: 50 } }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(stream).not.toEmitAnything({ timeout: 45 });\n    await expect(stream).toEmitNext({ timeout: 6 });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: bQuery }));\n\n    await expect(stream).not.toEmitAnything({ timeout: 45 });\n    await expect(stream).toEmitNext({ timeout: 6 });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"allows per-instance default dynamic delay to be defined for all mocks\", async () => {\n  const aQuery = gql`\n    query A {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query B {\n      b\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query: aQuery },\n        result: { data: { a: \"a\" } },\n      },\n      {\n        request: { query: bQuery },\n        result: { data: { a: \"b\" } },\n      },\n    ],\n    {\n      defaultOptions: {\n        delay: (operation) => (operation.operationName === \"A\" ? 50 : 20),\n      },\n    }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(stream).not.toEmitAnything({ timeout: 45 });\n    await expect(stream).toEmitNext({ timeout: 6 });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: bQuery }));\n\n    await expect(stream).not.toEmitAnything({ timeout: 15 });\n    await expect(stream).toEmitNext({ timeout: 6 });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"prefers configured delay over default delay\", async () => {\n  using _ = withRestoredDefaults();\n\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query },\n        result: { data: { a: \"a\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { a: \"a\" } },\n      },\n    ],\n    { defaultOptions: { delay: 50 } }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitNext({ timeout: 25 });\n    await expect(stream).toComplete();\n  }\n\n  // This uses the default delay\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).not.toEmitAnything({ timeout: 45 });\n    await expect(stream).toEmitNext({ timeout: 6 });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"prefers configured delay > instance defaults > global defaults\", async () => {\n  using _ = withRestoredDefaults();\n\n  MockLink.defaultOptions = {\n    delay: 50,\n  };\n\n  const query = gql`\n    query {\n      a\n    }\n  `;\n\n  {\n    const link = new MockLink([\n      {\n        request: { query },\n        result: { data: { a: \"a\" } },\n        delay: 20,\n      },\n      {\n        request: { query },\n        result: { data: { a: \"a\" } },\n      },\n    ]);\n\n    const stream1 = new ObservableStream(execute(link, { query }));\n\n    await expect(stream1).toEmitNext({ timeout: 25 });\n    await expect(stream1).toComplete();\n\n    const stream2 = new ObservableStream(execute(link, { query }));\n\n    await expect(stream2).not.toEmitAnything({ timeout: 45 });\n    await expect(stream2).toEmitNext({ timeout: 6 });\n    await expect(stream2).toComplete();\n  }\n\n  {\n    const link = new MockLink(\n      [\n        {\n          request: { query },\n          result: { data: { a: \"a\" } },\n          delay: 20,\n        },\n        {\n          request: { query },\n          result: { data: { a: \"a\" } },\n        },\n      ],\n      { defaultOptions: { delay: 30 } }\n    );\n\n    const stream1 = new ObservableStream(execute(link, { query }));\n\n    await expect(stream1).toEmitNext({ timeout: 25 });\n    await expect(stream1).toComplete();\n\n    const stream2 = new ObservableStream(execute(link, { query }));\n\n    await expect(stream2).not.toEmitAnything({ timeout: 25 });\n    await expect(stream2).toEmitNext({ timeout: 6 });\n    await expect(stream2).toComplete();\n  }\n});\n\ntest(\"uses realistic delay by default\", async () => {\n  const query = gql`\n    query A {\n      a\n    }\n  `;\n  const link = new MockLink([\n    { request: { query }, result: { data: { a: \"a\" } } },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    // The default min is 20 so we don't expect to see anything before then\n    await expect(stream).not.toEmitAnything({ timeout: 15 });\n    // The default max is 50 so we should definitely have a result now\n    await expect(stream).toEmitNext({ timeout: 36 });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"matches like mocks sequentially\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink([\n    { request: { query }, result: { data: { a: \"a\" } } },\n    { request: { query }, result: { data: { a: \"b\" } } },\n    { request: { query }, result: { data: { a: \"c\" } } },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"a\" } });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"b\" } });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"c\" } });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"matches out-of-order queries\", async () => {\n  const aQuery = gql`\n    query {\n      a\n    }\n  `;\n  const bQuery = gql`\n    query {\n      b\n    }\n  `;\n  const link = new MockLink([\n    { request: { query: aQuery }, result: { data: { a: \"a\" } } },\n    { request: { query: bQuery }, result: { data: { b: \"b\" } } },\n    { request: { query: aQuery }, result: { data: { a: \"c\" } } },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"a\" } });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: aQuery }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"c\" } });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: bQuery }));\n\n    await expect(stream).toEmitTypedValue({ data: { b: \"b\" } });\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"returns error when no mock matches request\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n\n  {\n    const link = new MockLink([], { showWarnings: false });\n    const stream = new ObservableStream(execute(link, { query }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n\n  {\n    const link = new MockLink(\n      [\n        {\n          request: {\n            query: gql`\n              query {\n                b\n              }\n            `,\n          },\n          result: { data: { b: \"b\" } },\n        },\n      ],\n      { showWarnings: false }\n    );\n    const stream = new ObservableStream(execute(link, { query }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ntest(\"consumes matched mock\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query },\n        result: { data: { a: \"a\" } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: \"a\" } });\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ntest(\"returns matched mock with variables\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink([\n    {\n      request: { query, variables: { id: 1 } },\n      result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n    },\n    {\n      request: { query, variables: { id: 2 } },\n      result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n    },\n  ]);\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 2 } })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", name: \"User 2\" } },\n  });\n  await expect(stream).toComplete();\n});\n\ntest(\"matches variables with undefined values\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink([\n    {\n      request: { query, variables: { id: 1, foo: undefined } },\n      result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n    },\n  ]);\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 1 } })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", name: \"User 1\" } },\n  });\n  await expect(stream).toComplete();\n});\n\ntest(\"should fill in default variables if they are missing in mocked requests\", async () => {\n  const query = gql`\n    query GetTodo($done: Boolean = true, $user: String!) {\n      todo(user: $user, done: $done) {\n        id\n      }\n    }\n  `;\n  const mocks = [\n    {\n      // default should get filled in here\n      request: { query, variables: { user: \"Tim\" } },\n      result: {\n        data: { todo: { id: 1 } },\n      },\n    },\n    {\n      // we provide our own `done`, so it should not get filled in\n      request: { query, variables: { user: \"Tim\", done: false } },\n      result: {\n        data: { todo: { id: 2 } },\n      },\n    },\n    {\n      // one more that has a different user variable and should never match\n      request: { query, variables: { user: \"Tom\" } },\n      result: {\n        data: { todo: { id: 2 } },\n      },\n    },\n  ];\n\n  // Apollo Client will always fill in default values for missing variables\n  // in the operation before calling the Link, so we have to do the same here\n  // when we call `execute`\n  const defaults = { done: true };\n  const link = new MockLink(mocks, { showWarnings: false });\n  {\n    // Non-optional variable is missing, should not match.\n    const stream = new ObservableStream(\n      execute(link, { query, variables: { ...defaults } })\n    );\n    await expect(stream).toEmitError();\n  }\n  {\n    // Execute called incorrectly without a default variable filled in.\n    // This will never happen in Apollo Client since AC always fills these\n    // before calling `execute`, so it's okay if it results in a \"no match\"\n    // scenario here.\n    const stream = new ObservableStream(\n      execute(link, { query, variables: { user: \"Tim\" } })\n    );\n    await expect(stream).toEmitError();\n  }\n  {\n    // Expect default value to be filled in the mock request.\n    const stream = new ObservableStream(\n      execute(link, { query, variables: { ...defaults, user: \"Tim\" } })\n    );\n    await expect(stream).toEmitTypedValue({ data: { todo: { id: 1 } } });\n  }\n  {\n    // Test that defaults don't overwrite explicitly different values in a mock request.\n    const stream = new ObservableStream(\n      execute(link, {\n        query,\n        variables: { ...defaults, user: \"Tim\", done: false },\n      })\n    );\n    await expect(stream).toEmitTypedValue({ data: { todo: { id: 2 } } });\n  }\n});\n\ntest(\"does not show variables in error message if none configured\", async () => {\n  const query = gql`\n    query {\n      a\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, {\n      query: gql`\n        query {\n          b\n        }\n      `,\n    })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"shows all configured variables for queries that did not match request\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables: { id: 1 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n      },\n      {\n        request: { query, variables: { id: 3 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 3\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 4 } })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"shows <undefined> for mocks with no configured variables\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 3 } })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"shows default variables from query in error message for mocks with no configured variables\", async () => {\n  const query = gql`\n    query ($id: ID! = 1) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 3 } })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"shows empty object for variables when configured with empty vars\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables: {} },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n      {\n        request: { query, variables: { id: 2 } },\n        result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 3 } })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"throws error when a query is not provided\", async () => {\n  expect(\n    () =>\n      new MockLink([\n        {\n          // @ts-expect-error\n          request: {},\n          result: { data: null },\n        },\n      ])\n  ).toThrow(/^Expecting a parsed GraphQL document/);\n});\n\ntest(\"throws error when query is a plain string\", async () => {\n  expect(\n    () =>\n      new MockLink([\n        {\n          request: {\n            // @ts-ignore\n            query: `\n              query {\n                foo\n              }\n            `,\n          },\n          result: {\n            data: null,\n          },\n        },\n      ])\n  ).toThrow(/^Expecting a parsed GraphQL document/);\n});\n\ntest(\"throws error when given a client-only query\", async () => {\n  expect(\n    () =>\n      new MockLink([\n        {\n          request: {\n            query: gql`\n              query {\n                foo @client\n              }\n            `,\n          },\n          result: {\n            data: {\n              foo: \"never\",\n            },\n          },\n        },\n      ])\n  ).toThrow(\n    new InvariantError(\n      \"Cannot mock a client-only query. Mocked responses should contain at least one non-client field.\"\n    )\n  );\n});\n\ntest(\"throws error when passing maxUsageCount <= 0\", async () => {\n  expect(\n    () =>\n      new MockLink([\n        {\n          request: {\n            query: gql`\n              query {\n                foo\n              }\n            `,\n          },\n          maxUsageCount: -1,\n          result: {\n            data: null,\n          },\n        },\n      ])\n  ).toThrow(\n    new InvariantError(\n      \"Mocked response `maxUsageCount` must be greater than 0. Given -1\"\n    )\n  );\n\n  expect(\n    () =>\n      new MockLink([\n        {\n          request: {\n            query: gql`\n              query {\n                foo\n              }\n            `,\n          },\n          maxUsageCount: 0,\n          result: {\n            data: null,\n          },\n        },\n      ])\n  ).toThrow(\n    new InvariantError(\n      \"Mocked response `maxUsageCount` must be greater than 0. Given 0\"\n    )\n  );\n});\n\ntest(\"passes variables to the `variables` callback function\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n\n  const variables = { id: 1 };\n  const variableMatcher = jest.fn().mockReturnValue(true);\n\n  const link = new MockLink([\n    {\n      request: { query, variables: variableMatcher },\n      result: { data: { user: { __typename: \"User\", name: \"Test\" } } },\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", name: \"Test\" } },\n  });\n\n  expect(variableMatcher).toHaveBeenCalledTimes(1);\n  expect(variableMatcher).toHaveBeenCalledWith(variables);\n});\n\ntest(\"uses mock when `variables` as callback returns true\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: { query, variables: ({ id }) => id === 1 },\n      result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n    },\n    {\n      request: { query, variables: ({ id }) => id === 2 },\n      result: { data: { user: { __typename: \"User\", name: \"User 2\" } } },\n    },\n  ]);\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 2 } })\n  );\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", name: \"User 2\" } },\n  });\n});\n\ntest(\"fails when variables returns false\", async () => {\n  const query = gql`\n    query ($id: ID!) {\n      user(id: $id) {\n        name\n      }\n    }\n  `;\n\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables: () => false },\n        result: { data: { user: { __typename: \"User\", name: \"User 1\" } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: 1 } })\n  );\n\n  const error = await stream.takeError();\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"removes @nonreactive directives from fields\", async () => {\n  const serverQuery = gql`\n    query A {\n      a\n      b\n      c\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n            c @nonreactive\n          }\n        `,\n      },\n      result: { data: { a: 1, b: 2, c: 3 } },\n    },\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n            c\n          }\n        `,\n      },\n      result: { data: { a: 4, b: 5, c: 6 } },\n    },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { a: 1, b: 2, c: 3 },\n    });\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { a: 4, b: 5, c: 6 },\n    });\n  }\n});\n\ntest(\"removes @connection directives\", async () => {\n  const serverQuery = gql`\n    query A {\n      a\n      b\n      c\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n            c @connection(key: \"test\")\n          }\n        `,\n      },\n      result: { data: { a: 1, b: 2, c: 3 } },\n    },\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n            c\n          }\n        `,\n      },\n      result: { data: { a: 4, b: 5, c: 6 } },\n    },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { a: 1, b: 2, c: 3 },\n    });\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { a: 4, b: 5, c: 6 },\n    });\n  }\n});\n\ntest(\"removes fields with @client directives\", async () => {\n  const serverQuery = gql`\n    query A {\n      a\n      b\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n            c @client\n          }\n        `,\n      },\n      result: { data: { a: 1, b: 2 } },\n    },\n    {\n      request: {\n        query: gql`\n          query A {\n            a\n            b\n          }\n        `,\n      },\n      result: { data: { a: 3, b: 4 } },\n    },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: 1, b: 2 } });\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query: serverQuery }));\n\n    await expect(stream).toEmitTypedValue({ data: { a: 3, b: 4 } });\n  }\n});\n\ntest(\"shows warning in console when a mock cannot be matched\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query {\n      foo\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: {\n        query: gql`\n          query OtherQuery {\n            otherQuery {\n              id\n            }\n          }\n        `,\n      },\n      result: { data: { otherQuery: { id: 1 } } },\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query }));\n  await expect(stream).toEmitError();\n\n  expect(console.warn).toHaveBeenCalledTimes(1);\n  expect(console.warn).toHaveBeenCalledWith(\n    expect.stringContaining(\"No more mocked responses\")\n  );\n});\n\ntest(\"silences console warning for unmatched mocks when `showWarnings` is `false`\", async () => {\n  using _ = spyOnConsole(\"warn\");\n  const query = gql`\n    query {\n      foo\n    }\n  `;\n\n  const link = new MockLink(\n    [\n      {\n        request: {\n          query: gql`\n            query OtherQuery {\n              otherQuery {\n                id\n              }\n            }\n          `,\n        },\n        result: { data: { otherQuery: { id: 1 } } },\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  const stream = new ObservableStream(execute(link, { query }));\n  await expect(stream).toEmitError();\n\n  expect(console.warn).not.toHaveBeenCalled();\n});\n\ntest(\"shows undefined and NaN in debug messages\", async () => {\n  using _ = spyOnConsole(\"warn\");\n\n  const query = gql`\n    query ($id: ID!, $filter: Boolean) {\n      usersByTestId(id: $id, filter: $filter) {\n        id\n      }\n    }\n  `;\n\n  const link = new MockLink([\n    {\n      request: { query, variables: { id: 1, filter: true } },\n      // The actual response data makes no difference in this test\n      result: { data: { usersByTestId: null } },\n    },\n  ]);\n\n  const stream = new ObservableStream(\n    execute(link, { query, variables: { id: NaN, filter: undefined } })\n  );\n\n  const error = await stream.takeError();\n\n  expect(error.message).toMatchSnapshot();\n});\n\ntest(\"uses a mock a configured number of times when `maxUsageCount` is configured\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const result = { data: { user: { __typename: \"User\", id: 1 } } };\n  const variables = { username: \"username\" };\n\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables },\n        maxUsageCount: 2,\n        result,\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result);\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result);\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ntest(\"uses a mock infinite number of times when `maxUsageCount` is configured with Number.POSITIVE_INFINITY\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const result = { data: { user: { __typename: \"User\", id: 1 } } };\n  const variables = { username: \"username\" };\n\n  const link = new MockLink([\n    {\n      request: { query, variables },\n      maxUsageCount: Number.POSITIVE_INFINITY,\n      result,\n      delay: 0,\n    },\n  ]);\n\n  for (let i = 0; i < 100; i++) {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result);\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"uses a mock once when `maxUsageCount` is not configured\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const result = { data: { user: { __typename: \"User\", id: 1 } } };\n  const variables = { username: \"username\" };\n\n  const link = new MockLink([{ request: { query, variables }, result }], {\n    showWarnings: false,\n  });\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result);\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ntest(\"can still use other mocks after a mock has been fully consumed\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const result1 = { data: { user: { __typename: \"User\", id: 1 } } };\n  const result2 = { data: { user: { __typename: \"User\", id: 2 } } };\n  const variables = { username: \"username\" };\n\n  const link = new MockLink([\n    {\n      request: { query, variables },\n      maxUsageCount: 2,\n      result: result1,\n    },\n    {\n      request: { query, variables },\n      result: result2,\n    },\n  ]);\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result1);\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result1);\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue(result2);\n    await expect(stream).toComplete();\n  }\n});\n\ntest(\"`result` accepts callback function\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        username\n      }\n    }\n  `;\n\n  const variables = { username: \"username\" };\n\n  const link = new MockLink([\n    {\n      request: { query, variables },\n      result: (vars) => ({\n        data: { user: { __typename: \"User\", name: vars.username } },\n      }),\n    },\n  ]);\n\n  const stream = new ObservableStream(execute(link, { query, variables }));\n\n  await expect(stream).toEmitTypedValue({\n    data: { user: { __typename: \"User\", name: variables.username } },\n  });\n  await expect(stream).toComplete();\n});\n\ntest(\"mocks is consumed after running `result` callback function\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const variables = { username: \"username\" };\n\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables },\n        result: (vars) => ({\n          data: { user: { __typename: \"User\", name: vars.username } },\n        }),\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { user: { __typename: \"User\", name: variables.username } },\n    });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ntest(\"can use `result` as callback with `maxUsageCount`\", async () => {\n  const query = gql`\n    query GetUser($username: String!) {\n      user(username: $username) {\n        id\n      }\n    }\n  `;\n\n  const variables = { username: \"username\" };\n\n  const link = new MockLink(\n    [\n      {\n        request: { query, variables },\n        result: (vars) => ({\n          data: { user: { __typename: \"User\", name: vars.username } },\n        }),\n        maxUsageCount: 2,\n      },\n    ],\n    { showWarnings: false }\n  );\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { user: { __typename: \"User\", name: variables.username } },\n    });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    await expect(stream).toEmitTypedValue({\n      data: { user: { __typename: \"User\", name: variables.username } },\n    });\n    await expect(stream).toComplete();\n  }\n\n  {\n    const stream = new ObservableStream(execute(link, { query, variables }));\n\n    const error = await stream.takeError();\n    expect(error.message).toMatchSnapshot();\n  }\n});\n\ndescribe.skip(\"type tests\", () => {\n  const ANY = {} as any;\n  test(\"covariant behaviour: `MockLink.MockedResponses<X,Y>` should be assignable to `MockLink.MockedResponse`\", () => {\n    let unspecificArray: MockLink.MockedResponse[] = [];\n    let specificArray: MockLink.MockedResponse<\n      { foo: string },\n      { foo: string }\n    >[] = [];\n    let unspecificResponse: MockLink.MockedResponse = ANY;\n    let specificResponse: MockLink.MockedResponse<\n      { foo: string },\n      { foo: string }\n    > = ANY;\n\n    unspecificArray.push(specificResponse);\n    unspecificArray.push(unspecificResponse);\n\n    specificArray.push(specificResponse);\n    // @ts-expect-error\n    specificArray.push(unspecificResponse);\n\n    unspecificArray = [specificResponse];\n    unspecificArray = [unspecificResponse];\n    unspecificArray = [specificResponse, unspecificResponse];\n\n    specificArray = [specificResponse];\n    // @ts-expect-error\n    specificArray = [unspecificResponse];\n    // @ts-expect-error\n    specificArray = [specificResponse, unspecificResponse];\n\n    unspecificResponse = specificResponse;\n    // @ts-expect-error\n    specificResponse = unspecificResponse;\n  });\n\n  describe(\"MockLink.MockedResponse.result as a callback\", () => {\n    const setup = () => {\n      const weaklyTypedMockResponse: MockLink.MockedResponse = {\n        request: {\n          query: gql`\n            query A {\n              a\n            }\n          `,\n        },\n      };\n\n      const stronglyTypedMockResponse: MockLink.MockedResponse<\n        { a: string },\n        { input: string }\n      > = {\n        request: {\n          query: gql`\n            query A {\n              a\n            }\n          `,\n        },\n      };\n\n      return {\n        weaklyTypedMockResponse,\n        stronglyTypedMockResponse,\n      };\n    };\n\n    test(\"returned 'data' can be any object with untyped response\", () => {\n      const { weaklyTypedMockResponse } = setup();\n\n      weaklyTypedMockResponse.result = ({ fake: { faker } }) => ({\n        data: {\n          pretend: faker,\n        },\n      });\n    });\n\n    test(\"can't return output that doesn't match TData\", () => {\n      const { stronglyTypedMockResponse } = setup();\n\n      // @ts-expect-error return type does not match `TData`\n      stronglyTypedMockResponse.result = () => ({\n        data: {\n          a: 123,\n        },\n      });\n    });\n\n    test(\"can't use input variables that don't exist in TVariables\", () => {\n      const { stronglyTypedMockResponse } = setup();\n\n      // @ts-expect-error unknown variables\n      stronglyTypedMockResponse.result = ({ fake: { faker } }) => ({\n        data: {\n          a: faker,\n        },\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/testing/core/mocking/mockLink.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type { DocumentNode } from \"graphql\";\nimport { asapScheduler, Observable, observeOn, throwError } from \"rxjs\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport type { Unmasked } from \"@apollo/client/masking\";\nimport { addTypenameToDocument, print } from \"@apollo/client/utilities\";\nimport {\n  checkDocument,\n  cloneDeep,\n  getDefaultValues,\n  getOperationDefinition,\n  isDocumentNode,\n  makeUniqueId,\n  removeDirectivesFromDocument,\n} from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\n/** @internal */\ntype CovariantUnaryFunction<out Arg, out Ret> = { fn(arg: Arg): Ret }[\"fn\"];\n\ntype VariableMatcher<V = Record<string, any>> = CovariantUnaryFunction<\n  V,\n  boolean\n>;\n\ninterface NormalizedMockedResponse {\n  original: MockLink.MockedResponse;\n  request: MockLink.MockedRequest;\n  variablesWithDefaults: Record<string, any>;\n  maxUsageCount: number;\n  result?: ApolloLink.Result | MockLink.ResultFunction<ApolloLink.Result, any>;\n  error?: Error;\n  delay: number | MockLink.DelayFunction;\n}\n\ntype UnmatchedVariables = Array<\n  Record<string, any> | \"<undefined>\" | `<function ${string}>`\n>;\n\nexport declare namespace MockLink {\n  export type DelayFunction = (operation: ApolloLink.Operation) => number;\n  export type Delay = number | DelayFunction;\n  export interface DefaultOptions {\n    delay?: MockLink.Delay;\n  }\n\n  export interface MockedRequest<\n    TVariables extends OperationVariables = OperationVariables,\n  > {\n    query: DocumentNode;\n    variables?: TVariables | VariableMatcher<TVariables>;\n  }\n\n  export interface MockedResponse<\n    /** @ts-ignore */\n    out TData = Record<string, any>,\n    out TVariables extends OperationVariables = Record<string, any>,\n  > {\n    request: MockedRequest<TVariables>;\n    maxUsageCount?: number;\n    result?:\n      | ApolloLink.Result<Unmasked<TData>>\n      | ResultFunction<ApolloLink.Result<Unmasked<TData>>, TVariables>;\n    error?: Error;\n    delay?: number | MockLink.DelayFunction;\n  }\n\n  export type ResultFunction<\n    T,\n    V = Record<string, any>,\n  > = CovariantUnaryFunction<V, T>;\n\n  export interface Options {\n    showWarnings?: boolean;\n    defaultOptions?: DefaultOptions;\n  }\n}\n\nexport function realisticDelay({\n  min = 20,\n  max = 50,\n}: { min?: number; max?: number } = {}): MockLink.DelayFunction {\n  invariant(max > min, \"realisticDelay: `min` must be less than `max`\");\n\n  return () => Math.floor(Math.random() * (max - min) + min);\n}\n\nexport class MockLink extends ApolloLink {\n  public operation!: ApolloLink.Operation;\n  public showWarnings: boolean = true;\n\n  private defaultDelay: MockLink.Delay;\n  private mockedResponsesByKey: { [key: string]: NormalizedMockedResponse[] } =\n    {};\n\n  public static defaultOptions: MockLink.DefaultOptions = {\n    delay: realisticDelay(),\n  };\n\n  constructor(\n    mockedResponses: ReadonlyArray<\n      MockLink.MockedResponse<Record<string, any>, Record<string, any>>\n    >,\n    options: MockLink.Options = {}\n  ) {\n    super();\n    const defaultOptions = options.defaultOptions ?? MockLink.defaultOptions;\n\n    this.showWarnings = options.showWarnings ?? true;\n    this.defaultDelay = defaultOptions?.delay ?? realisticDelay();\n\n    if (mockedResponses) {\n      mockedResponses.forEach((mockedResponse) => {\n        this.addMockedResponse(mockedResponse);\n      });\n    }\n  }\n\n  public addMockedResponse(mockedResponse: MockLink.MockedResponse) {\n    validateMockedResponse(mockedResponse);\n\n    const normalized = this.normalizeMockedResponse(mockedResponse);\n    this.getMockedResponses(normalized.request).push(normalized);\n  }\n\n  public request(\n    operation: ApolloLink.Operation\n  ): Observable<ApolloLink.Result> {\n    this.operation = operation;\n    const unmatchedVars: UnmatchedVariables = [];\n    const mocks = this.getMockedResponses(operation);\n\n    const index = mocks.findIndex((mock) => {\n      const { variables } = mock.request;\n\n      if (typeof variables === \"function\") {\n        const matched = variables(operation.variables);\n\n        if (!matched) {\n          unmatchedVars.push(`<function ${variables.name}>`);\n        }\n\n        return matched;\n      }\n\n      const withDefaults = mock.variablesWithDefaults;\n\n      if (equal(withDefaults, operation.variables)) {\n        return true;\n      }\n\n      unmatchedVars.push(\n        // Include default variables from the query in unmatched variables\n        // output\n        Object.keys(withDefaults).length > 0 ?\n          withDefaults\n        : variables || \"<undefined>\"\n      );\n      return false;\n    });\n\n    const matched = index >= 0 ? mocks[index] : void 0;\n\n    if (!matched) {\n      const message = getErrorMessage(operation, unmatchedVars);\n\n      if (this.showWarnings) {\n        console.warn(\n          message +\n            \"\\nThis typically indicates a configuration error in your mocks \" +\n            \"setup, usually due to a typo or mismatched variable.\"\n        );\n      }\n\n      return throwError(() => new Error(message)).pipe(\n        observeOn(asapScheduler)\n      );\n    }\n\n    if (matched.maxUsageCount > 1) {\n      matched.maxUsageCount--;\n    } else {\n      mocks.splice(index, 1);\n    }\n\n    const delay =\n      typeof matched.delay === \"function\" ?\n        matched.delay(operation)\n      : matched.delay;\n\n    if (!matched.result && !matched.error && delay !== Infinity) {\n      return throwError(\n        () =>\n          new Error(\n            `Mocked response should contain either \\`result\\`, \\`error\\` or a \\`delay\\` of \\`Infinity\\`:\\n${stringifyMockedResponse(\n              matched.original\n            )}`\n          )\n      );\n    }\n\n    if (matched.delay === Infinity) {\n      return new Observable();\n    }\n\n    return new Observable((observer) => {\n      const timer = setTimeout(() => {\n        if (matched.error) {\n          return observer.error(matched.error);\n        }\n\n        if (matched.result) {\n          observer.next(\n            typeof matched.result === \"function\" ?\n              matched.result(operation.variables)\n            : matched.result\n          );\n        }\n        observer.complete();\n      }, delay);\n\n      return () => {\n        clearTimeout(timer);\n      };\n    });\n  }\n\n  private getMockedResponses(request: MockLink.MockedRequest) {\n    const key = JSON.stringify({\n      query: print(addTypenameToDocument(request.query)),\n    });\n\n    let mockedResponses = this.mockedResponsesByKey[key];\n\n    if (!mockedResponses) {\n      mockedResponses = this.mockedResponsesByKey[key] = [];\n    }\n\n    return mockedResponses;\n  }\n\n  private normalizeMockedResponse(\n    mockedResponse: MockLink.MockedResponse\n  ): NormalizedMockedResponse {\n    const { request } = mockedResponse;\n    const response = cloneDeep(mockedResponse) as NormalizedMockedResponse;\n\n    response.original = mockedResponse;\n    response.request.query = getServerQuery(request.query);\n    response.maxUsageCount ??= 1;\n    response.variablesWithDefaults = {\n      ...getDefaultValues(getOperationDefinition(request.query)),\n      ...request.variables,\n    };\n    response.delay ??= this.defaultDelay;\n\n    return response;\n  }\n}\n\nfunction getErrorMessage(\n  operation: ApolloLink.Operation,\n  unmatchedVars: UnmatchedVariables\n) {\n  return `No more mocked responses for the query:\n${print(operation.query)}\n\nRequest variables: ${stringifyForDebugging(operation.variables)}\n${\n  unmatchedVars.length > 0 ?\n    `\nFailed to match variables against ${unmatchedVars.length} mock${\n      unmatchedVars.length === 1 ? \"\" : \"s\"\n    } for this query. The available mocks had the following variables:\n${unmatchedVars.map((d) => `  ${stringifyForDebugging(d)}`).join(\"\\n\")}\n`\n  : \"\"\n}`;\n}\n\nfunction getServerQuery(query: DocumentNode) {\n  const queryWithoutClientOnlyDirectives = removeDirectivesFromDocument(\n    [{ name: \"connection\" }, { name: \"nonreactive\" }, { name: \"unmask\" }],\n    query\n  );\n\n  invariant(queryWithoutClientOnlyDirectives, \"query is required\");\n\n  const serverQuery = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    queryWithoutClientOnlyDirectives\n  );\n\n  invariant(\n    serverQuery,\n    \"Cannot mock a client-only query. Mocked responses should contain at least one non-client field.\"\n  );\n\n  return serverQuery;\n}\n\nfunction validateMockedResponse(mock: MockLink.MockedResponse) {\n  checkDocument(mock.request.query);\n\n  invariant(\n    (mock.maxUsageCount ?? 1) > 0,\n    \"Mocked response `maxUsageCount` must be greater than 0. Given %s\",\n    mock.maxUsageCount\n  );\n}\n\n/** @internal */\nexport function stringifyMockedResponse(\n  mockedResponse: MockLink.MockedResponse\n) {\n  return JSON.stringify(\n    mockedResponse,\n    (_, value) => {\n      if (isDocumentNode(value)) {\n        return print(value);\n      }\n\n      if (typeof value === \"function\") {\n        return \"<function>\";\n      }\n\n      return value;\n    },\n    2\n  );\n}\n\nexport interface MockApolloLink extends ApolloLink {\n  operation?: ApolloLink.Operation;\n}\n\n// This is similar to the stringifyForDisplay utility we ship, but includes\n// support for NaN in addition to undefined. More values may be handled in the\n// future. This is not added to the primary stringifyForDisplay helper since it\n// is used for the cache and other purposes. We need this for debugging only.\nfunction stringifyForDebugging(value: any, space = 0): string {\n  if (typeof value === \"string\") {\n    return value;\n  }\n\n  const undefId = makeUniqueId(\"undefined\");\n  const nanId = makeUniqueId(\"NaN\");\n\n  return JSON.stringify(\n    value,\n    (_, value) => {\n      if (value === void 0) {\n        return undefId;\n      }\n\n      if (Number.isNaN(value)) {\n        return nanId;\n      }\n\n      return value;\n    },\n    space\n  )\n    .replace(new RegExp(JSON.stringify(undefId), \"g\"), \"<undefined>\")\n    .replace(new RegExp(JSON.stringify(nanId), \"g\"), \"NaN\");\n}\n"
  },
  {
    "path": "src/testing/core/mocking/mockSubscriptionLink.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport { ApolloLink } from \"@apollo/client/link\";\n\nexport declare namespace MockSubscriptionLink {\n  export interface Result {\n    result?: ApolloLink.Result;\n    error?: Error;\n    delay?: number;\n  }\n}\n\nexport class MockSubscriptionLink extends ApolloLink {\n  public unsubscribers: any[] = [];\n  public setups: any[] = [];\n  public operation?: ApolloLink.Operation;\n\n  private observers: any[] = [];\n\n  constructor() {\n    super();\n  }\n\n  public request(operation: ApolloLink.Operation) {\n    this.operation = operation;\n    return new Observable<ApolloLink.Result>((observer) => {\n      this.setups.forEach((x) => x());\n      this.observers.push(observer);\n      return () => {\n        this.unsubscribers.forEach((x) => x());\n      };\n    });\n  }\n\n  public simulateResult(result: MockSubscriptionLink.Result, complete = false) {\n    setTimeout(() => {\n      const { observers } = this;\n      if (!observers.length) throw new Error(\"subscription torn down\");\n      observers.forEach((observer) => {\n        if (result.result && observer.next) observer.next(result.result);\n        if (result.error && observer.error) observer.error(result.error);\n        if (complete && observer.complete) observer.complete();\n      });\n    }, result.delay || 0);\n  }\n\n  public simulateComplete() {\n    const { observers } = this;\n    if (!observers.length) throw new Error(\"subscription torn down\");\n    observers.forEach((observer) => {\n      if (observer.complete) observer.complete();\n    });\n  }\n\n  public onSetup(listener: any): void {\n    this.setups = this.setups.concat([listener]);\n  }\n\n  public onUnsubscribe(listener: any): void {\n    this.unsubscribers = this.unsubscribers.concat([listener]);\n  }\n}\n"
  },
  {
    "path": "src/testing/core/types/deprecated.ts",
    "content": "import type { OperationVariables } from \"@apollo/client\";\n\nimport type { MockLink } from \"../mocking/mockLink.js\";\n\n/** @deprecated Use `MockLink.MockedRequest` instead */\nexport type MockedRequest<\n  TVariables extends OperationVariables = Record<string, any>,\n> = MockLink.MockedRequest<TVariables>;\n\n/** @deprecated Use `MockLink.MockedResponse` instead */\nexport type MockedResponse<\n  TData = Record<string, any>,\n  TVariables extends OperationVariables = Record<string, any>,\n> = MockLink.MockedResponse<TData, TVariables>;\n\n/** @deprecated Use `MockLink.Options` instead */\nexport type MockLinkOptions = MockLink.Options;\n\n/** @deprecated Use `MockLink.ResultFunction` instead */\nexport type ResultFunction<\n  T,\n  V = Record<string, any>,\n> = MockLink.ResultFunction<T, V>;\n"
  },
  {
    "path": "src/testing/index.ts",
    "content": "export type {\n  MockedRequest,\n  MockedResponse,\n  MockLinkOptions,\n  ResultFunction,\n} from \"./core/types/deprecated.js\";\nexport { MockLink, realisticDelay } from \"./core/mocking/mockLink.js\";\nexport { MockSubscriptionLink } from \"./core/mocking/mockSubscriptionLink.js\";\n"
  },
  {
    "path": "src/testing/internal/ObservableStream.ts",
    "content": "import { ReadableStream } from \"node:stream/web\";\n\nimport type { Tester } from \"@jest/expect-utils\";\nimport { equals, iterableEquality } from \"@jest/expect-utils\";\nimport { expect } from \"@jest/globals\";\nimport * as matcherUtils from \"jest-matcher-utils\";\nimport type { Observable, Subscribable, Unsubscribable } from \"rxjs\";\n\nexport interface TakeOptions {\n  timeout?: number;\n}\ntype ObservableEvent<T> =\n  | { type: \"next\"; value: T }\n  | { type: \"error\"; error: any }\n  | { type: \"complete\" };\n\nfunction formatMessage(\n  matcherName: string,\n  expected: ObservableEvent<any>,\n  actual: ObservableEvent<any>\n) {\n  return (\n    matcherUtils.matcherHint(matcherName, \"stream\", \"expected\") +\n    \"\\n\\n\" +\n    matcherUtils.printDiffOrStringify(\n      expected,\n      actual,\n      \"Expected\",\n      \"Received\",\n      true\n    )\n  );\n}\n\nexport class EventMismatchError extends Error {\n  private actual: ObservableEvent<any>;\n  private expected: ObservableEvent<any>;\n\n  static is(error: unknown): error is EventMismatchError {\n    return error instanceof Error && error.name === \"EventMismatchError\";\n  }\n\n  constructor(expected: ObservableEvent<any>, actual: ObservableEvent<any>) {\n    super(formatMessage(\"toEqual\", expected, actual));\n    this.name = \"EventMismatchError\";\n    this.actual = actual;\n    this.expected = expected;\n\n    Object.setPrototypeOf(this, EventMismatchError.prototype);\n  }\n\n  formatMessage(matcherName: string) {\n    return formatMessage(matcherName, this.expected, this.actual);\n  }\n}\n\nexport class ObservableStream<T> {\n  private reader: ReadableStreamDefaultReader<ObservableEvent<T>>;\n  private subscription!: Unsubscribable;\n  private readerQueue: Array<Promise<ObservableEvent<T>>> = [];\n\n  constructor(observable: Observable<T> | Subscribable<T>) {\n    this.unsubscribe = this.unsubscribe.bind(this);\n    this.reader = new ReadableStream<ObservableEvent<T>>({\n      start: (controller) => {\n        this.subscription = observable.subscribe({\n          next: (value) => controller.enqueue({ type: \"next\", value }),\n          error: (error) => controller.enqueue({ type: \"error\", error }),\n          complete: () => controller.enqueue({ type: \"complete\" }),\n        });\n      },\n    }).getReader();\n  }\n\n  peek({ timeout = 100 }: TakeOptions = {}) {\n    // Calling `peek` multiple times in a row should not advance the reader\n    // multiple times until this value has been consumed.\n    let readerPromise = this.readerQueue[0];\n\n    if (!readerPromise) {\n      // Since this.reader.read() advances the reader in the stream, we don't\n      // want to consume this promise entirely, otherwise we will miss it when\n      // calling `take`. Instead, we push it into a queue that can be consumed\n      // by `take` the next time its called so that we avoid advancing the\n      // reader until we are finished processing all peeked values.\n      readerPromise = this.readNextValue();\n      this.readerQueue.push(readerPromise);\n    }\n\n    return Promise.race([\n      readerPromise,\n      new Promise<ObservableEvent<T>>((_, reject) => {\n        setTimeout(\n          reject,\n          timeout,\n          new Error(\"Timeout waiting for next event\")\n        );\n      }),\n    ]);\n  }\n\n  take({ timeout = 100 }: TakeOptions = {}) {\n    return Promise.race([\n      this.readerQueue.shift() || this.readNextValue(),\n      new Promise<ObservableEvent<T>>((_, reject) => {\n        setTimeout(\n          reject,\n          timeout,\n          new Error(\"Timeout waiting for next event\")\n        );\n      }),\n    ]).then((value) => {\n      if (value.type === \"next\") {\n        this.current = value.value;\n      }\n      return value;\n    });\n  }\n\n  [Symbol.dispose]() {\n    this.unsubscribe();\n  }\n\n  unsubscribe() {\n    this.subscription.unsubscribe();\n  }\n\n  async takeNext(options?: TakeOptions): Promise<T> {\n    const event = await this.take(options);\n    validateEquals(event, { type: \"next\", value: expect.anything() });\n    return (event as ObservableEvent<T> & { type: \"next\" }).value;\n  }\n\n  async takeError(options?: TakeOptions): Promise<any> {\n    const event = await this.take(options);\n    validateEquals(event, { type: \"error\", error: expect.anything() });\n    return (event as ObservableEvent<T> & { type: \"error\" }).error;\n  }\n\n  async takeComplete(options?: TakeOptions): Promise<void> {\n    const event = await this.take(options);\n    validateEquals(event, { type: \"complete\" });\n  }\n\n  private async readNextValue() {\n    return this.reader.read().then((result) => result.value!);\n  }\n\n  private current?: T;\n  getCurrent() {\n    return this.current;\n  }\n}\n\n// Lightweight expect(...).toEqual(...) check that avoids using `expect` so that\n// `expect.assertions(num)` does not double count assertions when using the take*\n// functions inside of expect(stream).toEmit* matchers.\nfunction validateEquals(\n  actualEvent: ObservableEvent<any>,\n  expectedEvent: ObservableEvent<any>\n) {\n  // Uses the same matchers as expect(...).toEqual(...)\n  // https://github.com/jestjs/jest/blob/611d1a4ba0008d67b5dcda485177f0813b2b573e/packages/expect/src/matchers.ts#L626-L629\n  const isEqual = equals(actualEvent, expectedEvent, [\n    ...getCustomMatchers(),\n    iterableEquality,\n  ]);\n\n  if (isEqual) {\n    return;\n  }\n\n  throw new EventMismatchError(expectedEvent, actualEvent);\n}\n\nfunction getCustomMatchers(): Array<Tester> {\n  // https://github.com/jestjs/jest/blob/611d1a4ba0008d67b5dcda485177f0813b2b573e/packages/expect/src/jestMatchersObject.ts#L141-L143\n  const JEST_MATCHERS_OBJECT = Symbol.for(\"$$jest-matchers-object\");\n  return (globalThis as any)[JEST_MATCHERS_OBJECT].customEqualityTesters;\n}\n"
  },
  {
    "path": "src/testing/internal/__tests__/ObservableStream.test.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport { ObservableStream } from \"@apollo/client/testing/internal\";\n\nit(\"allows to step through an observable until completion\", async () => {\n  const stream = new ObservableStream(\n    new Observable<number>((observer) => {\n      observer.next(1);\n      observer.next(2);\n      observer.next(3);\n      observer.complete();\n    })\n  );\n  await expect(stream.takeNext()).resolves.toBe(1);\n  await expect(stream.takeNext()).resolves.toBe(2);\n  await expect(stream.takeNext()).resolves.toBe(3);\n  await expect(stream.takeComplete()).resolves.toBeUndefined();\n});\n\nit(\"allows to step through an observable until error\", async () => {\n  const stream = new ObservableStream(\n    new Observable<number>((observer) => {\n      observer.next(1);\n      observer.next(2);\n      observer.next(3);\n      observer.error(new Error(\"expected\"));\n    })\n  );\n  await expect(stream.takeNext()).resolves.toBe(1);\n  await expect(stream.takeNext()).resolves.toBe(2);\n  await expect(stream.takeNext()).resolves.toBe(3);\n  await expect(stream.takeError()).resolves.toEqual(expect.any(Error));\n});\n\nit(\"will time out if no more value is omitted\", async () => {\n  const stream = new ObservableStream(\n    new Observable<number>((observer) => {\n      observer.next(1);\n      observer.next(2);\n    })\n  );\n  await expect(stream.takeNext()).resolves.toBe(1);\n  await expect(stream.takeNext()).resolves.toBe(2);\n  await expect(stream.takeNext()).rejects.toEqual(expect.any(Error));\n});\n\nit.each([\n  [\"takeNext\", \"complete\"],\n  [\"takeNext\", \"error\"],\n  [\"takeError\", \"complete\"],\n  [\"takeError\", \"next\"],\n  [\"takeComplete\", \"next\"],\n  [\"takeComplete\", \"error\"],\n])(\"errors when %s receives %s instead\", async (expected, gotten) => {\n  const stream = new ObservableStream(\n    new Observable<number>((observer) => {\n      observer.next(1);\n      observer.next(2);\n      // @ts-ignore\n      observer[gotten](3);\n    })\n  );\n  await expect(stream.takeNext()).resolves.toBe(1);\n  await expect(stream.takeNext()).resolves.toBe(2);\n  // @ts-ignore\n  await expect(stream[expected]()).rejects.toEqual(expect.any(Error));\n});\n\nit.each([\n  [\"takeNext\", \"next\"],\n  [\"takeError\", \"error\"],\n  [\"takeComplete\", \"complete\"],\n])(\"succeeds when %s, receives %s\", async (expected, gotten) => {\n  const stream = new ObservableStream(\n    new Observable<number>((observer) => {\n      observer.next(1);\n      observer.next(2);\n      // @ts-ignore\n      observer[gotten](3);\n    })\n  );\n  await expect(stream.takeNext()).resolves.toBe(1);\n  await expect(stream.takeNext()).resolves.toBe(2);\n  // @ts-ignore this should just not throw\n  await stream[expected]();\n});\n"
  },
  {
    "path": "src/testing/internal/asyncIterableSubject.ts",
    "content": "import { Subject } from \"rxjs\";\n\nexport function asyncIterableSubject<T>() {\n  const subject = new Subject<T>();\n\n  const stream = new ReadableStream<T>({\n    start: (controller) => {\n      subject.subscribe({\n        next: (value) => controller.enqueue(value),\n        complete: () => controller.close(),\n      });\n    },\n  });\n\n  return { subject, stream };\n}\n"
  },
  {
    "path": "src/testing/internal/declarations.d.ts",
    "content": "import { Streaming } from \"@apollo/client\";\nimport type { Defer20220824Handler } from \"@apollo/client/incremental\";\nimport type { GraphQLCodegenDataMasking } from \"@apollo/client/masking\";\nimport type { HKT } from \"@apollo/client/utilities\";\nimport { DeepPartial } from \"@apollo/client/utilities\";\n\n// This type override is used in tests only so we can differentiate between\n// `TData` and `Streaming<TData>` in our type tests. This file doesn't make it\n// into the final build, so it doesn't affect the userland behavior of the library.\n\ntype StreamingOverride<TData> = TData & { __streaming?: true };\ninterface StreamingOverrideHKT extends HKT {\n  return: StreamingOverride<this[\"arg1\"]>;\n}\n\ndeclare module \"@apollo/client\" {\n  export interface TypeOverrides\n    extends GraphQLCodegenDataMasking.TypeOverrides,\n      Defer20220824Handler.TypeOverrides {\n    Streaming: StreamingOverrideHKT;\n  }\n}\n"
  },
  {
    "path": "src/testing/internal/disposables/__tests__/spyOnConsole.test.ts",
    "content": "import { spyOnConsole } from \"@apollo/client/testing/internal\";\n\nconst originalLog = console.log;\nconst originalWarn = console.warn;\nconst originalError = console.error;\nconst originalDebug = console.debug;\nconst originalInfo = console.info;\n\ndescribe(\"spyOnConsole\", () => {\n  test(\"intercepts calls to `console.log` and `console.info`\", () => {\n    using consoleSpies = spyOnConsole(\"log\", \"info\");\n    console.log(\"hello\");\n    console.info(\"world\");\n    expect(consoleSpies.log).toHaveBeenCalledWith(\"hello\");\n    expect(consoleSpies.info).toHaveBeenCalledWith(\"world\");\n  });\n\n  test(\"restores the original `console` methods\", () => {\n    {\n      using _consoleSpies = spyOnConsole(\n        \"log\",\n        \"info\",\n        \"warn\",\n        \"error\",\n        \"debug\"\n      );\n      expect(console.log).not.toBe(originalLog);\n      expect(console.warn).not.toBe(originalWarn);\n      expect(console.error).not.toBe(originalError);\n      expect(console.debug).not.toBe(originalDebug);\n      expect(console.info).not.toBe(originalInfo);\n    }\n    expect(console.log).toBe(originalLog);\n    expect(console.warn).toBe(originalWarn);\n    expect(console.error).toBe(originalError);\n    expect(console.debug).toBe(originalDebug);\n    expect(console.info).toBe(originalInfo);\n  });\n\n  test(\"only mocks requested methods\", () => {\n    {\n      using consoleSpies = spyOnConsole(\"log\", \"warn\");\n      expect(consoleSpies.log).toBeDefined();\n      expect(consoleSpies.warn).toBeDefined();\n      // @ts-expect-error\n      expect(consoleSpies.error).not.toBeDefined();\n      // @ts-expect-error\n      expect(consoleSpies.debug).not.toBeDefined();\n      // @ts-expect-error\n      expect(consoleSpies.info).not.toBeDefined();\n      expect(console.log).not.toBe(originalLog);\n      expect(console.warn).not.toBe(originalWarn);\n      expect(console.error).toBe(originalError);\n      expect(console.debug).toBe(originalDebug);\n      expect(console.info).toBe(originalInfo);\n    }\n    expect(console.log).toBe(originalLog);\n    expect(console.warn).toBe(originalWarn);\n    expect(console.error).toBe(originalError);\n    expect(console.debug).toBe(originalDebug);\n    expect(console.info).toBe(originalInfo);\n  });\n});\n"
  },
  {
    "path": "src/testing/internal/disposables/__tests__/withCleanup.test.ts",
    "content": "import { withCleanup } from \"@apollo/client/testing/internal\";\ndescribe(\"withCleanup\", () => {\n  it(\"calls cleanup\", () => {\n    let cleanedUp = false;\n    {\n      using _x = withCleanup({}, () => {\n        cleanedUp = true;\n      });\n      expect(cleanedUp).toBe(false);\n    }\n    expect(cleanedUp).toBe(true);\n  });\n});\n"
  },
  {
    "path": "src/testing/internal/disposables/enableFakeTimers.ts",
    "content": "import { withCleanup } from \"./withCleanup.js\";\n\ndeclare global {\n  interface DateConstructor {\n    /* Jest uses @sinonjs/fake-timers, that add this flag */\n    isFake: boolean;\n  }\n}\n\nexport function enableFakeTimers(\n  config?: FakeTimersConfig | LegacyFakeTimersConfig\n) {\n  if (global.Date.isFake === true) {\n    // Nothing to do here, fake timers have already been set up.\n    // That also means we don't want to clean that up later.\n    return withCleanup({}, () => {});\n  }\n\n  jest.useFakeTimers(config);\n  return withCleanup({}, () => {\n    if (global.Date.isFake === true) {\n      jest.runOnlyPendingTimers();\n      jest.useRealTimers();\n    }\n  });\n}\n"
  },
  {
    "path": "src/testing/internal/disposables/index.ts",
    "content": "export { spyOnConsole } from \"./spyOnConsole.js\";\nexport { withCleanup } from \"./withCleanup.js\";\nexport { enableFakeTimers } from \"./enableFakeTimers.js\";\nexport { withProdMode } from \"./withProdMode.js\";\n"
  },
  {
    "path": "src/testing/internal/disposables/spyOnConsole.ts",
    "content": "import { withCleanup } from \"./withCleanup.js\";\n\nconst noOp = () => {};\nconst restore = (spy: jest.SpyInstance) => spy.mockRestore();\n\ntype ConsoleMethod = \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n\ntype Spies<Keys extends ConsoleMethod[]> = Record<\n  Keys[number],\n  jest.SpyInstance<void, any[], any>\n>;\n\nexport function spyOnConsole<Keys extends ConsoleMethod[]>(\n  ...spyOn: Keys\n): Spies<Keys> & Disposable {\n  const spies = {} as Spies<Keys>;\n  for (const key of spyOn) {\n    // @ts-ignore\n    spies[key] = jest.spyOn(console, key).mockImplementation(noOp);\n  }\n  return withCleanup(spies, (spies) => {\n    for (const spy of Object.values(spies) as jest.SpyInstance[]) {\n      restore(spy);\n    }\n  });\n}\n\nspyOnConsole.takeSnapshots = <Keys extends ConsoleMethod[]>(\n  ...spyOn: Keys\n): Spies<Keys> & Disposable =>\n  withCleanup(spyOnConsole(...spyOn), (spies) => {\n    for (const spy of Object.values(spies) as jest.SpyInstance[]) {\n      expect(spy).toMatchSnapshot();\n    }\n  });\n"
  },
  {
    "path": "src/testing/internal/disposables/withCleanup.ts",
    "content": "/** @internal */\nexport function withCleanup<T extends object>(\n  item: T,\n  cleanup: (item: T) => void\n): T & Disposable {\n  return {\n    ...item,\n    [Symbol.dispose]() {\n      cleanup(item);\n      // if `item` already has a cleanup function, we also need to call the original cleanup function\n      // (e.g. if something is wrapped in `withCleanup` twice)\n      if (Symbol.dispose in item) {\n        (item as Disposable)[Symbol.dispose]();\n      }\n    },\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/disposables/withProdMode.ts",
    "content": "import * as environment from \"@apollo/client/utilities/environment\";\n\nimport { withCleanup } from \"./withCleanup.js\";\n\nexport function withProdMode() {\n  const prev = { prevDEV: environment.__DEV__ };\n  Object.defineProperty(environment, \"__DEV__\", {\n    value: false,\n    configurable: true,\n  });\n\n  return withCleanup(prev, ({ prevDEV }) => {\n    Object.defineProperty(environment, \"__DEV__\", { value: prevDEV });\n  });\n}\n"
  },
  {
    "path": "src/testing/internal/incremental/executeSchemaGraphQL17Alpha2.ts",
    "content": "import type {\n  FormattedExecutionResult,\n  FormattedInitialIncrementalExecutionResult,\n  FormattedSubsequentIncrementalExecutionResult,\n  GraphQLSchema,\n} from \"graphql-17-alpha2\";\nimport { experimentalExecuteIncrementally } from \"graphql-17-alpha2\";\n\nimport type { DocumentNode } from \"@apollo/client\";\n\nexport async function* executeSchemaGraphQL17Alpha2(\n  schema: GraphQLSchema,\n  document: DocumentNode,\n  rootValue: unknown = {}\n): AsyncGenerator<\n  | FormattedInitialIncrementalExecutionResult\n  | FormattedSubsequentIncrementalExecutionResult\n  | FormattedExecutionResult,\n  void\n> {\n  const result = await experimentalExecuteIncrementally({\n    schema,\n    document,\n    rootValue,\n  });\n\n  if (\"initialResult\" in result) {\n    yield JSON.parse(JSON.stringify(result.initialResult));\n\n    for await (const patch of result.subsequentResults) {\n      yield JSON.parse(JSON.stringify(patch));\n    }\n  } else {\n    yield JSON.parse(JSON.stringify(result));\n  }\n}\n"
  },
  {
    "path": "src/testing/internal/incremental/executeSchemaGraphQL17Alpha9.ts",
    "content": "import type {\n  FormattedExecutionResult,\n  FormattedInitialIncrementalExecutionResult,\n  FormattedSubsequentIncrementalExecutionResult,\n  GraphQLSchema,\n} from \"graphql-17-alpha9\";\nimport { experimentalExecuteIncrementally } from \"graphql-17-alpha9\";\n\nimport type { DocumentNode } from \"@apollo/client\";\n\nexport async function* executeSchemaGraphQL17Alpha9(\n  schema: GraphQLSchema,\n  document: DocumentNode,\n  rootValue: unknown = {},\n  enableEarlyExecution?: boolean\n): AsyncGenerator<\n  | FormattedInitialIncrementalExecutionResult\n  | FormattedSubsequentIncrementalExecutionResult\n  | FormattedExecutionResult,\n  void\n> {\n  const result = await experimentalExecuteIncrementally({\n    schema,\n    document,\n    rootValue,\n    enableEarlyExecution,\n  });\n\n  if (\"initialResult\" in result) {\n    yield JSON.parse(JSON.stringify(result.initialResult));\n\n    for await (const patch of result.subsequentResults) {\n      yield JSON.parse(JSON.stringify(patch));\n    }\n  } else {\n    yield JSON.parse(JSON.stringify(result));\n  }\n}\n"
  },
  {
    "path": "src/testing/internal/index.ts",
    "content": "export {\n  enableFakeTimers,\n  spyOnConsole,\n  withCleanup,\n  withProdMode,\n} from \"./disposables/index.js\";\nexport { ObservableStream } from \"./ObservableStream.js\";\n\nexport type {\n  MaskedVariablesCaseData,\n  PaginatedCaseData,\n  PaginatedCaseVariables,\n  SimpleCaseData,\n  VariablesCaseData,\n  VariablesCaseVariables,\n} from \"./scenarios/index.js\";\nexport {\n  addDelayToMocks,\n  setupMaskedVariablesCase,\n  setupPaginatedCase,\n  setupSimpleCase,\n  setupVariablesCase,\n} from \"./scenarios/index.js\";\nexport { createClientWrapper, createMockWrapper } from \"./renderHelpers.js\";\nexport { actAsync } from \"./rtl/actAsync.js\";\nexport { asyncIterableSubject } from \"./asyncIterableSubject.js\";\nexport { executeSchemaGraphQL17Alpha2 } from \"./incremental/executeSchemaGraphQL17Alpha2.js\";\nexport { executeSchemaGraphQL17Alpha9 } from \"./incremental/executeSchemaGraphQL17Alpha9.js\";\nexport { promiseWithResolvers } from \"./promiseWithResolvers.js\";\nexport { renderAsync } from \"./rtl/renderAsync.js\";\nexport { renderHookAsync } from \"./rtl/renderHookAsync.js\";\nexport { mockDefer20220824 } from \"./multipart/mockDefer20220824.js\";\nexport { mockDeferStreamGraphQL17Alpha9 } from \"./multipart/mockDeferStreamGraphql17Alpha9.js\";\nexport { mockMultipartSubscriptionStream } from \"./multipart/mockMultipartSubscriptionStream.js\";\nexport { resetApolloContext } from \"./resetApolloContext.js\";\nexport {\n  createOperationWithDefaultContext,\n  executeWithDefaultContext,\n} from \"./link.js\";\nexport { markAsStreaming } from \"./markAsStreaming.js\";\nexport { wait } from \"./wait.js\";\n\nexport { friendListSchemaGraphQL17Alpha2 } from \"./schemas/friendList.graphql17Alpha2.js\";\nexport { friendListSchemaGraphQL17Alpha9 } from \"./schemas/friendList.graphql17Alpha9.js\";\n"
  },
  {
    "path": "src/testing/internal/link.ts",
    "content": "import { ApolloClient, execute, InMemoryCache } from \"@apollo/client\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { createOperation } from \"@apollo/client/link/utils\";\n\nfunction createDefaultExecuteContext() {\n  return {\n    client: new ApolloClient({\n      cache: new InMemoryCache(),\n      link: ApolloLink.empty(),\n    }),\n  };\n}\n\nexport function executeWithDefaultContext(\n  link: ApolloLink,\n  request: ApolloLink.Request,\n  context: ApolloLink.ExecuteContext = createDefaultExecuteContext()\n) {\n  return execute(link, request, context);\n}\n\nexport function createOperationWithDefaultContext(\n  request: ApolloLink.Request,\n  executeContext: ApolloLink.ExecuteContext = createDefaultExecuteContext()\n) {\n  return createOperation(request, executeContext);\n}\n"
  },
  {
    "path": "src/testing/internal/markAsStreaming.ts",
    "content": "import type { DataValue } from \"@apollo/client\";\n\nexport function markAsStreaming<TData>(data: TData) {\n  return data as DataValue.Streaming<TData>;\n}\n"
  },
  {
    "path": "src/testing/internal/messageChannelPolyfill.ts",
    "content": "import { MessageChannel as MC } from \"node:worker_threads\";\n\nconst messageChannels: MC[] = [];\n\nafterEach(() => {\n  let mc: MC | undefined;\n  while ((mc = messageChannels.pop())) {\n    mc.port1.close();\n    mc.port2.close();\n  }\n});\n//@ts-ignore\nglobalThis.MessageChannel = function MessageChannel() {\n  const mc = new MC();\n  messageChannels.push(mc);\n  return mc;\n};\n"
  },
  {
    "path": "src/testing/internal/multipart/mockDefer20220824.ts",
    "content": "import type {\n  FormattedInitialIncrementalExecutionResult,\n  FormattedSubsequentIncrementalExecutionResult,\n  GraphQLFormattedError,\n} from \"graphql-17-alpha2\";\n\nimport { mockMultipartStream } from \"./utils.js\";\n\nexport function mockDefer20220824<\n  TData = Record<string, unknown>,\n  TExtensions = Record<string, unknown>,\n>() {\n  const { httpLink, enqueue } = mockMultipartStream<\n    | FormattedInitialIncrementalExecutionResult<TData, TExtensions>\n    | FormattedSubsequentIncrementalExecutionResult<TData, TExtensions>\n  >({\n    responseHeaders: new Headers({\n      \"Content-Type\": 'multipart/mixed; boundary=\"-\"; deferSpec=20220824',\n    }),\n  });\n  return {\n    httpLink,\n    enqueueInitialChunk(\n      chunk: FormattedInitialIncrementalExecutionResult<TData, TExtensions>\n    ) {\n      enqueue(chunk, chunk.hasNext);\n    },\n    enqueueSubsequentChunk(\n      chunk: FormattedSubsequentIncrementalExecutionResult<TData, TExtensions>\n    ) {\n      enqueue(chunk, chunk.hasNext);\n    },\n    enqueueErrorChunk(errors: GraphQLFormattedError[]) {\n      enqueue(\n        {\n          hasNext: true,\n          incremental: [\n            {\n              errors,\n            },\n          ],\n        },\n        true\n      );\n    },\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/multipart/mockDeferStreamGraphql17Alpha9.ts",
    "content": "import type {\n  FormattedInitialIncrementalExecutionResult,\n  FormattedSubsequentIncrementalExecutionResult,\n} from \"graphql-17-alpha9\";\n\nimport { mockMultipartStream } from \"./utils.js\";\n\nexport function mockDeferStreamGraphQL17Alpha9<\n  TData = Record<string, unknown>,\n  TExtensions = Record<string, unknown>,\n>() {\n  const { httpLink, enqueue } = mockMultipartStream<\n    | FormattedInitialIncrementalExecutionResult<TData, TExtensions>\n    | FormattedSubsequentIncrementalExecutionResult<TData, TExtensions>\n  >({\n    responseHeaders: new Headers({\n      \"Content-Type\": 'multipart/mixed; boundary=\"-\"',\n    }),\n  });\n  return {\n    httpLink,\n    enqueueInitialChunk(\n      chunk: FormattedInitialIncrementalExecutionResult<TData, TExtensions>\n    ) {\n      enqueue(chunk, chunk.hasNext);\n    },\n    enqueueSubsequentChunk(\n      chunk: FormattedSubsequentIncrementalExecutionResult<TData, TExtensions>\n    ) {\n      enqueue(chunk, chunk.hasNext);\n    },\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/multipart/mockMultipartSubscriptionStream.ts",
    "content": "import type { ApolloPayloadResult } from \"@apollo/client\";\n\nimport { mockMultipartStream } from \"./utils.js\";\n\nexport function mockMultipartSubscriptionStream<\n  TData = Record<string, unknown>,\n  TExtensions = Record<string, unknown>,\n>() {\n  const { httpLink, enqueue } = mockMultipartStream<\n    ApolloPayloadResult<TData, TExtensions>\n  >({\n    responseHeaders: new Headers({\n      \"Content-Type\": \"multipart/mixed\",\n    }),\n  });\n\n  enqueueHeartbeat();\n\n  function enqueueHeartbeat() {\n    enqueue({} as any, true);\n  }\n\n  return {\n    httpLink,\n    enqueueHeartbeat,\n    enqueuePayloadResult(\n      payload: ApolloPayloadResult<TData, TExtensions>[\"payload\"],\n      hasNext = true\n    ) {\n      enqueue({ payload }, hasNext);\n    },\n    enqueueProtocolErrors(errors: ApolloPayloadResult[\"errors\"]) {\n      enqueue({ payload: null, errors }, false);\n    },\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/multipart/utils.ts",
    "content": "import {\n  ReadableStream as NodeReadableStream,\n  TextEncoderStream,\n  TransformStream,\n} from \"node:stream/web\";\n\nimport { HttpLink } from \"@apollo/client/link/http\";\n\nconst hasNextSymbol = Symbol(\"hasNext\");\n\nexport function mockMultipartStream<Chunks>({\n  responseHeaders,\n}: {\n  responseHeaders: Headers;\n}) {\n  type Payload = Chunks & { [hasNextSymbol]: boolean };\n  const CLOSE = Symbol();\n  let streamController: ReadableStreamDefaultController<Payload> | null = null;\n  let sentInitialChunk = false;\n\n  const queue: Array<Payload | typeof CLOSE> = [];\n\n  function processQueue() {\n    if (!streamController) {\n      throw new Error(\"Cannot process queue without stream controller\");\n    }\n\n    let chunk;\n    while ((chunk = queue.shift())) {\n      if (chunk === CLOSE) {\n        streamController.close();\n      } else {\n        streamController.enqueue(chunk);\n      }\n    }\n  }\n\n  function createStream() {\n    return new NodeReadableStream<Chunks & { [hasNextSymbol]: boolean }>({\n      start(c) {\n        streamController = c;\n        processQueue();\n      },\n    })\n      .pipeThrough(\n        new TransformStream<Chunks & { [hasNextSymbol]: boolean }, string>({\n          transform: (chunk, controller) => {\n            controller.enqueue(\n              (!sentInitialChunk ? \"\\r\\n---\\r\\n\" : \"\") +\n                \"content-type: application/json; charset=utf-8\\r\\n\\r\\n\" +\n                JSON.stringify(chunk) +\n                (chunk[hasNextSymbol] ? \"\\r\\n---\\r\\n\" : \"\\r\\n-----\\r\\n\")\n            );\n            sentInitialChunk = true;\n          },\n        })\n      )\n      .pipeThrough(new TextEncoderStream());\n  }\n\n  const httpLink = new HttpLink({\n    fetch(input, init) {\n      return Promise.resolve(\n        new Response(\n          createStream() satisfies NodeReadableStream<Uint8Array> as ReadableStream<Uint8Array>,\n          {\n            status: 200,\n            headers: responseHeaders,\n          }\n        )\n      );\n    },\n  });\n\n  function queueNext(event: Payload | typeof CLOSE) {\n    queue.push(event);\n\n    if (streamController) {\n      processQueue();\n    }\n  }\n\n  function close() {\n    queueNext(CLOSE);\n\n    streamController = null;\n    sentInitialChunk = false;\n  }\n\n  function enqueue(chunk: Chunks, hasNext: boolean) {\n    queueNext({ ...chunk, [hasNextSymbol]: hasNext });\n\n    if (!hasNext) {\n      close();\n    }\n  }\n\n  return {\n    httpLink,\n    enqueue,\n    close,\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/promiseWithResolvers.ts",
    "content": "export function promiseWithResolvers<T>(): {\n  promise: Promise<T>;\n  resolve: (value: T | Promise<T>) => void;\n  reject: (reason?: any) => void;\n} {\n  let resolve!: (value: T | Promise<T>) => void;\n  let reject!: (reason?: any) => void;\n\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res;\n    reject = rej;\n  });\n\n  return { promise, resolve, reject };\n}\n"
  },
  {
    "path": "src/testing/internal/renderHelpers.tsx",
    "content": "import * as React from \"react\";\n\nimport type { ApolloClient } from \"@apollo/client\";\nimport { ApolloProvider } from \"@apollo/client/react\";\nimport type { MockedProviderProps } from \"@apollo/client/testing/react\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\n\nexport function createClientWrapper(\n  client: ApolloClient,\n  Wrapper: React.JSXElementConstructor<{\n    children: React.ReactNode;\n  }> = React.Fragment\n): React.JSXElementConstructor<{\n  children: React.ReactNode;\n}> {\n  return ({ children }) => {\n    return (\n      <ApolloProvider client={client}>\n        <Wrapper>{children}</Wrapper>\n      </ApolloProvider>\n    );\n  };\n}\n\nexport function createMockWrapper(\n  renderOptions: MockedProviderProps,\n  Wrapper: React.JSXElementConstructor<{\n    children: React.ReactNode;\n  }> = React.Fragment\n): React.JSXElementConstructor<{\n  children: React.ReactNode;\n}> {\n  return ({ children }) => {\n    return (\n      <MockedProvider {...renderOptions}>\n        <Wrapper>{children}</Wrapper>\n      </MockedProvider>\n    );\n  };\n}\n"
  },
  {
    "path": "src/testing/internal/resetApolloContext.ts",
    "content": "import * as React from \"react\";\n\n/**\n * When writing tests that switch between renderers (e.g. between different SSR renderers),\n * we need to reset the Apollo Client context to avoid warnings like:\n *\n * > Detected multiple renderers concurrently rendering the same context provider. This is currently unsupported.\n *\n * This function resets the Apollo Client context to a fresh context.\n * That also prevents context values to be carried from one renderer to another,\n * which might otherwise happen.\n */\nexport function resetApolloContext() {\n  Object.defineProperty(React.createContext, Symbol.for(\"__APOLLO_CONTEXT__\"), {\n    value: Object.assign(React.createContext({}), {\n      displayName: \"ApolloContext\",\n    }),\n    enumerable: false,\n    writable: false,\n    configurable: true,\n  });\n}\n"
  },
  {
    "path": "src/testing/internal/rtl/actAsync.ts",
    "content": "// This is a helper required for React 19 testing.\n// There are currently multiple directions this could play out in RTL and none of\n// them has been released yet, so we are inlining this helper for now.\n// See https://github.com/testing-library/react-testing-library/pull/1214\n// and https://github.com/testing-library/react-testing-library/pull/1365\n\nimport * as React from \"react\";\nimport * as DeprecatedReactTestUtils from \"react-dom/test-utils\";\n\nconst reactAct =\n  typeof React.act === \"function\" ? React.act : DeprecatedReactTestUtils.act;\n\nexport function actAsync<T>(scope: () => T | Promise<T>): Promise<T> {\n  return reactAct(async () => {\n    return await scope();\n  });\n}\n"
  },
  {
    "path": "src/testing/internal/rtl/renderAsync.ts",
    "content": "// This is a helper required for React 19 testing.\n// There are currently multiple directions this could play out in RTL and none of\n// them has been released yet, so we are inlining this helper for now.\n// See https://github.com/testing-library/react-testing-library/pull/1214\n// and https://github.com/testing-library/react-testing-library/pull/1365\n\nimport type { queries, Queries } from \"@testing-library/dom\";\nimport type { RenderOptions, RenderResult } from \"@testing-library/react\";\nimport { act, render } from \"@testing-library/react\";\nimport type * as ReactDOMClient from \"react-dom/client\";\n\ntype RendererableContainer = ReactDOMClient.Container;\ntype HydrateableContainer = Parameters<\n  (typeof ReactDOMClient)[\"hydrateRoot\"]\n>[0];\n\nexport function renderAsync<\n  Q extends Queries = typeof queries,\n  Container extends RendererableContainer | HydrateableContainer = HTMLElement,\n  BaseElement extends RendererableContainer | HydrateableContainer = Container,\n>(\n  ui: React.ReactNode,\n  options: RenderOptions<Q, Container, BaseElement>\n): Promise<RenderResult<Q, Container, BaseElement>>;\nexport function renderAsync(\n  ui: React.ReactNode,\n  options?: Omit<RenderOptions, \"queries\"> | undefined\n): Promise<RenderResult>;\n\nexport function renderAsync(...args: [any, any]): any {\n  return act(async () => {\n    return await render(...args);\n  });\n}\n"
  },
  {
    "path": "src/testing/internal/rtl/renderHookAsync.tsx",
    "content": "// This is a helper required for React 19 testing.\n// There are currently multiple directions this could play out in RTL and none of\n// them has been released yet, so we are inlining this helper for now.\n// See https://github.com/testing-library/react-testing-library/pull/1214\n// and https://github.com/testing-library/react-testing-library/pull/1365\n\nimport type { queries, Queries } from \"@testing-library/dom\";\nimport type {\n  RenderHookOptions,\n  RenderHookResult,\n} from \"@testing-library/react\";\nimport * as React from \"react\";\nimport * as ReactDOM from \"react-dom\";\nimport type * as ReactDOMClient from \"react-dom/client\";\n\nimport { renderAsync } from \"./renderAsync.js\";\n\ntype RendererableContainer = ReactDOMClient.Container;\ntype HydrateableContainer = Parameters<\n  (typeof ReactDOMClient)[\"hydrateRoot\"]\n>[0];\n\nexport async function renderHookAsync<\n  Result,\n  Props,\n  Q extends Queries = typeof queries,\n  Container extends RendererableContainer | HydrateableContainer = HTMLElement,\n  BaseElement extends RendererableContainer | HydrateableContainer = Container,\n>(\n  renderCallback: (initialProps: Props) => Result,\n  options: RenderHookOptions<Props, Q, Container, BaseElement> | undefined = {}\n): Promise<RenderHookResult<Result, Props>> {\n  const { initialProps, ...renderOptions } = options;\n\n  // @ts-expect-error\n  if (renderOptions.legacyRoot && typeof ReactDOM.render !== \"function\") {\n    const error = new Error(\n      \"`legacyRoot: true` is not supported in this version of React. \" +\n        \"If your app runs React 19 or later, you should remove this flag. \" +\n        \"If your app runs React 18 or earlier, visit https://react.dev/blog/2022/03/08/react-18-upgrade-guide for upgrade instructions.\"\n    );\n    Error.captureStackTrace(error, renderHookAsync);\n    throw error;\n  }\n\n  const result = React.createRef<Result>() as { current: Result };\n\n  function TestComponent({\n    renderCallbackProps,\n  }: {\n    renderCallbackProps: Props;\n  }) {\n    const pendingResult = renderCallback(renderCallbackProps);\n\n    React.useEffect(() => {\n      result.current = pendingResult;\n    });\n\n    return null;\n  }\n\n  const { rerender: baseRerender, unmount } = await renderAsync(\n    <TestComponent renderCallbackProps={initialProps!} />,\n    renderOptions\n  );\n\n  function rerender(rerenderCallbackProps?: Props) {\n    return baseRerender(\n      <TestComponent renderCallbackProps={rerenderCallbackProps!} />\n    );\n  }\n\n  return { result, rerender, unmount };\n}\n"
  },
  {
    "path": "src/testing/internal/scenarios/index.ts",
    "content": "import { Observable } from \"rxjs\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { ApolloLink, gql } from \"@apollo/client\";\nimport type { MockLink } from \"@apollo/client/testing\";\n\nexport interface SimpleCaseData {\n  greeting: string;\n}\n\nexport function setupSimpleCase() {\n  const query: TypedDocumentNode<SimpleCaseData, Record<string, never>> = gql`\n    query GreetingQuery {\n      greeting\n    }\n  `;\n\n  const mocks: MockLink.MockedResponse<SimpleCaseData>[] = [\n    {\n      request: { query },\n      result: { data: { greeting: \"Hello\" } },\n      delay: 20,\n    },\n  ];\n\n  return { query, mocks };\n}\n\nexport interface VariablesCaseData {\n  character: {\n    __typename: \"Character\";\n    id: string;\n    name: string;\n  };\n}\n\nexport interface VariablesCaseVariables {\n  id: string;\n}\n\nexport function setupVariablesCase({\n  delay = 20,\n}: { delay?: MockLink.Delay } = {}) {\n  const query: TypedDocumentNode<VariablesCaseData, VariablesCaseVariables> =\n    gql`\n      query CharacterQuery($id: ID!) {\n        character(id: $id) {\n          id\n          name\n        }\n      }\n    `;\n  const CHARACTERS = [\"Spider-Man\", \"Black Widow\", \"Iron Man\", \"Hulk\"];\n\n  const mocks: MockLink.MockedResponse<\n    VariablesCaseData,\n    VariablesCaseVariables\n  >[] = [...CHARACTERS].map((name, index) => ({\n    request: { query, variables: { id: String(index + 1) } },\n    result: {\n      data: {\n        character: { __typename: \"Character\", id: String(index + 1), name },\n      },\n    },\n    delay,\n  }));\n\n  return { mocks, query };\n}\n\ntype MaskedVariablesCaseFragment = {\n  __typename: \"Character\";\n  name: string;\n} & { \" $fragmentName\"?: \"MaskedVariablesCaseFragment\" };\n\nexport interface MaskedVariablesCaseData {\n  character: {\n    __typename: \"Character\";\n    id: string;\n  } & {\n    \" $fragmentRefs\"?: {\n      MaskedVariablesCaseFragment: MaskedVariablesCaseFragment;\n    };\n  };\n}\n\nexport interface UnmaskedVariablesCaseData {\n  character: {\n    __typename: \"Character\";\n    id: string;\n    name: string;\n  };\n}\n\nexport function setupMaskedVariablesCase() {\n  const document = gql`\n    query CharacterQuery($id: ID!) {\n      character(id: $id) {\n        id\n        ...CharacterFragment\n      }\n    }\n\n    fragment CharacterFragment on Character {\n      name\n    }\n  `;\n  const query: TypedDocumentNode<\n    MaskedVariablesCaseData,\n    VariablesCaseVariables\n  > = document;\n\n  const unmaskedQuery: TypedDocumentNode<\n    UnmaskedVariablesCaseData,\n    VariablesCaseVariables\n  > = document;\n\n  const CHARACTERS = [\"Spider-Man\", \"Black Widow\", \"Iron Man\", \"Hulk\"];\n\n  const mocks: MockLink.MockedResponse<MaskedVariablesCaseData>[] = [\n    ...CHARACTERS,\n  ].map((name, index) => ({\n    request: { query, variables: { id: String(index + 1) } },\n    result: {\n      data: {\n        character: { __typename: \"Character\", id: String(index + 1), name },\n      },\n    },\n    delay: 20,\n  }));\n\n  return { mocks, query, unmaskedQuery };\n}\n\nexport function addDelayToMocks<T extends MockLink.MockedResponse<unknown>[]>(\n  mocks: T,\n  delay = 150,\n  override = false\n) {\n  return mocks.map((mock) =>\n    override ? { ...mock, delay } : { delay, ...mock }\n  );\n}\n\ninterface Letter {\n  __typename: \"Letter\";\n  letter: string;\n  position: number;\n}\n\nexport interface PaginatedCaseData {\n  letters: Letter[];\n}\n\nexport interface PaginatedCaseVariables {\n  limit?: number;\n  offset?: number;\n}\n\nexport function setupPaginatedCase() {\n  const query: TypedDocumentNode<PaginatedCaseData, PaginatedCaseVariables> =\n    gql`\n      query LettersQuery($limit: Int, $offset: Int) {\n        letters(limit: $limit, offset: $offset) {\n          letter\n          position\n        }\n      }\n    `;\n\n  const data = \"ABCDEFGHIJKLMNOPQRSTUV\".split(\"\").map((letter, index) => ({\n    __typename: \"Letter\",\n    letter,\n    position: index + 1,\n  }));\n\n  const link = new ApolloLink((operation) => {\n    const { offset = 0, limit = 2 } = operation.variables;\n    const letters = data.slice(offset, offset + limit);\n\n    return new Observable((observer) => {\n      setTimeout(() => {\n        observer.next({ data: { letters } });\n        observer.complete();\n      }, 10);\n    });\n  });\n\n  return { query, link, data };\n}\n"
  },
  {
    "path": "src/testing/internal/schemas/friendList.graphql17Alpha2.ts",
    "content": "import {\n  GraphQLID,\n  GraphQLInt,\n  GraphQLList,\n  GraphQLNonNull,\n  GraphQLObjectType,\n  GraphQLSchema,\n  GraphQLString,\n} from \"graphql-17-alpha2\";\n\nconst friendType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n    nonNullName: { type: new GraphQLNonNull(GraphQLString) },\n  },\n  name: \"Friend\",\n});\n\nconst query = new GraphQLObjectType({\n  fields: {\n    scalarList: {\n      type: new GraphQLList(GraphQLString),\n    },\n    scalarListList: {\n      type: new GraphQLList(new GraphQLList(GraphQLString)),\n    },\n    friendList: {\n      type: new GraphQLList(friendType),\n      args: {\n        offset: {\n          type: GraphQLInt,\n        },\n      },\n    },\n    nonNullFriendList: {\n      type: new GraphQLList(new GraphQLNonNull(friendType)),\n    },\n    nestedObject: {\n      type: new GraphQLObjectType({\n        name: \"NestedObject\",\n        fields: {\n          scalarField: {\n            type: GraphQLString,\n          },\n          nonNullScalarField: {\n            type: new GraphQLNonNull(GraphQLString),\n          },\n          nestedFriendList: { type: new GraphQLList(friendType) },\n          deeperNestedObject: {\n            type: new GraphQLObjectType({\n              name: \"DeeperNestedObject\",\n              fields: {\n                nonNullScalarField: {\n                  type: new GraphQLNonNull(GraphQLString),\n                },\n                deeperNestedFriendList: { type: new GraphQLList(friendType) },\n              },\n            }),\n          },\n        },\n      }),\n    },\n  },\n  name: \"Query\",\n});\n\nexport const friendListSchemaGraphQL17Alpha2 = new GraphQLSchema({ query });\n"
  },
  {
    "path": "src/testing/internal/schemas/friendList.graphql17Alpha9.ts",
    "content": "import {\n  GraphQLID,\n  GraphQLInt,\n  GraphQLList,\n  GraphQLNonNull,\n  GraphQLObjectType,\n  GraphQLSchema,\n  GraphQLString,\n} from \"graphql-17-alpha9\";\n\nconst friendType = new GraphQLObjectType({\n  fields: {\n    id: { type: GraphQLID },\n    name: { type: GraphQLString },\n    nonNullName: { type: new GraphQLNonNull(GraphQLString) },\n    scalarList: { type: new GraphQLList(GraphQLString) },\n  },\n  name: \"Friend\",\n});\n\nconst query = new GraphQLObjectType({\n  fields: {\n    scalarList: {\n      type: new GraphQLList(GraphQLString),\n    },\n    scalarListList: {\n      type: new GraphQLList(new GraphQLList(GraphQLString)),\n    },\n    friendList: {\n      type: new GraphQLList(friendType),\n      args: {\n        offset: {\n          type: GraphQLInt,\n        },\n      },\n    },\n    nonNullFriendList: {\n      type: new GraphQLList(new GraphQLNonNull(friendType)),\n    },\n    nestedObject: {\n      type: new GraphQLObjectType({\n        name: \"NestedObject\",\n        fields: {\n          scalarField: {\n            type: GraphQLString,\n          },\n          nonNullScalarField: {\n            type: new GraphQLNonNull(GraphQLString),\n          },\n          nestedFriendList: { type: new GraphQLList(friendType) },\n          scalarList: { type: new GraphQLList(GraphQLString) },\n          deeperNestedObject: {\n            type: new GraphQLObjectType({\n              name: \"DeeperNestedObject\",\n              fields: {\n                nonNullScalarField: {\n                  type: new GraphQLNonNull(GraphQLString),\n                },\n                deeperNestedFriendList: { type: new GraphQLList(friendType) },\n              },\n            }),\n          },\n        },\n      }),\n    },\n  },\n  name: \"Query\",\n});\n\nexport const friendListSchemaGraphQL17Alpha9 = new GraphQLSchema({ query });\n"
  },
  {
    "path": "src/testing/internal/wait.ts",
    "content": "export async function wait(ms: number) {\n  return new Promise<void>((resolve) => setTimeout(resolve, ms));\n}\n"
  },
  {
    "path": "src/testing/matchers/arrayWithLength.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nexport const arrayWithLength: MatcherFunction<[length: number]> = function (\n  actual,\n  length\n) {\n  if (!Array.isArray(actual)) {\n    throw new Error(\"Actual value must be an array\");\n  }\n\n  const pass = actual.length === length;\n\n  return {\n    pass,\n    message: () =>\n      `expected array to ${pass ? \"not be\" : \"be\"} of length ${length}`,\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/index.d.ts",
    "content": "import type {\n  RenderStream,\n  SnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport type { RenderStreamMatchers } from \"@testing-library/react-render-stream/expect\";\nimport type { MatcherHintOptions } from \"jest-matcher-utils\";\n\nimport type {\n  ApolloClient,\n  DocumentNode,\n  InMemoryCache,\n  ObservableQuery,\n  OperationVariables,\n} from \"@apollo/client\";\nimport type { QueryRef } from \"@apollo/client/react\";\n\nimport type { ObservableStream } from \"../internal/index.js\";\nimport { NextRenderOptions } from \"../internal/index.js\";\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\n\nimport type { KeyOptions } from \"./toHaveFragmentWatches.ts\";\nimport type {\n  CommonStream,\n  ToEmitSimilarValueOptions,\n  ToRerenderWithSimilarSnapshotOptions,\n} from \"./toRerenderWithSimilarSnapshot.ts\";\n\n// Unfortunately TypeScript does not have a way to determine if a generic\n// argument is a class or not, so we need to manually keep track of known class\n// instances that we filter out.\ntype KnownClassInstances = ApolloClient | ObservableQuery<any, any>;\ntype FilterUnserializableProperties<\n  T,\n  Options extends { includeKnownClassInstances: boolean } = {\n    includeKnownClassInstances: false;\n  },\n> = T extends Array<infer TItem> ? Array<FilterUnserializableProperties<TItem>>\n: T extends Record<string, any> ?\n  {\n    [K in keyof T as T[K] extends (...args: any[]) => any ? never\n    : false extends Options[\"includeKnownClassInstances\"] ?\n      T[K] extends KnownClassInstances ?\n        never\n      : K\n    : K]: T[K];\n  }\n: T;\n\ninterface ApolloCustomMatchers<R = void, T = {}> {\n  /**\n   * Used to determine if a queryRef has been disposed.\n   */\n  toBeDisposed: T extends QueryRef<any, any, any> ? () => R\n  : { error: \"matcher needs to be called on a QueryRef\" };\n  /**\n   * Used to determine if two GraphQL query documents are equal to each other by\n   * comparing their printed values. The document must be parsed by `gql`.\n   */\n  toMatchDocument(document: DocumentNode): R;\n\n  toHaveFragmentWatchesOn: T extends ApolloClient ?\n    (fragment: DocumentNode, keyOptions: Array<KeyOptions>) => R\n  : { error: \"matcher needs to be called on an ApolloClient instance\" };\n\n  toHaveNumWatches: T extends InMemoryCache ? (size: number) => R\n  : { error: \"matcher needs to be called on an InMemoryCache instance\" };\n\n  /**\n   * Used to determine if the Suspense cache has a cache entry.\n   */\n  toHaveSuspenseCacheEntryUsing: T extends ApolloClient<any> ?\n    (\n      query: DocumentNode,\n      options?: {\n        variables?: OperationVariables;\n        queryKey?: string | number | any[];\n      }\n    ) => R\n  : { error: \"matcher needs to be called on an ApolloClient instance\" };\n\n  toBeGarbageCollected: T extends WeakRef<any> ? () => Promise<R>\n  : { error: \"matcher needs to be called on a WeakRef instance\" };\n\n  toComplete: T extends ObservableStream<any> ?\n    (options?: TakeOptions) => Promise<R>\n  : { error: \"matcher needs to be called on an ObservableStream instance\" };\n\n  toEmitAnything: T extends ObservableStream<any> ?\n    (options?: TakeOptions) => Promise<R>\n  : { error: \"matcher needs to be called on an ObservableStream instance\" };\n\n  toEmitError: T extends ObservableStream<any> ?\n    (error?: any, options?: TakeOptions) => Promise<R>\n  : { error: \"matcher needs to be called on an ObservableStream instance\" };\n\n  /**\n   * Used to determine if the observable stream emitted a `next` event. Use\n   * `toEmitValue` to check if the `next` event emitted a specific value.\n   */\n  toEmitNext: T extends ObservableStream<any> ?\n    (options?: TakeOptions) => Promise<R>\n  : { error: \"matcher needs to be called on an ObservableStream instance\" };\n\n  toEmitTypedValue: T extends ObservableStream<infer TResult> ?\n    (\n      expected: FilterUnserializableProperties<TResult>,\n\n      options?: TakeOptions & {\n        received?: string;\n        expected?: string;\n        hintOptions?: MatcherHintOptions;\n      }\n    ) => Promise<R>\n  : { error: \"toEmitTypedValue needs to be called on an ObservableStream\" };\n\n  toStrictEqualTyped: [T] extends [Promise<infer TResult>] ?\n    <\n      TOptions extends {\n        includeKnownClassInstances?: boolean;\n        received?: string;\n        expected?: string;\n        hintOptions?: MatcherHintOptions;\n      } = {\n        includeKnownClassInstances?: false;\n        received?: string;\n        expected?: string;\n        hintOptions?: MatcherHintOptions;\n      },\n    >(\n      expected: FilterUnserializableProperties<\n        TResult,\n        { includeKnownClassInstances: TOptions[\"includeKnownClassInstances\"] }\n      >,\n      options?: TOptions\n    ) => R\n  : <\n      TOptions extends {\n        includeKnownClassInstances?: boolean;\n        received?: string;\n        expected?: string;\n        hintOptions?: MatcherHintOptions;\n      } = {\n        includeKnownClassInstances?: false;\n        received?: string;\n        expected?: string;\n        hintOptions?: MatcherHintOptions;\n      },\n    >(\n      expected: FilterUnserializableProperties<\n        T,\n        { includeKnownClassInstances: TOptions[\"includeKnownClassInstances\"] }\n      >,\n      options?: TOptions\n    ) => R;\n\n  toEmitSimilarValue: T extends CommonStream<infer Snapshot> ?\n    (options: ToEmitSimilarValueOptions<Snapshot>) => Promise<R>\n  : {\n      error: \"matcher needs to be called on a `CommonStream` (e.g. ObservableStream) instance\";\n    };\n\n  toRerenderWithSimilarSnapshot: T extends RenderStream<infer Snapshot> ?\n    (options?: ToRerenderWithSimilarSnapshotOptions<Snapshot>) => Promise<R>\n  : T extends SnapshotStream<infer Snapshot, any> ?\n    (options?: ToRerenderWithSimilarSnapshotOptions<Snapshot>) => Promise<R>\n  : {\n      error: \"matcher needs to be called on a `RenderStream` instance\";\n    };\n}\n\ninterface ApolloCustomAsymmetricMatchers {\n  arrayWithLength: (length: number) => any;\n}\n\ndeclare global {\n  namespace jest {\n    interface Matchers<R = void, T = {}>\n      extends ApolloCustomMatchers<R, T>,\n        RenderStreamMatchers<R, T> {}\n\n    interface Expect extends ApolloCustomAsymmetricMatchers {}\n  }\n}\n"
  },
  {
    "path": "src/testing/matchers/index.ts",
    "content": "import { expect } from \"@jest/globals\";\n\nimport { arrayWithLength } from \"./arrayWithLength.js\";\nimport { toBeDisposed } from \"./toBeDisposed.js\";\nimport { toBeGarbageCollected } from \"./toBeGarbageCollected.js\";\nimport { toComplete } from \"./toComplete.js\";\nimport { toEmitAnything } from \"./toEmitAnything.js\";\nimport { toEmitError } from \"./toEmitError.js\";\nimport { toEmitNext } from \"./toEmitNext.js\";\nimport { toEmitTypedValue } from \"./toEmitTypedValue.js\";\nimport { toHaveFragmentWatchesOn } from \"./toHaveFragmentWatchesOn.js\";\nimport { toHaveNumWatches } from \"./toHaveNumWatches.js\";\nimport { toHaveSuspenseCacheEntryUsing } from \"./toHaveSuspenseCacheEntryUsing.js\";\nimport { toMatchDocument } from \"./toMatchDocument.js\";\nimport {\n  toEmitSimilarValue,\n  toRerenderWithSimilarSnapshot,\n} from \"./toRerenderWithSimilarSnapshot.js\";\nimport { toStrictEqualTyped } from \"./toStrictEqualTyped.js\";\n\nexpect.extend({\n  arrayWithLength,\n  toComplete,\n  toEmitAnything,\n  toEmitError,\n  toEmitNext,\n  toEmitTypedValue,\n  toBeDisposed,\n  toHaveFragmentWatchesOn,\n  toHaveNumWatches,\n  toHaveSuspenseCacheEntryUsing,\n  toMatchDocument,\n  toBeGarbageCollected,\n  toStrictEqualTyped,\n  toRerenderWithSimilarSnapshot,\n  toEmitSimilarValue,\n});\n"
  },
  {
    "path": "src/testing/matchers/isSameClient.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { ApolloClient } from \"@apollo/client\";\n\nexport const isSameClient: Tester = function (a, b) {\n  const isAClient = a instanceof ApolloClient;\n  const isBClient = b instanceof ApolloClient;\n\n  if (isAClient && isBClient) {\n    return a === b;\n  } else if (isAClient === isBClient) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/testing/matchers/isSameObservableQuery.ts",
    "content": "import type { Tester } from \"@jest/expect-utils\";\n\nimport { ObservableQuery } from \"@apollo/client\";\n\nexport const isSameObservableQuery: Tester = function (a, b) {\n  const isAObservableQuery = a instanceof ObservableQuery;\n  const isBObservableQuery = b instanceof ObservableQuery;\n\n  if (isAObservableQuery && isBObservableQuery) {\n    return a === b;\n  } else if (isAObservableQuery === isBObservableQuery) {\n    return undefined;\n  } else {\n    return false;\n  }\n};\n"
  },
  {
    "path": "src/testing/matchers/toBeDisposed.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { QueryRef } from \"@apollo/client/react\";\nimport {\n  assertWrappedQueryRef,\n  unwrapQueryRef,\n} from \"@apollo/client/react/internal\";\n\nexport const toBeDisposed: MatcherFunction<[]> = function (_queryRef) {\n  const hint = this.utils.matcherHint(\"toBeDisposed\", \"queryRef\", \"\", {\n    isNot: this.isNot,\n  });\n\n  const queryRef = _queryRef as QueryRef;\n  assertWrappedQueryRef(queryRef);\n\n  const pass = unwrapQueryRef(queryRef).disposed;\n\n  return {\n    pass,\n    message: () => {\n      return `${hint}\\n\\nExpected queryRef ${\n        this.isNot ? \"not \" : \"\"\n      }to be disposed, but it was${this.isNot ? \"\" : \" not\"}.`;\n    },\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/toBeGarbageCollected.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\n// this is necessary because this file is picked up by `tsc` (it's not a test),\n// but our main `tsconfig.json` doesn't include `\"ES2021.WeakRef\"` on purpose\ndeclare class WeakRef<T extends WeakKey> {\n  constructor(target: T);\n  deref(): T | undefined;\n}\n\nexport const toBeGarbageCollected: MatcherFunction<[weakRef: WeakRef<any>]> =\n  async function (actual) {\n    const hint = this.utils.matcherHint(\"toBeGarbageCollected\");\n\n    if (!(actual instanceof WeakRef)) {\n      throw new Error(\n        hint +\n          \"\\n\\n\" +\n          `Expected value to be a WeakRef, but it was a ${typeof actual}.`\n      );\n    }\n\n    let pass = false;\n    let interval: NodeJS.Timeout | undefined;\n    let timeout: NodeJS.Timeout | undefined;\n    await Promise.race([\n      new Promise<void>((resolve) => {\n        timeout = setTimeout(resolve, 1000);\n      }),\n      new Promise<void>((resolve) => {\n        interval = setInterval(() => {\n          global.gc!();\n          pass = actual.deref() === undefined;\n          if (pass) {\n            resolve();\n          }\n        }, 1);\n      }),\n    ]);\n\n    clearInterval(interval);\n    clearTimeout(timeout);\n\n    return {\n      pass,\n      message: () => {\n        if (pass) {\n          return (\n            hint +\n            \"\\n\\n\" +\n            \"Expected value to not be cache-collected, but it was.\"\n          );\n        }\n\n        return (\n          hint + \"\\n\\n Expected value to be cache-collected, but it was not.\"\n        );\n      },\n    };\n  };\n"
  },
  {
    "path": "src/testing/matchers/toComplete.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { ObservableStream } from \"@apollo/client/testing/internal\";\n\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\nimport { EventMismatchError } from \"../internal/ObservableStream.js\";\n\nexport const toComplete: MatcherFunction<[options?: TakeOptions]> =\n  async function (actual, options) {\n    const stream = actual as ObservableStream<any>;\n    const hint = this.utils.matcherHint(\"toComplete\", \"stream\", \"\");\n\n    try {\n      await stream.takeComplete(options);\n\n      return {\n        pass: true,\n        message: () => {\n          return hint + \"\\n\\nExpected stream not to complete but it did.\";\n        },\n      };\n    } catch (error) {\n      if (\n        error instanceof Error &&\n        error.message === \"Timeout waiting for next event\"\n      ) {\n        return {\n          pass: false,\n          message: () =>\n            hint + \"\\n\\nExpected stream to complete but it did not.\",\n        };\n      } else if (EventMismatchError.is(error)) {\n        return {\n          pass: false,\n          message: () => error.formatMessage(\"toEmitNext\"),\n        };\n      } else {\n        throw error;\n      }\n    }\n  };\n"
  },
  {
    "path": "src/testing/matchers/toEmitAnything.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { ObservableStream } from \"@apollo/client/testing/internal\";\n\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\n\nexport const toEmitAnything: MatcherFunction<[options?: TakeOptions]> =\n  async function (actual, options) {\n    const stream = actual as ObservableStream<any>;\n    const hint = this.utils.matcherHint(\"toEmitAnything\", \"stream\", \"\");\n\n    try {\n      const value = await stream.peek(options);\n\n      return {\n        pass: true,\n        message: () => {\n          return (\n            hint +\n            \"\\n\\nExpected stream not to emit anything but it did.\" +\n            \"\\n\\nReceived:\\n\" +\n            this.utils.printReceived(value)\n          );\n        },\n      };\n    } catch (error) {\n      if (\n        error instanceof Error &&\n        error.message === \"Timeout waiting for next event\"\n      ) {\n        return {\n          pass: false,\n          message: () =>\n            hint + \"\\n\\nExpected stream to emit an event but it did not.\",\n        };\n      } else {\n        throw error;\n      }\n    }\n  };\n"
  },
  {
    "path": "src/testing/matchers/toEmitError.ts",
    "content": "import type { MatcherContext, MatcherFunction } from \"expect\";\n\nimport type { ObservableStream } from \"@apollo/client/testing/internal\";\n\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\nimport { EventMismatchError } from \"../internal/ObservableStream.js\";\n\nfunction isErrorEqual(this: MatcherContext, expected: any, actual: any) {\n  if (typeof expected === \"string\" && actual instanceof Error) {\n    return actual.message === expected;\n  }\n\n  return this.equals(expected, actual, this.customTesters);\n}\n\nexport const toEmitError: MatcherFunction<\n  [value?: any, options?: TakeOptions]\n> = async function (actual, expected, options) {\n  const stream = actual as ObservableStream<any>;\n  const hint = this.utils.matcherHint(\n    this.isNot ? \".not.toEmitError\" : \"toEmitError\",\n    \"stream\",\n    \"error\"\n  );\n\n  try {\n    const error = await stream.takeError(options);\n    const pass =\n      expected === undefined ? true : isErrorEqual.call(this, expected, error);\n\n    return {\n      pass,\n      message: () => {\n        if (pass) {\n          return (\n            hint +\n            \"\\n\\nExpected stream not to emit error but it did.\" +\n            `\\n\\nReceived:` +\n            `\\n` +\n            this.utils.printReceived(error)\n          );\n        }\n\n        return (\n          hint +\n          \"\\n\\n\" +\n          this.utils.printDiffOrStringify(\n            expected,\n            typeof expected === \"string\" ? error.message : error,\n            \"Expected\",\n            \"Received\",\n            true\n          )\n        );\n      },\n    };\n  } catch (error) {\n    if (\n      error instanceof Error &&\n      error.message === \"Timeout waiting for next event\"\n    ) {\n      return {\n        pass: false,\n        message: () =>\n          hint + \"\\n\\nExpected stream to emit an error but it did not.\",\n      };\n    } else if (EventMismatchError.is(error)) {\n      return {\n        pass: false,\n        message: () => error.formatMessage(\"toEmitError\"),\n      };\n    } else {\n      throw error;\n    }\n  }\n};\n"
  },
  {
    "path": "src/testing/matchers/toEmitNext.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { ObservableStream } from \"@apollo/client/testing/internal\";\n\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\nimport { EventMismatchError } from \"../internal/ObservableStream.js\";\n\nexport const toEmitNext: MatcherFunction<[options?: TakeOptions]> =\n  async function (actual, options) {\n    const stream = actual as ObservableStream<any>;\n    const hint = this.utils.matcherHint(\n      this.isNot ? \".not.toEmitValue\" : \"toEmitValue\",\n      \"stream\",\n      \"expected\"\n    );\n\n    try {\n      await stream.takeNext(options);\n\n      return {\n        pass: true,\n        message: () => {\n          return hint + \"\\n\\nExpected stream not to emit a value but it did.\";\n        },\n      };\n    } catch (error) {\n      if (\n        error instanceof Error &&\n        error.message === \"Timeout waiting for next event\"\n      ) {\n        return {\n          pass: false,\n          message: () =>\n            hint + \"\\n\\nExpected stream to emit a value but it did not.\",\n        };\n      } else if (EventMismatchError.is(error)) {\n        return {\n          pass: false,\n          message: () => error.formatMessage(\"toEmitNext\"),\n        };\n      } else {\n        throw error;\n      }\n    }\n  };\n"
  },
  {
    "path": "src/testing/matchers/toEmitTypedValue.ts",
    "content": "import { iterableEquality } from \"@jest/expect-utils\";\nimport type { MatcherFunction } from \"expect\";\nimport type { MatcherHintOptions } from \"jest-matcher-utils\";\n\nimport type { ObservableStream } from \"@apollo/client/testing/internal\";\n\nimport type { TakeOptions } from \"../internal/ObservableStream.js\";\nimport { EventMismatchError } from \"../internal/ObservableStream.js\";\n\nimport { getSerializableProperties } from \"./utils/getSerializableProperties.js\";\n\nexport const toEmitTypedValue: MatcherFunction<\n  [\n    value: any,\n    options?: TakeOptions & {\n      received?: string;\n      expected?: string;\n      hintOptions?: MatcherHintOptions;\n    },\n  ]\n> = async function (actual, expected, options) {\n  const stream = actual as ObservableStream<any>;\n  const hint = this.utils.matcherHint(\n    this.isNot ? \".not.toEmitTypedValue\" : \"toEmitTypedValue\",\n    options?.received || \"stream\",\n    options?.expected || \"expected\",\n    { ...options?.hintOptions, isNot: this.isNot }\n  );\n\n  try {\n    const value = await stream.takeNext(options);\n    const serializableProperties = getSerializableProperties(value);\n\n    const pass = this.equals(\n      serializableProperties,\n      expected,\n      // https://github.com/jestjs/jest/blob/22029ba06b69716699254bb9397f2b3bc7b3cf3b/packages/expect/src/matchers.ts#L62-L67\n      [...this.customTesters, iterableEquality],\n      true\n    );\n\n    return {\n      pass,\n      message: () => {\n        if (pass) {\n          return (\n            hint +\n            \"\\n\\nExpected stream not to emit a fetch result equal to expected but it did.\"\n          );\n        }\n\n        return (\n          hint +\n          \"\\n\\n\" +\n          this.utils.printDiffOrStringify(\n            expected,\n            serializableProperties,\n            \"Expected\",\n            \"Received\",\n            true\n          )\n        );\n      },\n    };\n  } catch (error) {\n    if (\n      error instanceof Error &&\n      error.message === \"Timeout waiting for next event\"\n    ) {\n      return {\n        pass: false,\n        message: () =>\n          hint + \"\\n\\nExpected stream to emit a value but it did not.\",\n      };\n    } else if (EventMismatchError.is(error)) {\n      return {\n        pass: false,\n        message: () => error.formatMessage(\"toEmitTypedValue\"),\n      };\n    } else {\n      throw error;\n    }\n  }\n};\n"
  },
  {
    "path": "src/testing/matchers/toHaveFragmentWatchesOn.ts",
    "content": "import { iterableEquality } from \"@jest/expect-utils\";\nimport type { Trie } from \"@wry/trie\";\nimport type { MatcherFunction } from \"expect\";\n\nimport type {\n  ApolloClient,\n  Cache,\n  DocumentNode,\n  InMemoryCache,\n} from \"@apollo/client\";\n\nexport type KeyOptions = Pick<\n  Cache.WatchOptions,\n  \"id\" | \"optimistic\" | \"variables\"\n>;\n\nexport const toHaveFragmentWatchesOn: MatcherFunction<\n  [fragment: DocumentNode, keyOptions: Array<KeyOptions>]\n> = function (_client, fragment, keyOptions) {\n  const hint = this.utils.matcherHint(\n    \"toHaveFragmentWatches\",\n    \"client\",\n    \"keyOptions\",\n    {\n      isNot: this.isNot,\n    }\n  );\n  const client = _client as ApolloClient;\n  const cache = client.cache as InMemoryCache;\n\n  function getFragmentWatches() {\n    // testing implementation detail to ensure cache.fragmentWatches also cleans up\n    const watchedItems: Trie<any> | undefined = cache[\"fragmentWatches\"][\n      \"weak\"\n    ].get(\n      client.cache[\"getFragmentDoc\"](\n        client[\"transform\"](fragment, true),\n        undefined\n      )\n    );\n    function* iterateStrongTrieChildren(\n      trie: Trie<any> | undefined,\n      path: any[]\n    ): Generator<any[]> {\n      if (!trie) return;\n      if (trie[\"data\"]) {\n        yield path;\n      }\n      if (trie[\"strong\"]) {\n        for (const [key, value] of Array.from(\n          (trie[\"strong\"] as Map<any, Trie<any> | undefined>)?.entries()\n        )) {\n          yield* iterateStrongTrieChildren(value, path.concat(key));\n        }\n      }\n    }\n\n    return Array.from(iterateStrongTrieChildren(watchedItems, []));\n  }\n\n  const watches = getFragmentWatches().map((cacheKey) => {\n    if (cacheKey.length > 1) {\n      throw new Error(\n        \"The `watchFragment` watcher cache key has changed. Please update the toHaveFragmentWatchesOn matcher.\"\n      );\n    }\n\n    return JSON.parse(cacheKey[0]);\n  });\n\n  const pass = this.equals(watches, keyOptions, [\n    ...this.customTesters,\n    iterableEquality,\n  ]);\n\n  return {\n    pass,\n    message: () => {\n      if (pass) {\n        return (\n          hint +\n          \"\\n\\nExpected client not to have fragment watches equal to expected but it did.\"\n        );\n      }\n\n      return (\n        hint +\n        \"\\n\\n\" +\n        this.utils.printDiffOrStringify(\n          keyOptions,\n          watches,\n          \"Expected\",\n          \"Received\",\n          true\n        )\n      );\n    },\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/toHaveNumWatches.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { InMemoryCache } from \"@apollo/client\";\n\nexport const toHaveNumWatches: MatcherFunction<[size: number]> = function (\n  _cache,\n  size\n) {\n  const hint = this.utils.matcherHint(\"toHaveNumWatches\", \"cache\", \"size\", {\n    isNot: this.isNot,\n  });\n  const cache = _cache as InMemoryCache;\n  const watchSize = cache[\"watches\"].size;\n  const watchIds = Array.from(cache[\"watches\"].values()).map(\n    (watch) => `'${watch.id ?? \"ROOT_QUERY\"}'`\n  );\n  const pass = watchSize === size;\n\n  const plural = (size: number) => (size === 1 ? \"watch\" : \"watches\");\n\n  return {\n    pass,\n    message: () => {\n      return `${hint}\\n\\nExpected cache ${\n        this.isNot ? \"not \" : \"\"\n      }to have ${this.utils.printExpected(size)} ${plural(\n        size\n      )} but instead it had ${this.utils.printReceived(watchSize)} ${plural(\n        watchSize\n      )}.\\n\\nWatches: ${this.utils.printReceived(\n        \"[\" + watchIds.join(\", \") + \"]\"\n      )}`;\n    },\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/toHaveSuspenseCacheEntryUsing.ts",
    "content": "import type { MatcherFunction } from \"expect\";\nimport type { DocumentNode } from \"graphql\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport { ApolloClient } from \"@apollo/client\";\nimport { canonicalStringify } from \"@apollo/client/cache\";\nimport type { CacheKey } from \"@apollo/client/react/internal\";\nimport { getSuspenseCache } from \"@apollo/client/react/internal\";\n\nexport const toHaveSuspenseCacheEntryUsing: MatcherFunction<\n  [\n    query: DocumentNode,\n    options: {\n      variables?: OperationVariables;\n      queryKey?: string | number | any[];\n    },\n  ]\n> = function (client, query, { variables, queryKey = [] } = {}) {\n  if (!(client instanceof ApolloClient)) {\n    throw new Error(\"Actual must be an instance of `ApolloClient`\");\n  }\n\n  const suspenseCache = getSuspenseCache(client);\n\n  const cacheKey: CacheKey = [\n    query,\n    canonicalStringify(variables),\n    ...([] as any[]).concat(queryKey),\n  ];\n  const queryRef = suspenseCache[\"queryRefs\"].lookupArray(cacheKey)?.current;\n\n  return {\n    pass: !!queryRef,\n    message: () => {\n      return `Expected suspense cache ${\n        queryRef ? \"not \" : \"\"\n      }to have cache entry using key`;\n    },\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/toMatchDocument.ts",
    "content": "import type { MatcherFunction } from \"expect\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport { print } from \"@apollo/client/utilities\";\nimport { checkDocument } from \"@apollo/client/utilities/internal\";\n\nexport const toMatchDocument: MatcherFunction<[document: DocumentNode]> =\n  function (actual, document) {\n    const hint = this.utils.matcherHint(\"toMatchDocument\");\n    const actualDocument = print(\n      validateDocument(\n        actual,\n        hint +\n          `\\n\\n${this.utils.RECEIVED_COLOR(\n            \"received\"\n          )} document must be a parsed document.`\n      )\n    );\n    const expectedDocument = print(\n      validateDocument(\n        document,\n        hint +\n          `\\n\\n${this.utils.EXPECTED_COLOR(\n            \"expected\"\n          )} document must be a parsed document.`\n      )\n    );\n\n    const pass = actualDocument === expectedDocument;\n\n    return {\n      pass,\n      message: () => {\n        const hint = this.utils.matcherHint(\n          \"toMatchDocument\",\n          undefined,\n          undefined,\n          { isNot: this.isNot }\n        );\n\n        if (pass) {\n          return (\n            hint +\n            \"\\n\\n\" +\n            \"Received:\\n\\n\" +\n            this.utils.RECEIVED_COLOR(actualDocument)\n          );\n        }\n\n        return (\n          hint + \"\\n\\n\" + this.utils.diff(expectedDocument, actualDocument)\n        );\n      },\n    };\n  };\n\nfunction validateDocument(document: unknown, message: string) {\n  try {\n    checkDocument(document as DocumentNode);\n  } catch (e) {\n    throw new Error(message);\n  }\n\n  return document as DocumentNode;\n}\n"
  },
  {
    "path": "src/testing/matchers/toRerenderWithSimilarSnapshot.ts",
    "content": "import type {\n  NextRenderOptions,\n  RenderStream,\n  SnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport { WaitForRenderTimeoutError } from \"@testing-library/react-render-stream\";\nimport type { MatcherContext } from \"expect\";\nimport type { MatcherFunction } from \"expect\";\n\nimport { getSerializableProperties } from \"./utils/getSerializableProperties.js\";\n\nexport interface ToRerenderWithSimilarSnapshotOptions<T>\n  extends Partial<NextRenderOptions> {\n  expected?(previous: T): T;\n}\n\nexport type ToEmitSimilarValueOptions<T> =\n  ToRerenderWithSimilarSnapshotOptions<T>;\n\nexport type CommonStream<T = unknown> = {\n  getCurrent(): undefined | T;\n  takeNext(options: Partial<NextRenderOptions>): Promise<T>;\n};\n\nexport const toEmitSimilarValue = async function toEmitSimilarValue(\n  this: MatcherContext,\n  actual,\n  {\n    expected: getExpected = (previous) => previous,\n    ...options\n  }: ToEmitSimilarValueOptions<any> = {}\n) {\n  const stream = actual as CommonStream;\n  const hint = this.utils.matcherHint(\n    \"toRerenderWithSimilarSnapshot\",\n    undefined,\n    undefined,\n    {\n      isNot: this.isNot,\n    }\n  );\n  let pass = true;\n  const previousResult = stream.getCurrent();\n  let reason = \"rerender.\";\n  try {\n    const expected = getSerializableProperties(getExpected(previousResult));\n    const nextResult = await stream.takeNext({ timeout: 100, ...options });\n    const received = getSerializableProperties(nextResult);\n\n    pass = this.equals(\n      expected,\n      received,\n      // https://github.com/jestjs/jest/blob/22029ba06b69716699254bb9397f2b3bc7b3cf3b/packages/expect/src/matchers.ts#L62-L67\n      [...this.customTesters, this.utils.iterableEquality],\n      true\n    );\n    reason =\n      \"match: \\n\" +\n      this.utils.printDiffOrStringify(\n        expected,\n        received,\n        \"Expected\",\n        \"Received\",\n        true\n      );\n  } catch (e) {\n    if (e instanceof WaitForRenderTimeoutError) {\n      pass = false;\n    } else {\n      throw e;\n    }\n  }\n\n  return {\n    pass,\n    message() {\n      return (\n        `${hint}\\n\\nExpected component to${\n          pass ? \" not\" : \"\"\n        } rerender, with a similar result ` +\n        `but it did${pass ? \"\" : \" not\"} ${reason}`\n      );\n    },\n    reason,\n  };\n} satisfies MatcherFunction<[options?: ToEmitSimilarValueOptions<any>]>;\n\nexport const toRerenderWithSimilarSnapshot: MatcherFunction<\n  [options?: NextRenderOptions]\n> = async function toRerenderWithSimilarSnapshot(\n  this: MatcherContext,\n  actual,\n  options\n) {\n  const hint = this.utils.matcherHint(\n    \"toRerenderWithStrictEqualSnapshot\",\n    undefined,\n    undefined,\n    {\n      isNot: this.isNot,\n    }\n  );\n  const stream = actual as RenderStream<any> | SnapshotStream<any, any>;\n  const common: CommonStream =\n    \"getCurrentRender\" in stream ?\n      {\n        getCurrent: () => stream.getCurrentRender()?.snapshot,\n        takeNext: (options) =>\n          stream.takeRender(options).then((result) => result.snapshot),\n      }\n    : {\n        getCurrent: () => stream.getCurrentSnapshot(),\n        takeNext: () => stream.takeSnapshot(),\n      };\n  const { pass, reason } = await toEmitSimilarValue.call(this, common, options);\n\n  return {\n    pass,\n    message() {\n      return (\n        `${hint}\\n\\nExpected component to${\n          pass ? \" not\" : \"\"\n        } rerender, with a similar snapshot ` +\n        `but it was${pass ? \"\" : \" not\"} ${reason}`\n      );\n    },\n  };\n} satisfies MatcherFunction<\n  [options?: ToRerenderWithSimilarSnapshotOptions<any>]\n>;\n"
  },
  {
    "path": "src/testing/matchers/toStrictEqualTyped.ts",
    "content": "import { iterableEquality } from \"@jest/expect-utils\";\nimport type { MatcherFunction } from \"expect\";\nimport type { MatcherHintOptions } from \"jest-matcher-utils\";\n\nimport { isSameClient } from \"./isSameClient.js\";\nimport { isSameObservableQuery } from \"./isSameObservableQuery.js\";\nimport { getSerializableProperties } from \"./utils/getSerializableProperties.js\";\n\nexport const toStrictEqualTyped: MatcherFunction<\n  [\n    value: any,\n    options?: {\n      includeKnownClassInstances?: boolean;\n      received?: string;\n      expected?: string;\n      hintOptions?: MatcherHintOptions;\n    },\n  ]\n> = function (actual, expected, options = {}) {\n  const { includeKnownClassInstances = false } = options;\n  const value = actual as Record<string, any>;\n  const hint = this.utils.matcherHint(\n    this.isNot ? \".not.toStrictEqualTyped\" : \"toStrictEqualTyped\",\n    options?.received || \"value\",\n    options?.expected || \"expected\",\n    { ...options.hintOptions, isNot: this.isNot, promise: this.promise }\n  );\n\n  const serializableProperties = getSerializableProperties(value, {\n    includeKnownClassInstances,\n  });\n\n  const testers =\n    includeKnownClassInstances ? [isSameClient, isSameObservableQuery] : [];\n\n  const pass = this.equals(\n    serializableProperties,\n    expected,\n    // https://github.com/jestjs/jest/blob/22029ba06b69716699254bb9397f2b3bc7b3cf3b/packages/expect/src/matchers.ts#L62-L67\n    [...testers, ...this.customTesters, iterableEquality],\n    true\n  );\n\n  return {\n    pass,\n    message: () => {\n      if (pass) {\n        return hint + `\\n\\nExpected: not ${this.utils.printExpected(expected)}`;\n      }\n\n      return (\n        hint +\n        \"\\n\\n\" +\n        this.utils.printDiffOrStringify(\n          expected,\n          serializableProperties,\n          \"Expected\",\n          \"Received\",\n          true\n        )\n      );\n    },\n  };\n};\n"
  },
  {
    "path": "src/testing/matchers/utils/getSerializableProperties.ts",
    "content": "import { ApolloClient, ObservableQuery } from \"@apollo/client\";\nimport { isPlainObject } from \"@apollo/client/utilities/internal\";\n\nfunction isKnownClassInstance(value: unknown) {\n  return [ApolloClient, ObservableQuery].some((c) => value instanceof c);\n}\n\nexport function getSerializableProperties(\n  obj: unknown,\n  {\n    includeKnownClassInstances = false,\n  }: {\n    includeKnownClassInstances?: boolean;\n  } = {}\n): any {\n  if (Array.isArray(obj)) {\n    return obj.map((item) =>\n      getSerializableProperties(item, {\n        includeKnownClassInstances,\n      })\n    );\n  }\n\n  if (isPlainObject(obj)) {\n    return [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj)].reduce(\n      (memo, key) => {\n        const value = obj[key as any];\n        if (\n          typeof value === \"function\" ||\n          (!includeKnownClassInstances && isKnownClassInstance(value))\n        ) {\n          return memo;\n        }\n\n        // Recurse if we have a nested object/array\n        if (isPlainObject(value) || Array.isArray(value)) {\n          return {\n            ...memo,\n            [key]: getSerializableProperties(value, {\n              includeKnownClassInstances,\n            }),\n          };\n        }\n        return { ...memo, [key]: value };\n      },\n      {} as Record<string, any>\n    );\n  }\n\n  return obj;\n}\n"
  },
  {
    "path": "src/testing/react/MockedProvider.tsx",
    "content": "import * as React from \"react\";\n\nimport { ApolloClient } from \"@apollo/client\";\nimport type { ApolloCache } from \"@apollo/client/cache\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport type { ApolloLink } from \"@apollo/client/link\";\nimport type { LocalState } from \"@apollo/client/local-state\";\nimport { ApolloProvider } from \"@apollo/client/react\";\nimport { MockLink } from \"@apollo/client/testing\";\n\nexport interface MockedProviderProps {\n  mocks?: ReadonlyArray<MockLink.MockedResponse<any, any>>;\n  defaultOptions?: ApolloClient.DefaultOptions;\n  cache?: ApolloCache;\n  localState?: LocalState;\n  childProps?: object;\n  children?: any;\n  link?: ApolloLink;\n  showWarnings?: boolean;\n  mockLinkDefaultOptions?: MockLink.DefaultOptions;\n  /**\n   * Configuration used by the [Apollo Client Devtools extension](https://www.apollographql.com/docs/react/development-testing/developer-tooling/#apollo-client-devtools) for this client.\n   *\n   * @since 3.14.0\n   */\n  devtools?: ApolloClient.Options[\"devtools\"];\n}\n\ninterface MockedProviderState {\n  client: ApolloClient;\n}\n\nexport class MockedProvider extends React.Component<\n  MockedProviderProps,\n  MockedProviderState\n> {\n  constructor(props: MockedProviderProps) {\n    super(props);\n\n    const {\n      mocks,\n      defaultOptions,\n      cache,\n      localState,\n      link,\n      showWarnings,\n      mockLinkDefaultOptions,\n      devtools,\n    } = this.props;\n    const client = new ApolloClient({\n      cache: cache || new Cache(),\n      defaultOptions,\n      link:\n        link ||\n        new MockLink(mocks || [], {\n          showWarnings,\n          defaultOptions: mockLinkDefaultOptions,\n        }),\n      localState,\n      devtools,\n    });\n\n    this.state = {\n      client,\n    };\n  }\n\n  public render() {\n    const { children, childProps } = this.props;\n    const { client } = this.state;\n\n    return React.isValidElement(children) ?\n        <ApolloProvider client={client}>\n          {React.cloneElement(React.Children.only(children), { ...childProps })}\n        </ApolloProvider>\n      : null;\n  }\n\n  public componentWillUnmount() {\n    // Since this.state.client was created in the constructor, it's this\n    // MockedProvider's responsibility to terminate it.\n    this.state.client.stop();\n  }\n}\n"
  },
  {
    "path": "src/testing/react/__tests__/MockedProvider.test.tsx",
    "content": "import { render, screen } from \"@testing-library/react\";\nimport {\n  disableActEnvironment,\n  renderHookToSnapshotStream,\n} from \"@testing-library/react-render-stream\";\nimport type { DocumentNode } from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\nimport type { Observable } from \"rxjs\";\nimport { EMPTY } from \"rxjs\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { NetworkStatus } from \"@apollo/client\";\nimport { InMemoryCache } from \"@apollo/client/cache\";\nimport { ApolloLink } from \"@apollo/client/link\";\nimport { useQuery } from \"@apollo/client/react\";\nimport { MockLink } from \"@apollo/client/testing\";\nimport {\n  createMockWrapper,\n  spyOnConsole,\n} from \"@apollo/client/testing/internal\";\nimport { MockedProvider } from \"@apollo/client/testing/react\";\n\nconst IS_REACT_17 = React.version.startsWith(\"17\");\n\nconst variables = {\n  username: \"mock_username\",\n};\n\nconst userWithoutTypeName = {\n  id: \"user_id\",\n};\n\nconst user = {\n  __typename: \"User\",\n  ...userWithoutTypeName,\n};\n\nconst query: TypedDocumentNode<Data, Variables> = gql`\n  query GetUser($username: String!) {\n    user(username: $username) {\n      id\n    }\n  }\n`;\n\nconst queryWithTypename: DocumentNode = gql`\n  query GetUser($username: String!) {\n    user(username: $username) {\n      id\n      __typename\n    }\n  }\n`;\n\nconst mocks: ReadonlyArray<MockLink.MockedResponse> = [\n  {\n    request: {\n      query,\n      variables,\n    },\n    result: { data: { user } },\n  },\n];\n\ninterface Data {\n  user: {\n    __typename?: string;\n    id: string;\n  };\n}\n\ninterface Variables {\n  username: string;\n}\n\nlet errorThrown = false;\nconst errorLink = new ApolloLink((operation, forward) => {\n  let observer: Observable<ApolloLink.Result> | null = EMPTY;\n  try {\n    observer = forward(operation);\n  } catch (error) {\n    errorThrown = true;\n  }\n  return observer;\n});\n\ndescribe(\"General use\", () => {\n  beforeEach(() => {\n    errorThrown = false;\n  });\n\n  it(\"should mock the data\", async () => {\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should pass the variables to the result function\", async () => {\n    const mock: MockLink.MockedResponse<Data, Variables> = {\n      request: {\n        query,\n        variables,\n      },\n      result: jest.fn().mockReturnValue({ data: { user } }),\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: [mock] }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(mock.result).toHaveBeenCalledTimes(1);\n    expect(mock.result).toHaveBeenCalledWith(variables);\n  });\n\n  it(\"should pass the variables to the `variables` callback function\", async () => {\n    const mock: MockLink.MockedResponse<Data, Variables> = {\n      request: {\n        query,\n        variables: jest.fn().mockReturnValue(true),\n      },\n      result: { data: { user } },\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: [mock] }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(mock.request.variables).toHaveBeenCalledTimes(1);\n    expect(mock.request.variables).toHaveBeenCalledWith(variables);\n  });\n\n  it(\"should use the mock if the `variables` callback function returns true\", async () => {\n    const mock: MockLink.MockedResponse<Data, Variables> = {\n      request: {\n        query,\n        variables: (v) => v.username === variables.username,\n      },\n      result: { data: { user } },\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: [mock] }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should allow querying with the typename\", async () => {\n    const mocksWithTypename = [\n      {\n        request: {\n          query: queryWithTypename,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: mocksWithTypename }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should allow using a custom cache\", async () => {\n    const cache = new InMemoryCache();\n    cache.writeQuery({\n      query,\n      variables,\n      data: { user },\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: [], cache }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should error if the variables in the mock and component do not match\", async () => {\n    const variables = {\n      username: \"other_user\",\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ showWarnings: false, mocks }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringContaining(\n          \"No more mocked responses for the query\"\n        ),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n  });\n\n  it(\"should error if the `variables` as callback returns false\", async () => {\n    const mock: MockLink.MockedResponse<Data, Variables> = {\n      request: {\n        query,\n        variables: () => false,\n      },\n      result: { data: { user } },\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ showWarnings: false, mocks: [mock] }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringContaining(\n          \"No more mocked responses for the query\"\n        ),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n  });\n\n  it(\"should error if the variables do not deep equal\", async () => {\n    const mocks = [\n      {\n        request: {\n          query,\n          variables: {\n            age: 13,\n            username: \"some_user\",\n          },\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    const variables = {\n      username: \"some_user\",\n      age: 42,\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ showWarnings: false, mocks }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringContaining(\n          \"No more mocked responses for the query\"\n        ),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n  });\n\n  it(\"should not error if the variables match but have different order\", async () => {\n    const mocks = [\n      {\n        request: {\n          query,\n          variables: {\n            age: 13,\n            username: \"some_user\",\n          },\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    const variables = {\n      username: \"some_user\",\n      age: 13,\n    };\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should support mocking a network error\", async () => {\n    const mocksError = [\n      {\n        request: {\n          query,\n          variables,\n        },\n        error: new Error(\"something went wrong\"),\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks: mocksError }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: new Error(\"something went wrong\"),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"should error if the query in the mock and component do not match\", async () => {\n    const mocks = [\n      {\n        request: {\n          query: gql`\n            query OtherQuery {\n              otherQuery {\n                id\n              }\n            }\n          `,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ showWarnings: false, mocks }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringContaining(\n          \"No more mocked responses for the query\"\n        ),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n  });\n\n  it(\"should pass down props prop in mock as props for the component\", () => {\n    function Component({ ...variables }) {\n      expect(variables.foo).toBe(\"bar\");\n      expect(variables.baz).toBe(\"qux\");\n      return null;\n    }\n\n    render(\n      <MockedProvider mocks={mocks} childProps={{ foo: \"bar\", baz: \"qux\" }}>\n        <Component {...variables} />\n      </MockedProvider>\n    );\n  });\n\n  it(\"should not crash on unmount if there is no query manager\", () => {\n    function Component() {\n      return null;\n    }\n\n    const { unmount } = render(\n      <MockedProvider>\n        <Component />\n      </MockedProvider>\n    );\n\n    unmount();\n  });\n\n  it(\"should support returning mocked results from a function\", async () => {\n    const user = {\n      __typename: \"User\",\n      id: 12345,\n    };\n\n    const query: DocumentNode = gql`\n      query GetUser($username: String!) {\n        user(username: $username) {\n          id\n        }\n      }\n    `;\n\n    const variables = {\n      username: \"jsmith\",\n    };\n\n    const mocks = [\n      {\n        request: { query, variables },\n        result: jest.fn().mockReturnValue({\n          data: {\n            user: {\n              __typename: \"User\",\n              id: 12345,\n            },\n          },\n        }),\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ mocks }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    expect(mocks[0].result).toHaveBeenCalledTimes(1);\n    expect(mocks[0].result).toHaveBeenCalledWith(variables);\n  });\n\n  it('should return \"No more mocked responses\" errors in response', async () => {\n    const link = ApolloLink.from([\n      errorLink,\n      new MockLink([], { showWarnings: false }),\n    ]);\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ link }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringContaining(\n          \"No more mocked responses for the query\"\n        ),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n\n    // The \"No more mocked responses\" error should not be thrown as an\n    // uncaught exception.\n    expect(errorThrown).toBeFalsy();\n  });\n\n  it(\"Uses a mock a configured number of times when `maxUsageCount` is configured\", async () => {\n    const variables = {\n      username: \"mock_username\",\n    };\n\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        request: { query, variables },\n        maxUsageCount: 2,\n        result: { data: { user } },\n      },\n    ];\n\n    const mockLink = new MockLink(mocks, { showWarnings: false });\n    const link = ApolloLink.from([errorLink, mockLink]);\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ link }) }\n    );\n    const { takeSnapshot, getCurrentSnapshot } = renderStream;\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    // First refetch (usage count 2)\n    await getCurrentSnapshot().refetch();\n\n    await expect(renderStream).toRerenderWithSimilarSnapshot({\n      expected: (previous) => ({\n        ...previous,\n        loading: true,\n        networkStatus: NetworkStatus.refetch,\n      }),\n    });\n\n    await expect(renderStream).toRerenderWithSimilarSnapshot({\n      expected: (previous) => ({\n        ...previous,\n        loading: false,\n        networkStatus: NetworkStatus.ready,\n      }),\n    });\n\n    // Second refetch (exceeds maxUsageCount, should error)\n    await getCurrentSnapshot()\n      .refetch()\n      .catch(() => {});\n\n    if (IS_REACT_17) {\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n        }),\n      });\n    }\n\n    await expect(renderStream).toRerenderWithSimilarSnapshot({\n      expected: (previous) => ({\n        ...previous,\n        error: expect.objectContaining({\n          message: expect.stringContaining(\"No more mocked responses\"),\n        }),\n        loading: false,\n        networkStatus: NetworkStatus.error,\n      }),\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it(\"Uses a mock infinite number of times when `maxUsageCount` is configured with Number.POSITIVE_INFINITY\", async () => {\n    const variables = {\n      username: \"mock_username\",\n    };\n\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        request: { query, variables },\n        maxUsageCount: Number.POSITIVE_INFINITY,\n        result: { data: { user } },\n        delay: 0,\n      },\n    ];\n\n    const mockLink = new MockLink(mocks, { showWarnings: false });\n    const link = ApolloLink.from([errorLink, mockLink]);\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(\n        () => useQuery(query, { variables: variables }),\n        { wrapper: createMockWrapper({ link }) }\n      );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables: variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n\n    // Refetch 100 times - all should succeed\n    for (let i = 0; i < 100; i++) {\n      await getCurrentSnapshot().refetch();\n    }\n  });\n\n  it(\"uses a mock once when `maxUsageCount` is not configured\", async () => {\n    const variables = { username: \"mock_username\" };\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        request: {\n          query,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    const mockLink = new MockLink(mocks, { showWarnings: false });\n    const link = ApolloLink.from([errorLink, mockLink]);\n\n    using _disabledAct = disableActEnvironment();\n    const renderStream = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      { wrapper: createMockWrapper({ link }) }\n    );\n    const { takeSnapshot, getCurrentSnapshot } = renderStream;\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(getCurrentSnapshot().refetch()).rejects.toThrow(\n      /No more mocked responses/\n    );\n\n    if (IS_REACT_17) {\n      await expect(renderStream).toRerenderWithSimilarSnapshot({\n        expected: (previous) => ({\n          ...previous,\n          loading: true,\n          networkStatus: NetworkStatus.refetch,\n        }),\n      });\n    }\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      error: expect.objectContaining({\n        message: expect.stringMatching(/No more mocked responses/),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n  });\n\n  it(\"can still use other mocks after a mock has been fully consumed\", async () => {\n    const variables = { username: \"mock_username\" };\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        request: {\n          query,\n          variables,\n        },\n        maxUsageCount: 2,\n        result: { data: { user } },\n      },\n      {\n        request: {\n          query,\n          variables,\n        },\n        result: {\n          data: {\n            user: {\n              __typename: \"User\",\n              id: \"new_id\",\n            },\n          },\n        },\n      },\n    ];\n\n    const mockLink = new MockLink(mocks, { showWarnings: false });\n    const link = ApolloLink.from([errorLink, mockLink]);\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ link }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    getCurrentSnapshot().refetch();\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables,\n    });\n\n    getCurrentSnapshot().refetch();\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: { user },\n      dataState: \"complete\",\n      loading: true,\n      networkStatus: NetworkStatus.refetch,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        user: {\n          __typename: \"User\",\n          id: \"new_id\",\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: { user },\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n  });\n\n  it('should return \"Mocked response should contain\" errors in response', async () => {\n    const link = ApolloLink.from([\n      errorLink,\n      new MockLink([\n        {\n          request: {\n            query,\n            variables,\n          },\n        },\n      ]),\n    ]);\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot, getCurrentSnapshot } =\n      await renderHookToSnapshotStream(() => useQuery(query, { variables }), {\n        wrapper: createMockWrapper({ link }),\n      });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringMatching(/Mocked response should contain/),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot).not.toRerender();\n    expect(getCurrentSnapshot().error).toMatchSnapshot();\n    // The \"Mocked response should contain\" error should not be thrown as an\n    // uncaught exception.\n    expect(errorThrown).toBeFalsy();\n  });\n\n  it(\"shows a warning in the console when there is no matched mock\", async () => {\n    const consoleSpy = jest.spyOn(console, \"warn\").mockImplementation(() => {});\n    const mocksDifferentQuery = [\n      {\n        request: {\n          query: gql`\n            query OtherQuery {\n              otherQuery {\n                id\n              }\n            }\n          `,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      {\n        wrapper: createMockWrapper({ mocks: mocksDifferentQuery }),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringMatching(/No more mocked responses/),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    expect(console.warn).toHaveBeenCalledTimes(1);\n    expect(console.warn).toHaveBeenCalledWith(\n      expect.stringContaining(\"No more mocked responses for the query\")\n    );\n\n    consoleSpy.mockRestore();\n  });\n\n  it(\"silences console warning for unmatched mocks when `showWarnings` is `false`\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const mocksDifferentQuery = [\n      {\n        request: {\n          query: gql`\n            query OtherQuery {\n              otherQuery {\n                id\n              }\n            }\n          `,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      {\n        wrapper: createMockWrapper({\n          mocks: mocksDifferentQuery,\n          showWarnings: false,\n        }),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringMatching(/No more mocked responses/),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  it(\"silences console warning for unmatched mocks when passing `showWarnings` to `MockLink` directly\", async () => {\n    using _ = spyOnConsole(\"warn\");\n    const mocksDifferentQuery = [\n      {\n        request: {\n          query: gql`\n            query OtherQuery {\n              otherQuery {\n                id\n              }\n            }\n          `,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    const link = new MockLink(mocksDifferentQuery, {\n      showWarnings: false,\n    });\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(query, { variables }),\n      {\n        wrapper: createMockWrapper({ link }),\n      }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      loading: true,\n      networkStatus: NetworkStatus.loading,\n      previousData: undefined,\n      variables,\n    });\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: undefined,\n      dataState: \"empty\",\n      error: expect.objectContaining({\n        message: expect.stringMatching(/No more mocked responses/),\n      }),\n      loading: false,\n      networkStatus: NetworkStatus.error,\n      previousData: undefined,\n      variables,\n    });\n\n    expect(console.warn).not.toHaveBeenCalled();\n  });\n\n  it(\"should support loading state testing with delay\", async () => {\n    jest.useFakeTimers();\n\n    function Component({ username }: Variables) {\n      const { loading, data } = useQuery<Data, Variables>(query, { variables });\n\n      if (loading || data === undefined) return <p>Loading the user ID...</p>;\n\n      return <p>The user ID is '{data.user.id}'</p>;\n    }\n\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        delay: 30000, // prevent React from batching the loading state away\n        request: {\n          query,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    render(\n      <MockedProvider mocks={mocks}>\n        <Component {...variables} />\n      </MockedProvider>\n    );\n\n    expect(\n      await screen.findByText(\"Loading the user ID...\")\n    ).toBeInTheDocument();\n\n    jest.advanceTimersByTime(30_000);\n\n    expect(\n      await screen.findByText(\"The user ID is 'user_id'\")\n    ).toBeInTheDocument();\n\n    jest.useRealTimers();\n  });\n\n  it(\"should support an infinite loading state with result and delay: Infinity\", async () => {\n    jest.useFakeTimers();\n\n    function Component({ username }: Variables) {\n      const { loading, data } = useQuery<Data, Variables>(query, {\n        variables,\n      });\n\n      if (loading) return <p>Loading the user ID...</p>;\n      if (data === undefined) return <p>Undefined data</p>;\n\n      return <p>The user ID is '{data.user.id}'</p>;\n    }\n\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        delay: Infinity, // keep loading forever.\n        request: {\n          query,\n          variables,\n        },\n        result: { data: { user } },\n      },\n    ];\n\n    render(\n      <MockedProvider mocks={mocks}>\n        <Component {...variables} />\n      </MockedProvider>\n    );\n\n    expect(\n      await screen.findByText(\"Loading the user ID...\")\n    ).toBeInTheDocument();\n\n    jest.advanceTimersByTime(Number.MAX_SAFE_INTEGER);\n\n    expect(\n      await screen.findByText(\"Loading the user ID...\")\n    ).toBeInTheDocument();\n\n    expect(screen.queryByText(/The user ID is/i)).toBeNull();\n\n    jest.useRealTimers();\n  });\n\n  it(\"should support an infinite loading state with error and delay: Infinity\", async () => {\n    jest.useFakeTimers();\n\n    function Component({ username }: Variables) {\n      const { loading, data } = useQuery<Data, Variables>(query, {\n        variables,\n      });\n\n      if (loading) return <p>Loading the user ID...</p>;\n      if (data === undefined) return <p>Undefined data</p>;\n\n      return <p>The user ID is '{data.user.id}'</p>;\n    }\n\n    const mocks: ReadonlyArray<MockLink.MockedResponse> = [\n      {\n        delay: Infinity, // keep loading forever.\n        request: {\n          query,\n          variables,\n        },\n        error: new Error(\"something went wrong\"),\n      },\n    ];\n\n    render(\n      <MockedProvider mocks={mocks}>\n        <Component {...variables} />\n      </MockedProvider>\n    );\n\n    expect(\n      await screen.findByText(\"Loading the user ID...\")\n    ).toBeInTheDocument();\n\n    jest.advanceTimersByTime(Number.MAX_SAFE_INTEGER);\n\n    expect(\n      await screen.findByText(\"Loading the user ID...\")\n    ).toBeInTheDocument();\n\n    expect(screen.queryByText(/The user ID is/i)).toBeNull();\n\n    jest.useRealTimers();\n  });\n});\n\ndescribe(\"@client testing\", () => {\n  it(\"should support @client fields with a custom cache\", async () => {\n    const cache = new InMemoryCache();\n\n    cache.writeQuery({\n      query: gql`\n        {\n          networkStatus {\n            isOnline\n          }\n        }\n      `,\n      data: {\n        networkStatus: {\n          __typename: \"NetworkStatus\",\n          isOnline: true,\n        },\n      },\n    });\n\n    const clientQuery = gql`\n      {\n        networkStatus @client {\n          isOnline\n        }\n      }\n    `;\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(clientQuery),\n      { wrapper: createMockWrapper({ cache }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        networkStatus: {\n          __typename: \"NetworkStatus\",\n          isOnline: true,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  });\n\n  it(\"should support @client fields with field policies\", async () => {\n    const cache = new InMemoryCache({\n      typePolicies: {\n        Query: {\n          fields: {\n            networkStatus() {\n              return {\n                __typename: \"NetworkStatus\",\n                isOnline: true,\n              };\n            },\n          },\n        },\n      },\n    });\n\n    const clientQuery = gql`\n      {\n        networkStatus @client {\n          isOnline\n        }\n      }\n    `;\n\n    using _disabledAct = disableActEnvironment();\n    const { takeSnapshot } = await renderHookToSnapshotStream(\n      () => useQuery(clientQuery),\n      { wrapper: createMockWrapper({ cache }) }\n    );\n\n    await expect(takeSnapshot()).resolves.toStrictEqualTyped({\n      data: {\n        networkStatus: {\n          __typename: \"NetworkStatus\",\n          isOnline: true,\n        },\n      },\n      dataState: \"complete\",\n      loading: false,\n      networkStatus: NetworkStatus.ready,\n      previousData: undefined,\n      variables: {},\n    });\n  });\n});\n"
  },
  {
    "path": "src/testing/react/__tests__/__snapshots__/MockedProvider.test.tsx.snap",
    "content": "// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing\n\nexports[`General use should error if the \\`variables\\` as callback returns false 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"mock_username\"}\n\nFailed to match variables against 1 mock for this query. The available mocks had the following variables:\n  <function variables>\n]\n`;\n\nexports[`General use should error if the query in the mock and component do not match 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"mock_username\"}\n]\n`;\n\nexports[`General use should error if the variables do not deep equal 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"some_user\",\"age\":42}\n\nFailed to match variables against 1 mock for this query. The available mocks had the following variables:\n  {\"age\":13,\"username\":\"some_user\"}\n]\n`;\n\nexports[`General use should error if the variables in the mock and component do not match 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"other_user\"}\n\nFailed to match variables against 1 mock for this query. The available mocks had the following variables:\n  {\"username\":\"mock_username\"}\n]\n`;\n\nexports[`General use should return \"Mocked response should contain\" errors in response 1`] = `\n[Error: Mocked response should contain either \\`result\\`, \\`error\\` or a \\`delay\\` of \\`Infinity\\`:\n{\n  \"request\": {\n    \"query\": \"query GetUser($username: String!) {\\\\n  user(username: $username) {\\\\n    id\\\\n  }\\\\n}\",\n    \"variables\": {\n      \"username\": \"mock_username\"\n    }\n  }\n}]\n`;\n\nexports[`General use should return \"No more mocked responses\" errors in response 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"mock_username\"}\n]\n`;\n\nexports[`General use uses a mock once when \\`maxUsageCount\\` is not configured 1`] = `\n[Error: No more mocked responses for the query:\nquery GetUser($username: String!) {\n  user(username: $username) {\n    id\n    __typename\n  }\n}\n\nRequest variables: {\"username\":\"mock_username\"}\n]\n`;\n"
  },
  {
    "path": "src/testing/react/__tests__/mockSubscriptionLink.test.tsx",
    "content": "import { render, waitFor } from \"@testing-library/react\";\nimport { gql } from \"graphql-tag\";\nimport React from \"react\";\n\nimport { ApolloClient } from \"@apollo/client\";\nimport { InMemoryCache as Cache } from \"@apollo/client/cache\";\nimport { ApolloProvider, useSubscription } from \"@apollo/client/react\";\nimport { MockSubscriptionLink } from \"@apollo/client/testing\";\n\ndescribe(\"mockSubscriptionLink\", () => {\n  it(\"should work with multiple subscribers to the same mock websocket\", async () => {\n    const subscription = gql`\n      subscription {\n        car {\n          make\n        }\n      }\n    `;\n\n    const link = new MockSubscriptionLink();\n    const client = new ApolloClient({\n      link,\n      cache: new Cache(),\n    });\n\n    let renderCountA = 0;\n    const ComponentA = () => {\n      useSubscription(subscription);\n      renderCountA += 1;\n      return null;\n    };\n\n    let renderCountB = 0;\n    const ComponentB = () => {\n      useSubscription(subscription);\n      renderCountB += 1;\n      return null;\n    };\n\n    const results = [\"Audi\", \"BMW\", \"Mercedes\", \"Hyundai\"].map((make) => ({\n      result: { data: { car: { make } } },\n    }));\n\n    const Component = () => {\n      const [index, setIndex] = React.useState(0);\n      React.useEffect(() => {\n        if (index >= results.length) return;\n        link.simulateResult(results[index]);\n        setIndex(index + 1);\n      }, [index]);\n      return null;\n    };\n\n    render(\n      <ApolloProvider client={client}>\n        <div>\n          <Component />\n          <ComponentA />\n          <ComponentB />\n        </div>\n      </ApolloProvider>\n    );\n\n    const numRenders = results.length + 1;\n\n    // automatic batching in React 18 means we only see 2 renders vs. 5 in v17\n    await waitFor(\n      () => {\n        expect(renderCountA).toBe(numRenders);\n      },\n      { timeout: 1000 }\n    );\n    expect(renderCountB).toBe(numRenders);\n  });\n});\n"
  },
  {
    "path": "src/testing/react/index.ts",
    "content": "export { MockedProvider } from \"./MockedProvider.js\";\nexport type { MockedProviderProps } from \"./MockedProvider.js\";\n"
  },
  {
    "path": "src/utilities/DeepPartial.ts",
    "content": "// Inspired by type-fest PartialDeep: https://github.com/sindresorhus/type-fest/blob/9feb8c89be9a0f2f688bf2f497230298a8e2472e/source/partial-deep.d.ts\n//\n// We're including the license to give credit to the original implementation.\n// https://github.com/sindresorhus/type-fest/blob/main/license-mit\n\n/*\n * MIT License\n *\n * Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\nimport type { Primitive } from \"@apollo/client/utilities/internal\";\n\ntype DeepPartialPrimitive = Primitive | Date | RegExp;\n\n/**\n * Deeply makes all properties in `T` optional.\n */\nexport type DeepPartial<T> =\n  T extends DeepPartialPrimitive ? T\n  : T extends Map<infer TKey, infer TValue> ? DeepPartialMap<TKey, TValue>\n  : T extends ReadonlyMap<infer TKey, infer TValue> ?\n    DeepPartialReadonlyMap<TKey, TValue>\n  : T extends Set<infer TItem> ? DeepPartialSet<TItem>\n  : T extends ReadonlySet<infer TItem> ? DeepPartialReadonlySet<TItem>\n  : T extends (...args: any[]) => unknown ? T | undefined\n  : T extends object ?\n    T extends (\n      ReadonlyArray<infer TItem> // Test for arrays/tuples\n    ) ?\n      TItem[] extends (\n        T // Test for non-tuples\n      ) ?\n        readonly TItem[] extends T ?\n          ReadonlyArray<DeepPartial<TItem>>\n        : Array<DeepPartial<TItem>>\n      : DeepPartialObject<T>\n    : DeepPartialObject<T>\n  : unknown;\n\ntype DeepPartialMap<TKey, TValue> = {} & Map<\n  DeepPartial<TKey>,\n  DeepPartial<TValue>\n>;\n\ntype DeepPartialReadonlyMap<TKey, TValue> = {} & ReadonlyMap<\n  DeepPartial<TKey>,\n  DeepPartial<TValue>\n>;\n\ntype DeepPartialSet<T> = {} & Set<DeepPartial<T>>;\ntype DeepPartialReadonlySet<T> = {} & ReadonlySet<DeepPartial<T>>;\n\ntype DeepPartialObject<T extends object> = {\n  [K in keyof T]?: DeepPartial<T[K]>;\n};\n"
  },
  {
    "path": "src/utilities/HKT.ts",
    "content": "/**\n * A helper interface to implement Higher-Kinded-Types (HKT) in TypeScript.\n *\n * @example\n * For example usage, see `src/masking/GraphQLCodegenDataMasking.ts`.\n *\n * @beta\n * The Higher-Kinded-Types implementation might change between minor versions,\n * as we discover ways of making it more performant and/or our requirements to\n * the HKT implementation change.\n *\n * We still want to encourage you to provide your own implementations of the types\n * we make overridable this way, but keep in mind that this might require some\n * extra work updating.\n *\n * @example\n *\n * ```ts\n * interface Concat extends HKT {\n *   arg1: string;\n *   arg2: string;\n *   return: `${this[\"arg1\"]}${this[\"arg2\"]}`;\n * }\n *\n * type Result = ApplyHKT<Concat, \"Hello, \", \"world!\">;\n * // Result is \"Hello, world!\"\n * ```\n */\nexport interface HKT {\n  arg1: unknown;\n  arg2: unknown;\n  arg3: unknown;\n  arg4: unknown;\n  return: unknown;\n}\n"
  },
  {
    "path": "src/utilities/caching/__tests__/getMemoryInternals.ts",
    "content": "import crypto from \"crypto\";\n\nimport {\n  ApolloClient,\n  ApolloLink,\n  DocumentTransform,\n  gql,\n  InMemoryCache,\n} from \"@apollo/client\";\nimport { createFragmentRegistry } from \"@apollo/client/cache\";\nimport { PersistedQueryLink } from \"@apollo/client/link/persisted-queries\";\nimport { RemoveTypenameFromVariablesLink } from \"@apollo/client/link/remove-typename\";\nimport { cacheSizes } from \"@apollo/client/utilities\";\n\n// this is compiled away so we need to import it from sources\nimport { defaultCacheSizes } from \"../sizes.js\";\n\nfunction sha256(data: string) {\n  const hash = crypto.createHash(\"sha256\");\n  hash.update(data);\n  return hash.digest(\"hex\");\n}\n\nconst defaultCacheSizesAsObject = {\n  canonicalStringify: defaultCacheSizes[\"canonicalStringify\"],\n  checkDocument: defaultCacheSizes[\"checkDocument\"],\n  print: defaultCacheSizes[\"print\"],\n  \"documentTransform.cache\": defaultCacheSizes[\"documentTransform.cache\"],\n  \"queryManager.getDocumentInfo\":\n    defaultCacheSizes[\"queryManager.getDocumentInfo\"],\n  \"PersistedQueryLink.persistedQueryHashes\":\n    defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"],\n  \"fragmentRegistry.transform\": defaultCacheSizes[\"fragmentRegistry.transform\"],\n  \"fragmentRegistry.lookup\": defaultCacheSizes[\"fragmentRegistry.lookup\"],\n  \"fragmentRegistry.findFragmentSpreads\":\n    defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"],\n  \"cache.fragmentQueryDocuments\":\n    defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n  \"removeTypenameFromVariables.getVariableDefinitions\":\n    defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"],\n  \"inMemoryCache.maybeBroadcastWatch\":\n    defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n  \"inMemoryCache.executeSelectionSet\":\n    defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n  \"inMemoryCache.executeSubSelectedArray\":\n    defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n};\n\nit(\"returns information about cache usage (empty caches)\", () => {\n  const client = new ApolloClient({\n    documentTransform: new DocumentTransform((x) => x, {\n      cache: true,\n    }).concat(\n      new DocumentTransform((x) => x, {\n        cache: true,\n      })\n    ),\n    cache: new InMemoryCache({\n      fragments: createFragmentRegistry(),\n    }),\n    link: new PersistedQueryLink({\n      sha256,\n    })\n      .concat(new RemoveTypenameFromVariablesLink())\n      .concat(ApolloLink.empty()),\n  });\n  expect(client.getMemoryInternals?.()).toEqual({\n    limits: defaultCacheSizesAsObject,\n    sizes: {\n      canonicalStringify: 0,\n      print: 0,\n      addTypenameDocumentTransform: [\n        {\n          cache: 0,\n        },\n      ],\n      queryManager: {\n        getDocumentInfo: 0,\n        documentTransforms: [\n          {\n            cache: 0,\n          },\n          {\n            cache: 0,\n          },\n        ],\n      },\n      fragmentRegistry: {\n        findFragmentSpreads: 0,\n        lookup: 0,\n        transform: 0,\n      },\n      cache: {\n        fragmentQueryDocuments: 0,\n      },\n      inMemoryCache: {\n        executeSelectionSet: 0,\n        executeSubSelectedArray: 0,\n        maybeBroadcastWatch: 0,\n      },\n      links: [\n        {\n          PersistedQueryLink: {\n            persistedQueryHashes: 0,\n          },\n        },\n        {\n          removeTypenameFromVariables: {\n            getVariableDefinitions: 0,\n          },\n        },\n      ],\n    },\n  });\n});\n\nit(\"returns information about cache usage (some query triggered)\", () => {\n  const client = new ApolloClient({\n    documentTransform: new DocumentTransform((x) => x, {\n      cache: true,\n    }).concat(\n      new DocumentTransform((x) => x, {\n        cache: true,\n      })\n    ),\n    cache: new InMemoryCache({\n      fragments: createFragmentRegistry(),\n    }),\n    link: new PersistedQueryLink({\n      sha256,\n    })\n      .concat(new RemoveTypenameFromVariablesLink())\n      .concat(ApolloLink.empty()),\n  });\n\n  client\n    .query({\n      query: gql`\n        query {\n          hello\n        }\n      `,\n    })\n    .catch(() => {});\n  expect(client.getMemoryInternals?.()).toStrictEqual({\n    limits: defaultCacheSizesAsObject,\n    sizes: {\n      canonicalStringify: 0,\n      print: 1,\n      addTypenameDocumentTransform: [\n        {\n          cache: 1,\n        },\n      ],\n      queryManager: {\n        getDocumentInfo: 1,\n        documentTransforms: [\n          {\n            cache: 1,\n          },\n          {\n            cache: 1,\n          },\n        ],\n      },\n      fragmentRegistry: {\n        findFragmentSpreads: 1,\n        lookup: 0,\n        transform: 1,\n      },\n      cache: {\n        fragmentQueryDocuments: 0,\n      },\n      inMemoryCache: {\n        executeSelectionSet: 1,\n        executeSubSelectedArray: 0,\n        maybeBroadcastWatch: 0,\n      },\n      links: [\n        {\n          PersistedQueryLink: {\n            persistedQueryHashes: 1,\n          },\n        },\n        {\n          removeTypenameFromVariables: {\n            getVariableDefinitions: 0,\n          },\n        },\n      ],\n    },\n  });\n});\n\nit(\"reports user-declared cacheSizes\", () => {\n  const client = new ApolloClient({\n    cache: new InMemoryCache({}),\n    link: ApolloLink.empty(),\n  });\n\n  cacheSizes[\"inMemoryCache.executeSubSelectedArray\"] = 90;\n\n  expect(client.getMemoryInternals?.().limits).toStrictEqual({\n    ...defaultCacheSizesAsObject,\n    \"inMemoryCache.executeSubSelectedArray\": 90,\n  });\n});\n"
  },
  {
    "path": "src/utilities/caching/__tests__/sizes.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport type { CacheSizes, defaultCacheSizes } from \"../sizes.js\";\n\ntest.skip(\"type tests\", () => {\n  expectTypeOf<keyof CacheSizes>().toMatchTypeOf<\n    keyof typeof defaultCacheSizes\n  >();\n  expectTypeOf<keyof typeof defaultCacheSizes>().toMatchTypeOf<\n    keyof CacheSizes\n  >();\n});\n"
  },
  {
    "path": "src/utilities/caching/index.ts",
    "content": "export type { CacheSizes } from \"./sizes.js\";\nexport { cacheSizes, defaultCacheSizes } from \"./sizes.js\";\n"
  },
  {
    "path": "src/utilities/caching/sizes.ts",
    "content": "import { global } from \"@apollo/client/utilities/internal/globals\";\n\ndeclare global {\n  interface Window {\n    [cacheSizeSymbol]?: Partial<CacheSizes>;\n  }\n}\n\n/**\n * The cache sizes used by various Apollo Client caches.\n *\n * @remarks\n * All configurable caches hold memoized values. If an item is\n * cache-collected, it incurs only a small performance impact and\n * doesn't cause data loss. A smaller cache size might save you memory.\n *\n * You should choose cache sizes appropriate for storing a reasonable\n * number of values rather than every value. To prevent too much recalculation,\n * choose cache sizes that are at least large enough to hold memoized values for\n * all hooks/queries on the screen at any given time.\n */\n/*\n * We assume a \"base value\" of 1000 here, which is already very generous.\n * In most applications, it will be very unlikely that 1000 different queries\n * are on screen at the same time.\n */\nexport interface CacheSizes {\n  /**\n   * Cache size for the [`print`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/print.ts) function.\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * This method is called to transform a GraphQL query AST parsed by `gql`\n   * back into a GraphQL string.\n   *\n   * @privateRemarks\n   * This method is called from the `QueryManager` and various `ApolloLink`s,\n   * always with the \"serverQuery\", so the server-facing part of a transformed\n   * `DocumentNode`.\n   */\n  print: number;\n  /**\n   * Cache size for the cache of [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts)\n   * instances with the `cache` option set to `true`.\n   *\n   * Can be called with user-defined or already-transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * The cache size here should be chosen with other `DocumentTransform`s in mind.\n   * For example, if there was a `DocumentTransform` that would take `x` `DocumentNode`s,\n   * and returned a differently-transformed `DocumentNode` depending if the app is\n   * online or offline, then we assume that the cache returns `2*x` documents.\n   * If that were concatenated with another `DocumentTransform` that would\n   * also duplicate the cache size, you'd need to account for `4*x` documents\n   * returned by the second transform.\n   *\n   * Due to an implementation detail of Apollo Client, if you use custom document\n   * transforms you should always add `n` (the \"base\" number of user-provided\n   * Documents) to the resulting cache size.\n   *\n   * If we assume that the user-provided transforms receive `n` documents and\n   * return `n` documents, the cache size should be `2*n`.\n   *\n   * If we assume that the chain of user-provided transforms receive `n` documents and\n   * return `4*n` documents, the cache size should be `5*n`.\n   *\n   * This size should also then be used in every other cache that mentions that\n   * it operates on a \"transformed\" `DocumentNode`.\n   *\n   * @privateRemarks\n   * Cache size for the `performWork` method of each [`DocumentTransform`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/graphql/DocumentTransform.ts).\n   *\n   * No user-provided DocumentNode will actually be \"the last one\", as we run the\n   * `defaultDocumentTransform` before _and_ after the user-provided transforms.\n   * For that reason, we need the extra `n` here - `n` for \"before transformation\"\n   * plus the actual maximum cache size of the user-provided transform chain.\n   *\n   * This method is called from `transformDocument`, which is called from\n   * `QueryManager` with a user-provided DocumentNode.\n   * It is also called with already-transformed DocumentNodes, assuming the\n   * user provided additional transforms.\n   */\n  \"documentTransform.cache\": number;\n  /**\n   * A cache inside of [`QueryManager`](https://github.com/apollographql/apollo-client/blob/main/src/core/QueryManager.ts).\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   * Cache size for the `transformCache` used in the `getDocumentInfo` method of `QueryManager`.\n   * Called throughout the `QueryManager` with transformed DocumentNodes.\n   */\n  \"queryManager.getDocumentInfo\": number;\n  /**\n   * A cache inside of [`PersistedQueryLink`](https://github.com/apollographql/apollo-client/blob/main/src/link/persisted-queries/index.ts).\n   *\n   * It is called with transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @remarks\n   * This cache is used to cache the hashes of persisted queries.\n   *\n   * @privateRemarks\n   * Cache size for the `hashesByQuery` cache in the `PersistedQueryLink`.\n   */\n  \"PersistedQueryLink.persistedQueryHashes\": number;\n  /**\n   * Cache used by [`canonicalStringify`](https://github.com/apollographql/apollo-client/blob/main/src/utilities/common/canonicalStringify.ts).\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * This cache contains the sorted keys of objects that are stringified by\n   * `canonicalStringify`.\n   * It uses the stringified unsorted keys of objects as keys.\n   * The cache will not grow beyond the size of different object **shapes**\n   * encountered in an application, no matter how much actual data gets stringified.\n   *\n   * @privateRemarks\n   * Cache size for the `sortingMap` in `canonicalStringify`.\n   */\n  canonicalStringify: number;\n  /**\n   * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * Can be called with user-defined or already-transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   *\n   * Cache size for the `transform` method of FragmentRegistry.\n   * This function is called as part of the `defaultDocumentTransform` which will be called with\n   * user-provided and already-transformed DocumentNodes.\n   */\n  \"fragmentRegistry.transform\": number;\n  /**\n   * A cache inside of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * This function is called with fragment names in the form of a string.\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * The size of this case should be chosen with the number of fragments in\n   * your application in mind.\n   *\n   * Note:\n   * This function is a dependency of `fragmentRegistry.transform`, so having too small of a cache size here\n   * might involuntarily invalidate values in the `transform` cache.\n   *\n   * @privateRemarks\n   * Cache size for the `lookup` method of FragmentRegistry.\n   */\n  \"fragmentRegistry.lookup\": number;\n  /**\n   * Cache size for the `findFragmentSpreads` method of [`FragmentRegistry`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/fragmentRegistry.ts).\n   *\n   * This function is called with transformed `DocumentNode`s, as well as recursively\n   * with every fragment spread referenced within that, or a fragment referenced by a\n   * fragment spread.\n   *\n   * @defaultValue\n   * Defaults to `4000`.\n   *\n   * @remarks\n   *\n   * Note: This function is a dependency of `fragmentRegistry.transform`, so having too small of cache size here\n   * might involuntarily invalidate values in the `transform` cache.\n   */\n  \"fragmentRegistry.findFragmentSpreads\": number;\n  /**\n   * Cache size for the `getFragmentDoc` method of [`ApolloCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/core/cache.ts).\n   *\n   * This function is called with user-provided fragment definitions.\n   *\n   * @defaultValue\n   * Defaults to `1000`.\n   *\n   * @remarks\n   * This function is called from `readFragment` with user-provided fragment definitions.\n   */\n  \"cache.fragmentQueryDocuments\": number;\n  /**\n   * Cache used in [`removeTypenameFromVariables`](https://github.com/apollographql/apollo-client/blob/main/src/link/remove-typename/removeTypenameFromVariables.ts).\n   *\n   * This function is called transformed `DocumentNode`s.\n   *\n   * @defaultValue\n   * Defaults to `2000`.\n   *\n   * @privateRemarks\n   * Cache size for the `getVariableDefinitions` function of `removeTypenameFromVariables`.\n   */\n  \"removeTypenameFromVariables.getVariableDefinitions\": number;\n  /**\n   * Cache size for the `maybeBroadcastWatch` method on [`InMemoryCache`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/inMemoryCache.ts).\n   *\n   * @defaultValue\n   * Defaults to `5000`.\n   *\n   * @remarks\n   * This method is used for dependency tracking in the `InMemoryCache` and\n   * prevents from unnecessary re-renders.\n   * It is recommended to keep this value significantly higher than the number of\n   * possible subscribers you will have active at the same time in your application\n   * at any time.\n   */\n  \"inMemoryCache.maybeBroadcastWatch\": number;\n  /**\n   * Cache size for the `executeSelectionSet` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n   *\n   * @defaultValue\n   * Defaults to `50000`.\n   *\n   * @remarks\n   * Every object that is read from the cache will be cached here, so it is\n   * recommended to set this to a high value.\n   */\n  \"inMemoryCache.executeSelectionSet\": number;\n  /**\n   * Cache size for the `executeSubSelectedArray` method on [`StoreReader`](https://github.com/apollographql/apollo-client/blob/main/src/cache/inmemory/readFromStore.ts).\n   *\n   * @defaultValue\n   * Defaults to `10000`.\n   *\n   * @remarks\n   * Every array that is read from the cache will be cached here, so it is\n   * recommended to set this to a high value.\n   */\n  \"inMemoryCache.executeSubSelectedArray\": number;\n  /**\n   * Used by the internal `checkDocument` that traverses GraphQL documents and throws an error if the document is invalid.\n   * if they are not valid.\n   */\n  checkDocument: number;\n}\n\nconst cacheSizeSymbol = Symbol.for(\"apollo.cacheSize\");\n/**\n * The global cache size configuration for Apollo Client.\n *\n * @remarks\n *\n * You can directly modify this object, but any modification will\n * only have an effect on caches that are created after the modification.\n *\n * So for global caches, such as `canonicalStringify` and `print`,\n * you might need to call `.reset` on them, which will essentially re-create them.\n *\n * Alternatively, you can set `globalThis[Symbol.for(\"apollo.cacheSize\")]` before\n * you load the Apollo Client package:\n *\n * @example\n *\n * ```ts\n * globalThis[Symbol.for(\"apollo.cacheSize\")] = {\n *   print: 100,\n * } satisfies Partial<CacheSizes>; // the `satisfies` is optional if using TypeScript\n * ```\n */\nexport const cacheSizes: Partial<CacheSizes> = { ...global[cacheSizeSymbol] };\n\nexport const enum defaultCacheSizes {\n  checkDocument = 2000,\n  canonicalStringify = 1000,\n  print = 2000,\n  \"documentTransform.cache\" = 2000,\n  \"queryManager.getDocumentInfo\" = 2000,\n  \"PersistedQueryLink.persistedQueryHashes\" = 2000,\n  \"fragmentRegistry.transform\" = 2000,\n  \"fragmentRegistry.lookup\" = 1000,\n  \"fragmentRegistry.findFragmentSpreads\" = 4000,\n  \"cache.fragmentQueryDocuments\" = 1000,\n  \"removeTypenameFromVariables.getVariableDefinitions\" = 2000,\n  \"inMemoryCache.maybeBroadcastWatch\" = 5000,\n  \"inMemoryCache.executeSelectionSet\" = 50000,\n  \"inMemoryCache.executeSubSelectedArray\" = 10000,\n}\n"
  },
  {
    "path": "src/utilities/common/__tests__/canonicalStringify.ts",
    "content": "import { canonicalStringify } from \"@apollo/client/utilities\";\n\nfunction forEachPermutation(\n  keys: string[],\n  callback: (permutation: string[]) => void\n) {\n  if (keys.length <= 1) {\n    callback(keys);\n    return;\n  }\n  const first = keys[0];\n  const rest = keys.slice(1);\n  forEachPermutation(rest, (permutation) => {\n    for (let i = 0; i <= permutation.length; ++i) {\n      callback([...permutation.slice(0, i), first, ...permutation.slice(i)]);\n    }\n  });\n}\n\nfunction allObjectPermutations<T extends Record<string, any>>(obj: T) {\n  const keys = Object.keys(obj);\n  const permutations: T[] = [];\n  forEachPermutation(keys, (permutation) => {\n    const permutationObj = Object.create(Object.getPrototypeOf(obj));\n    permutation.forEach((key) => {\n      permutationObj[key] = obj[key];\n    });\n    permutations.push(permutationObj);\n  });\n  return permutations;\n}\n\ndescribe(\"canonicalStringify\", () => {\n  beforeEach(() => {\n    canonicalStringify.reset();\n  });\n\n  it(\"should not modify original object\", () => {\n    const obj = { c: 3, a: 1, b: 2 };\n    expect(canonicalStringify(obj)).toBe('{\"a\":1,\"b\":2,\"c\":3}');\n    expect(Object.keys(obj)).toEqual([\"c\", \"a\", \"b\"]);\n  });\n\n  it(\"forEachPermutation should work\", () => {\n    const permutations: string[][] = [];\n    forEachPermutation([\"a\", \"b\", \"c\"], (permutation) => {\n      permutations.push(permutation);\n    });\n    expect(permutations).toEqual([\n      [\"a\", \"b\", \"c\"],\n      [\"b\", \"a\", \"c\"],\n      [\"b\", \"c\", \"a\"],\n      [\"a\", \"c\", \"b\"],\n      [\"c\", \"a\", \"b\"],\n      [\"c\", \"b\", \"a\"],\n    ]);\n  });\n\n  it(\"canonicalStringify should stably stringify all permutations of an object\", () => {\n    const unstableStrings = new Set<string>();\n    const stableStrings = new Set<string>();\n\n    allObjectPermutations({\n      c: 3,\n      a: 1,\n      b: 2,\n    }).forEach((obj) => {\n      unstableStrings.add(JSON.stringify(obj));\n      stableStrings.add(canonicalStringify(obj));\n\n      expect(canonicalStringify(obj)).toBe('{\"a\":1,\"b\":2,\"c\":3}');\n\n      allObjectPermutations({\n        z: \"z\",\n        y: [\"y\", obj, \"why\"],\n        x: \"x\",\n      }).forEach((parent) => {\n        expect(canonicalStringify(parent)).toBe(\n          '{\"x\":\"x\",\"y\":[\"y\",{\"a\":1,\"b\":2,\"c\":3},\"why\"],\"z\":\"z\"}'\n        );\n      });\n    });\n\n    expect(unstableStrings.size).toBe(6);\n    expect(stableStrings.size).toBe(1);\n  });\n\n  it(\"should not modify keys of custom-prototype objects\", () => {\n    class Custom {\n      z = \"z\";\n      y = \"y\";\n      x = \"x\";\n      b = \"b\";\n      a = \"a\";\n      c = \"c\";\n    }\n\n    const obj = {\n      z: \"z\",\n      x: \"x\",\n      y: new Custom(),\n    };\n\n    expect(Object.keys(obj.y)).toEqual([\"z\", \"y\", \"x\", \"b\", \"a\", \"c\"]);\n\n    expect(canonicalStringify(obj)).toBe(\n      '{\"x\":\"x\",\"y\":{\"z\":\"z\",\"y\":\"y\",\"x\":\"x\",\"b\":\"b\",\"a\":\"a\",\"c\":\"c\"},\"z\":\"z\"}'\n    );\n  });\n});\n"
  },
  {
    "path": "src/utilities/common/__tests__/stripTypename.ts",
    "content": "import { stripTypename } from \"@apollo/client/utilities\";\n\ntest(\"omits __typename from a shallow object\", () => {\n  expect(\n    stripTypename({ __typename: \"Person\", firstName: \"Foo\", lastName: \"Bar\" })\n  ).toEqual({ firstName: \"Foo\", lastName: \"Bar\" });\n});\n\ntest(\"omits __typename from arbitrarily nested object\", () => {\n  expect(\n    stripTypename({\n      __typename: \"Profile\",\n      user: {\n        __typename: \"User\",\n        firstName: \"Foo\",\n        lastName: \"Bar\",\n        location: {\n          __typename: \"Location\",\n          city: \"Denver\",\n          country: \"USA\",\n        },\n      },\n    })\n  ).toEqual({\n    user: {\n      firstName: \"Foo\",\n      lastName: \"Bar\",\n      location: {\n        city: \"Denver\",\n        country: \"USA\",\n      },\n    },\n  });\n});\n\ntest(\"omits the __typename from arrays\", () => {\n  expect(\n    stripTypename([\n      { __typename: \"Todo\", name: \"Take out trash\" },\n      { __typename: \"Todo\", name: \"Clean room\" },\n    ])\n  ).toEqual([{ name: \"Take out trash\" }, { name: \"Clean room\" }]);\n});\n\ntest(\"omits __typename from arbitrarily nested arrays\", () => {\n  expect(\n    stripTypename([\n      [{ __typename: \"Foo\", foo: \"foo\" }],\n      [{ __typename: \"Bar\", bar: \"bar\" }, [{ __typename: \"Baz\", baz: \"baz\" }]],\n    ])\n  ).toEqual([[{ foo: \"foo\" }], [{ bar: \"bar\" }, [{ baz: \"baz\" }]]]);\n});\n\ntest(\"returns primitives unchanged\", () => {\n  expect(stripTypename(\"a\")).toBe(\"a\");\n  expect(stripTypename(1)).toBe(1);\n  expect(stripTypename(true)).toBe(true);\n  expect(stripTypename(null)).toBe(null);\n  expect(stripTypename(undefined)).toBe(undefined);\n});\n"
  },
  {
    "path": "src/utilities/common/stripTypename.ts",
    "content": "import { omitDeep } from \"@apollo/client/utilities/internal\";\n\n/**\n * Deeply removes all `__typename` properties in the given object or array.\n *\n * @param value - The object or array that should have `__typename` removed.\n * @returns The object with all `__typename` properties removed.\n *\n * @example\n *\n * ```ts\n * stripTypename({\n *   __typename: \"User\",\n *   id: 1,\n *   profile: { __typename: \"Profile\", name: \"John Doe\" },\n * });\n * // => { id: 1, profile: { name: \"John Doe\"}}\n * ```\n */\nexport function stripTypename<T>(value: T) {\n  return omitDeep(value, \"__typename\");\n}\n"
  },
  {
    "path": "src/utilities/environment/index.development.ts",
    "content": "export const __DEV__ = true as boolean;\n"
  },
  {
    "path": "src/utilities/environment/index.production.ts",
    "content": "export const __DEV__ = false as boolean;\n"
  },
  {
    "path": "src/utilities/environment/index.ts",
    "content": "declare const globalThis: { __DEV__?: boolean };\n\nexport const __DEV__: boolean = globalThis.__DEV__ === true;\n"
  },
  {
    "path": "src/utilities/graphql/DocumentTransform.ts",
    "content": "import { WeakCache } from \"@wry/caches\";\nimport { Trie } from \"@wry/trie\";\nimport type { DocumentNode } from \"graphql\";\nimport { wrap } from \"optimism\";\n\nimport { checkDocument } from \"@apollo/client/utilities/internal\";\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { cacheSizes } from \"../caching/sizes.js\";\n\nexport type DocumentTransformCacheKey = ReadonlyArray<unknown>;\n\ntype TransformFn = (document: DocumentNode) => DocumentNode;\n\ninterface DocumentTransformOptions {\n  /**\n   * Determines whether to cache the transformed GraphQL document. Caching can\n   * speed up repeated calls to the document transform for the same input\n   * document. Set to `false` to completely disable caching for the document\n   * transform. When disabled, this option takes precedence over the [`getCacheKey`](#getcachekey)\n   * option.\n   *\n   * @defaultValue `true`\n   */\n  cache?: boolean;\n  /**\n   * Defines a custom cache key for a GraphQL document that will determine whether to re-run the document transform when given the same input GraphQL document. Returns an array that defines the cache key. Return `undefined` to disable caching for that GraphQL document.\n   *\n   * > [!NOTE]\n   * > The items in the array can be any type, but each item needs to be\n   * > referentially stable to guarantee a stable cache key.\n   *\n   * @defaultValue `(document) => [document]`\n   */\n  getCacheKey?: (\n    document: DocumentNode\n  ) => DocumentTransformCacheKey | undefined;\n}\n\nfunction identity(document: DocumentNode) {\n  return document;\n}\n\n/**\n * A class for transforming GraphQL documents. See the [Document transforms\n * documentation](https://www.apollographql.com/docs/react/data/document-transforms) for more details on using them.\n *\n * @example\n *\n * ```ts\n * import { DocumentTransform } from \"@apollo/client/utilities\";\n * import { visit } from \"graphql\";\n *\n * const documentTransform = new DocumentTransform((doc) => {\n *   return visit(doc, {\n *     // ...\n *   });\n * });\n *\n * const transformedDoc = documentTransform.transformDocument(myDocument);\n * ```\n */\nexport class DocumentTransform {\n  private readonly transform: TransformFn;\n  private cached: boolean;\n\n  private readonly resultCache = new WeakSet<DocumentNode>();\n\n  // This default implementation of getCacheKey can be overridden by providing\n  // options.getCacheKey to the DocumentTransform constructor. In general, a\n  // getCacheKey function may either return an array of keys (often including\n  // the document) to be used as a cache key, or undefined to indicate the\n  // transform for this document should not be cached.\n  private getCacheKey(\n    document: DocumentNode\n  ): DocumentTransformCacheKey | undefined {\n    return [document];\n  }\n\n  /**\n   * Creates a DocumentTransform that returns the input document unchanged.\n   *\n   * @returns The input document\n   */\n  static identity() {\n    // No need to cache this transform since it just returns the document\n    // unchanged. This should save a bit of memory that would otherwise be\n    // needed to populate the `documentCache` of this transform.\n    return new DocumentTransform(identity, { cache: false });\n  }\n\n  /**\n   * Creates a DocumentTransform that conditionally applies one of two transforms.\n   *\n   * @param predicate - Function that determines which transform to apply\n   * @param left - Transform to apply when `predicate` returns `true`\n   * @param right - Transform to apply when `predicate` returns `false`. If not provided, it defaults to `DocumentTransform.identity()`.\n   * @returns A DocumentTransform that conditionally applies a document transform based on the predicate\n   *\n   * @example\n   *\n   * ```ts\n   * import { isQueryOperation } from \"@apollo/client/utilities\";\n   *\n   * const conditionalTransform = DocumentTransform.split(\n   *   (document) => isQueryOperation(document),\n   *   queryTransform,\n   *   mutationTransform\n   * );\n   * ```\n   */\n  static split(\n    predicate: (document: DocumentNode) => boolean,\n    left: DocumentTransform,\n    right: DocumentTransform = DocumentTransform.identity()\n  ) {\n    return Object.assign(\n      new DocumentTransform(\n        (document) => {\n          const documentTransform = predicate(document) ? left : right;\n\n          return documentTransform.transformDocument(document);\n        },\n        // Reasonably assume both `left` and `right` transforms handle their own caching\n        { cache: false }\n      ),\n      { left, right }\n    );\n  }\n\n  constructor(transform: TransformFn, options: DocumentTransformOptions = {}) {\n    this.transform = transform;\n\n    if (options.getCacheKey) {\n      // Override default `getCacheKey` function, which returns [document].\n      this.getCacheKey = options.getCacheKey;\n    }\n    this.cached = options.cache !== false;\n\n    this.resetCache();\n  }\n\n  /**\n   * Resets the internal cache of this transform, if it is cached.\n   */\n  resetCache() {\n    if (this.cached) {\n      const stableCacheKeys = new Trie<WeakKey>();\n      this.performWork = wrap(\n        DocumentTransform.prototype.performWork.bind(this),\n        {\n          makeCacheKey: (document) => {\n            const cacheKeys = this.getCacheKey(document);\n            if (cacheKeys) {\n              invariant(\n                Array.isArray(cacheKeys),\n                \"`getCacheKey` must return an array or undefined\"\n              );\n              return stableCacheKeys.lookupArray(cacheKeys);\n            }\n          },\n          max: cacheSizes[\"documentTransform.cache\"],\n          cache: WeakCache<any, any>,\n        }\n      );\n    }\n  }\n\n  private performWork(document: DocumentNode) {\n    checkDocument(document);\n    return this.transform(document);\n  }\n\n  /**\n   * Transforms a GraphQL document using the configured transform function.\n   *\n   * @remarks\n   *\n   * Note that `transformDocument` caches the transformed document. Calling\n   * `transformDocument` again with the already-transformed document will\n   * immediately return it.\n   *\n   * @param document - The GraphQL document to transform\n   * @returns The transformed document\n   *\n   * @example\n   *\n   * ```ts\n   * const document = gql`\n   *   # ...\n   * `;\n   *\n   * const documentTransform = new DocumentTransform(transformFn);\n   * const transformedDocument = documentTransform.transformDocument(document);\n   * ```\n   */\n  transformDocument(document: DocumentNode) {\n    // If a user passes an already transformed result back to this function,\n    // immediately return it.\n    if (this.resultCache.has(document)) {\n      return document;\n    }\n\n    const transformedDocument = this.performWork(document);\n\n    this.resultCache.add(transformedDocument);\n\n    return transformedDocument;\n  }\n\n  /**\n   * Combines this document transform with another document transform. The\n   * returned document transform first applies the current document transform,\n   * then applies the other document transform.\n   *\n   * @param otherTransform - The transform to apply after this one\n   * @returns A new DocumentTransform that applies both transforms in sequence\n   *\n   * @example\n   *\n   * ```ts\n   * const combinedTransform = addTypenameTransform.concat(\n   *   removeDirectivesTransform\n   * );\n   * ```\n   */\n  concat(otherTransform: DocumentTransform): DocumentTransform {\n    return Object.assign(\n      new DocumentTransform(\n        (document) => {\n          return otherTransform.transformDocument(\n            this.transformDocument(document)\n          );\n        },\n        // Reasonably assume both transforms handle their own caching\n        { cache: false }\n      ),\n      {\n        left: this,\n        right: otherTransform,\n      }\n    );\n  }\n\n  /**\n   * @internal\n   * Used to iterate through all transforms that are concatenations or `split` links.\n   */\n  readonly left?: DocumentTransform;\n  /**\n   * @internal\n   * Used to iterate through all transforms that are concatenations or `split` links.\n   */\n  readonly right?: DocumentTransform;\n}\n"
  },
  {
    "path": "src/utilities/graphql/__tests__/DocumentTransform.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport { Kind, visit } from \"graphql\";\nimport { gql } from \"graphql-tag\";\n\nimport {\n  DocumentTransform,\n  isMutationOperation,\n  isQueryOperation,\n} from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\n\nfunction stripDirective(directive: string) {\n  return (document: DocumentNode) => {\n    return removeDirectivesFromDocument([{ name: directive }], document)!;\n  };\n}\n\nfunction renameDirective(target: string, replacement: string) {\n  return (document: DocumentNode) => {\n    return visit(document, {\n      Directive(node) {\n        if (node.name.value === target) {\n          return {\n            ...node,\n            name: { kind: Kind.NAME, value: replacement },\n          };\n        }\n      },\n    });\n  };\n}\n\nfunction addClientDirectiveToField(fieldName: string) {\n  return (document: DocumentNode) => {\n    return visit(document, {\n      Field: {\n        leave: (node) => {\n          if (node.name.value === fieldName) {\n            return {\n              ...node,\n              directives: [\n                {\n                  kind: Kind.DIRECTIVE,\n                  name: { kind: Kind.NAME, value: \"client\" },\n                },\n              ],\n            };\n          }\n        },\n      },\n    });\n  };\n}\n\ntest(\"can transform a document\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const transform = new DocumentTransform(stripDirective(\"client\"));\n\n  const result = transform.transformDocument(query);\n\n  expect(result).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n});\n\ntest(\"returns unmodified document if trying to transform an already computed result\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name @custom\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const cachedTransform = new DocumentTransform(stripDirective(\"client\"));\n  const uncachedTransform = new DocumentTransform(stripDirective(\"custom\"), {\n    cache: false,\n  });\n\n  const withoutClient = cachedTransform.transformDocument(query);\n  const withoutCustom = uncachedTransform.transformDocument(query);\n\n  expect(cachedTransform.transformDocument(withoutClient)).toBe(withoutClient);\n\n  expect(uncachedTransform.transformDocument(withoutCustom)).toBe(\n    withoutCustom\n  );\n});\n\ntest(\"caches the result of the transform by default\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const transform = jest.fn(stripDirective(\"client\"));\n  const documentTransform = new DocumentTransform(transform);\n\n  const result1 = documentTransform.transformDocument(query);\n\n  expect(result1).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n});\n\ntest(\"allows custom cache keys to be defined\", () => {\n  const query = gql`\n    query TestQuery {\n      user @network {\n        name\n      }\n    }\n  `;\n\n  const onlineQuery = gql`\n    query TestQuery {\n      user {\n        name\n      }\n    }\n  `;\n\n  const offlineQuery = gql`\n    query TestQuery {\n      user @client {\n        name\n      }\n    }\n  `;\n\n  let online = true;\n\n  const onlineTransform = new DocumentTransform(stripDirective(\"network\"));\n  const offlineTransform = new DocumentTransform(\n    renameDirective(\"network\", \"client\")\n  );\n\n  const transform = jest.fn((document: DocumentNode) => {\n    return online ?\n        onlineTransform.transformDocument(document)\n      : offlineTransform.transformDocument(document);\n  });\n\n  const documentTransform = new DocumentTransform(transform, {\n    getCacheKey: (document) => [document, online],\n  });\n\n  const result1 = documentTransform.transformDocument(query);\n\n  expect(result1).toMatchDocument(onlineQuery);\n  expect(transform).toHaveBeenCalledTimes(1);\n\n  online = false;\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(offlineQuery);\n  expect(transform).toHaveBeenCalledTimes(2);\n\n  online = true;\n\n  const result3 = documentTransform.transformDocument(query);\n\n  expect(result3).toMatchDocument(onlineQuery);\n  expect(transform).toHaveBeenCalledTimes(2);\n\n  online = false;\n\n  const result4 = documentTransform.transformDocument(query);\n\n  expect(result4).toMatchDocument(offlineQuery);\n  expect(transform).toHaveBeenCalledTimes(2);\n});\n\ntest(\"can disable caching the result output\", () => {\n  const query = gql`\n    query {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const transform = jest.fn(stripDirective(\"client\"));\n  const documentTransform = new DocumentTransform(transform, { cache: false });\n\n  const result1 = documentTransform.transformDocument(query);\n\n  expect(result1).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(2);\n});\n\ntest(\"can combine 2 transforms with `concat`\", async () => {\n  const query = gql`\n    query TestQuery {\n      user @nonreactive {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const stripClient = new DocumentTransform(stripDirective(\"client\"));\n  const stripNonReactive = new DocumentTransform(stripDirective(\"nonreactive\"));\n  const documentTransform = stripClient.concat(stripNonReactive);\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n});\n\ntest(\"runs concatenated transform after original transform\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const addClientDirectiveToName = new DocumentTransform(\n    addClientDirectiveToField(\"name\")\n  );\n\n  expect(addClientDirectiveToName.transformDocument(query)).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name @client\n        isLoggedIn @client\n      }\n    }\n  `);\n\n  const stripClient = new DocumentTransform(stripDirective(\"client\"));\n  const documentTransform = addClientDirectiveToName.concat(stripClient);\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(expected);\n});\n\ntest(\"can combine multiple transforms with `concat`\", async () => {\n  const query = gql`\n    query TestQuery {\n      user @nonreactive {\n        name @connection\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const stripClient = new DocumentTransform(stripDirective(\"client\"));\n  const stripNonReactive = new DocumentTransform(stripDirective(\"nonreactive\"));\n  const stripConnection = new DocumentTransform(stripDirective(\"connection\"));\n  const documentTransform = stripClient\n    .concat(stripNonReactive)\n    .concat(stripConnection);\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n});\n\ntest(\"caches the result output from a combined transform when both transforms are cached\", async () => {\n  const query = gql`\n    query TestQuery {\n      user @nonreactive {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const stripClient = jest.fn(stripDirective(\"client\"));\n  const stripNonReactive = jest.fn(stripDirective(\"nonreactive\"));\n\n  const stripClientTransform = new DocumentTransform(stripClient);\n  const stripNonReactiveTransform = new DocumentTransform(stripNonReactive);\n  const documentTransform = stripClientTransform.concat(\n    stripNonReactiveTransform\n  );\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(expected);\n  expect(stripClient).toHaveBeenCalledTimes(1);\n  expect(stripNonReactive).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  expect(stripClient).toHaveBeenCalledTimes(1);\n  expect(stripNonReactive).toHaveBeenCalledTimes(1);\n});\n\ntest(\"allows non cached transforms to be run when concatenated\", async () => {\n  const query = gql`\n    query TestQuery {\n      user @nonreactive {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const stripClient = jest.fn(stripDirective(\"client\"));\n  const stripNonReactive = jest.fn(stripDirective(\"nonreactive\"));\n\n  const stripClientTransform = new DocumentTransform(stripClient, {\n    cache: true,\n  });\n  const stripNonReactiveTransform = new DocumentTransform(stripNonReactive, {\n    cache: false,\n  });\n\n  // Try ordering the transforms both ways to ensure the cached transform has\n  // no effect on whether the non-cached transform runs\n  const documentTransform =\n    stripNonReactiveTransform.concat(stripClientTransform);\n\n  const reversedTransform = stripClientTransform.concat(\n    stripNonReactiveTransform\n  );\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(expected);\n  expect(stripClient).toHaveBeenCalledTimes(1);\n  expect(stripNonReactive).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  // Even though stripClient is cached, it is called a second time because\n  // stripNonReactive returns a new document instance each time it runs.\n  expect(stripClient).toHaveBeenCalledTimes(2);\n  expect(stripNonReactive).toHaveBeenCalledTimes(2);\n\n  stripClient.mockClear();\n  stripNonReactive.mockClear();\n\n  const reversed = reversedTransform.transformDocument(query);\n\n  expect(reversed).toMatchDocument(expected);\n  expect(stripClient).toHaveBeenCalledTimes(1);\n  expect(stripNonReactive).toHaveBeenCalledTimes(1);\n\n  const reversed2 = reversedTransform.transformDocument(query);\n\n  expect(reversed2).toMatchDocument(expected);\n  // Now that the cached transform is first, we can make sure it doesn't run\n  // again. We verify the non-cached that is run after the cached transform does\n  // get a chance to execute.\n  expect(stripClient).toHaveBeenCalledTimes(1);\n  expect(stripNonReactive).toHaveBeenCalledTimes(2);\n});\n\ntest(\"can conditionally run transforms using `DocumentTransform.split`\", () => {\n  const mutation = gql`\n    mutation TestMutation {\n      incrementCounter @client {\n        count\n      }\n    }\n  `;\n\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const documentTransform = DocumentTransform.split(\n    isQueryOperation,\n    new DocumentTransform(stripDirective(\"client\"))\n  );\n\n  const queryResult = documentTransform.transformDocument(query);\n  const mutationResult = documentTransform.transformDocument(mutation);\n\n  expect(queryResult).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n\n  expect(mutationResult).toMatchDocument(mutation);\n});\n\ntest(\"properly caches the result of `filter` when the original transform is cached\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const transform = jest.fn(stripDirective(\"client\"));\n  const documentTransform = DocumentTransform.split(\n    isQueryOperation,\n    new DocumentTransform(transform, { cache: true })\n  );\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n});\n\ntest(\"reruns transform returned from `DocumentTransform.split` when the original transform is not cached\", () => {\n  const query = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const expected = gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `;\n\n  const transform = jest.fn(stripDirective(\"client\"));\n  const documentTransform = DocumentTransform.split(\n    isQueryOperation,\n    new DocumentTransform(transform, { cache: false })\n  );\n\n  const result = documentTransform.transformDocument(query);\n\n  expect(result).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(1);\n\n  const result2 = documentTransform.transformDocument(query);\n\n  expect(result2).toMatchDocument(expected);\n  expect(transform).toHaveBeenCalledTimes(2);\n});\n\ntest(\"properly handles combinations of `DocumentTransform.split` and `filter`\", () => {\n  const mutation = gql`\n    mutation TestMutation {\n      incrementCounter @client {\n        count @nonreactive\n      }\n    }\n  `;\n\n  const query = gql`\n    query TestQuery {\n      user {\n        name @nonreactive\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const stripClient = new DocumentTransform(stripDirective(\"client\"));\n  const stripNonReactive = new DocumentTransform(stripDirective(\"nonreactive\"));\n\n  // Strip both @client and @nonreactive but only on query types\n  const queryOnlyTransform = DocumentTransform.split(\n    isQueryOperation,\n    stripClient.concat(stripNonReactive)\n  );\n\n  // Only strip @client from mutations but remove @nonreactive from all\n  const conditionalStrip = DocumentTransform.split(\n    isMutationOperation,\n    stripClient\n  ).concat(stripNonReactive);\n\n  expect(queryOnlyTransform.transformDocument(query)).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n\n  expect(queryOnlyTransform.transformDocument(mutation)).toMatchDocument(\n    mutation\n  );\n\n  expect(conditionalStrip.transformDocument(query)).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `);\n\n  expect(conditionalStrip.transformDocument(mutation)).toMatchDocument(gql`\n    mutation TestMutation {\n      incrementCounter {\n        count\n      }\n    }\n  `);\n});\n\ntest(\"executes other transform when using `DocumentTransform.split` when condition is false\", () => {\n  const mutation = gql`\n    mutation TestMutation {\n      incrementCounter @client {\n        count @nonreactive\n      }\n    }\n  `;\n\n  const query = gql`\n    query TestQuery {\n      user {\n        name @nonreactive\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const stripClient = new DocumentTransform(stripDirective(\"client\"));\n  const stripNonReactive = new DocumentTransform(stripDirective(\"nonreactive\"));\n\n  // strip both directives for queries, but only @nonreactive for mutations\n  const documentTransform = DocumentTransform.split(\n    isQueryOperation,\n    stripClient.concat(stripNonReactive),\n    stripNonReactive\n  );\n\n  expect(documentTransform.transformDocument(query)).toMatchDocument(gql`\n    query TestQuery {\n      user {\n        name\n        isLoggedIn\n      }\n    }\n  `);\n\n  expect(documentTransform.transformDocument(mutation)).toMatchDocument(gql`\n    mutation TestMutation {\n      incrementCounter @client {\n        count\n      }\n    }\n  `);\n});\n\ntest(\"errors when passing a document that has not been parsed with `gql`\", () => {\n  const query = `\n    query TestQuery {\n      user {\n        name\n        isLoggedIn @client\n      }\n    }\n  `;\n\n  const documentTransform = new DocumentTransform((document) => document);\n\n  expect(() => {\n    documentTransform.transformDocument(query as unknown as DocumentNode);\n  }).toThrow(/wrap the query string in a \"gql\" tag/);\n});\n"
  },
  {
    "path": "src/utilities/graphql/__tests__/transform.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport { Kind, print } from \"graphql\";\nimport { disableFragmentWarnings, gql } from \"graphql-tag\";\n\n// Turn off warnings for repeated fragment names\ndisableFragmentWarnings();\n\nimport { addTypenameToDocument } from \"@apollo/client/utilities\";\nimport { getQueryDefinition } from \"@apollo/client/utilities/internal\";\n\ndescribe(\"query transforms\", () => {\n  it(\"should correctly add typenames\", () => {\n    let testQuery = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n          }\n        }\n      }\n    `;\n    const newQueryDoc = addTypenameToDocument(testQuery);\n\n    const expectedQuery = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n            __typename\n          }\n          __typename\n        }\n      }\n    `;\n    const expectedQueryStr = print(expectedQuery);\n\n    expect(print(newQueryDoc)).toBe(expectedQueryStr);\n  });\n\n  it(\"should not add duplicates\", () => {\n    let testQuery = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n            __typename\n          }\n        }\n      }\n    `;\n    const newQueryDoc = addTypenameToDocument(testQuery);\n\n    const expectedQuery = gql`\n      query {\n        author {\n          name {\n            firstName\n            lastName\n            __typename\n          }\n          __typename\n        }\n      }\n    `;\n    const expectedQueryStr = print(expectedQuery);\n\n    expect(print(newQueryDoc)).toBe(expectedQueryStr);\n  });\n\n  it(\"should not screw up on a FragmentSpread within the query AST\", () => {\n    const testQuery = gql`\n      query withFragments {\n        user(id: 4) {\n          friends(first: 10) {\n            ...friendFields\n          }\n        }\n      }\n    `;\n    const expectedQuery = getQueryDefinition(gql`\n      query withFragments {\n        user(id: 4) {\n          friends(first: 10) {\n            ...friendFields\n            __typename\n          }\n          __typename\n        }\n      }\n    `);\n    const modifiedQuery = addTypenameToDocument(testQuery);\n    expect(print(expectedQuery)).toBe(print(getQueryDefinition(modifiedQuery)));\n  });\n\n  it(\"should modify all definitions in a document\", () => {\n    const testQuery = gql`\n      query withFragments {\n        user(id: 4) {\n          friends(first: 10) {\n            ...friendFields\n          }\n        }\n      }\n\n      fragment friendFields on User {\n        firstName\n        lastName\n      }\n    `;\n\n    const newQueryDoc = addTypenameToDocument(testQuery);\n\n    const expectedQuery = gql`\n      query withFragments {\n        user(id: 4) {\n          friends(first: 10) {\n            ...friendFields\n            __typename\n          }\n          __typename\n        }\n      }\n\n      fragment friendFields on User {\n        firstName\n        lastName\n        __typename\n      }\n    `;\n\n    expect(print(expectedQuery)).toBe(print(newQueryDoc));\n  });\n\n  it(\"should be capable of modifying any ASTNode\", () => {\n    const originalQuery = gql`\n      query withFragments {\n        user(id: 4) {\n          friends(first: 10) {\n            ...friendFields\n          }\n        }\n      }\n\n      fragment friendFields on User {\n        firstName\n        lastName\n      }\n    `;\n\n    const fragmentSubtree: DocumentNode = {\n      ...originalQuery,\n      definitions: originalQuery.definitions.map((def) => {\n        if (def.kind === Kind.FRAGMENT_DEFINITION) {\n          return addTypenameToDocument(def);\n        }\n        return def;\n      }),\n    };\n\n    expect(print(fragmentSubtree)).toEqual(\n      print(gql`\n        query withFragments {\n          user(id: 4) {\n            friends(first: 10) {\n              ...friendFields\n            }\n          }\n        }\n\n        fragment friendFields on User {\n          firstName\n          lastName\n          __typename\n        }\n      `)\n    );\n\n    const userFieldSubtree: DocumentNode = {\n      ...originalQuery,\n      definitions: originalQuery.definitions.map((def) => {\n        if (def.kind === Kind.OPERATION_DEFINITION) {\n          return {\n            ...def,\n            selectionSet: {\n              ...def.selectionSet,\n              selections: def.selectionSet.selections.map((selection) => {\n                if (\n                  selection.kind === Kind.FIELD &&\n                  selection.name.value === \"user\"\n                ) {\n                  return addTypenameToDocument(selection);\n                }\n                return selection;\n              }),\n            },\n          };\n        }\n        return def;\n      }),\n    };\n\n    expect(print(userFieldSubtree)).toEqual(\n      print(gql`\n        query withFragments {\n          user(id: 4) {\n            friends(first: 10) {\n              ...friendFields\n              __typename\n            }\n            __typename\n          }\n        }\n\n        fragment friendFields on User {\n          firstName\n          lastName\n        }\n      `)\n    );\n\n    const wholeQueryFromJustTheFragment =\n      addTypenameToDocument(userFieldSubtree);\n\n    const wholeQueryFromUserFieldSubtree =\n      addTypenameToDocument(fragmentSubtree);\n\n    expect(print(wholeQueryFromUserFieldSubtree)).toEqual(\n      print(wholeQueryFromJustTheFragment)\n    );\n\n    expect(print(wholeQueryFromUserFieldSubtree)).toEqual(\n      print(gql`\n        query withFragments {\n          user(id: 4) {\n            friends(first: 10) {\n              ...friendFields\n              __typename\n            }\n            __typename\n          }\n        }\n\n        fragment friendFields on User {\n          firstName\n          lastName\n          __typename\n        }\n      `)\n    );\n  });\n\n  it(\"should be able to apply a QueryTransformer correctly\", () => {\n    const testQuery = gql`\n      query {\n        author {\n          firstName\n          lastName\n        }\n      }\n    `;\n\n    const expectedQuery = getQueryDefinition(gql`\n      query {\n        author {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `);\n\n    const modifiedQuery = addTypenameToDocument(testQuery);\n    expect(print(expectedQuery)).toBe(print(getQueryDefinition(modifiedQuery)));\n  });\n\n  it(\"should be able to apply a MutationTransformer correctly\", () => {\n    const testQuery = gql`\n      mutation {\n        createAuthor(firstName: \"John\", lastName: \"Smith\") {\n          firstName\n          lastName\n        }\n      }\n    `;\n    const expectedQuery = gql`\n      mutation {\n        createAuthor(firstName: \"John\", lastName: \"Smith\") {\n          firstName\n          lastName\n          __typename\n        }\n      }\n    `;\n\n    const modifiedQuery = addTypenameToDocument(testQuery);\n    expect(print(expectedQuery)).toBe(print(modifiedQuery));\n  });\n\n  it(\"should add typename fields correctly on this one query\", () => {\n    const testQuery = gql`\n      query Feed($type: FeedType!) {\n        # Eventually move this into a no fetch query right on the entry\n        # since we literally just need this info to determine whether to\n        # show upvote/downvote buttons\n        currentUser {\n          login\n        }\n        feed(type: $type) {\n          createdAt\n          score\n          commentCount\n          id\n          postedBy {\n            login\n            html_url\n          }\n          repository {\n            name\n            full_name\n            description\n            html_url\n            stargazers_count\n            open_issues_count\n            created_at\n            owner {\n              avatar_url\n            }\n          }\n        }\n      }\n    `;\n    const expectedQuery = getQueryDefinition(gql`\n      query Feed($type: FeedType!) {\n        currentUser {\n          login\n          __typename\n        }\n        feed(type: $type) {\n          createdAt\n          score\n          commentCount\n          id\n          postedBy {\n            login\n            html_url\n            __typename\n          }\n          repository {\n            name\n            full_name\n            description\n            html_url\n            stargazers_count\n            open_issues_count\n            created_at\n            owner {\n              avatar_url\n              __typename\n            }\n            __typename\n          }\n          __typename\n        }\n      }\n    `);\n    const modifiedQuery = addTypenameToDocument(testQuery);\n    expect(print(expectedQuery)).toBe(print(getQueryDefinition(modifiedQuery)));\n  });\n});\n"
  },
  {
    "path": "src/utilities/graphql/isFormattedExecutionResult.ts",
    "content": "import type { FormattedExecutionResult } from \"graphql\";\n\n/**\n * Determines whether the given object is a valid GraphQL execution result\n * according to the GraphQL specification.\n *\n * @remarks\n *\n * A valid execution result must be an object that contains only `data`,\n * `errors`, and/or `extensions` properties. At least one of `data` or `errors`\n * must be present.\n *\n * @param result - The object to test\n * @returns `true` if the object conforms to the GraphQL execution result format\n *\n * @example\n *\n * ```ts\n * import { isFormattedExecutionResult } from \"@apollo/client/utilities\";\n *\n * // Valid execution result\n * const validResult = { data: { user: { name: \"John\" } } };\n * console.log(isFormattedExecutionResult(validResult)); // true\n *\n * // Invalid - contains non-standard properties\n * const invalidResult = { data: {}, customField: \"value\" };\n * console.log(isFormattedExecutionResult(invalidResult)); // false\n * ```\n */\nexport function isFormattedExecutionResult(\n  result?: object\n): result is FormattedExecutionResult {\n  return (\n    !!result &&\n    (\"errors\" in result || \"data\" in result) &&\n    Object.keys(result).every(\n      (key) => key === \"errors\" || key === \"data\" || key === \"extensions\"\n    )\n  );\n}\n"
  },
  {
    "path": "src/utilities/graphql/operations.ts",
    "content": "import type { DocumentNode } from \"@apollo/client\";\nimport { getOperationDefinition } from \"@apollo/client/utilities/internal\";\n\nfunction isOperation(\n  document: DocumentNode,\n  operation: \"query\" | \"mutation\" | \"subscription\"\n) {\n  return getOperationDefinition(document)?.operation === operation;\n}\n\n/**\n * Determine if a document is a mutation document.\n *\n * @remarks\n * If you are authoring an Apollo link, you might not need this utility.\n * Prefer using the `operationType` property the `operation` object instead.\n *\n * @param document - The GraphQL document to check\n * @returns A boolean indicating if the document is a mutation operation\n *\n * @example\n *\n * ```ts\n * import { isMutationOperation } from \"@apollo/client/utilities\";\n *\n * const mutation = gql`\n *   mutation MyMutation {\n *     # ...\n *   }\n * `;\n *\n * isMutationOperation(mutation); // true\n * ```\n */\nexport function isMutationOperation(document: DocumentNode) {\n  return isOperation(document, \"mutation\");\n}\n\n/**\n * Determine if a document is a query document.\n *\n * @remarks\n * If you are authoring an Apollo link, you might not need this utility.\n * Prefer using the `operationType` property the `operation` object instead.\n *\n * @param document - The GraphQL document to check\n * @returns A boolean indicating if the document is a query operation\n *\n * @example\n *\n * ```ts\n * import { isQueryOperation } from \"@apollo/client/utilities\";\n *\n * const query = gql`\n *   query MyQuery {\n *     # ...\n *   }\n * `;\n *\n * isQueryOperation(query); // true\n * ```\n */\nexport function isQueryOperation(document: DocumentNode) {\n  return isOperation(document, \"query\");\n}\n\n/**\n * Determine if a document is a subscription document.\n *\n * @remarks\n * If you are authoring an Apollo link, you might not need this utility.\n * Prefer using the `operationType` property the `operation` object instead.\n *\n * @param document - The GraphQL document to check\n * @returns A boolean indicating if the document is a subscription operation\n *\n * @example\n *\n * ```ts\n * import { isSubscriptionOperation } from \"@apollo/client/utilities\";\n *\n * const subscription = gql`\n *   subscription MySubscription {\n *     # ...\n *   }\n * `;\n *\n * isSubscriptionOperation(subscription); // true\n * ```\n */\nexport function isSubscriptionOperation(document: DocumentNode) {\n  return isOperation(document, \"subscription\");\n}\n"
  },
  {
    "path": "src/utilities/graphql/print.ts",
    "content": "import type { ASTNode } from \"graphql\";\nimport { print as origPrint } from \"graphql\";\n\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  AutoCleanedWeakCache,\n  registerGlobalCache,\n} from \"@apollo/client/utilities/internal\";\n\nimport { cacheSizes, defaultCacheSizes } from \"../caching/index.js\";\n\nlet printCache!: AutoCleanedWeakCache<ASTNode, string>;\n\n/**\n * Converts an AST into a string, using one set of reasonable\n * formatting rules.\n *\n * @remarks This is the same function as the GraphQL.js `print` function but\n * with an added cache to avoid recomputation when encountering the same\n * `ASTNode` more than once.\n */\nexport const print = Object.assign(\n  (ast: ASTNode) => {\n    let result = printCache.get(ast);\n\n    if (!result) {\n      result = origPrint(ast);\n      printCache.set(ast, result);\n    }\n    return result;\n  },\n  {\n    reset() {\n      printCache = new AutoCleanedWeakCache<ASTNode, string>(\n        cacheSizes.print || defaultCacheSizes.print\n      );\n    },\n  }\n);\nprint.reset();\n\nif (__DEV__) {\n  registerGlobalCache(\"print\", () => (printCache ? printCache.size : 0));\n}\n"
  },
  {
    "path": "src/utilities/graphql/storeUtils.ts",
    "content": "/**\n * Representation of a reference object inside the cache.\n */\nexport interface Reference {\n  readonly __ref: string;\n}\n\n/**\n * Determines if a given object is a reference object.\n *\n * @param obj - The object to check if its a reference object\n *\n * @example\n *\n * ```ts\n * import { isReference } from \"@apollo/client/utilities\";\n *\n * isReference({ __ref: \"User:1\" }); // true\n * isReference({ __typename: \"User\", id: 1 }); // false\n * ```\n */\nexport function isReference(obj: any): obj is Reference {\n  return Boolean(\n    obj && typeof obj === \"object\" && typeof obj.__ref === \"string\"\n  );\n}\n\n/**\n * Represents the union of valid values that can be stored in the cache.\n */\nexport type StoreValue =\n  | number\n  | string\n  | string[]\n  | Reference\n  | Reference[]\n  | null\n  | undefined\n  | void\n  | Object;\n\n/**\n * Represents an object that is stored in the cache.\n */\nexport interface StoreObject {\n  __typename?: string;\n  [storeFieldName: string]: StoreValue;\n}\n\n/**\n * Workaround for a TypeScript quirk:\n * types per default have an implicit index signature that makes them\n * assignable to `StoreObject`.\n * interfaces do not have that implicit index signature, so they cannot\n * be assigned to `StoreObject`.\n * This type just maps over a type or interface that is passed in,\n * implicitly adding the index signature.\n * That way, the result can be assigned to `StoreObject`.\n *\n * This is important if some user-defined interface is used e.g.\n * in cache.modify, where the `toReference` method expects a\n * `StoreObject` as input.\n */\nexport type AsStoreObject<T extends { __typename?: string }> = {\n  [K in keyof T]: T[K];\n};\n"
  },
  {
    "path": "src/utilities/graphql/transform.ts",
    "content": "import type { ASTNode, FieldNode, OperationDefinitionNode } from \"graphql\";\nimport { Kind, visit } from \"graphql\";\n\nconst TYPENAME_FIELD: FieldNode = {\n  kind: Kind.FIELD,\n  name: {\n    kind: Kind.NAME,\n    value: \"__typename\",\n  },\n};\n\n/**\n * Adds `__typename` to all selection sets in the document except for the root\n * selection set.\n *\n * @param doc - The `ASTNode` to add `__typename` to\n *\n * @example\n *\n * ```ts\n * const document = gql`\n *   # ...\n * `;\n *\n * const withTypename = addTypenameToDocument(document);\n * ```\n */\nexport const addTypenameToDocument = Object.assign(\n  function <TNode extends ASTNode>(doc: TNode): TNode {\n    return visit(doc, {\n      SelectionSet: {\n        enter(node, _key, parent) {\n          // Don't add __typename to OperationDefinitions.\n          if (\n            parent &&\n            (parent as OperationDefinitionNode).kind ===\n              Kind.OPERATION_DEFINITION\n          ) {\n            return;\n          }\n\n          // No changes if no selections.\n          const { selections } = node;\n          if (!selections) {\n            return;\n          }\n\n          // If selections already have a __typename, or are part of an\n          // introspection query, do nothing.\n          const skip = selections.some((selection) => {\n            return (\n              selection.kind === Kind.FIELD &&\n              (selection.name.value === \"__typename\" ||\n                selection.name.value.lastIndexOf(\"__\", 0) === 0)\n            );\n          });\n          if (skip) {\n            return;\n          }\n\n          // If this SelectionSet is @export-ed as an input variable, it should\n          // not have a __typename field (see issue #4691).\n          const field = parent as FieldNode;\n          if (\n            field.kind === Kind.FIELD &&\n            field.directives &&\n            field.directives.some((d) => d.name.value === \"export\")\n          ) {\n            return;\n          }\n\n          // Create and return a new SelectionSet with a __typename Field.\n          return {\n            ...node,\n            selections: [...selections, TYPENAME_FIELD],\n          };\n        },\n      },\n    });\n  },\n  {\n    added(field: FieldNode): boolean {\n      return field === TYPENAME_FIELD;\n    },\n  }\n);\n"
  },
  {
    "path": "src/utilities/index.ts",
    "content": "export { Observable } from \"rxjs\";\n\nexport type { DeepPartial } from \"./DeepPartial.js\";\n\nexport type { DocumentTransformCacheKey } from \"./graphql/DocumentTransform.js\";\nexport { DocumentTransform } from \"./graphql/DocumentTransform.js\";\n\nexport { print } from \"./graphql/print.js\";\nexport { isFormattedExecutionResult } from \"./graphql/isFormattedExecutionResult.js\";\n\nexport type {\n  AsStoreObject,\n  Reference,\n  StoreObject,\n  StoreValue,\n} from \"./graphql/storeUtils.js\";\nexport { isReference } from \"./graphql/storeUtils.js\";\n\nexport { addTypenameToDocument } from \"./graphql/transform.js\";\n\nexport {\n  isMutationOperation,\n  isQueryOperation,\n  isSubscriptionOperation,\n} from \"./graphql/operations.js\";\nexport {\n  canonicalStringify,\n  getMainDefinition,\n} from \"@apollo/client/utilities/internal\";\n\nexport {\n  concatPagination,\n  offsetLimitPagination,\n  relayStylePagination,\n} from \"./policies/pagination.js\";\n\nexport { stripTypename } from \"./common/stripTypename.js\";\n\nexport { cacheSizes } from \"./caching/index.js\";\nexport type { CacheSizes } from \"./caching/index.js\";\n\nexport type { HKT } from \"./HKT.js\";\n\nexport { isNetworkRequestInFlight } from \"./isNetworkRequestInFlight.js\";\nexport { isNetworkRequestSettled } from \"./isNetworkRequestSettled.js\";\n"
  },
  {
    "path": "src/utilities/internal/DeepMerger.ts",
    "content": "import { isNonNullObject } from \"./isNonNullObject.js\";\n\nconst { hasOwnProperty } = Object.prototype;\n\ntype ReconcilerFunction = (\n  this: DeepMerger,\n  target: Record<string | number, any>,\n  source: Record<string | number, any>,\n  property: string | number\n) => any;\n\nconst defaultReconciler: ReconcilerFunction = function (\n  target,\n  source,\n  property\n) {\n  return this.merge(target[property], source[property]);\n};\n\n/** @internal */\nexport declare namespace DeepMerger {\n  export interface Options {\n    arrayMerge?: DeepMerger.ArrayMergeStrategy;\n    reconciler?: ReconcilerFunction;\n  }\n\n  export interface MergeOptions {\n    atPath?: ReadonlyArray<string | number>;\n  }\n\n  export type ArrayMergeStrategy =\n    // Truncate the target array to the source length, then deep merge the array\n    // items at the same index\n    | \"truncate\"\n    // Combine arrays and deep merge array items for items at the same index.\n    // This is the default\n    | \"combine\";\n}\n\nconst objForKey = (key: string | number) => {\n  return isNaN(+key) ? {} : [];\n};\n\n/** @internal */\nexport class DeepMerger {\n  private reconciler: ReconcilerFunction;\n  constructor(private options: DeepMerger.Options = {}) {\n    this.reconciler = options.reconciler || defaultReconciler;\n  }\n\n  public merge(\n    target: any,\n    source: any,\n    mergeOptions: DeepMerger.MergeOptions = {}\n  ): any {\n    const atPath = mergeOptions.atPath;\n\n    if (atPath?.length) {\n      const [head, ...tail] = atPath;\n      if (target === undefined) {\n        target = objForKey(head);\n      }\n      let nestedTarget = target[head];\n      if (nestedTarget === undefined && tail.length) {\n        nestedTarget = objForKey(tail[0]);\n      }\n      const nestedSource = this.merge(nestedTarget, source, {\n        ...mergeOptions,\n        atPath: tail,\n      });\n      if (nestedTarget !== nestedSource) {\n        target = this.shallowCopyForMerge(target);\n        target[head] = nestedSource;\n      }\n      return target;\n    }\n\n    if (\n      Array.isArray(target) &&\n      Array.isArray(source) &&\n      this.options.arrayMerge === \"truncate\" &&\n      target.length > source.length\n    ) {\n      target = target.slice(0, source.length);\n      this.pastCopies.add(target);\n    }\n\n    if (isNonNullObject(source) && isNonNullObject(target)) {\n      Object.keys(source).forEach((sourceKey) => {\n        if (hasOwnProperty.call(target, sourceKey)) {\n          const targetValue = target[sourceKey];\n          if (source[sourceKey] !== targetValue) {\n            const result = this.reconciler(target, source, sourceKey);\n            // A well-implemented reconciler may return targetValue to indicate\n            // the merge changed nothing about the structure of the target.\n            if (result !== targetValue) {\n              target = this.shallowCopyForMerge(target);\n              target[sourceKey] = result;\n            }\n          }\n        } else {\n          // If there is no collision, the target can safely share memory with\n          // the source, and the recursion can terminate here.\n          target = this.shallowCopyForMerge(target);\n          target[sourceKey] = source[sourceKey];\n        }\n      });\n\n      return target;\n    }\n\n    // If source (or target) is not an object, let source replace target.\n    return source;\n  }\n\n  public isObject = isNonNullObject;\n\n  private pastCopies = new Set<any>();\n\n  public shallowCopyForMerge<T>(value: T): T {\n    if (isNonNullObject(value)) {\n      if (!this.pastCopies.has(value)) {\n        if (Array.isArray(value)) {\n          value = (value as any).slice(0);\n        } else {\n          value = {\n            __proto__: Object.getPrototypeOf(value),\n            ...value,\n          };\n        }\n        this.pastCopies.add(value);\n      }\n    }\n    return value;\n  }\n}\n"
  },
  {
    "path": "src/utilities/internal/__tests__/DeepMerger.test.ts",
    "content": "import { DeepMerger } from \"@apollo/client/utilities/internal\";\n\ntest(\"supports custom reconciler functions\", function () {\n  const merger = new DeepMerger({\n    reconciler(target, source, key) {\n      const targetValue = target[key];\n      const sourceValue = source[key];\n      if (Array.isArray(sourceValue)) {\n        if (!Array.isArray(targetValue)) {\n          return sourceValue;\n        }\n        return [...targetValue, ...sourceValue];\n      }\n      return this.merge(targetValue, sourceValue);\n    },\n  });\n\n  expect(\n    merger.merge(\n      {\n        a: [1, 2, 3],\n        b: \"replace me\",\n      },\n      {\n        a: [4, 5],\n        b: [\"I\", \"win\"],\n      }\n    )\n  ).toEqual({\n    a: [1, 2, 3, 4, 5],\n    b: [\"I\", \"win\"],\n  });\n});\n\ntest(\"deep merges each array item keeping length by default\", () => {\n  const target = [{ a: 1, b: { c: 2 } }, { e: 5 }];\n  const source = [{ a: 2, b: { c: 2, d: 3 } }];\n\n  const result = new DeepMerger().merge(target, source);\n\n  expect(result).toEqual([{ a: 2, b: { c: 2, d: 3 } }, { e: 5 }]);\n});\n\ntest(\"deep merges each array item and truncates source to target length when using truncate arrayMerge\", () => {\n  const target = [{ a: 1, b: { c: 2 } }, { e: 5 }];\n  const source = [{ a: 2, b: { c: 2, d: 3 } }];\n\n  const result = new DeepMerger({\n    arrayMerge: \"truncate\",\n  }).merge(target, source);\n\n  expect(result).toEqual([{ a: 2, b: { c: 2, d: 3 } }]);\n});\n\ntest(\"maintains source length when using truncate arrayMerge when source is longer than target length\", () => {\n  const target = [{ a: 1, b: { c: 2 } }];\n  const source = [{ a: 2 }, { e: 2 }];\n\n  const result = new DeepMerger({\n    arrayMerge: \"truncate\",\n  }).merge(target, source);\n\n  expect(result).toEqual([{ a: 2, b: { c: 2 } }, { e: 2 }]);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/canUseDOM.test.ts",
    "content": "import { canUseDOM } from \"@apollo/client/utilities/internal\";\n\n// https://github.com/apollographql/apollo-client/pull/9675\ntest(\"sets canUseDOM to true when using Jest in Node.js with jsdom\", () => {\n  expect(canUseDOM).toBe(true);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/checkDocument.test.ts",
    "content": "import { OperationTypeNode } from \"graphql\";\n\nimport { gql } from \"@apollo/client\";\nimport { checkDocument } from \"@apollo/client/utilities/internal\";\nimport { InvariantError } from \"@apollo/client/utilities/invariant\";\n\ntest(\"should correctly check a document for correctness\", () => {\n  const multipleQueries = gql`\n    query {\n      author {\n        firstName\n        lastName\n      }\n    }\n\n    query {\n      author {\n        address\n      }\n    }\n  `;\n  expect(() => {\n    checkDocument(multipleQueries);\n  }).toThrow();\n\n  const namedFragment = gql`\n    query {\n      author {\n        ...authorDetails\n      }\n    }\n\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n  `;\n  expect(() => {\n    checkDocument(namedFragment);\n  }).not.toThrow();\n});\n\ntest(\"caches the result of checking a valid document\", () => {\n  let kindLookupCount = 0;\n  const query = new Proxy(\n    gql`\n      query {\n        me\n      }\n    `,\n    {\n      get(target, prop) {\n        if (prop === \"kind\") {\n          kindLookupCount++;\n        }\n        return Reflect.get(target, prop);\n      },\n    }\n  );\n  checkDocument(query, OperationTypeNode.QUERY);\n  expect(kindLookupCount).toBeGreaterThan(0);\n  kindLookupCount = 0;\n  checkDocument(query, OperationTypeNode.QUERY);\n  expect(kindLookupCount).toBe(0);\n});\n\ntest(\"caches thrown errors\", () => {\n  let kindLookupCount = 0;\n  const query = new Proxy(\n    gql`\n      query {\n        __typename: me\n      }\n    `,\n    {\n      get(target, prop) {\n        if (prop === \"kind\") {\n          kindLookupCount++;\n        }\n        return Reflect.get(target, prop);\n      },\n    }\n  );\n  expect(() => checkDocument(query, OperationTypeNode.QUERY)).toThrow(\n    new InvariantError(\n      '`__typename` is a forbidden field alias name in the selection set for field `me` in query \"(anonymous)\".'\n    )\n  );\n  expect(kindLookupCount).toBeGreaterThan(0);\n  kindLookupCount = 0;\n  expect(() => checkDocument(query, OperationTypeNode.QUERY)).toThrow(\n    new InvariantError(\n      '`__typename` is a forbidden field alias name in the selection set for field `me` in query \"(anonymous)\".'\n    )\n  );\n  expect(kindLookupCount).toBe(0);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/cloneDeep.test.ts",
    "content": "import { cloneDeep } from \"@apollo/client/utilities/internal\";\n\ntest(\"will clone primitive values\", () => {\n  expect(cloneDeep(undefined)).toEqual(undefined);\n  expect(cloneDeep(null)).toEqual(null);\n  expect(cloneDeep(true)).toEqual(true);\n  expect(cloneDeep(false)).toEqual(false);\n  expect(cloneDeep(-1)).toEqual(-1);\n  expect(cloneDeep(+1)).toEqual(+1);\n  expect(cloneDeep(0.5)).toEqual(0.5);\n  expect(cloneDeep(\"hello\")).toEqual(\"hello\");\n  expect(cloneDeep(\"world\")).toEqual(\"world\");\n});\n\ntest(\"will clone objects\", () => {\n  const value1 = {};\n  const value2 = { a: 1, b: 2, c: 3 };\n  const value3 = { x: { a: 1, b: 2, c: 3 }, y: { a: 1, b: 2, c: 3 } };\n\n  const clonedValue1 = cloneDeep(value1);\n  const clonedValue2 = cloneDeep(value2);\n  const clonedValue3 = cloneDeep(value3);\n\n  expect(clonedValue1).toEqual(value1);\n  expect(clonedValue2).toEqual(value2);\n  expect(clonedValue3).toEqual(value3);\n\n  expect(clonedValue1).toEqual(value1);\n  expect(clonedValue2).toEqual(value2);\n  expect(clonedValue3).toEqual(value3);\n  expect(clonedValue3.x).toEqual(value3.x);\n  expect(clonedValue3.y).toEqual(value3.y);\n});\n\ntest(\"will clone arrays\", () => {\n  const value1: Array<number> = [];\n  const value2 = [1, 2, 3];\n  const value3 = [\n    [1, 2, 3],\n    [1, 2, 3],\n  ];\n\n  const clonedValue1 = cloneDeep(value1);\n  const clonedValue2 = cloneDeep(value2);\n  const clonedValue3 = cloneDeep(value3);\n\n  expect(clonedValue1).toEqual(value1);\n  expect(clonedValue2).toEqual(value2);\n  expect(clonedValue3).toEqual(value3);\n\n  expect(clonedValue1).toEqual(value1);\n  expect(clonedValue2).toEqual(value2);\n  expect(clonedValue3).toEqual(value3);\n  expect(clonedValue3[0]).toEqual(value3[0]);\n  expect(clonedValue3[1]).toEqual(value3[1]);\n});\n\ntest(\"should not attempt to follow circular references\", () => {\n  const someObject: any = {\n    prop1: \"value1\",\n    anotherObject: null,\n  };\n  const anotherObject = {\n    someObject,\n  };\n  someObject.anotherObject = anotherObject;\n  expect(() => {\n    cloneDeep(someObject);\n  }).not.toThrow();\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/compact.test.ts",
    "content": "import { compact } from \"@apollo/client/utilities/internal\";\n\nconst hasOwn = Object.prototype.hasOwnProperty;\n\ntest(\"should produce an empty object when called without args\", () => {\n  expect(compact()).toEqual({});\n});\n\ntest(\"should merge objects without modifying them\", () => {\n  const a = { a: 1, ay: \"a\" };\n  const b = { b: 2, bee: \"b\" };\n  const c = compact(a, b);\n\n  expect(c).toEqual({\n    ...a,\n    ...b,\n  });\n\n  expect(Object.keys(a)).toEqual([\"a\", \"ay\"]);\n  expect(Object.keys(b)).toEqual([\"b\", \"bee\"]);\n});\n\ntest(\"should clean undefined values from single objects\", () => {\n  const source = {\n    zero: 0,\n    undef: void 0,\n    three: 3,\n  };\n\n  const result = compact(source);\n\n  expect(result).toEqual({\n    zero: 0,\n    three: 3,\n  });\n\n  expect(Object.keys(result)).toEqual([\"zero\", \"three\"]);\n});\n\ntest(\"should skip over undefined values in later objects\", () => {\n  expect(\n    compact({ a: 1, b: 2 }, { b: void 0, c: 3 }, { a: 4, c: void 0 })\n  ).toEqual({\n    a: 4,\n    b: 2,\n    c: 3,\n  });\n});\n\ntest(\"should not leave undefined properties in result object\", () => {\n  const result = compact({ a: 1, b: void 0 }, { a: 2, c: void 0 });\n  expect(hasOwn.call(result, \"a\")).toBe(true);\n  expect(hasOwn.call(result, \"b\")).toBe(false);\n  expect(hasOwn.call(result, \"c\")).toBe(false);\n  expect(result).toEqual({ a: 2 });\n});\n\ntest(\"should preserve symbol options\", () => {\n  const symA = Symbol(\"a\");\n  const symB = Symbol(\"b\");\n\n  const result = compact(\n    {\n      [symA]: 123,\n      [symB]: 456,\n      foo: \"bar\",\n    },\n    {\n      [symA]: 789,\n      baz: \"qux\",\n    },\n    {\n      [symA]: void 0,\n      byd: \"tbd\",\n    }\n  );\n  expect(result).toStrictEqualTyped({\n    [symA]: 789,\n    [symB]: 456,\n    foo: \"bar\",\n    baz: \"qux\",\n    byd: \"tbd\",\n  });\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/createFragmentMap.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport type { FragmentMap } from \"@apollo/client/utilities/internal\";\nimport {\n  createFragmentMap,\n  getFragmentDefinitions,\n} from \"@apollo/client/utilities/internal\";\n\ntest(\"should create the fragment map correctly\", () => {\n  const fragments = getFragmentDefinitions(gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    fragment moreAuthorDetails on Author {\n      address\n    }\n  `);\n  const fragmentMap = createFragmentMap(fragments);\n  const expectedTable: FragmentMap = {\n    authorDetails: fragments[0],\n    moreAuthorDetails: fragments[1],\n  };\n  expect(fragmentMap).toEqual(expectedTable);\n});\n\ntest(\"should return an empty fragment map if passed undefined argument\", () => {\n  expect(createFragmentMap(undefined)).toEqual({});\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/equalByQuery.ts",
    "content": "import { GraphQLError } from \"graphql\";\n\nimport type { TypedDocumentNode } from \"@apollo/client\";\nimport { CombinedGraphQLErrors, gql } from \"@apollo/client\";\nimport { equalByQuery } from \"@apollo/client/utilities/internal\";\n\ndescribe(\"equalByQuery\", () => {\n  it(\"is importable and a function\", () => {\n    expect(typeof equalByQuery).toBe(\"function\");\n  });\n\n  it(\"works with a basic single-field query\", () => {\n    const query = gql`\n      query {\n        hello\n      }\n    `;\n\n    expect(\n      equalByQuery(query, { data: { hello: \"hi\" } }, { data: { hello: \"hi\" } })\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { hello: \"hi\", unrelated: 1 } },\n        { data: { hello: \"hi\", unrelated: 100 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(query, { data: { hello: \"hi\" } }, { data: { hello: \"hey\" } })\n    ).toBe(false);\n\n    expect(equalByQuery(query, { data: {} }, { data: { hello: \"hi\" } })).toBe(\n      false\n    );\n\n    expect(equalByQuery(query, { data: { hello: \"hi\" } }, { data: {} })).toBe(\n      false\n    );\n\n    expect(equalByQuery(query, { data: { hello: \"hi\" } }, { data: null })).toBe(\n      false\n    );\n\n    expect(equalByQuery(query, { data: null }, { data: { hello: \"hi\" } })).toBe(\n      false\n    );\n\n    expect(equalByQuery(query, { data: null }, { data: null })).toBe(true);\n\n    expect(equalByQuery(query, { data: {} }, { data: {} })).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { unrelated: \"whatever\" } },\n        { data: { unrelated: \"no matter\" } }\n      )\n    ).toBe(true);\n  });\n\n  it(\"is not confused by properties in different orders\", () => {\n    const query = gql`\n      query {\n        a\n        b\n        c\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { b: 2, c: 3, a: 1 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { d: \"bogus\", a: 1, b: 2, c: 3 } },\n        { data: { b: 2, c: 3, a: 1, d: \"also bogus\" } }\n      )\n    ).toBe(true);\n  });\n\n  it(\"respects the @nonreactive directive on fields\", () => {\n    const query = gql`\n      query {\n        a\n        b\n        c @nonreactive\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 2, c: \"different\" } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: \"different\", b: 2, c: 4 } }\n      )\n    ).toBe(false);\n  });\n\n  describe(\"@skip and @include directives\", () => {\n    // The @skip and @include directives use query variables to determine\n    // whether subtrees of the query should be executed at all, so they can\n    // influence the comparison of results in ways similar to @nonreactive. The\n    // key difference is that @skip and @include will be sent to the server,\n    // whereas @nonreactive is a client-only directive, and does not prevent\n    // execution of nonreactive fields/subtrees on the server.\n    it(\"respects @skip directive, depending on variables\", () => {\n      const skipQuery = gql`\n        query SkipC($condition: Boolean!) {\n          a\n          b\n          c @skip(if: $condition)\n        }\n      `;\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: false }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2 } },\n          { condition: false }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2 } },\n          { condition: true }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: false }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: true }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2 } },\n          { condition: false }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          skipQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2 } },\n          { condition: true }\n        )\n      ).toBe(true);\n    });\n\n    it(\"respects @include directive, depending on variables\", () => {\n      const includeQuery = gql`\n        query IncludeC($condition: Boolean!) {\n          a\n          b\n          c @include(if: $condition)\n        }\n      `;\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: true }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2 } },\n          { condition: true }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2, c: 3 } },\n          { data: { a: 1, b: 2 } },\n          { condition: false }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: true }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2, c: 3 } },\n          { condition: false }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2 } },\n          { condition: true }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          includeQuery,\n          { data: { a: 1, b: 2 } },\n          { data: { a: 1, b: 2 } },\n          { condition: false }\n        )\n      ).toBe(true);\n    });\n  });\n\n  it(\"considers errors as well as data\", () => {\n    const query = gql`\n      query {\n        a\n        b @nonreactive\n        c\n      }\n    `;\n\n    const data123 = { a: 1, b: 2, c: 3 };\n    const oopsError = new GraphQLError(\"oops\");\n    const differentError = new GraphQLError(\"different\");\n\n    expect(\n      equalByQuery(\n        query,\n        { data: data123 },\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        },\n        { data: data123 }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        },\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        },\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [differentError],\n          }),\n        }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        },\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({\n            data: data123,\n            errors: [oopsError],\n          }),\n        },\n        {\n          data: { ...data123, b: 100 },\n          error: new CombinedGraphQLErrors({\n            data: { ...data123, b: 100 },\n            errors: [oopsError],\n          }),\n        }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({ data: data123, errors: [] }),\n        },\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({ data: data123, errors: [] }),\n        }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        {\n          data: data123,\n          error: new CombinedGraphQLErrors({ data: data123, errors: [] }),\n        },\n        {\n          data: { ...data123, b: 100 },\n          error: new CombinedGraphQLErrors({\n            data: { ...data123, b: 100 },\n            errors: [],\n          }),\n        }\n      )\n    ).toBe(true);\n  });\n\n  it(\"respects the @nonreactive directive on inline fragments\", () => {\n    const query = gql`\n      query {\n        a\n        ... @nonreactive {\n          b\n          c\n        }\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 30 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 10, b: 20, c: 30 } }\n      )\n    ).toBe(false);\n  });\n\n  it(\"respects the @nonreactive directive on named fragment ...spreads\", () => {\n    const query = gql`\n      query {\n        a\n        ...BCFragment @nonreactive\n      }\n\n      fragment BCFragment on Query {\n        b\n        c\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 2, c: 30 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 3 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 30 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 10, b: 20, c: 30 } }\n      )\n    ).toBe(false);\n  });\n\n  it(\"respects the @nonreactive directive on named fragment definitions\", () => {\n    const query = gql`\n      query {\n        a\n        ...BCFragment\n      }\n\n      fragment BCFragment on Query @nonreactive {\n        b\n        c\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 2, c: 30 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 3 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 30 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 10, b: 20, c: 30 } }\n      )\n    ).toBe(false);\n  });\n\n  it(\"traverses fragments without @nonreactive\", () => {\n    const query = gql`\n      query {\n        a\n        ...BCFragment\n      }\n\n      fragment BCFragment on Query {\n        b\n        c\n      }\n    `;\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 2, c: 3 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { c: 3, a: 1, b: 2 } }\n      )\n    ).toBe(true);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 2, c: 30 } }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 3 } }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 1, b: 20, c: 30 } }\n      )\n    ).toBe(false);\n\n    expect(\n      equalByQuery(\n        query,\n        { data: { a: 1, b: 2, c: 3 } },\n        { data: { a: 10, b: 20, c: 30 } }\n      )\n    ).toBe(false);\n  });\n\n  type Thing = {\n    __typename: \"Thing\";\n    id: string;\n    stable: number;\n    volatile: number;\n  };\n\n  it.each<TypedDocumentNode<Thing>>([\n    gql`\n      query {\n        things {\n          __typename\n          id\n          stable\n          volatile @nonreactive\n        }\n      }\n    `,\n    gql`\n      query {\n        things {\n          __typename\n          id\n          ...ThingDetails\n        }\n      }\n\n      fragment ThingDetails on Thing {\n        stable\n        volatile @nonreactive\n      }\n    `,\n    gql`\n      query {\n        things {\n          __typename\n          id\n          ... on Thing {\n            stable\n            volatile @nonreactive\n          }\n        }\n      }\n    `,\n    gql`\n      query {\n        things {\n          __typename\n          id\n          stable\n          ... on Thing @nonreactive {\n            volatile\n          }\n        }\n      }\n    `,\n    gql`\n      query {\n        things {\n          __typename\n          id\n          stable\n          ...Volatile @nonreactive\n        }\n      }\n\n      fragment Volatile on Thing {\n        volatile\n      }\n    `,\n    gql`\n      query {\n        things {\n          __typename\n          id\n          stable\n          ... @nonreactive {\n            volatile\n          }\n        }\n      }\n    `,\n  ])(\n    \"iterates over array-valued result fields ignoring @nonreactive (%#)\",\n    (query) => {\n      let nextVolatileIntegerPart = 0;\n      const makeThing = (id: string, stable = 1): Thing => ({\n        __typename: \"Thing\",\n        id,\n        stable,\n        // Thing.volatile is always a different randomized number, which normally\n        // would threatens any deep comparison of Thing objects. These test cases\n        // demonstrate (among other things) that we can make the result comparison\n        // insensitive to this volatility by marking the volatile field with the\n        // @nonreactive directive.\n        volatile: nextVolatileIntegerPart++ + Math.random(),\n      });\n\n      const makeThings = (\n        lettersToSplit: string,\n        stable: number = 1\n      ): Thing[] => lettersToSplit.split(\"\").map((id) => makeThing(id, stable));\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"abc\") } },\n          { data: { things: [makeThing(\"a\"), makeThing(\"b\"), makeThing(\"c\")] } }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"abcdefg\", 2) } },\n          { data: { things: makeThings(\"abcdefg\") } }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"abcdefg\", 2) } },\n          { data: { things: makeThings(\"abcdefg\", 3) } }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"abcdefg\", 3) } },\n          { data: { things: makeThings(\"abcdefg\", 3) } }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"ab\", 2345) } },\n          { data: { things: [makeThing(\"a\"), makeThing(\"b\", 2345)] } }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"ab\", 3456) } },\n          { data: { things: [makeThing(\"a\", 3456), makeThing(\"b\")] } }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"ab\", 3456) } },\n          { data: { things: [makeThing(\"a\", 3456), makeThing(\"b\", 3456)] } }\n        )\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          query,\n          { data: { things: makeThings(\"abc\") } },\n          { data: { things: \"not an array\" } }\n        )\n      ).toBe(false);\n\n      expect(\n        equalByQuery(query, { data: { things: {} } }, { data: { things: [] } })\n      ).toBe(false);\n\n      expect(\n        equalByQuery(query, { data: { things: [] } }, { data: { things: {} } })\n      ).toBe(false);\n\n      expect(\n        equalByQuery(query, { data: { things: [] } }, { data: { things: [] } })\n      ).toBe(true);\n\n      expect(\n        equalByQuery(\n          query,\n          // There's nothing inherently array-like about the Query.things field as\n          // it's represented in query syntax, since `query { things { id } }` could\n          // (depending on the server/schema) return a single object for the things\n          // field, rather than an array. Although this might seem like a strange\n          // edge case to test, it demonstrates the equalByQuery function can handle\n          // any combination of array/non-array values.\n          { data: { things: {} } },\n          { data: { things: {} } }\n        )\n      ).toBe(true);\n    }\n  );\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getDefaultValues.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport {\n  getDefaultValues,\n  getQueryDefinition,\n} from \"@apollo/client/utilities/internal\";\n\ntest(\"will create an empty variable object if no default values are provided\", () => {\n  const basicQuery = gql`\n    query people($first: Int, $second: String) {\n      allPeople(first: $first) {\n        people {\n          name\n        }\n      }\n    }\n  `;\n\n  expect(getDefaultValues(getQueryDefinition(basicQuery))).toEqual({});\n});\n\ntest(\"will create a variable object based on the definition node with default values\", () => {\n  const basicQuery = gql`\n    query people($first: Int = 1, $second: String!) {\n      allPeople(first: $first) {\n        people {\n          name\n        }\n      }\n    }\n  `;\n\n  expect(getDefaultValues(getQueryDefinition(basicQuery))).toEqual({\n    first: 1,\n  });\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getFragmentDefinitions.test.ts",
    "content": "import type { FragmentDefinitionNode } from \"graphql\";\nimport { print } from \"graphql\";\n\nimport { gql } from \"@apollo/client\";\nimport { getFragmentDefinitions } from \"@apollo/client/utilities/internal\";\n\ntest(\"should get fragment definitions from a document containing a single fragment\", () => {\n  const singleFragmentDefinition = gql`\n    query {\n      author {\n        ...authorDetails\n      }\n    }\n\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n  `;\n  const expectedDoc = gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n  `;\n  const expectedResult: FragmentDefinitionNode[] = [\n    expectedDoc.definitions[0] as FragmentDefinitionNode,\n  ];\n  const actualResult = getFragmentDefinitions(singleFragmentDefinition);\n\n  expect(actualResult.length).toEqual(expectedResult.length);\n  expect(print(actualResult[0])).toBe(print(expectedResult[0]));\n});\n\ntest(\"should get fragment definitions from a document containing a multiple fragments\", () => {\n  const multipleFragmentDefinitions = gql`\n    query {\n      author {\n        ...authorDetails\n        ...moreAuthorDetails\n      }\n    }\n\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    fragment moreAuthorDetails on Author {\n      address\n    }\n  `;\n  const expectedDoc = gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    fragment moreAuthorDetails on Author {\n      address\n    }\n  `;\n  const expectedResult: FragmentDefinitionNode[] = [\n    expectedDoc.definitions[0] as FragmentDefinitionNode,\n    expectedDoc.definitions[1] as FragmentDefinitionNode,\n  ];\n  const actualResult = getFragmentDefinitions(multipleFragmentDefinitions);\n  expect(actualResult.map(print)).toEqual(expectedResult.map(print));\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getFragmentQueryDocument.test.ts",
    "content": "import { disableFragmentWarnings, gql } from \"@apollo/client\";\nimport { getFragmentQueryDocument } from \"@apollo/client/utilities/internal\";\n\n// Turn off warnings for repeated fragment names\ndisableFragmentWarnings();\n\ntest(\"will throw an error if there is an operation\", () => {\n  expect(() =>\n    getFragmentQueryDocument(gql`\n      {\n        a\n        b\n        c\n      }\n    `)\n  ).toThrow(\n    \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n  );\n  expect(() =>\n    getFragmentQueryDocument(gql`\n      query {\n        a\n        b\n        c\n      }\n    `)\n  ).toThrow(\n    \"Found a query operation. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n  );\n  expect(() =>\n    getFragmentQueryDocument(gql`\n      query Named {\n        a\n        b\n        c\n      }\n    `)\n  ).toThrow(\n    \"Found a query operation named 'Named'. No operations are allowed when using a fragment as a query. Only fragments are allowed.\"\n  );\n  expect(() =>\n    getFragmentQueryDocument(gql`\n      mutation Named {\n        a\n        b\n        c\n      }\n    `)\n  ).toThrow(\n    \"Found a mutation operation named 'Named'. No operations are allowed when using a fragment as a query. \" +\n      \"Only fragments are allowed.\"\n  );\n  expect(() =>\n    getFragmentQueryDocument(gql`\n      subscription Named {\n        a\n        b\n        c\n      }\n    `)\n  ).toThrow(\n    \"Found a subscription operation named 'Named'. No operations are allowed when using a fragment as a query. \" +\n      \"Only fragments are allowed.\"\n  );\n});\n\ntest(\"will throw an error if there is not exactly one fragment but no `fragmentName`\", () => {\n  expect(() => {\n    getFragmentQueryDocument(gql`\n      fragment foo on Foo {\n        a\n        b\n        c\n      }\n\n      fragment bar on Bar {\n        d\n        e\n        f\n      }\n    `);\n  }).toThrow(\n    \"Found 2 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n  );\n  expect(() => {\n    getFragmentQueryDocument(gql`\n      fragment foo on Foo {\n        a\n        b\n        c\n      }\n\n      fragment bar on Bar {\n        d\n        e\n        f\n      }\n\n      fragment baz on Baz {\n        g\n        h\n        i\n      }\n    `);\n  }).toThrow(\n    \"Found 3 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n  );\n  expect(() => {\n    getFragmentQueryDocument(gql`\n      scalar Foo\n    `);\n  }).toThrow(\n    \"Found 0 fragments. `fragmentName` must be provided when there is not exactly 1 fragment.\"\n  );\n});\n\ntest(\"will create a query document where the single fragment is spread in the root query\", () => {\n  expect(\n    getFragmentQueryDocument(gql`\n      fragment foo on Foo {\n        a\n        b\n        c\n      }\n    `)\n  ).toMatchDocument(gql`\n    {\n      ...foo\n    }\n\n    fragment foo on Foo {\n      a\n      b\n      c\n    }\n  `);\n});\n\ntest(\"will create a query document where the named fragment is spread in the root query\", () => {\n  expect(\n    getFragmentQueryDocument(\n      gql`\n        fragment foo on Foo {\n          a\n          b\n          c\n        }\n\n        fragment bar on Bar {\n          d\n          e\n          f\n          ...foo\n        }\n\n        fragment baz on Baz {\n          g\n          h\n          i\n          ...foo\n          ...bar\n        }\n      `,\n      \"foo\"\n    )\n  ).toMatchDocument(gql`\n    {\n      ...foo\n    }\n\n    fragment foo on Foo {\n      a\n      b\n      c\n    }\n\n    fragment bar on Bar {\n      d\n      e\n      f\n      ...foo\n    }\n\n    fragment baz on Baz {\n      g\n      h\n      i\n      ...foo\n      ...bar\n    }\n  `);\n  expect(\n    getFragmentQueryDocument(\n      gql`\n        fragment foo on Foo {\n          a\n          b\n          c\n        }\n\n        fragment bar on Bar {\n          d\n          e\n          f\n          ...foo\n        }\n\n        fragment baz on Baz {\n          g\n          h\n          i\n          ...foo\n          ...bar\n        }\n      `,\n      \"bar\"\n    )\n  ).toMatchDocument(gql`\n    {\n      ...bar\n    }\n\n    fragment foo on Foo {\n      a\n      b\n      c\n    }\n\n    fragment bar on Bar {\n      d\n      e\n      f\n      ...foo\n    }\n\n    fragment baz on Baz {\n      g\n      h\n      i\n      ...foo\n      ...bar\n    }\n  `);\n  expect(\n    getFragmentQueryDocument(\n      gql`\n        fragment foo on Foo {\n          a\n          b\n          c\n        }\n\n        fragment bar on Bar {\n          d\n          e\n          f\n          ...foo\n        }\n\n        fragment baz on Baz {\n          g\n          h\n          i\n          ...foo\n          ...bar\n        }\n      `,\n      \"baz\"\n    )\n  ).toMatchDocument(gql`\n    {\n      ...baz\n    }\n\n    fragment foo on Foo {\n      a\n      b\n      c\n    }\n\n    fragment bar on Bar {\n      d\n      e\n      f\n      ...foo\n    }\n\n    fragment baz on Baz {\n      g\n      h\n      i\n      ...foo\n      ...bar\n    }\n  `);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getOperationName.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport type { DocumentNode } from \"@apollo/client\";\nimport { gql } from \"@apollo/client\";\nimport { getOperationName } from \"@apollo/client/utilities/internal\";\n\ntest(\"should get the operation name out of a query\", () => {\n  const query = gql`\n    query nameOfQuery {\n      fortuneCookie\n    }\n  `;\n\n  const operationName = getOperationName(query);\n\n  expect(operationName).toEqual(\"nameOfQuery\");\n});\n\ntest(\"should get the operation name out of a mutation\", () => {\n  const query = gql`\n    mutation nameOfMutation {\n      fortuneCookie\n    }\n  `;\n\n  const operationName = getOperationName(query);\n\n  expect(operationName).toEqual(\"nameOfMutation\");\n});\n\ntest(\"should return undefined if the query does not have an operation name\", () => {\n  const query = gql`\n    {\n      fortuneCookie\n    }\n  `;\n\n  const operationName = getOperationName(query);\n\n  expect(operationName).toEqual(undefined);\n});\n\ntest(\"returns fallback if the query does not have an operation name and a fallback is provided\", () => {\n  const query = gql`\n    {\n      fortuneCookie\n    }\n  `;\n\n  const operationName = getOperationName(query, \"(anonymous)\");\n\n  expect(operationName).toEqual(\"(anonymous)\");\n});\n\ndeclare const query: DocumentNode;\n\ndescribe.skip(\"type tests\", () => {\n  test(\"returns string | undefined without fallback\", () => {\n    expectTypeOf(getOperationName(query)).toEqualTypeOf<string | undefined>();\n  });\n\n  test(\"returns string | undefined with undefined fallback\", () => {\n    expectTypeOf(getOperationName(query, undefined)).toEqualTypeOf<\n      string | undefined\n    >();\n  });\n\n  test(\"returns string with string fallback\", () => {\n    expectTypeOf(getOperationName(query, \"anonymous\")).toEqualTypeOf<string>();\n  });\n\n  test(\"returns string | null with null fallback\", () => {\n    expectTypeOf(getOperationName(query, null)).toEqualTypeOf<string | null>();\n  });\n\n  test(\"does not allow values other than string, null, undefined\", () => {\n    getOperationName(\n      query,\n      // @ts-expect-error\n      1\n    );\n\n    getOperationName(\n      query,\n      // @ts-expect-error\n      true\n    );\n\n    getOperationName(\n      query,\n      // @ts-expect-error\n      {}\n    );\n\n    getOperationName(\n      query,\n      // @ts-expect-error\n      []\n    );\n\n    getOperationName(\n      query,\n      // @ts-expect-error\n      Symbol()\n    );\n  });\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getQueryDefinition.test.ts",
    "content": "import type { OperationDefinitionNode } from \"graphql\";\nimport { print } from \"graphql\";\n\nimport { gql } from \"@apollo/client\";\nimport { getQueryDefinition } from \"@apollo/client/utilities/internal\";\n\ntest(\"should get the correct query definition out of a query containing multiple fragments\", () => {\n  const queryWithFragments = gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    fragment moreAuthorDetails on Author {\n      address\n    }\n\n    query {\n      author {\n        ...authorDetails\n        ...moreAuthorDetails\n      }\n    }\n  `;\n  const expectedDoc = gql`\n    query {\n      author {\n        ...authorDetails\n        ...moreAuthorDetails\n      }\n    }\n  `;\n  const expectedResult: OperationDefinitionNode = expectedDoc\n    .definitions[0] as OperationDefinitionNode;\n  const actualResult = getQueryDefinition(queryWithFragments);\n\n  expect(print(actualResult)).toEqual(print(expectedResult));\n});\n\ntest(\"should throw if we try to get the query definition of a document with no query\", () => {\n  const mutationWithFragments = gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    mutation {\n      createAuthor(firstName: \"John\", lastName: \"Smith\") {\n        ...authorDetails\n      }\n    }\n  `;\n  expect(() => {\n    getQueryDefinition(mutationWithFragments);\n  }).toThrow();\n});\n\ntest(\"should throw if type definitions found in document\", () => {\n  const queryWithTypeDefinition = gql`\n    fragment authorDetails on Author {\n      firstName\n      lastName\n    }\n\n    query ($search: AuthorSearchInputType) {\n      author(search: $search) {\n        ...authorDetails\n      }\n    }\n\n    input AuthorSearchInputType {\n      firstName: String\n    }\n  `;\n  expect(() => {\n    getQueryDefinition(queryWithTypeDefinition);\n  }).toThrow(\n    'Schema type definitions not allowed in queries. Found: \"InputObjectTypeDefinition\"'\n  );\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/getStoreKeyName.test.ts",
    "content": "import { getStoreKeyName } from \"@apollo/client/utilities/internal\";\n\ntest(\"should return a deterministic version of the store key name no matter which order the args object properties are in\", () => {\n  const validStoreKeyName = 'someField({\"prop1\":\"value1\",\"prop2\":\"value2\"})';\n  let generatedStoreKeyName = getStoreKeyName(\"someField\", {\n    prop1: \"value1\",\n    prop2: \"value2\",\n  });\n  expect(generatedStoreKeyName).toEqual(validStoreKeyName);\n\n  generatedStoreKeyName = getStoreKeyName(\"someField\", {\n    prop2: \"value2\",\n    prop1: \"value1\",\n  });\n  expect(generatedStoreKeyName).toEqual(validStoreKeyName);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/hasDirectives.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport { hasDirectives } from \"@apollo/client/utilities/internal\";\n\ntest(\"should allow searching the ast for a directive\", () => {\n  const query = gql`\n    query Simple {\n      field @live\n    }\n  `;\n\n  expect(hasDirectives([\"live\"], query)).toBe(true);\n  expect(hasDirectives([\"defer\"], query)).toBe(false);\n});\n\ntest(\"works for all operation types\", () => {\n  const query = gql`\n    {\n      field @live {\n        subField {\n          hello @live\n        }\n      }\n    }\n  `;\n\n  const mutation = gql`\n    mutation Directive {\n      mutate {\n        field {\n          subField {\n            hello @live\n          }\n        }\n      }\n    }\n  `;\n\n  const subscription = gql`\n    subscription LiveDirective {\n      sub {\n        field {\n          subField {\n            hello @live\n          }\n        }\n      }\n    }\n  `;\n\n  [query, mutation, subscription].forEach((x) => {\n    expect(hasDirectives([\"live\"], x)).toBe(true);\n    expect(hasDirectives([\"defer\"], x)).toBe(false);\n  });\n});\n\ntest(\"works for simple fragments\", () => {\n  const query = gql`\n    query Simple {\n      ...fieldFragment\n    }\n\n    fragment fieldFragment on Field {\n      foo @live\n    }\n  `;\n  expect(hasDirectives([\"live\"], query)).toBe(true);\n  expect(hasDirectives([\"defer\"], query)).toBe(false);\n});\n\ntest(\"works for nested fragments\", () => {\n  const query = gql`\n    query Simple {\n      ...fieldFragment1\n    }\n\n    fragment fieldFragment1 on Field {\n      bar {\n        baz {\n          ...nestedFragment\n        }\n      }\n    }\n\n    fragment nestedFragment on Field {\n      foo @live\n    }\n  `;\n  expect(hasDirectives([\"live\"], query)).toBe(true);\n  expect(hasDirectives([\"defer\"], query)).toBe(false);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/maybeDeepFreeze.test.ts",
    "content": "import { maybeDeepFreeze } from \"@apollo/client/utilities/internal\";\n\ntest(\"should deep freeze\", () => {\n  const foo: any = { bar: undefined };\n  maybeDeepFreeze(foo);\n  expect(() => (foo.bar = 1)).toThrow();\n  expect(foo.bar).toBeUndefined();\n});\n\ntest(\"should properly freeze objects without hasOwnProperty\", () => {\n  const foo: Record<string, any> = {};\n  foo.bar = undefined;\n  maybeDeepFreeze(foo);\n  expect(() => (foo.bar = 1)).toThrow();\n});\n\ntest(\"should avoid freezing Uint8Array\", () => {\n  const result = maybeDeepFreeze({ array: new Uint8Array(1) });\n  expect(Object.isFrozen(result)).toBe(true);\n  expect(Object.isFrozen(result.array)).toBe(false);\n});\n\ntest(\"should avoid freezing Buffer\", () => {\n  const result = maybeDeepFreeze({ oyez: Buffer.from(\"oyez\") });\n  expect(Object.isFrozen(result)).toBe(true);\n  expect(Object.isFrozen(result.oyez)).toBe(false);\n});\n\ntest(\"should not freeze child properties of unfreezable objects\", () => {\n  const result = maybeDeepFreeze({\n    buffer: Object.assign(Buffer.from(\"oyez\"), {\n      doNotFreeze: { please: \"thanks\" },\n    }),\n  });\n  expect(Object.isFrozen(result)).toBe(true);\n  expect(Object.isFrozen(result.buffer)).toBe(false);\n  expect(Object.isFrozen(result.buffer.doNotFreeze)).toBe(false);\n  expect(result.buffer.doNotFreeze).toEqual({ please: \"thanks\" });\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/mergeDeep.test.ts",
    "content": "import { mergeDeep } from \"@apollo/client/utilities/internal\";\n\ntest(\"should return an object if first argument falsy\", function () {\n  expect(mergeDeep()).toEqual({});\n  expect(mergeDeep(null)).toEqual({});\n  expect(mergeDeep(null, { foo: 42 })).toEqual({ foo: 42 });\n});\n\ntest(\"should preserve identity for single arguments\", function () {\n  const arg = {};\n  expect(mergeDeep(arg)).toBe(arg);\n});\n\ntest(\"should preserve identity when merging non-conflicting objects\", function () {\n  const a = { a: { name: \"ay\" } };\n  const b = { b: { name: \"bee\" } };\n  const c = mergeDeep(a, b);\n  expect(c.a).toBe(a.a);\n  expect(c.b).toBe(b.b);\n  expect(c).toEqual({\n    a: { name: \"ay\" },\n    b: { name: \"bee\" },\n  });\n});\n\ntest(\"should shallow-copy conflicting fields\", function () {\n  const a = { conflict: { fromA: [1, 2, 3] } };\n  const b = { conflict: { fromB: [4, 5] } };\n  const c = mergeDeep(a, b);\n  expect(c.conflict).not.toBe(a.conflict);\n  expect(c.conflict).not.toBe(b.conflict);\n  expect(c.conflict.fromA).toBe(a.conflict.fromA);\n  expect(c.conflict.fromB).toBe(b.conflict.fromB);\n  expect(c).toEqual({\n    conflict: {\n      fromA: [1, 2, 3],\n      fromB: [4, 5],\n    },\n  });\n});\n\ntest(\"should resolve conflicts among more than two objects\", function () {\n  const sources = [];\n\n  for (let i = 0; i < 100; ++i) {\n    sources.push({\n      [\"unique\" + i]: { value: i },\n      conflict: {\n        [\"from\" + i]: { value: i },\n        nested: {\n          [\"nested\" + i]: { value: i },\n        },\n      },\n    });\n  }\n\n  const merged = mergeDeep(...sources);\n\n  sources.forEach((source, i) => {\n    expect(merged[\"unique\" + i].value).toBe(i);\n    expect(source[\"unique\" + i]).toBe(merged[\"unique\" + i]);\n\n    expect(merged.conflict).not.toBe(source.conflict);\n    expect(merged.conflict[\"from\" + i].value).toBe(i);\n    expect(merged.conflict[\"from\" + i]).toBe(source.conflict[\"from\" + i]);\n\n    expect(merged.conflict.nested).not.toBe(source.conflict.nested);\n    expect(merged.conflict.nested[\"nested\" + i].value).toBe(i);\n    expect(merged.conflict.nested[\"nested\" + i]).toBe(\n      source.conflict.nested[\"nested\" + i]\n    );\n  });\n});\n\ntest(\"can merge array elements\", function () {\n  const a = [{ a: 1 }, { a: \"ay\" }, \"a\"];\n  const b = [{ b: 2 }, { b: \"bee\" }, \"b\"];\n  const c = [{ c: 3 }, { c: \"cee\" }, \"c\"];\n  const d = { 1: { d: \"dee\" } };\n\n  expect(mergeDeep(a, b, c, d)).toEqual([\n    { a: 1, b: 2, c: 3 },\n    { a: \"ay\", b: \"bee\", c: \"cee\", d: \"dee\" },\n    \"c\",\n  ]);\n});\n\ntest(\"lets the last conflicting value win\", function () {\n  expect(mergeDeep(\"a\", \"b\", \"c\")).toBe(\"c\");\n\n  expect(\n    mergeDeep(\n      { a: \"a\", conflict: 1 },\n      { b: \"b\", conflict: 2 },\n      { c: \"c\", conflict: 3 }\n    )\n  ).toEqual({\n    a: \"a\",\n    b: \"b\",\n    c: \"c\",\n    conflict: 3,\n  });\n\n  // prettier-ignore\n  expect(\n      mergeDeep(\n        ['a', ['b', 'c'], 'd'],\n        [/*empty*/, ['B'], 'D'],\n      )\n    ).toEqual(\n      ['a', ['B', 'c'], 'D'],\n    );\n\n  // prettier-ignore\n  expect(\n      mergeDeep(\n        ['a', ['b', 'c'], 'd'],\n        ['A', [/*empty*/, 'C']],\n      )\n    ).toEqual(\n      ['A', ['b', 'C'], 'd'],\n    );\n});\n\ntest(\"mergeDeep returns the intersection of its argument types\", function () {\n  const abc = mergeDeep({ str: \"hi\", a: 1 }, { a: 3, b: 2 }, { b: 1, c: 2 });\n  // The point of this test is that the following lines type-check without\n  // resorting to any `any` loopholes:\n  expect(abc.str.slice(0)).toBe(\"hi\");\n  expect(abc.a * 2).toBe(6);\n  expect(abc.b - 0).toBe(1);\n  expect(abc.c / 2).toBe(1);\n});\n\ntest(\"returns original object references when possible\", function () {\n  const target = {\n    a: 1,\n    b: {\n      c: 3,\n      d: 4,\n    },\n    e: 5,\n  };\n\n  expect(\n    mergeDeep(target, {\n      b: {\n        c: 3,\n      },\n    })\n  ).toBe(target);\n\n  const partial = mergeDeep(target, {\n    a: 1,\n    b: {\n      c: 3,\n    },\n    e: \"eee\",\n  });\n\n  expect(partial).not.toBe(target);\n  expect(partial.b).toBe(target.b);\n\n  const multiple = mergeDeep(\n    target,\n    {\n      a: 1,\n    },\n    {\n      b: {\n        d: 4,\n      },\n    },\n    {\n      e: 5,\n    }\n  );\n\n  expect(multiple).toBe(target);\n\n  const targetWithArrays = {\n    a: 1,\n    b: [\n      2,\n      {\n        c: [3, 4],\n        d: 5,\n      },\n      6,\n    ],\n    e: [7, 8, 9],\n  };\n\n  expect(\n    mergeDeep(targetWithArrays, {\n      e: [],\n    })\n  ).toBe(targetWithArrays);\n\n  expect(\n    mergeDeep(targetWithArrays, {\n      e: [, , /*hole*/ /*hole*/ 9],\n    })\n  ).toBe(targetWithArrays);\n\n  expect(\n    mergeDeep(targetWithArrays, {\n      a: 1,\n      e: [7, 8],\n    })\n  ).toBe(targetWithArrays);\n\n  expect(\n    mergeDeep(targetWithArrays, {\n      b: [\n        2,\n        {\n          c: [],\n          d: 5,\n        },\n      ],\n    })\n  ).toBe(targetWithArrays);\n\n  expect(\n    mergeDeep(targetWithArrays, {\n      b: [\n        2,\n        {\n          c: [3],\n          d: 5,\n        },\n        6,\n      ],\n      e: [],\n    })\n  ).toBe(targetWithArrays);\n\n  const nestedInequality = mergeDeep(targetWithArrays, {\n    b: [\n      2,\n      {\n        c: [3],\n        d: 5,\n      },\n      \"wrong\",\n    ],\n    e: [],\n  });\n\n  expect(nestedInequality).not.toBe(targetWithArrays);\n  expect(nestedInequality.b).not.toBe(targetWithArrays.b);\n  expect(nestedInequality.b[1]).toEqual({\n    c: [3, 4],\n    d: 5,\n  });\n  expect(nestedInequality.b[1]).toBe(targetWithArrays.b[1]);\n\n  expect(\n    mergeDeep(\n      targetWithArrays,\n      JSON.parse(JSON.stringify(targetWithArrays)),\n      JSON.parse(JSON.stringify(targetWithArrays)),\n      JSON.parse(JSON.stringify(targetWithArrays))\n    )\n  ).toBe(targetWithArrays);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/mergeDeepArray.test.ts",
    "content": "import { mergeDeepArray } from \"@apollo/client/utilities/internal\";\n\ntest(\"mergeDeepArray returns the supertype of its argument types\", function () {\n  class F {\n    check() {\n      return \"ok\";\n    }\n  }\n  const fs: F[] = [new F(), new F(), new F()];\n  // Although mergeDeepArray doesn't have the same tuple type awareness as\n  // mergeDeep, it does infer that F should be the return type here:\n  expect(mergeDeepArray(fs).check()).toBe(\"ok\");\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/omitDeep.test.ts",
    "content": "import { omitDeep } from \"@apollo/client/utilities/internal\";\n\ntest(\"omits the key from a shallow object\", () => {\n  expect(omitDeep({ omit: \"a\", keep: \"b\", other: \"c\" }, \"omit\")).toEqual({\n    keep: \"b\",\n    other: \"c\",\n  });\n});\n\ntest(\"omits the key from arbitrarily nested object\", () => {\n  expect(\n    omitDeep(\n      {\n        omit: \"a\",\n        keep: {\n          omit: \"a\",\n          keep: \"b\",\n          other: { omit: \"a\", keep: \"b\", other: \"c\" },\n        },\n      },\n      \"omit\"\n    )\n  ).toEqual({\n    keep: {\n      keep: \"b\",\n      other: { keep: \"b\", other: \"c\" },\n    },\n  });\n});\n\ntest(\"omits the key from arrays\", () => {\n  expect(\n    omitDeep(\n      [\n        { omit: \"a\", keep: \"b\", other: \"c\" },\n        { omit: \"a\", keep: \"b\", other: \"c\" },\n      ],\n      \"omit\"\n    )\n  ).toEqual([\n    { keep: \"b\", other: \"c\" },\n    { keep: \"b\", other: \"c\" },\n  ]);\n});\n\ntest(\"omits the key from arbitrarily nested arrays\", () => {\n  expect(\n    omitDeep(\n      [\n        [{ omit: \"a\", keep: \"b\", other: \"c\" }],\n        [\n          { omit: \"a\", keep: \"b\", other: \"c\" },\n          [{ omit: \"a\", keep: \"b\", other: \"c\" }],\n        ],\n      ],\n      \"omit\"\n    )\n  ).toEqual([\n    [{ keep: \"b\", other: \"c\" }],\n    [{ keep: \"b\", other: \"c\" }, [{ keep: \"b\", other: \"c\" }]],\n  ]);\n});\n\ntest(\"returns primitives unchanged\", () => {\n  expect(omitDeep(\"a\", \"ignored\")).toBe(\"a\");\n  expect(omitDeep(1, \"ignored\")).toBe(1);\n  expect(omitDeep(true, \"ignored\")).toBe(true);\n  expect(omitDeep(null, \"ignored\")).toBe(null);\n  expect(omitDeep(undefined, \"ignored\")).toBe(undefined);\n  expect(omitDeep(Symbol.for(\"foo\"), \"ignored\")).toBe(Symbol.for(\"foo\"));\n});\n\ntest(\"handles circular references\", () => {\n  let b: any;\n  const a = { omit: \"foo\", b };\n  b = { a, omit: \"foo\" };\n  a.b = b;\n\n  const variables = { a, b, omit: \"foo\" };\n\n  const result = omitDeep(variables, \"omit\");\n\n  expect(result).not.toHaveProperty(\"omit\");\n  expect(result.a).not.toHaveProperty(\"omit\");\n  expect(result.b).not.toHaveProperty(\"omit\");\n});\n\ntest(\"returns same object unmodified if key is not found\", () => {\n  const obj = {\n    a: \"a\",\n    b: \"b\",\n    c: { d: \"d\", e: \"e\" },\n  };\n\n  const arr = [{ a: \"a\", b: \"b\", c: \"c\" }, { foo: \"bar\" }];\n\n  expect(omitDeep(obj, \"omit\")).toBe(obj);\n  expect(omitDeep(arr, \"omit\")).toBe(arr);\n});\n\ntest(\"returns unmodified subtrees for subtrees that do not contain the key\", () => {\n  const original = {\n    a: \"a\",\n    foo: { bar: \"true\" },\n    baz: [{ foo: \"bar\" }],\n    omitOne: [{ foo: \"bar\", omit: true }, { foo: \"bar\" }],\n  };\n\n  const result = omitDeep(original, \"omit\");\n\n  expect(result).not.toBe(original);\n  expect(result.foo).toBe(original.foo);\n  expect(result.baz).toBe(original.baz);\n  expect(result.omitOne).not.toBe(original.omitOne);\n  expect(result.omitOne[0]).not.toBe(original.omitOne[0]);\n  expect(result.omitOne[1]).toBe(original.omitOne[1]);\n});\n\ntest(\"only considers plain objects and ignores class instances when omitting properties\", () => {\n  class Thing {\n    foo = \"bar\";\n    omit = false;\n  }\n\n  const thing = new Thing();\n  const original = { thing };\n\n  const result = omitDeep(original, \"omit\");\n\n  expect(result.thing).toBe(thing);\n  expect(result.thing).toHaveProperty(\"omit\", false);\n\n  const modifiedThing = omitDeep(thing, \"omit\");\n\n  expect(modifiedThing).toBe(thing);\n  expect(modifiedThing).toHaveProperty(\"omit\", false);\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/removeDirectivesFromDocument.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport { addTypenameToDocument } from \"@apollo/client/utilities\";\nimport { removeDirectivesFromDocument } from \"@apollo/client/utilities/internal\";\n\ntest(\"should remove inline fragments using a directive\", () => {\n  const query = gql`\n    query Simple {\n      networkField\n      field {\n        ... on TypeA {\n          typeAThing\n        }\n        ... on TypeB @client {\n          typeBThing @client\n        }\n      }\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      networkField\n      field {\n        ... on TypeA {\n          typeAThing\n        }\n      }\n    }\n  `);\n});\n\ntest(\"should not remove unused variable definitions unless the field is removed\", () => {\n  const query = gql`\n    query Simple($variable: String!) {\n      field(usingVariable: $variable) @client\n      networkField\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument([{ name: \"client\" }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple($variable: String!) {\n      field(usingVariable: $variable)\n      networkField\n    }\n  `);\n});\n\ntest(\"should remove unused variable definitions associated with the removed directive\", () => {\n  const query = gql`\n    query Simple($variable: String!) {\n      field(usingVariable: $variable) @client\n      networkField\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      networkField\n    }\n  `);\n});\n\ntest(\"should not remove used variable definitions\", () => {\n  const query = gql`\n    query Simple($variable: String!) {\n      field(usingVariable: $variable) @client\n      networkField(usingVariable: $variable)\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple($variable: String!) {\n      networkField(usingVariable: $variable)\n    }\n  `);\n});\n\ntest(\"should remove fragment spreads and definitions associated with the removed directive\", () => {\n  const query = gql`\n    query Simple {\n      networkField\n      field @client {\n        ...ClientFragment\n      }\n    }\n\n    fragment ClientFragment on Thing {\n      otherField\n      bar\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      networkField\n    }\n  `);\n});\n\ntest(\"should not remove fragment spreads and definitions used without the removed directive\", () => {\n  const query = gql`\n    query Simple {\n      networkField {\n        ...ClientFragment\n      }\n      field @client {\n        ...ClientFragment\n      }\n    }\n\n    fragment ClientFragment on Thing {\n      otherField\n      bar\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"client\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      networkField {\n        ...ClientFragment\n      }\n    }\n\n    fragment ClientFragment on Thing {\n      otherField\n      bar\n    }\n  `);\n});\n\ntest(\"should remove a simple directive\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument([{ name: \"storage\" }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      field\n    }\n  `);\n});\n\ntest(\"should remove a simple directive [test function]\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n    }\n  `;\n\n  const test = ({ name: { value } }: { name: any }) => value === \"storage\";\n  const doc = removeDirectivesFromDocument([{ test }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      field\n    }\n  `);\n});\n\ntest(\"should remove only the wanted directive\", () => {\n  const query = gql`\n    query Simple {\n      maybe @skip(if: false)\n      field @storage(if: true)\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument([{ name: \"storage\" }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      maybe @skip(if: false)\n      field\n    }\n  `);\n});\n\ntest(\"should remove only the wanted directive [test function]\", () => {\n  const query = gql`\n    query Simple {\n      maybe @skip(if: false)\n      field @storage(if: true)\n    }\n  `;\n\n  const test = ({ name: { value } }: { name: any }) => value === \"storage\";\n  const doc = removeDirectivesFromDocument([{ test }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      maybe @skip(if: false)\n      field\n    }\n  `);\n});\n\ntest(\"should remove multiple directives in the query\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n      other: field @storage\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument([{ name: \"storage\" }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      field\n      other: field\n    }\n  `);\n});\n\ntest(\"should remove multiple directives of different kinds in the query\", () => {\n  const query = gql`\n    query Simple {\n      maybe @skip(if: false)\n      field @storage(if: true)\n      other: field @client\n    }\n  `;\n\n  const removed = [\n    { name: \"storage\" },\n    {\n      test: (directive: any) => directive.name.value === \"client\",\n    },\n  ];\n  const doc = removeDirectivesFromDocument(removed, query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      maybe @skip(if: false)\n      field\n      other: field\n    }\n  `);\n});\n\ntest(\"should remove a simple directive and its field if needed\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n      keep\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      keep\n    }\n  `);\n});\n\ntest(\"should remove a simple directive [test function]\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n      keep\n    }\n  `;\n\n  const test = ({ name: { value } }: { name: any }) => value === \"storage\";\n  const doc = removeDirectivesFromDocument([{ test, remove: true }], query);\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      keep\n    }\n  `);\n});\n\ntest(\"should return null if the query is no longer valid\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toBe(null);\n});\n\ntest(\"should return null if the query is no longer valid [test function]\", () => {\n  const query = gql`\n    query Simple {\n      field @storage(if: true)\n    }\n  `;\n\n  const test = ({ name: { value } }: { name: any }) => value === \"storage\";\n  const doc = removeDirectivesFromDocument([{ test, remove: true }], query);\n\n  expect(doc).toBe(null);\n});\n\ntest(\"should not return null if nothing was removed\", () => {\n  const query = gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      field\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toBe(query);\n});\n\ntest(\"should return null only if the query is not valid through nested fragments\", () => {\n  const query = gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      ...inDirection\n    }\n\n    fragment inDirection on Thing {\n      field @storage\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toBe(null);\n});\n\ntest(\"should only remove values asked through nested fragments\", () => {\n  const query = gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      ...inDirection\n    }\n\n    fragment inDirection on Thing {\n      field @storage\n      bar\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toMatchDocument(gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      ...inDirection\n    }\n\n    fragment inDirection on Thing {\n      bar\n    }\n  `);\n});\n\ntest(\"should return null even through fragments if needed\", () => {\n  const query = gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      field @storage\n    }\n  `;\n\n  const doc = removeDirectivesFromDocument(\n    [{ name: \"storage\", remove: true }],\n    query\n  );\n\n  expect(doc).toBe(null);\n});\n\ntest(\"should not throw in combination with addTypenameToDocument\", () => {\n  const query = gql`\n    query Simple {\n      ...fragmentSpread\n    }\n\n    fragment fragmentSpread on Thing {\n      ...inDirection\n    }\n\n    fragment inDirection on Thing {\n      field @storage\n    }\n  `;\n\n  expect(() => {\n    removeDirectivesFromDocument(\n      [{ name: \"storage\", remove: true }],\n      addTypenameToDocument(query)\n    );\n  }).not.toThrow();\n});\n"
  },
  {
    "path": "src/utilities/internal/__tests__/shouldInclude.test.ts",
    "content": "import { gql } from \"@apollo/client\";\nimport {\n  cloneDeep,\n  getQueryDefinition,\n  shouldInclude,\n} from \"@apollo/client/utilities/internal\";\n\ntest(\"should should not include a skipped field\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should include an included field\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @include(if: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should not include a not include: false field\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @include(if: false)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should include a skip: false field\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: false)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should not include a field if skip: true and include: true\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: true) @include(if: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should not include a field if skip: true and include: false\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: true) @include(if: false)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should include a field if skip: false and include: true\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: false) @include(if: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should not include a field if skip: false and include: false\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: false) @include(if: false)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, {})).toBe(true);\n});\n\ntest(\"should leave the original query unmodified\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(if: false) @include(if: false)\n    }\n  `;\n  const queryClone = cloneDeep(query);\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  shouldInclude(field, {});\n  expect(query).toEqual(queryClone);\n});\n\ntest(\"does not throw an error on an unsupported directive\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @dosomething(if: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n\n  expect(() => {\n    shouldInclude(field, {});\n  }).not.toThrow();\n});\n\ntest(\"throws an error on an invalid argument for the skip directive\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @skip(nothing: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n\n  expect(() => {\n    shouldInclude(field, {});\n  }).toThrow();\n});\n\ntest(\"throws an error on an invalid argument for the include directive\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @include(nothing: true)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n\n  expect(() => {\n    shouldInclude(field, {});\n  }).toThrow();\n});\n\ntest(\"throws an error on an invalid variable name within a directive argument\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @include(if: $neverDefined)\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(() => {\n    shouldInclude(field, {});\n  }).toThrow();\n});\n\ntest(\"evaluates variables on skip fields\", () => {\n  const query = gql`\n    query ($shouldSkip: Boolean) {\n      fortuneCookie @skip(if: $shouldSkip)\n    }\n  `;\n  const variables = {\n    shouldSkip: true,\n  };\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, variables)).toBe(true);\n});\n\ntest(\"evaluates variables on include fields\", () => {\n  const query = gql`\n    query ($shouldSkip: Boolean) {\n      fortuneCookie @include(if: $shouldInclude)\n    }\n  `;\n  const variables = {\n    shouldInclude: false,\n  };\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(!shouldInclude(field, variables)).toBe(true);\n});\n\ntest(\"throws an error if the value of the argument is not a variable or boolean\", () => {\n  const query = gql`\n    query {\n      fortuneCookie @include(if: \"string\")\n    }\n  `;\n  const field = getQueryDefinition(query).selectionSet.selections[0];\n  expect(() => {\n    shouldInclude(field, {});\n  }).toThrow();\n});\n"
  },
  {
    "path": "src/utilities/internal/argumentsObjectFromField.ts",
    "content": "import type { DirectiveNode, FieldNode } from \"graphql\";\n\nimport { valueToObjectRepresentation } from \"./valueToObjectRepresentation.js\";\n\n/** @internal */\nexport function argumentsObjectFromField(\n  field: FieldNode | DirectiveNode,\n  variables?: Record<string, any>\n): Object | null {\n  if (field.arguments && field.arguments.length) {\n    const argObj: Object = {};\n    field.arguments.forEach(({ name, value }) =>\n      valueToObjectRepresentation(argObj, name, value, variables)\n    );\n    return argObj;\n  }\n  return null;\n}\n"
  },
  {
    "path": "src/utilities/internal/bindCacheKey.ts",
    "content": "import { defaultMakeCacheKey } from \"optimism\";\n\n/**\n * A variant of `optimism`'s `defaultMakeCacheKey` function that allows us to\n * pre-bind some arguments to be part of the cache key Trie path.\n *\n * This should always be used in place of `defaultMakeCacheKey` to bind\n * the `this` context of classes owning wrapped functions, to ensure that\n * the cache keys are collected from memory when the owning object is garbage collected.\n *\n * Without this, cache keys can stay in memory indefinitely, even though the owning\n * Apollo Client instance is long gone.\n * This is a risk in long-running processes with `[DocumentNode, string, string]`\n * style cache keys with persistent document nodes.\n */\nexport function bindCacheKey(...prebound: object[]): (...args: any) => object {\n  return defaultMakeCacheKey.bind(null, ...prebound);\n}\n"
  },
  {
    "path": "src/utilities/internal/caches.ts",
    "content": "import { StrongCache, WeakCache } from \"@wry/caches\";\n\ninterface CleanableCache {\n  size: number;\n  max?: number;\n  clean: () => void;\n}\nconst scheduledCleanup = new WeakSet<CleanableCache>();\nfunction schedule(cache: CleanableCache) {\n  if (cache.size <= (cache.max || -1)) {\n    return;\n  }\n  if (!scheduledCleanup.has(cache)) {\n    scheduledCleanup.add(cache);\n    setTimeout(() => {\n      cache.clean();\n      scheduledCleanup.delete(cache);\n    }, 100);\n  }\n}\n/**\n * @internal\n * A version of WeakCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of WeakCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `WeakCache`.\n */\nexport const AutoCleanedWeakCache = function (\n  max?: number | undefined,\n  dispose?: ((value: any, key: any) => void) | undefined\n) {\n  /*\n  Some builds of `WeakCache` are function prototypes, some are classes.\n  This library still builds with an ES5 target, so we can't extend the\n  real classes.\n  Instead, we have to use this workaround until we switch to a newer build\n  target.\n  */\n  const cache = new WeakCache(max, dispose);\n  cache.set = function (key: any, value: any) {\n    const ret = WeakCache.prototype.set.call(this, key, value);\n    schedule(this as any as CleanableCache);\n    return ret;\n  };\n  return cache;\n} as any as typeof WeakCache;\n/**\n * @internal\n */\nexport type AutoCleanedWeakCache<K extends object, V> = WeakCache<K, V>;\n\n/**\n * @internal\n * A version of StrongCache that will auto-schedule a cleanup of the cache when\n * a new item is added and the cache reached maximum size.\n * Throttled to once per 100ms.\n *\n * @privateRemarks\n * Should be used throughout the rest of the codebase instead of StrongCache,\n * with the notable exception of usage in `wrap` from `optimism` - that one\n * already handles cleanup and should remain a `StrongCache`.\n */\nexport const AutoCleanedStrongCache = function (\n  max?: number | undefined,\n  dispose?: ((value: any, key: any) => void) | undefined\n) {\n  /*\n  Some builds of `StrongCache` are function prototypes, some are classes.\n  This library still builds with an ES5 target, so we can't extend the\n  real classes.\n  Instead, we have to use this workaround until we switch to a newer build\n  target.\n  */\n  const cache = new StrongCache(max, dispose);\n  cache.set = function (key: any, value: any) {\n    const ret = StrongCache.prototype.set.call(this, key, value);\n    schedule(this as any as CleanableCache);\n    return ret;\n  };\n  return cache;\n} as any as typeof StrongCache;\n/**\n * @internal\n */\nexport type AutoCleanedStrongCache<K, V> = StrongCache<K, V>;\n"
  },
  {
    "path": "src/utilities/internal/canUseDOM.ts",
    "content": "import { maybe } from \"@apollo/client/utilities/internal/globals\";\n\n/** @internal */\nexport const canUseDOM =\n  typeof maybe(() => window.document.createElement) === \"function\";\n"
  },
  {
    "path": "src/utilities/internal/canonicalStringify.ts",
    "content": "import { __DEV__ } from \"@apollo/client/utilities/environment\";\n\nimport { cacheSizes, defaultCacheSizes } from \"../caching/sizes.js\";\n\nimport { AutoCleanedStrongCache } from \"./caches.js\";\nimport { registerGlobalCache } from \"./getMemoryInternals.js\";\n\n/**\n * Serializes a value to JSON with object keys in a consistent, sorted order.\n *\n * @remarks\n *\n * Unlike `JSON.stringify()`, this function ensures that object keys are always\n * serialized in the same alphabetical order, regardless of their original order.\n * This makes it suitable for creating consistent cache keys from objects,\n * comparing objects by their serialized representation, or generating\n * deterministic hashes of objects.\n *\n * To achieve performant sorting, this function uses a `Map` from JSON-serialized\n * arrays of keys (in any order) to sorted arrays of the same keys, with a\n * single sorted array reference shared by all permutations of the keys.\n *\n * As a drawback, this function will add a little more memory for every object\n * encountered that has different (more, less, a different order of) keys than\n * in the past.\n *\n * In a typical application, this extra memory usage should not play a\n * significant role, as `canonicalStringify` will be called for only a limited\n * number of object shapes, and the cache will not grow beyond a certain point.\n * But in some edge cases, this could be a problem. Use canonicalStringify.reset()\n * as a way to clear the memoization cache.\n *\n * @param value - The value to stringify\n * @returns JSON string with consistently ordered object keys\n *\n * @example\n *\n * ```ts\n * import { canonicalStringify } from \"@apollo/client/utilities\";\n *\n * const obj1 = { b: 2, a: 1 };\n * const obj2 = { a: 1, b: 2 };\n *\n * console.log(canonicalStringify(obj1)); // '{\"a\":1,\"b\":2}'\n * console.log(canonicalStringify(obj2)); // '{\"a\":1,\"b\":2}'\n * ```\n */\nexport const canonicalStringify = Object.assign(\n  function canonicalStringify(value: any): string {\n    return JSON.stringify(value, stableObjectReplacer);\n  },\n  {\n    reset() {\n      // Clearing the sortingMap will reclaim all cached memory, without\n      // affecting the logical results of canonicalStringify, but potentially\n      // sacrificing performance until the cache is refilled.\n      sortingMap = new AutoCleanedStrongCache<string, readonly string[]>(\n        cacheSizes.canonicalStringify || defaultCacheSizes.canonicalStringify\n      );\n    },\n  }\n);\n\nif (__DEV__) {\n  registerGlobalCache(\"canonicalStringify\", () => sortingMap.size);\n}\n\n// Values are JSON-serialized arrays of object keys (in any order), and values\n// are sorted arrays of the same keys.\nlet sortingMap!: AutoCleanedStrongCache<string, readonly string[]>;\ncanonicalStringify.reset();\n\n// The JSON.stringify function takes an optional second argument called a\n// replacer function. This function is called for each key-value pair in the\n// object being stringified, and its return value is used instead of the\n// original value. If the replacer function returns a new value, that value is\n// stringified as JSON instead of the original value of the property.\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#the_replacer_parameter\nfunction stableObjectReplacer(key: string, value: any) {\n  if (value && typeof value === \"object\") {\n    const proto = Object.getPrototypeOf(value);\n    // We don't want to mess with objects that are not \"plain\" objects, which\n    // means their prototype is either Object.prototype or null. This check also\n    // prevents needlessly rearranging the indices of arrays.\n    if (proto === Object.prototype || proto === null) {\n      const keys = Object.keys(value);\n      // If keys is already sorted, let JSON.stringify serialize the original\n      // value instead of creating a new object with keys in the same order.\n      if (keys.every(everyKeyInOrder)) return value;\n      const unsortedKey = JSON.stringify(keys);\n      let sortedKeys = sortingMap.get(unsortedKey);\n      if (!sortedKeys) {\n        keys.sort();\n        const sortedKey = JSON.stringify(keys);\n        // Checking for sortedKey in the sortingMap allows us to share the same\n        // sorted array reference for all permutations of the same set of keys.\n        sortedKeys = sortingMap.get(sortedKey) || keys;\n        sortingMap.set(unsortedKey, sortedKeys);\n        sortingMap.set(sortedKey, sortedKeys);\n      }\n      const sortedObject = Object.create(proto);\n      // Reassigning the keys in sorted order will cause JSON.stringify to\n      // serialize them in sorted order.\n      sortedKeys.forEach((key) => {\n        sortedObject[key] = value[key];\n      });\n      return sortedObject;\n    }\n  }\n  return value;\n}\n\n// Since everything that happens in stableObjectReplacer benefits from being as\n// efficient as possible, we use a static function as the callback for\n// keys.every in order to test if the provided keys are already sorted without\n// allocating extra memory for a callback.\nfunction everyKeyInOrder(\n  key: string,\n  i: number,\n  keys: readonly string[]\n): boolean {\n  return i === 0 || keys[i - 1] <= key;\n}\n"
  },
  {
    "path": "src/utilities/internal/checkDocument.ts",
    "content": "// Checks the document for errors and throws an exception if there is an error.\n\nimport type { ASTNode } from \"graphql\";\nimport type { DocumentNode, OperationTypeNode } from \"graphql\";\nimport { Kind, visit } from \"graphql\";\n\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nimport { defaultCacheSizes } from \"../../utilities/caching/sizes.js\";\nimport { cacheSizes } from \"../caching/sizes.js\";\n\nimport { getOperationName } from \"./getOperationName.js\";\nimport { memoize } from \"./memoize.js\";\n\n/**\n * Checks the document for errors and throws an exception if there is an error.\n *\n * @internal\n */\nexport const checkDocument: (\n  doc: DocumentNode,\n  expectedType?: OperationTypeNode\n) => void = memoize(\n  (doc: DocumentNode, expectedType?: OperationTypeNode): void => {\n    invariant(\n      doc && doc.kind === \"Document\",\n      `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n    );\n    const operations = doc.definitions.filter(\n      (d) => d.kind === \"OperationDefinition\"\n    );\n    if (__DEV__) {\n      doc.definitions.forEach((definition) => {\n        if (\n          definition.kind !== \"OperationDefinition\" &&\n          definition.kind !== \"FragmentDefinition\"\n        ) {\n          throw newInvariantError(\n            `Schema type definitions not allowed in queries. Found: \"%s\"`,\n            definition.kind\n          );\n        }\n      });\n\n      invariant(\n        operations.length <= 1,\n        `Ambiguous GraphQL document: contains %s operations`,\n        operations.length\n      );\n    }\n\n    if (expectedType) {\n      invariant(\n        operations.length == 1 && operations[0].operation === expectedType,\n        `Running a %s requires a graphql ` + `%s, but a %s was used instead.`,\n        expectedType,\n        expectedType,\n        operations[0].operation\n      );\n    }\n\n    visit(doc, {\n      Field(field, _, __, path) {\n        if (\n          field.alias &&\n          (field.alias.value === \"__typename\" ||\n            field.alias.value.startsWith(\"__ac_\")) &&\n          field.alias.value !== field.name.value\n        ) {\n          // not using `invariant` so path calculation only happens in error case\n          let current: ASTNode = doc,\n            fieldPath: string[] = [];\n          for (const key of path) {\n            current = (current as any)[key];\n            if (current.kind === Kind.FIELD) {\n              fieldPath.push(current.alias?.value || current.name.value);\n            }\n          }\n          fieldPath.splice(-1, 1, field.name.value);\n\n          throw newInvariantError(\n            '`%s` is a forbidden field alias name in the selection set for field `%s` in %s \"%s\".',\n            field.alias.value,\n            fieldPath.join(\".\"),\n            operations[0].operation,\n            getOperationName(doc, \"(anonymous)\")\n          );\n        }\n      },\n    });\n  },\n  {\n    max: cacheSizes[\"checkDocument\"] || defaultCacheSizes[\"checkDocument\"],\n  }\n);\n"
  },
  {
    "path": "src/utilities/internal/cloneDeep.ts",
    "content": "const { toString } = Object.prototype;\n\n/**\n * Deeply clones a value to create a new instance.\n *\n * @internal\n */\nexport function cloneDeep<T>(value: T): T {\n  return __cloneDeep(value);\n}\n\nfunction __cloneDeep<T>(val: T, seen?: Map<any, any>): T {\n  switch (toString.call(val)) {\n    case \"[object Array]\": {\n      seen = seen || new Map();\n      if (seen.has(val)) return seen.get(val);\n      const copy: T & any[] = (val as any).slice(0);\n      seen.set(val, copy);\n      copy.forEach(function (child, i) {\n        copy[i] = __cloneDeep(child, seen);\n      });\n      return copy;\n    }\n\n    case \"[object Object]\": {\n      seen = seen || new Map();\n      if (seen.has(val)) return seen.get(val);\n      // High fidelity polyfills of Object.create and Object.getPrototypeOf are\n      // possible in all JS environments, so we will assume they exist/work.\n      const copy = Object.create(Object.getPrototypeOf(val));\n      seen.set(val, copy);\n      Object.keys(val as T & Record<string, any>).forEach((key) => {\n        copy[key] = __cloneDeep((val as any)[key], seen);\n      });\n      return copy;\n    }\n\n    default:\n      return val;\n  }\n}\n"
  },
  {
    "path": "src/utilities/internal/combineLatestBatched.ts",
    "content": "import { EMPTY, Observable } from \"rxjs\";\n\n/**\n * Like `combineLatest` but with some differences:\n *\n * - It only works on arrays as an input\n * - Batches updates to each array index that contains a referentially equal\n *   observable\n * - Doesn't allow for custom scheduler\n * - Expects array of constructed observables instead of `Array<ObservableInput>`\n */\nexport function combineLatestBatched<T>(\n  observables: Array<Observable<T> & { dirty?: boolean }>\n) {\n  if (observables.length === 0) {\n    return EMPTY;\n  }\n\n  return new Observable<Array<T>>((observer) => {\n    const { length } = observables;\n    // Keeps track of current values for each observable\n    const values: T[] = new Array(length);\n    // Used to batch an update each item in the array that share an observable\n    // so that they can be emitted together.\n    const indexesByObservable = new Map<Observable<T>, Set<number>>();\n\n    observables.forEach((source, idx) => {\n      if (!indexesByObservable.has(source)) {\n        indexesByObservable.set(source, new Set());\n      }\n\n      indexesByObservable.get(source)!.add(idx);\n    });\n\n    // Track the number of active subscriptions so we know when to complete this\n    // observable\n    let active = indexesByObservable.size;\n    // Track how many observables are left to emit their first value\n    let remainingFirstValues = indexesByObservable.size;\n\n    let currentBatch: Set<Observable<T>> | undefined;\n\n    // Subscribe to each unique observable instead of the raw source array of\n    // observables since we want at most 1-subscription per unique observable.\n    // This ensures an update can write to multiple indexes before emitting the\n    // result.\n    indexesByObservable.forEach((indexes, source) => {\n      let hasFirstValue = false;\n      const subscription = source.subscribe({\n        next: (value) => {\n          indexes.forEach((idx) => (values[idx] = value));\n\n          if (!hasFirstValue) {\n            hasFirstValue = true;\n            remainingFirstValues--;\n          }\n\n          if (!remainingFirstValues) {\n            currentBatch ||= new Set(observables.filter((obs) => obs.dirty));\n            currentBatch.delete(source);\n            if (!currentBatch.size) {\n              observer.next(values.slice());\n              currentBatch = undefined;\n            }\n          }\n        },\n        complete: () => {\n          active--;\n\n          if (!active) {\n            observer.complete();\n          }\n        },\n        error: observer.error.bind(observer),\n      });\n\n      observer.add(subscription);\n    });\n  });\n}\n"
  },
  {
    "path": "src/utilities/internal/compact.ts",
    "content": "import type { TupleToIntersection } from \"./types/TupleToIntersection.js\";\n\n/**\n * Merges the provided objects shallowly and removes\n * all properties with an `undefined` value\n *\n * @internal\n */\nexport function compact<TArgs extends any[]>(\n  ...objects: TArgs\n): TupleToIntersection<TArgs> {\n  const result = {} as TupleToIntersection<TArgs>;\n\n  objects.forEach((obj) => {\n    if (!obj) return;\n    Reflect.ownKeys(obj).forEach((key: keyof typeof obj) => {\n      const value = obj[key];\n      if (value !== void 0) {\n        result[key] = value;\n      }\n    });\n  });\n\n  return result;\n}\n"
  },
  {
    "path": "src/utilities/internal/constants.ts",
    "content": "/**\n * @internal\n * Used to set `extensions` on the GraphQL result without exposing it\n * unnecessarily. Only use internally!\n */\nexport const extensionsSymbol = Symbol.for(\"apollo.result.extensions\");\n\n/**\n * For use in Cache implementations only.\n * This should not be used in userland code.\n */\nexport const streamInfoSymbol = Symbol.for(\"apollo.result.streamInfo\");\n\n/**\n * @internal\n * Used as key for `ApolloClient.WatchQueryOptions`.\n *\n * Meant for framework integrators only!\n */\nexport const variablesUnknownSymbol = Symbol.for(\n  \"apollo.observableQuery.variablesUnknown\"\n);\n"
  },
  {
    "path": "src/utilities/internal/createFragmentMap.ts",
    "content": "import type { FragmentDefinitionNode } from \"graphql\";\n\nimport type { FragmentMap } from \"./types/FragmentMap.js\";\n\n/**\n * Utility function that takes a list of fragment definitions and makes a hash out of them\n * that maps the name of the fragment to the fragment definition.\n *\n * @internal\n */\nexport function createFragmentMap(\n  fragments: FragmentDefinitionNode[] = []\n): FragmentMap {\n  const symTable: FragmentMap = {};\n  fragments.forEach((fragment) => {\n    symTable[fragment.name.value] = fragment;\n  });\n  return symTable;\n}\n"
  },
  {
    "path": "src/utilities/internal/createFulfilledPromise.ts",
    "content": "import type { FulfilledPromise } from \"./types/FulfilledPromise.js\";\n\n/** @internal */\nexport function createFulfilledPromise<TValue>(value: TValue) {\n  const promise = Promise.resolve(value) as FulfilledPromise<TValue>;\n\n  promise.status = \"fulfilled\";\n  promise.value = value;\n\n  return promise;\n}\n"
  },
  {
    "path": "src/utilities/internal/createRejectedPromise.ts",
    "content": "import type { RejectedPromise } from \"./types/RejectedPromise.js\";\n\n/** @internal */\nexport function createRejectedPromise<TValue = unknown>(reason: unknown) {\n  const promise = Promise.reject(reason) as RejectedPromise<TValue>;\n\n  // prevent potential edge cases leaking unhandled error rejections\n  promise.catch(() => {});\n\n  promise.status = \"rejected\";\n  promise.reason = reason;\n\n  return promise;\n}\n"
  },
  {
    "path": "src/utilities/internal/dealias.ts",
    "content": "import type { SelectionSetNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\n// Note: this is a shallow dealias function. We might consider a future\n// improvement of dealiasing all nested data. Until that need arises, we can\n// keep this simple.\nexport function dealias(\n  fieldValue: Record<string, any> | null | undefined,\n  selectionSet: SelectionSetNode\n) {\n  if (!fieldValue) {\n    return fieldValue;\n  }\n\n  const data = { ...fieldValue };\n\n  for (const selection of selectionSet.selections) {\n    if (selection.kind === Kind.FIELD && selection.alias) {\n      data[selection.name.value] = fieldValue[selection.alias.value];\n      delete data[selection.alias.value];\n    }\n  }\n\n  return data;\n}\n"
  },
  {
    "path": "src/utilities/internal/decoratePromise.ts",
    "content": "import type { DecoratedPromise } from \"./types/DecoratedPromise.js\";\nimport type { FulfilledPromise } from \"./types/FulfilledPromise.js\";\nimport type { PendingPromise } from \"./types/PendingPromise.js\";\nimport type { RejectedPromise } from \"./types/RejectedPromise.js\";\n\nfunction isDecoratedPromise<TValue>(\n  promise: Promise<TValue>\n): promise is DecoratedPromise<TValue> {\n  return \"status\" in promise;\n}\n\n/** @internal */\nexport function decoratePromise<TValue>(\n  promise: Promise<TValue>\n): DecoratedPromise<TValue> {\n  if (isDecoratedPromise(promise)) {\n    return promise;\n  }\n\n  const pendingPromise = promise as PendingPromise<TValue>;\n  pendingPromise.status = \"pending\";\n\n  pendingPromise.then(\n    (value) => {\n      if (pendingPromise.status === \"pending\") {\n        const fulfilledPromise =\n          pendingPromise as unknown as FulfilledPromise<TValue>;\n\n        fulfilledPromise.status = \"fulfilled\";\n        fulfilledPromise.value = value;\n      }\n    },\n    (reason: unknown) => {\n      if (pendingPromise.status === \"pending\") {\n        const rejectedPromise =\n          pendingPromise as unknown as RejectedPromise<TValue>;\n\n        rejectedPromise.status = \"rejected\";\n        rejectedPromise.reason = reason;\n      }\n    }\n  );\n\n  return promise as DecoratedPromise<TValue>;\n}\n"
  },
  {
    "path": "src/utilities/internal/deepFreeze.ts",
    "content": "import { __DEV__ } from \"@apollo/client/utilities/environment\";\n\nimport { isNonNullObject } from \"./isNonNullObject.js\";\n\n/** @internal only to be imported in tests */\nexport function deepFreeze(value: any) {\n  const workSet = new Set([value]);\n  workSet.forEach((obj) => {\n    if (isNonNullObject(obj) && shallowFreeze(obj) === obj) {\n      Object.getOwnPropertyNames(obj).forEach((name) => {\n        if (isNonNullObject(obj[name])) workSet.add(obj[name]);\n      });\n    }\n  });\n  return value;\n}\n\nfunction shallowFreeze<T extends object>(obj: T): T | null {\n  if (__DEV__ && !Object.isFrozen(obj)) {\n    try {\n      Object.freeze(obj);\n    } catch (e) {\n      // Some types like Uint8Array and Node.js's Buffer cannot be frozen, but\n      // they all throw a TypeError when you try, so we re-throw any exceptions\n      // that are not TypeErrors, since that would be unexpected.\n      if (e instanceof TypeError) return null;\n      throw e;\n    }\n  }\n  return obj;\n}\n"
  },
  {
    "path": "src/utilities/internal/equalByQuery.ts",
    "content": "import { equal } from \"@wry/equality\";\nimport type {\n  DirectiveNode,\n  DocumentNode,\n  FieldNode,\n  FragmentDefinitionNode,\n  FragmentSpreadNode,\n  InlineFragmentNode,\n  SelectionNode,\n  SelectionSetNode,\n} from \"graphql\";\n\nimport type { ObservableQuery } from \"@apollo/client\";\nimport type { OperationVariables } from \"@apollo/client\";\nimport type { FragmentMap } from \"@apollo/client/utilities/internal\";\n\nimport { createFragmentMap } from \"./createFragmentMap.js\";\nimport { getFragmentDefinitions } from \"./getFragmentDefinitions.js\";\nimport { getFragmentFromSelection } from \"./getFragmentFromSelection.js\";\nimport { getMainDefinition } from \"./getMainDefinition.js\";\nimport { isField } from \"./isField.js\";\nimport { resultKeyNameFromField } from \"./resultKeyNameFromField.js\";\nimport { shouldInclude } from \"./shouldInclude.js\";\n\n// Returns true if aResult and bResult are deeply equal according to the fields\n// selected by the given query, ignoring any fields marked as @nonreactive.\nexport function equalByQuery(\n  query: DocumentNode,\n  { data: aData, ...aRest }: Partial<ObservableQuery.Result<unknown>>,\n  { data: bData, ...bRest }: Partial<ObservableQuery.Result<unknown>>,\n  variables?: OperationVariables\n): boolean {\n  return (\n    equal(aRest, bRest) &&\n    equalBySelectionSet(getMainDefinition(query).selectionSet, aData, bData, {\n      fragmentMap: createFragmentMap(getFragmentDefinitions(query)),\n      variables,\n    })\n  );\n}\n\n// Encapsulates the information used by equalBySelectionSet that does not change\n// during the recursion.\ninterface CompareContext<TVariables extends OperationVariables> {\n  fragmentMap: FragmentMap;\n  variables: TVariables | undefined;\n}\n\nfunction equalBySelectionSet(\n  selectionSet: SelectionSetNode,\n  aResult: any,\n  bResult: any,\n  context: CompareContext<OperationVariables>\n): boolean {\n  if (aResult === bResult) {\n    return true;\n  }\n\n  const seenSelections = new Set<SelectionNode>();\n\n  // Returning true from this Array.prototype.every callback function skips the\n  // current field/subtree. Returning false aborts the entire traversal\n  // immediately, causing equalBySelectionSet to return false.\n  return selectionSet.selections.every((selection) => {\n    // Avoid re-processing the same selection at the same level of recursion, in\n    // case the same field gets included via multiple indirect fragment spreads.\n    if (seenSelections.has(selection)) return true;\n    seenSelections.add(selection);\n\n    // Ignore @skip(if: true) and @include(if: false) fields.\n    if (!shouldInclude(selection, context.variables)) return true;\n\n    // If the field or (named) fragment spread has a @nonreactive directive on\n    // it, we don't care if it's different, so we pretend it's the same.\n    if (selectionHasNonreactiveDirective(selection)) return true;\n\n    if (isField(selection)) {\n      const resultKey = resultKeyNameFromField(selection);\n      const aResultChild = aResult && aResult[resultKey];\n      const bResultChild = bResult && bResult[resultKey];\n      const childSelectionSet = selection.selectionSet;\n\n      if (!childSelectionSet) {\n        // These are scalar values, so we can compare them with deep equal\n        // without redoing the main recursive work.\n        return equal(aResultChild, bResultChild);\n      }\n\n      const aChildIsArray = Array.isArray(aResultChild);\n      const bChildIsArray = Array.isArray(bResultChild);\n      if (aChildIsArray !== bChildIsArray) return false;\n      if (aChildIsArray && bChildIsArray) {\n        const length = aResultChild.length;\n        if (bResultChild.length !== length) {\n          return false;\n        }\n        for (let i = 0; i < length; ++i) {\n          if (\n            !equalBySelectionSet(\n              childSelectionSet,\n              aResultChild[i],\n              bResultChild[i],\n              context\n            )\n          ) {\n            return false;\n          }\n        }\n        return true;\n      }\n\n      return equalBySelectionSet(\n        childSelectionSet,\n        aResultChild,\n        bResultChild,\n        context\n      );\n    } else {\n      const fragment = getFragmentFromSelection(selection, context.fragmentMap);\n      if (fragment) {\n        // The fragment might === selection if it's an inline fragment, but\n        // could be !== if it's a named fragment ...spread.\n        if (selectionHasNonreactiveDirective(fragment)) return true;\n\n        return equalBySelectionSet(\n          fragment.selectionSet,\n          // Notice that we reuse the same aResult and bResult values here,\n          // since the fragment ...spread does not specify a field name, but\n          // consists of multiple fields (within the fragment's selection set)\n          // that should be applied to the current result value(s).\n          aResult,\n          bResult,\n          context\n        );\n      }\n    }\n  });\n}\n\nfunction selectionHasNonreactiveDirective(\n  selection:\n    | FieldNode\n    | InlineFragmentNode\n    | FragmentSpreadNode\n    | FragmentDefinitionNode\n): boolean {\n  return (\n    !!selection.directives && selection.directives.some(directiveIsNonreactive)\n  );\n}\n\nfunction directiveIsNonreactive(dir: DirectiveNode): boolean {\n  return dir.name.value === \"nonreactive\";\n}\n"
  },
  {
    "path": "src/utilities/internal/filterMap.ts",
    "content": "import type { OperatorFunction } from \"rxjs\";\nimport { Observable } from \"rxjs\";\n\nexport function filterMap<T, R>(\n  fn: (value: T, context: undefined) => R | undefined\n): OperatorFunction<T, R>;\nexport function filterMap<T, R, Context>(\n  fn: (value: T, context: Context) => R | undefined,\n  makeContext: () => NoInfer<Context>\n): OperatorFunction<T, R>;\nexport function filterMap<T, R>(\n  fn: (value: T, context: any) => R | undefined,\n  makeContext = () => undefined\n): OperatorFunction<T, R> {\n  return (source) =>\n    new Observable<R>((subscriber) => {\n      let context = makeContext();\n      return source.subscribe({\n        next(value) {\n          let result: R | undefined;\n          try {\n            result = fn(value, context);\n          } catch (e) {\n            subscriber.error(e);\n          }\n          if (result === undefined) {\n            return;\n          }\n          subscriber.next(result);\n        },\n        error(err) {\n          subscriber.error(err);\n        },\n        complete() {\n          subscriber.complete();\n        },\n      });\n    });\n}\n"
  },
  {
    "path": "src/utilities/internal/getDefaultValues.ts",
    "content": "import type { OperationDefinitionNode, ValueNode } from \"graphql\";\n\nimport { valueToObjectRepresentation } from \"./valueToObjectRepresentation.js\";\n\n/** @internal */\nexport function getDefaultValues(\n  definition: OperationDefinitionNode | undefined\n): Record<string, any> {\n  const defaultValues = {};\n  const defs = definition && definition.variableDefinitions;\n  if (defs && defs.length) {\n    defs.forEach((def) => {\n      if (def.defaultValue) {\n        valueToObjectRepresentation(\n          defaultValues,\n          def.variable.name,\n          def.defaultValue as ValueNode\n        );\n      }\n    });\n  }\n  return defaultValues;\n}\n"
  },
  {
    "path": "src/utilities/internal/getFragmentDefinition.ts",
    "content": "import type { DocumentNode, FragmentDefinitionNode } from \"graphql\";\n\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\n/** @internal */\nexport function getFragmentDefinition(\n  doc: DocumentNode\n): FragmentDefinitionNode {\n  invariant(\n    doc.kind === \"Document\",\n    `Expecting a parsed GraphQL document. Perhaps you need to wrap the query \\\nstring in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql`\n  );\n\n  invariant(\n    doc.definitions.length <= 1,\n    \"Fragment must have exactly one definition.\"\n  );\n\n  const fragmentDef = doc.definitions[0] as FragmentDefinitionNode;\n\n  invariant(\n    fragmentDef.kind === \"FragmentDefinition\",\n    \"Must be a fragment definition.\"\n  );\n\n  return fragmentDef as FragmentDefinitionNode;\n}\n"
  },
  {
    "path": "src/utilities/internal/getFragmentDefinitions.ts",
    "content": "import type { DocumentNode, FragmentDefinitionNode } from \"graphql\";\n\n/** @internal */\nexport function getFragmentDefinitions(\n  doc: DocumentNode\n): FragmentDefinitionNode[] {\n  return doc.definitions.filter(\n    (definition): definition is FragmentDefinitionNode =>\n      definition.kind === \"FragmentDefinition\"\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/getFragmentFromSelection.ts",
    "content": "import type {\n  FragmentDefinitionNode,\n  InlineFragmentNode,\n  SelectionNode,\n} from \"graphql\";\n\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport type { FragmentMap } from \"./types/FragmentMap.js\";\nimport type { FragmentMapFunction } from \"./types/FragmentMapFunction.js\";\n\n/** @internal */\nexport function getFragmentFromSelection(\n  selection: SelectionNode,\n  fragmentMap?: FragmentMap | FragmentMapFunction\n): InlineFragmentNode | FragmentDefinitionNode | null {\n  switch (selection.kind) {\n    case \"InlineFragment\":\n      return selection;\n    case \"FragmentSpread\": {\n      const fragmentName = selection.name.value;\n      if (typeof fragmentMap === \"function\") {\n        return fragmentMap(fragmentName);\n      }\n      const fragment = fragmentMap && fragmentMap[fragmentName];\n      invariant(fragment, `No fragment named %s`, fragmentName);\n      return fragment || null;\n    }\n    default:\n      return null;\n  }\n}\n"
  },
  {
    "path": "src/utilities/internal/getFragmentQueryDocument.ts",
    "content": "import type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  Kind,\n  OperationTypeNode,\n} from \"graphql\";\n\nimport {\n  invariant,\n  newInvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\n/**\n * Returns a query document which adds a single query operation that only\n * spreads the target fragment inside of it.\n *\n * So for example a document of:\n *\n * ```graphql\n * fragment foo on Foo {\n *   a\n *   b\n *   c\n * }\n * ```\n *\n * Turns into:\n *\n * ```graphql\n * {\n *   ...foo\n * }\n *\n * fragment foo on Foo {\n *   a\n *   b\n *   c\n * }\n * ```\n *\n * The target fragment will either be the only fragment in the document, or a\n * fragment specified by the provided `fragmentName`. If there is more than one\n * fragment, but a `fragmentName` was not defined then an error will be thrown.\n *\n * @internal\n */\nexport function getFragmentQueryDocument(\n  document: DocumentNode,\n  fragmentName?: string\n): DocumentNode {\n  let actualFragmentName = fragmentName;\n\n  // Build an array of all our fragment definitions that will be used for\n  // validations. We also do some validations on the other definitions in the\n  // document while building this list.\n  const fragments: Array<FragmentDefinitionNode> = [];\n  document.definitions.forEach((definition) => {\n    // Throw an error if we encounter an operation definition because we will\n    // define our own operation definition later on.\n    if (definition.kind === \"OperationDefinition\") {\n      throw newInvariantError(\n        `Found a %s operation%s. ` +\n          \"No operations are allowed when using a fragment as a query. Only fragments are allowed.\",\n        definition.operation,\n        definition.name ? ` named '${definition.name.value}'` : \"\"\n      );\n    }\n    // Add our definition to the fragments array if it is a fragment\n    // definition.\n    if (definition.kind === \"FragmentDefinition\") {\n      fragments.push(definition);\n    }\n  });\n\n  // If the user did not give us a fragment name then let us try to get a\n  // name from a single fragment in the definition.\n  if (typeof actualFragmentName === \"undefined\") {\n    invariant(\n      fragments.length === 1,\n      `Found %s fragments. \\`fragmentName\\` must be provided when there is not exactly 1 fragment.`,\n      fragments.length\n    );\n    actualFragmentName = fragments[0].name.value;\n  }\n\n  // Generate a query document with an operation that simply spreads the\n  // fragment inside of it.\n  const query: DocumentNode = {\n    ...document,\n    definitions: [\n      {\n        kind: \"OperationDefinition\" as Kind.OPERATION_DEFINITION,\n        // OperationTypeNode is an enum\n        operation: \"query\" as OperationTypeNode,\n        selectionSet: {\n          kind: \"SelectionSet\" as Kind.SELECTION_SET,\n          selections: [\n            {\n              kind: \"FragmentSpread\" as Kind.FRAGMENT_SPREAD,\n              name: {\n                kind: \"Name\" as Kind.NAME,\n                value: actualFragmentName,\n              },\n            },\n          ],\n        },\n      },\n      ...document.definitions,\n    ],\n  };\n\n  return query;\n}\n"
  },
  {
    "path": "src/utilities/internal/getGraphQLErrorsFromResult.ts",
    "content": "import type { GraphQLFormattedError } from \"graphql\";\n\n/** @internal */\nexport function getGraphQLErrorsFromResult(result: {\n  errors?: ReadonlyArray<GraphQLFormattedError>;\n}): Array<GraphQLFormattedError> {\n  return [...(result.errors || [])];\n}\n"
  },
  {
    "path": "src/utilities/internal/getMainDefinition.ts",
    "content": "import type {\n  DocumentNode,\n  FragmentDefinitionNode,\n  OperationDefinitionNode,\n} from \"graphql\";\n\nimport { newInvariantError } from \"@apollo/client/utilities/invariant\";\n\nimport { checkDocument } from \"./checkDocument.js\";\n\n/**\n * Returns the first operation definition from a GraphQL document. The function\n * prioritizes operation definitions over fragment definitions, which makes it\n * suitable for documents that may contain both. If no operation definition is\n * found, the first fragment definition will be returned. If no definitions are\n * found, an error is thrown.\n *\n * @remarks\n *\n * Use this function when you need to perform more advanced tasks with the main\n * definition AST node. If you want to determine when a document is a specific\n * operation type, prefer the `isQueryOperation`, `isMutationOperation`, and\n * `isSubscriptionOperation` utility functions instead.\n *\n * @param queryDoc - The GraphQL document to extract the definition from\n * @returns The main operation or fragment definition AST node\n *\n * @example\n *\n * ```ts\n * import { gql } from \"@apollo/client\";\n * import { getMainDefinition } from \"@apollo/client/utilities\";\n *\n * const query = gql`\n *   query GetUser($id: ID!) {\n *     user(id: $id) {\n *       name\n *       email\n *     }\n *   }\n * `;\n *\n * const definition = getMainDefinition(query);\n * ```\n *\n * @throws When the document contains no operation or fragment definitions\n */\nexport function getMainDefinition(\n  queryDoc: DocumentNode\n): OperationDefinitionNode | FragmentDefinitionNode {\n  checkDocument(queryDoc);\n\n  let fragmentDefinition;\n\n  for (let definition of queryDoc.definitions) {\n    if (definition.kind === \"OperationDefinition\") {\n      return definition;\n    }\n\n    if (definition.kind === \"FragmentDefinition\" && !fragmentDefinition) {\n      // we do this because we want to allow multiple fragment definitions\n      // to precede an operation definition.\n      fragmentDefinition = definition;\n    }\n  }\n\n  if (fragmentDefinition) {\n    return fragmentDefinition;\n  }\n\n  throw newInvariantError(\n    \"Expected a parsed GraphQL query with a query, mutation, subscription, or a fragment.\"\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/getMemoryInternals.ts",
    "content": "import type { OptimisticWrapperFunction } from \"optimism\";\n\nimport type {\n  ApolloCache,\n  ApolloLink,\n  DocumentTransform,\n  InMemoryCache,\n} from \"@apollo/client\";\nimport type { ApolloClient } from \"@apollo/client\";\nimport { __DEV__ } from \"@apollo/client/utilities/environment\";\n\nimport type { CacheSizes } from \"../caching/sizes.js\";\nimport { cacheSizes, defaultCacheSizes } from \"../caching/sizes.js\";\n\nconst globalCaches: {\n  print?: () => number;\n  canonicalStringify?: () => number;\n} = {};\n\nexport function registerGlobalCache(\n  name: keyof typeof globalCaches,\n  getSize: () => number\n) {\n  globalCaches[name] = getSize;\n}\n\n/**\n * Transformative helper type to turn a function of the form\n *\n * ```ts\n * (this: any) => R;\n * ```\n *\n * into a function of the form\n *\n * ```ts\n * () => R;\n * ```\n *\n * preserving the return type, but removing the `this` parameter.\n *\n * @remarks\n *\n * Further down in the definitions of `_getApolloClientMemoryInternals`,\n * `_getApolloCacheMemoryInternals` and `_getInMemoryCacheMemoryInternals`,\n * having the `this` parameter annotation is extremely useful for type checking\n * inside the function.\n *\n * If this is preserved in the exported types, though, it leads to a situation\n * where `ApolloCache.getMemoryInternals` is a function that requires a `this`\n * of the type `ApolloCache`, while the extending class `InMemoryCache` has a\n * `getMemoryInternals` function that requires a `this` of the type\n * `InMemoryCache`.\n * This is not compatible with TypeScript's inheritance system (although it is\n * perfectly correct), and so TypeScript will complain loudly.\n *\n * We still want to define our functions with the `this` annotation, though,\n * and have the return type inferred.\n * (This requirement for return type inference here makes it impossible to use\n * a function overload that is more explicit on the inner overload than it is\n * on the external overload.)\n *\n * So in the end, we use this helper to remove the `this` annotation from the\n * exported function types, while keeping it in the internal implementation.\n */\ntype RemoveThis<T> = T extends (this: any) => infer R ? () => R : never;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloClientMemoryInternals =\n  __DEV__ ?\n    (_getApolloClientMemoryInternals as RemoveThis<\n      typeof _getApolloClientMemoryInternals\n    >)\n  : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getInMemoryCacheMemoryInternals =\n  __DEV__ ?\n    (_getInMemoryCacheMemoryInternals as RemoveThis<\n      typeof _getInMemoryCacheMemoryInternals\n    >)\n  : undefined;\n\n/**\n * For internal purposes only - please call `ApolloClient.getMemoryInternals` instead\n * @internal\n */\nexport const getApolloCacheMemoryInternals =\n  __DEV__ ?\n    (_getApolloCacheMemoryInternals as RemoveThis<\n      typeof _getApolloCacheMemoryInternals\n    >)\n  : undefined;\n\nfunction getCurrentCacheSizes() {\n  // `defaultCacheSizes` is a `const enum` that will be inlined during build, so we have to reconstruct it's shape here\n  const defaults: Record<keyof CacheSizes, number> = {\n    canonicalStringify: defaultCacheSizes[\"canonicalStringify\"],\n    checkDocument: defaultCacheSizes[\"checkDocument\"],\n    print: defaultCacheSizes[\"print\"],\n    \"documentTransform.cache\": defaultCacheSizes[\"documentTransform.cache\"],\n    \"queryManager.getDocumentInfo\":\n      defaultCacheSizes[\"queryManager.getDocumentInfo\"],\n    \"PersistedQueryLink.persistedQueryHashes\":\n      defaultCacheSizes[\"PersistedQueryLink.persistedQueryHashes\"],\n    \"fragmentRegistry.transform\":\n      defaultCacheSizes[\"fragmentRegistry.transform\"],\n    \"fragmentRegistry.lookup\": defaultCacheSizes[\"fragmentRegistry.lookup\"],\n    \"fragmentRegistry.findFragmentSpreads\":\n      defaultCacheSizes[\"fragmentRegistry.findFragmentSpreads\"],\n    \"cache.fragmentQueryDocuments\":\n      defaultCacheSizes[\"cache.fragmentQueryDocuments\"],\n    \"removeTypenameFromVariables.getVariableDefinitions\":\n      defaultCacheSizes[\"removeTypenameFromVariables.getVariableDefinitions\"],\n    \"inMemoryCache.maybeBroadcastWatch\":\n      defaultCacheSizes[\"inMemoryCache.maybeBroadcastWatch\"],\n    \"inMemoryCache.executeSelectionSet\":\n      defaultCacheSizes[\"inMemoryCache.executeSelectionSet\"],\n    \"inMemoryCache.executeSubSelectedArray\":\n      defaultCacheSizes[\"inMemoryCache.executeSubSelectedArray\"],\n  };\n  return Object.fromEntries(\n    Object.entries(defaults).map(([k, v]) => [\n      k,\n      cacheSizes[k as keyof CacheSizes] || v,\n    ])\n  );\n}\n\nfunction _getApolloClientMemoryInternals(this: ApolloClient) {\n  if (!__DEV__) throw new Error(\"only supported in development mode\");\n\n  return {\n    limits: getCurrentCacheSizes(),\n    sizes: {\n      print: globalCaches.print?.(),\n      canonicalStringify: globalCaches.canonicalStringify?.(),\n      links: linkInfo(this.link),\n      queryManager: {\n        getDocumentInfo: this[\"queryManager\"][\"transformCache\"].size,\n        documentTransforms: transformInfo(\n          this[\"queryManager\"].documentTransform\n        ),\n      },\n      ...(this.cache.getMemoryInternals?.() as Partial<\n        ReturnType<typeof _getApolloCacheMemoryInternals>\n      > &\n        Partial<ReturnType<typeof _getInMemoryCacheMemoryInternals>>),\n    },\n  };\n}\n\nfunction _getApolloCacheMemoryInternals(this: ApolloCache) {\n  return {\n    cache: {\n      fragmentQueryDocuments: getWrapperInformation(this[\"getFragmentDoc\"]),\n    },\n  };\n}\n\nfunction _getInMemoryCacheMemoryInternals(this: InMemoryCache) {\n  const fragments = this.config.fragments as\n    | undefined\n    | {\n        findFragmentSpreads?: Function;\n        transform?: Function;\n        lookup?: Function;\n      };\n\n  return {\n    ..._getApolloCacheMemoryInternals.apply(this as any),\n    addTypenameDocumentTransform: transformInfo(this[\"addTypenameTransform\"]),\n    inMemoryCache: {\n      executeSelectionSet: getWrapperInformation(\n        this[\"storeReader\"][\"executeSelectionSet\"]\n      ),\n      executeSubSelectedArray: getWrapperInformation(\n        this[\"storeReader\"][\"executeSubSelectedArray\"]\n      ),\n      maybeBroadcastWatch: getWrapperInformation(this[\"maybeBroadcastWatch\"]),\n    },\n    fragmentRegistry: {\n      findFragmentSpreads: getWrapperInformation(\n        fragments?.findFragmentSpreads\n      ),\n      lookup: getWrapperInformation(fragments?.lookup),\n      transform: getWrapperInformation(fragments?.transform),\n    },\n  };\n}\n\nfunction isWrapper(f?: Function): f is OptimisticWrapperFunction<any, any> {\n  return !!f && \"dirtyKey\" in f;\n}\n\nfunction getWrapperInformation(f?: Function) {\n  return isWrapper(f) ? f.size : undefined;\n}\n\nfunction isDefined<T>(value: T | undefined | null): value is T {\n  return value != null;\n}\n\nfunction transformInfo(transform?: DocumentTransform) {\n  return recurseTransformInfo(transform).map((cache) => ({ cache }));\n}\n\nfunction recurseTransformInfo(transform?: DocumentTransform): number[] {\n  return transform ?\n      [\n        getWrapperInformation(transform?.[\"performWork\"]),\n        ...recurseTransformInfo(transform?.[\"left\"]),\n        ...recurseTransformInfo(transform?.[\"right\"]),\n      ].filter(isDefined)\n    : [];\n}\n\nfunction linkInfo(link?: ApolloLink): unknown[] {\n  return link ?\n      [\n        link?.getMemoryInternals?.(),\n        ...linkInfo(link?.left),\n        ...linkInfo(link?.right),\n      ].filter(isDefined)\n    : [];\n}\n"
  },
  {
    "path": "src/utilities/internal/getOperationDefinition.ts",
    "content": "import type { DocumentNode, OperationDefinitionNode } from \"graphql\";\n\nimport { checkDocument } from \"./checkDocument.js\";\n\n/** @internal */\nexport function getOperationDefinition(\n  doc: DocumentNode\n): OperationDefinitionNode | undefined {\n  checkDocument(doc);\n  return doc.definitions.filter(\n    (definition): definition is OperationDefinitionNode =>\n      definition.kind === \"OperationDefinition\"\n  )[0];\n}\n"
  },
  {
    "path": "src/utilities/internal/getOperationName.ts",
    "content": "import type { DocumentNode, OperationDefinitionNode } from \"graphql\";\n\ntype OperationDefinitionWithName = OperationDefinitionNode & {\n  name: NonNullable<OperationDefinitionNode[\"name\"]>;\n};\n\n/** @internal */\nexport function getOperationName<\n  TFallback extends string | null | undefined = undefined,\n>(doc: DocumentNode, fallback?: TFallback): string | TFallback {\n  return (\n    doc.definitions.find(\n      (definition): definition is OperationDefinitionWithName =>\n        definition.kind === \"OperationDefinition\" && !!definition.name\n    )?.name.value ?? (fallback as TFallback)\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/getQueryDefinition.ts",
    "content": "import type { DocumentNode, OperationDefinitionNode } from \"graphql\";\n\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { getOperationDefinition } from \"./getOperationDefinition.js\";\n\n/** @internal */\nexport function getQueryDefinition(doc: DocumentNode): OperationDefinitionNode {\n  const queryDef = getOperationDefinition(doc)!;\n\n  invariant(\n    queryDef && queryDef.operation === \"query\",\n    \"Must contain a query definition.\"\n  );\n\n  return queryDef;\n}\n"
  },
  {
    "path": "src/utilities/internal/getStoreKeyName.ts",
    "content": "import { canonicalStringify } from \"./canonicalStringify.js\";\n\ntype Directives = {\n  [directiveName: string]: {\n    [argName: string]: any;\n  };\n};\n\nconst KNOWN_DIRECTIVES: string[] = [\n  \"connection\",\n  \"include\",\n  \"skip\",\n  \"client\",\n  \"rest\",\n  \"export\",\n  \"nonreactive\",\n  \"stream\",\n];\n\n// Default stable JSON.stringify implementation used by getStoreKeyName. Can be\n// updated/replaced with something better by calling\n// getStoreKeyName.setStringify(newStringifyFunction).\nlet storeKeyNameStringify: (value: any) => string = canonicalStringify;\n\n/** @internal */\nexport const getStoreKeyName = Object.assign(\n  function (\n    fieldName: string,\n    args?: Record<string, any> | null,\n    directives?: Directives\n  ): string {\n    if (\n      args &&\n      directives &&\n      directives[\"connection\"] &&\n      directives[\"connection\"][\"key\"]\n    ) {\n      if (\n        directives[\"connection\"][\"filter\"] &&\n        (directives[\"connection\"][\"filter\"] as string[]).length > 0\n      ) {\n        const filterKeys =\n          directives[\"connection\"][\"filter\"] ?\n            (directives[\"connection\"][\"filter\"] as string[])\n          : [];\n        filterKeys.sort();\n\n        const filteredArgs = {} as { [key: string]: any };\n        filterKeys.forEach((key) => {\n          filteredArgs[key] = args[key];\n        });\n\n        const stringifiedArgs: string = storeKeyNameStringify(filteredArgs);\n        if (stringifiedArgs !== \"{}\") {\n          return `${directives[\"connection\"][\"key\"]}(${stringifiedArgs})`;\n        }\n      }\n      return directives[\"connection\"][\"key\"];\n    }\n\n    let completeFieldName: string = fieldName;\n\n    if (args) {\n      // We can't use `JSON.stringify` here since it's non-deterministic,\n      // and can lead to different store key names being created even though\n      // the `args` object used during creation has the same properties/values.\n      const stringifiedArgs: string = storeKeyNameStringify(args);\n      if (stringifiedArgs !== \"{}\") {\n        completeFieldName += `(${stringifiedArgs})`;\n      }\n    }\n\n    if (directives) {\n      Object.keys(directives).forEach((key) => {\n        if (KNOWN_DIRECTIVES.indexOf(key) !== -1) return;\n        if (directives[key] && Object.keys(directives[key]).length) {\n          completeFieldName += `@${key}(${storeKeyNameStringify(\n            directives[key]\n          )})`;\n        } else {\n          completeFieldName += `@${key}`;\n        }\n      });\n    }\n\n    return completeFieldName;\n  },\n  {\n    setStringify(s: typeof storeKeyNameStringify) {\n      const previous = storeKeyNameStringify;\n      storeKeyNameStringify = s;\n      return previous;\n    },\n  }\n);\n"
  },
  {
    "path": "src/utilities/internal/globals/global.ts",
    "content": "import { maybe } from \"./maybe.js\";\n\nexport default (maybe(() => globalThis) ||\n  maybe(() => window) ||\n  maybe(() => self) ||\n  maybe(() => global) ||\n  // We don't expect the Function constructor ever to be invoked at runtime, as\n  // long as at least one of globalThis, window, self, or global is defined, so\n  // we are under no obligation to make it easy for static analysis tools to\n  // detect syntactic usage of the Function constructor. If you think you can\n  // improve your static analysis to detect this obfuscation, think again. This\n  // is an arms race you cannot win, at least not in JavaScript.\n  maybe(function () {\n    return maybe.constructor(\"return this\")();\n  })) as typeof globalThis & Window;\n"
  },
  {
    "path": "src/utilities/internal/globals/index.ts",
    "content": "export { maybe } from \"./maybe.js\";\nexport { default as global } from \"./global.js\";\n"
  },
  {
    "path": "src/utilities/internal/globals/maybe.ts",
    "content": "export function maybe<T>(thunk: () => T): T | undefined {\n  try {\n    return thunk();\n  } catch {}\n}\n"
  },
  {
    "path": "src/utilities/internal/graphQLResultHasError.ts",
    "content": "import type { FormattedExecutionResult } from \"graphql\";\n\n/** @internal */\nexport function graphQLResultHasError(\n  result: FormattedExecutionResult<any>\n): boolean {\n  return !!result.errors?.length;\n}\n"
  },
  {
    "path": "src/utilities/internal/hasDirectives.ts",
    "content": "import type { ASTNode } from \"graphql\";\nimport { BREAK, visit } from \"graphql\";\n\n/** @internal */\nexport function hasDirectives(names: string[], root: ASTNode, all?: boolean) {\n  const nameSet = new Set(names);\n  const uniqueCount = nameSet.size;\n\n  visit(root, {\n    Directive(node) {\n      if (nameSet.delete(node.name.value) && (!all || !nameSet.size)) {\n        return BREAK;\n      }\n    },\n  });\n\n  // If we found all the names, nameSet will be empty. If we only care about\n  // finding some of them, the < condition is sufficient.\n  return all ? !nameSet.size : nameSet.size < uniqueCount;\n}\n"
  },
  {
    "path": "src/utilities/internal/hasForcedResolvers.ts",
    "content": "import type { ASTNode } from \"graphql\";\nimport { BREAK, visit } from \"graphql\";\n\nexport function hasForcedResolvers(document: ASTNode) {\n  let forceResolvers = false;\n  visit(document, {\n    Directive: {\n      enter(node) {\n        if (node.name.value === \"client\" && node.arguments) {\n          forceResolvers = node.arguments.some(\n            (arg) =>\n              arg.name.value === \"always\" &&\n              arg.value.kind === \"BooleanValue\" &&\n              arg.value.value === true\n          );\n          if (forceResolvers) {\n            return BREAK;\n          }\n        }\n      },\n    },\n  });\n  return forceResolvers;\n}\n"
  },
  {
    "path": "src/utilities/internal/index.production.ts",
    "content": "// eslint-disable-next-line no-restricted-syntax\nexport * from \"./index.js\";\n\nfunction unsupported() {\n  throw new Error(\"only supported in development mode\");\n}\nexport const getApolloCacheMemoryInternals =\n    unsupported as typeof import(\"./getMemoryInternals.js\").getApolloCacheMemoryInternals,\n  getApolloClientMemoryInternals =\n    unsupported as typeof import(\"./getMemoryInternals.js\").getApolloClientMemoryInternals,\n  getInMemoryCacheMemoryInternals =\n    unsupported as typeof import(\"./getMemoryInternals.js\").getInMemoryCacheMemoryInternals;\n"
  },
  {
    "path": "src/utilities/internal/index.ts",
    "content": "export type { DecoratedPromise } from \"./types/DecoratedPromise.js\";\nexport type { DeepOmit } from \"./types/DeepOmit.js\";\nexport type { ExtensionsWithStreamInfo } from \"./types/ExtensionsWithStreamDetails.js\";\nexport type { FragmentMap } from \"./types/FragmentMap.js\";\nexport type { FragmentMapFunction } from \"./types/FragmentMapFunction.js\";\nexport type { FulfilledPromise } from \"./types/FulfilledPromise.js\";\nexport type { IsAny } from \"./types/IsAny.js\";\nexport type { NoInfer } from \"./types/NoInfer.js\";\nexport type { PendingPromise } from \"./types/PendingPromise.js\";\nexport type { Prettify } from \"./types/Prettify.js\";\nexport type { Primitive } from \"./types/Primitive.js\";\nexport type { RejectedPromise } from \"./types/RejectedPromise.js\";\nexport type { RemoveIndexSignature } from \"./types/RemoveIndexSignature.js\";\nexport type { StreamInfoTrie } from \"./types/StreamInfoTrie.js\";\nexport type { VariablesOption } from \"./types/VariablesOption.js\";\nexport type { DocumentationTypes } from \"./types/DocumentationTypes.js\";\n\nexport { argumentsObjectFromField } from \"./argumentsObjectFromField.js\";\nexport { canUseDOM } from \"./canUseDOM.js\";\nexport { checkDocument } from \"./checkDocument.js\";\nexport { cloneDeep } from \"./cloneDeep.js\";\nexport { combineLatestBatched } from \"./combineLatestBatched.js\";\nexport { compact } from \"./compact.js\";\nexport { createFragmentMap } from \"./createFragmentMap.js\";\nexport { createFulfilledPromise } from \"./createFulfilledPromise.js\";\nexport { createRejectedPromise } from \"./createRejectedPromise.js\";\nexport { dealias } from \"./dealias.js\";\nexport { decoratePromise } from \"./decoratePromise.js\";\nexport { DeepMerger } from \"./DeepMerger.js\";\nexport { getDefaultValues } from \"./getDefaultValues.js\";\nexport { getFragmentFromSelection } from \"./getFragmentFromSelection.js\";\nexport { getFragmentQueryDocument } from \"./getFragmentQueryDocument.js\";\nexport { getFragmentDefinition } from \"./getFragmentDefinition.js\";\nexport { getFragmentDefinitions } from \"./getFragmentDefinitions.js\";\nexport { getGraphQLErrorsFromResult } from \"./getGraphQLErrorsFromResult.js\";\nexport { getMainDefinition } from \"./getMainDefinition.js\";\nexport { getOperationDefinition } from \"./getOperationDefinition.js\";\nexport { getOperationName } from \"./getOperationName.js\";\nexport { getQueryDefinition } from \"./getQueryDefinition.js\";\nexport { getStoreKeyName } from \"./getStoreKeyName.js\";\nexport { graphQLResultHasError } from \"./graphQLResultHasError.js\";\nexport { hasDirectives } from \"./hasDirectives.js\";\nexport { hasForcedResolvers } from \"./hasForcedResolvers.js\";\nexport { isArray } from \"./isArray.js\";\nexport { isDocumentNode } from \"./isDocumentNode.js\";\nexport { isField } from \"./isField.js\";\nexport { isNonEmptyArray } from \"./isNonEmptyArray.js\";\nexport { isNonNullObject } from \"./isNonNullObject.js\";\nexport { isPlainObject } from \"./isPlainObject.js\";\nexport { makeReference } from \"./makeReference.js\";\nexport { makeUniqueId } from \"./makeUniqueId.js\";\nexport { maybeDeepFreeze } from \"./maybeDeepFreeze.js\";\nexport { mergeDeep } from \"./mergeDeep.js\";\nexport { mergeDeepArray } from \"./mergeDeepArray.js\";\nexport { mergeOptions } from \"./mergeOptions.js\";\nexport { omitDeep } from \"./omitDeep.js\";\nexport { preventUnhandledRejection } from \"./preventUnhandledRejection.js\";\nexport { removeDirectivesFromDocument } from \"./removeDirectivesFromDocument.js\";\nexport { removeMaskedFragmentSpreads } from \"./removeFragmentSpreads.js\";\nexport { resultKeyNameFromField } from \"./resultKeyNameFromField.js\";\nexport { shouldInclude } from \"./shouldInclude.js\";\nexport { storeKeyNameFromField } from \"./storeKeyNameFromField.js\";\nexport { stringifyForDisplay } from \"./stringifyForDisplay.js\";\nexport { toQueryResult } from \"./toQueryResult.js\";\nexport { filterMap } from \"./filterMap.js\";\nexport { equalByQuery } from \"./equalByQuery.js\";\nexport { canonicalStringify } from \"./canonicalStringify.js\";\nexport { mapObservableFragmentMemoized } from \"./mapObservableFragment.js\";\nexport {\n  extensionsSymbol,\n  streamInfoSymbol,\n  variablesUnknownSymbol,\n} from \"./constants.js\";\nexport { bindCacheKey } from \"./bindCacheKey.js\";\n\nexport {\n  getApolloCacheMemoryInternals,\n  getApolloClientMemoryInternals,\n  getInMemoryCacheMemoryInternals,\n  registerGlobalCache,\n} from \"../internal/getMemoryInternals.js\";\n\nexport { AutoCleanedStrongCache, AutoCleanedWeakCache } from \"./caches.js\";\n\nexport type { ApplyHKT } from \"./types/ApplyHKT.js\";\nexport type { ApplyHKTImplementationWithDefault } from \"./types/ApplyHKTImplementationWithDefault.js\";\n"
  },
  {
    "path": "src/utilities/internal/isArray.ts",
    "content": "/**\n * A version of Array.isArray that works better with readonly arrays.\n *\n * @internal\n */\nexport const isArray: (a: any) => a is any[] | readonly any[] = Array.isArray;\n"
  },
  {
    "path": "src/utilities/internal/isDocumentNode.ts",
    "content": "import type { DocumentNode } from \"graphql\";\n\nimport { isNonNullObject } from \"./isNonNullObject.js\";\n\n/** @internal */\nexport function isDocumentNode(value: unknown): value is DocumentNode {\n  return (\n    isNonNullObject(value) &&\n    (value as DocumentNode).kind === \"Document\" &&\n    Array.isArray((value as DocumentNode).definitions)\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/isField.ts",
    "content": "import type { FieldNode, SelectionNode } from \"graphql\";\n\n/** @internal */\nexport function isField(selection: SelectionNode): selection is FieldNode {\n  return selection.kind === \"Field\";\n}\n"
  },
  {
    "path": "src/utilities/internal/isNonEmptyArray.ts",
    "content": "/** @internal */\nexport function isNonEmptyArray<T>(\n  value: ArrayLike<T> | null | undefined\n): value is Array<T> {\n  return Array.isArray(value) && value.length > 0;\n}\n"
  },
  {
    "path": "src/utilities/internal/isNonNullObject.ts",
    "content": "/** @internal */\nexport function isNonNullObject(\n  obj: unknown\n): obj is Record<string | number, any> {\n  return obj !== null && typeof obj === \"object\";\n}\n"
  },
  {
    "path": "src/utilities/internal/isPlainObject.ts",
    "content": "/** @internal */\nexport function isPlainObject(\n  obj: unknown\n): obj is Record<string | number, any> {\n  return (\n    obj !== null &&\n    typeof obj === \"object\" &&\n    (Object.getPrototypeOf(obj) === Object.prototype ||\n      Object.getPrototypeOf(obj) === null)\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/makeReference.ts",
    "content": "import type { Reference } from \"@apollo/client/utilities\";\n\n/** @internal */\nexport function makeReference(id: string): Reference {\n  return { __ref: String(id) };\n}\n"
  },
  {
    "path": "src/utilities/internal/makeUniqueId.ts",
    "content": "const prefixCounts = new Map<string, number>();\n\n/**\n * These IDs won't be globally unique, but they will be unique within this\n * process, thanks to the counter, and unguessable thanks to the random suffix.\n *\n * @internal\n */\nexport function makeUniqueId(prefix: string) {\n  const count = prefixCounts.get(prefix) || 1;\n  prefixCounts.set(prefix, count + 1);\n  return `${prefix}:${count}:${Math.random().toString(36).slice(2)}`;\n}\n"
  },
  {
    "path": "src/utilities/internal/mapObservableFragment.ts",
    "content": "import { map, shareReplay } from \"rxjs\";\n\nimport type { ApolloCache } from \"@apollo/client\";\n\nimport { memoize } from \"./memoize.js\";\n\nfunction mapObservableFragment<From, To>(\n  observable: ApolloCache.ObservableFragment<From>,\n  mapFn: (\n    from: ApolloCache.WatchFragmentResult<From>\n  ) => ApolloCache.WatchFragmentResult<To>\n): ApolloCache.ObservableFragment<To> {\n  let currentResult: ApolloCache.WatchFragmentResult<From>;\n  let stableMappedResult: ApolloCache.WatchFragmentResult<To>;\n\n  function toMapped(\n    result: ApolloCache.WatchFragmentResult<From>\n  ): ApolloCache.WatchFragmentResult<To> {\n    if (result !== currentResult) {\n      currentResult = result;\n      stableMappedResult = mapFn(currentResult);\n    }\n    return stableMappedResult;\n  }\n\n  return Object.assign(\n    observable.pipe(\n      map(toMapped),\n      shareReplay({ bufferSize: 1, refCount: true })\n    ),\n    {\n      getCurrentResult: () => toMapped(observable.getCurrentResult()),\n    }\n  );\n}\n\nexport const mapObservableFragmentMemoized = memoize(\n  function mapObservableFragmentMemoized<From, To>(\n    observable: ApolloCache.ObservableFragment<From>,\n    /**\n     * used together with `observable` as memoization key, `mapFn` is explicitly not used as memoization key\n     */\n    _cacheKey: symbol,\n    mapFn: (\n      from: ApolloCache.WatchFragmentResult<From>\n    ) => ApolloCache.WatchFragmentResult<To>\n  ): ApolloCache.ObservableFragment<To> {\n    return mapObservableFragment(observable, mapFn);\n  },\n  { max: 1, makeCacheKey: (args) => args.slice(0, 2) }\n);\n"
  },
  {
    "path": "src/utilities/internal/maybeDeepFreeze.ts",
    "content": "import { __DEV__ } from \"@apollo/client/utilities/environment\";\n\nimport { deepFreeze } from \"./deepFreeze.js\";\n\n/** @internal */\nexport function maybeDeepFreeze<T>(obj: T): T {\n  if (__DEV__) {\n    deepFreeze(obj);\n  }\n  return obj;\n}\n"
  },
  {
    "path": "src/utilities/internal/memoize.ts",
    "content": "import { Trie } from \"@wry/trie\";\n\nimport { AutoCleanedWeakCache } from \"./caches.js\";\n\n/**\n * Naive alternative to `wrap` without any dependency tracking, potentially avoiding resulting memory leaks.\n */\nexport function memoize<TArgs extends any[], TResult>(\n  fn: (...args: TArgs) => TResult,\n  {\n    max,\n    makeCacheKey = (args) => args,\n  }: { max: number; makeCacheKey?: (args: TArgs) => [...any[]] }\n): (...args: TArgs) => TResult {\n  const keys = new Trie<{}>(true);\n  const cache = new AutoCleanedWeakCache<\n    {},\n    { result?: TResult; error?: unknown }\n  >(max);\n\n  return (...args: TArgs): TResult => {\n    const cacheKey = keys.lookupArray(makeCacheKey(args));\n    const cached = cache.get(cacheKey);\n    if (cached) {\n      if (cached.error) {\n        throw cached.error;\n      }\n      return cached.result!;\n    }\n\n    const entry = cache.set(cacheKey, {});\n    try {\n      return (entry.result = fn(...args));\n    } catch (error) {\n      entry.error = error;\n      throw error;\n    }\n  };\n}\n"
  },
  {
    "path": "src/utilities/internal/mergeDeep.ts",
    "content": "import { mergeDeepArray } from \"./mergeDeepArray.js\";\nimport type { TupleToIntersection } from \"./types/TupleToIntersection.js\";\n\n// These mergeDeep and mergeDeepArray utilities merge any number of objects\n// together, sharing as much memory as possible with the source objects, while\n// remaining careful to avoid modifying any source objects.\n\n// Logically, the return type of mergeDeep should be the intersection of\n// all the argument types. The binary call signature is by far the most\n// common, but we support 0- through 5-ary as well. After that, the\n// resulting type is just the inferred array element type. Note to nerds:\n// there is a more clever way of doing this that converts the tuple type\n// first to a union type (easy enough: T[number]) and then converts the\n// union to an intersection type using distributive conditional type\n// inference, but that approach has several fatal flaws (boolean becomes\n// true & false, and the inferred type ends up as unknown in many cases),\n// in addition to being nearly impossible to explain/understand.\n\n/** @internal */\nexport function mergeDeep<T extends any[]>(\n  ...sources: T\n): TupleToIntersection<T> {\n  return mergeDeepArray(sources);\n}\n"
  },
  {
    "path": "src/utilities/internal/mergeDeepArray.ts",
    "content": "import { DeepMerger } from \"./DeepMerger.js\";\n\n// In almost any situation where you could succeed in getting the\n// TypeScript compiler to infer a tuple type for the sources array, you\n// could just use mergeDeep instead of mergeDeepArray, so instead of\n// trying to convert T[] to an intersection type we just infer the array\n// element type, which works perfectly when the sources array has a\n// consistent element type.\n/** @internal */\nexport function mergeDeepArray<T>(sources: T[]): T {\n  let target = sources[0] || ({} as T);\n  const count = sources.length;\n  if (count > 1) {\n    const merger = new DeepMerger();\n    for (let i = 1; i < count; ++i) {\n      target = merger.merge(target, sources[i]);\n    }\n  }\n  return target;\n}\n"
  },
  {
    "path": "src/utilities/internal/mergeOptions.ts",
    "content": "import type { ApolloClient, OperationVariables } from \"@apollo/client\";\n\nimport { compact } from \"./compact.js\";\n\ntype OptionsUnion<TData, TVariables extends OperationVariables> =\n  | ApolloClient.WatchQueryOptions<TData, TVariables>\n  | ApolloClient.QueryOptions<TData, TVariables>\n  | ApolloClient.MutateOptions<TData, TVariables, any>;\n\n/** @internal */\nexport function mergeOptions<\n  TDefaultOptions extends Partial<OptionsUnion<any, any>>,\n  TOptions extends TDefaultOptions,\n>(\n  defaults: TDefaultOptions | Partial<TDefaultOptions> | undefined,\n  options: TOptions | Partial<TOptions>\n): TOptions & TDefaultOptions {\n  return compact(\n    defaults,\n    options,\n    options.variables && {\n      variables: compact({\n        ...(defaults && defaults.variables),\n        ...options.variables,\n      }),\n    }\n  );\n}\n"
  },
  {
    "path": "src/utilities/internal/omitDeep.ts",
    "content": "import { isPlainObject } from \"./isPlainObject.js\";\nimport type { DeepOmit } from \"./types/DeepOmit.js\";\n\n/** @internal */\nexport function omitDeep<T, K extends string>(value: T, key: K) {\n  return __omitDeep(value, key);\n}\n\nfunction __omitDeep<T, K extends string>(\n  value: T,\n  key: K,\n  known = new Map<any, any>()\n): DeepOmit<T, K> {\n  if (known.has(value)) {\n    return known.get(value);\n  }\n\n  let modified = false;\n\n  if (Array.isArray(value)) {\n    const array: any[] = [];\n    known.set(value, array);\n\n    value.forEach((value, index) => {\n      const result = __omitDeep(value, key, known);\n      modified ||= result !== value;\n\n      array[index] = result;\n    });\n\n    if (modified) {\n      return array as DeepOmit<T, K>;\n    }\n  } else if (isPlainObject(value)) {\n    const obj = Object.create(Object.getPrototypeOf(value));\n    known.set(value, obj);\n\n    Object.keys(value).forEach((k) => {\n      if (k === key) {\n        modified = true;\n        return;\n      }\n\n      const result = __omitDeep(value[k], key, known);\n      modified ||= result !== value[k];\n\n      obj[k] = result;\n    });\n\n    if (modified) {\n      return obj;\n    }\n  }\n\n  return value as DeepOmit<T, K>;\n}\n"
  },
  {
    "path": "src/utilities/internal/ponyfills/FinalizationRegistry.ts",
    "content": "import { invariant } from \"@apollo/client/utilities/invariant\";\n\ninterface Entry<T> {\n  targetRef: WeakRef<WeakKey>;\n  value: T;\n}\n\n/**\n * @internal\n *\n * An approximation of `FinalizationRegistry` based on `WeakRef`.\n * While there are registered values, checks every 500ms if any have been garbage collected.\n * The polling interval is cleared once all registered entries have been removed.\n */\nexport const FinalizationRegistry: typeof globalThis.FinalizationRegistry = class FinalizationRegistry<\n  T,\n> {\n  private intervalLength = 500;\n  private callback: (value: T) => void;\n  private references = new Set<Entry<T>>();\n  private unregisterTokens = new WeakMap<WeakKey, Entry<T>>();\n  private interval: ReturnType<typeof setInterval> | null = null;\n  constructor(callback: (value: T) => void) {\n    this.callback = callback;\n    this.handler = this.handler.bind(this);\n  }\n  handler() {\n    if (this.references.size === 0) {\n      clearInterval(this.interval!);\n      this.interval = null;\n      return;\n    }\n    this.references.forEach((entry) => {\n      if (entry.targetRef.deref() === undefined) {\n        this.references.delete(entry);\n        // Spec deviation: Not catching errors here, might get necessary if used in more places.\n        this.callback(entry.value);\n      }\n    });\n  }\n  register(target: WeakKey, value: T, unregisterToken?: WeakKey): void {\n    const entry = { targetRef: new WeakRef(target), value };\n    this.references.add(entry);\n    if (unregisterToken) {\n      // some simplifications here as it's an internal polyfill\n      // we don't allow the same unregisterToken to be reused\n      invariant(!this.unregisterTokens.has(unregisterToken));\n      this.unregisterTokens.set(unregisterToken, entry);\n    }\n    if (!this.interval) {\n      this.interval = setInterval(this.handler, this.intervalLength);\n    }\n  }\n  unregister(unregisterToken: WeakKey): boolean {\n    // Calling `(weak)Set.delete(undefined)` is not covered by the TypeScript types,\n    // but valid by the spec (see https://tc39.es/ecma262/multipage/keyed-collections.html#sec-weakset.prototype.delete).\n    // Shaving a few bytes here by skipping the undefined check.\n    this.references.delete(this.unregisterTokens.get(unregisterToken)!);\n    return this.unregisterTokens.delete(unregisterToken);\n  }\n  [Symbol.toStringTag] = \"FinalizationRegistry\" as const;\n};\n"
  },
  {
    "path": "src/utilities/internal/ponyfills/__tests__/FinalizationRegistry.test.ts",
    "content": "import { waitFor } from \"@testing-library/react\";\n\n// eslint-disable-next-line\nimport { FinalizationRegistry } from \"../FinalizationRegistry.js\";\n\ntest(\"register\", async () => {\n  const cleanedUp: number[] = [];\n  const registry = new FinalizationRegistry<number>((value) => {\n    cleanedUp.push(value);\n  });\n  // @ts-ignore we want to speed this up a bit\n  registry[\"intervalLength\"] = 1;\n\n  let obj1: {} | null = {};\n  let obj2: {} | null = {};\n  let obj3: {} | null = {};\n\n  registry.register(obj1, 1);\n  registry.register(obj2, 2);\n  registry.register(obj3, 3);\n\n  expect(cleanedUp).toStrictEqual([]);\n\n  obj1 = null;\n  await waitFor(() => {\n    global.gc!();\n    expect(cleanedUp).toStrictEqual([1]);\n  });\n\n  obj3 = null;\n  await waitFor(() => {\n    global.gc!();\n    expect(cleanedUp).toStrictEqual([1, 3]);\n  });\n\n  obj2 = null;\n  await waitFor(() => {\n    global.gc!();\n    expect(cleanedUp).toStrictEqual([1, 3, 2]);\n  });\n});\n\ntest(\"unregister\", async () => {\n  const cleanedUp: number[] = [];\n  const registry = new FinalizationRegistry<number>((value) => {\n    cleanedUp.push(value);\n  });\n  // @ts-ignore we want to speed this up a bit\n  registry[\"intervalLength\"] = 1;\n\n  let obj1: {} | null = {};\n  const token1 = {};\n  let obj2: {} | null = {};\n  const token2 = {};\n  let obj3: {} | null = {};\n  const token3 = {};\n\n  registry.register(obj1, 1, token1);\n  registry.register(obj2, 2, token2);\n  registry.register(obj3, 3, token3);\n\n  expect(cleanedUp).toStrictEqual([]);\n\n  obj1 = null;\n  await waitFor(() => {\n    global.gc!();\n    expect(cleanedUp).toStrictEqual([1]);\n  });\n\n  registry.unregister(token3);\n  obj3 = null;\n  await expect(\n    waitFor(() => {\n      global.gc!();\n      expect(cleanedUp).toStrictEqual([1, 3]);\n    })\n  ).rejects.toThrow();\n\n  obj2 = null;\n  await waitFor(() => {\n    global.gc!();\n    expect(cleanedUp).toStrictEqual([1, 2]);\n  });\n});\n"
  },
  {
    "path": "src/utilities/internal/ponyfills/index.react-native.ts",
    "content": "export { FinalizationRegistry } from \"./FinalizationRegistry.js\";\n"
  },
  {
    "path": "src/utilities/internal/ponyfills/index.ts",
    "content": "const F = FinalizationRegistry;\nexport { F as FinalizationRegistry };\n"
  },
  {
    "path": "src/utilities/internal/preventUnhandledRejection.ts",
    "content": "export function preventUnhandledRejection<T>(promise: Promise<T>): Promise<T> {\n  promise.catch(() => {});\n\n  return promise;\n}\n"
  },
  {
    "path": "src/utilities/internal/removeDirectivesFromDocument.ts",
    "content": "import type {\n  ASTNode,\n  ASTVisitFn,\n  DirectiveNode,\n  DocumentNode,\n  FieldNode,\n  FragmentDefinitionNode,\n  FragmentSpreadNode,\n  InlineFragmentNode,\n  OperationDefinitionNode,\n} from \"graphql\";\nimport { Kind, visit } from \"graphql\";\n\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\nimport { checkDocument } from \"./checkDocument.js\";\nimport { createFragmentMap } from \"./createFragmentMap.js\";\nimport { getFragmentDefinition } from \"./getFragmentDefinition.js\";\nimport { getFragmentDefinitions } from \"./getFragmentDefinitions.js\";\nimport { getOperationDefinition } from \"./getOperationDefinition.js\";\nimport { isArray } from \"./isArray.js\";\nimport { isNonEmptyArray } from \"./isNonEmptyArray.js\";\nimport type { FragmentMap } from \"./types/FragmentMap.js\";\n\n// https://github.com/graphql/graphql-js/blob/8d7c8fccf5a9846a50785de04abda58a7eb13fc0/src/language/visitor.ts#L20-L23\ninterface EnterLeaveVisitor<TVisitedNode extends ASTNode> {\n  readonly enter?: ASTVisitFn<TVisitedNode>;\n  readonly leave?: ASTVisitFn<TVisitedNode>;\n}\n\ntype RemoveDirectiveConfig = {\n  name?: string;\n  test?: (node: DirectiveNode) => boolean;\n  remove?: boolean;\n};\n\n/** @internal */\nexport function removeDirectivesFromDocument(\n  directives: RemoveDirectiveConfig[],\n  doc: DocumentNode\n): DocumentNode | null {\n  checkDocument(doc);\n\n  // Passing empty strings to makeInUseGetterFunction means we handle anonymous\n  // operations as if their names were \"\". Anonymous fragment definitions are\n  // not supposed to be possible, but the same default naming strategy seems\n  // appropriate for that case as well.\n  const getInUseByOperationName = makeInUseGetterFunction<string>(\"\");\n  const getInUseByFragmentName = makeInUseGetterFunction<string>(\"\");\n  const getInUse = (\n    ancestors: readonly (ASTNode | readonly ASTNode[])[]\n  ): InternalInUseInfo | null => {\n    for (\n      let p = 0, ancestor: ASTNode | readonly ASTNode[];\n      p < ancestors.length && (ancestor = ancestors[p]);\n      ++p\n    ) {\n      if (isArray(ancestor)) continue;\n      if (ancestor.kind === Kind.OPERATION_DEFINITION) {\n        // If an operation is anonymous, we use the empty string as its key.\n        return getInUseByOperationName(ancestor.name && ancestor.name.value);\n      }\n      if (ancestor.kind === Kind.FRAGMENT_DEFINITION) {\n        return getInUseByFragmentName(ancestor.name.value);\n      }\n    }\n    invariant.error(`Could not find operation or fragment`);\n    return null;\n  };\n\n  let operationCount = 0;\n  for (let i = doc.definitions.length - 1; i >= 0; --i) {\n    if (doc.definitions[i].kind === Kind.OPERATION_DEFINITION) {\n      ++operationCount;\n    }\n  }\n\n  const directiveMatcher = getDirectiveMatcher(directives);\n  const shouldRemoveField = (nodeDirectives: FieldNode[\"directives\"]) =>\n    isNonEmptyArray(nodeDirectives) &&\n    nodeDirectives\n      .map(directiveMatcher)\n      .some(\n        (config: RemoveDirectiveConfig | undefined) => config && config.remove\n      );\n\n  const originalFragmentDefsByPath = new Map<string, FragmentDefinitionNode>();\n\n  // Any time the first traversal of the document below makes a change like\n  // removing a fragment (by returning null), this variable should be set to\n  // true. Once it becomes true, it should never be set to false again. If this\n  // variable remains false throughout the traversal, then we can return the\n  // original doc immediately without any modifications.\n  let firstVisitMadeChanges = false;\n\n  const fieldOrInlineFragmentVisitor: EnterLeaveVisitor<\n    FieldNode | InlineFragmentNode\n  > = {\n    enter(node) {\n      if (shouldRemoveField(node.directives)) {\n        firstVisitMadeChanges = true;\n        return null;\n      }\n    },\n  };\n\n  const docWithoutDirectiveSubtrees = visit(doc, {\n    // These two AST node types share the same implementation, defined above.\n    Field: fieldOrInlineFragmentVisitor,\n    InlineFragment: fieldOrInlineFragmentVisitor,\n\n    VariableDefinition: {\n      enter() {\n        // VariableDefinition nodes do not count as variables in use, though\n        // they do contain Variable nodes that might be visited below. To avoid\n        // counting variable declarations as usages, we skip visiting the\n        // contents of this VariableDefinition node by returning false.\n        return false;\n      },\n    },\n\n    Variable: {\n      enter(node, _key, _parent, _path, ancestors) {\n        const inUse = getInUse(ancestors);\n        if (inUse) {\n          inUse.variables.add(node.name.value);\n        }\n      },\n    },\n\n    FragmentSpread: {\n      enter(node, _key, _parent, _path, ancestors) {\n        if (shouldRemoveField(node.directives)) {\n          firstVisitMadeChanges = true;\n          return null;\n        }\n        const inUse = getInUse(ancestors);\n        if (inUse) {\n          inUse.fragmentSpreads.add(node.name.value);\n        }\n        // We might like to remove this FragmentSpread by returning null here if\n        // the corresponding FragmentDefinition node is also going to be removed\n        // by the logic below, but we can't control the relative order of those\n        // events, so we have to postpone the removal of dangling FragmentSpread\n        // nodes until after the current visit of the document has finished.\n      },\n    },\n\n    FragmentDefinition: {\n      enter(node, _key, _parent, path) {\n        originalFragmentDefsByPath.set(JSON.stringify(path), node);\n      },\n      leave(node, _key, _parent, path) {\n        const originalNode = originalFragmentDefsByPath.get(\n          JSON.stringify(path)\n        );\n        if (node === originalNode) {\n          // If the FragmentNode received by this leave function is identical to\n          // the one received by the corresponding enter function (above), then\n          // the visitor must not have made any changes within this\n          // FragmentDefinition node. This fragment definition may still be\n          // removed if there are no ...spread references to it, but it won't be\n          // removed just because it has only a __typename field.\n          return node;\n        }\n\n        if (\n          // This logic applies only if the document contains one or more\n          // operations, since removing all fragments from a document containing\n          // only fragments makes the document useless.\n          operationCount > 0 &&\n          node.selectionSet.selections.every(\n            (selection) =>\n              selection.kind === Kind.FIELD &&\n              selection.name.value === \"__typename\"\n          )\n        ) {\n          // This is a somewhat opinionated choice: if a FragmentDefinition ends\n          // up having no fields other than __typename, we remove the whole\n          // fragment definition, and later prune ...spread references to it.\n          getInUseByFragmentName(node.name.value).removed = true;\n          firstVisitMadeChanges = true;\n          return null;\n        }\n      },\n    },\n\n    Directive: {\n      leave(node) {\n        // If a matching directive is found, remove the directive itself. Note\n        // that this does not remove the target (field, argument, etc) of the\n        // directive, but only the directive itself.\n        if (directiveMatcher(node)) {\n          firstVisitMadeChanges = true;\n          return null;\n        }\n      },\n    },\n  });\n\n  if (!firstVisitMadeChanges) {\n    // If our first pass did not change anything about the document, then there\n    // is no cleanup we need to do, and we can return the original doc.\n    return doc;\n  }\n\n  // Utility for making sure inUse.transitiveVars is recursively populated.\n  // Because this logic assumes inUse.fragmentSpreads has been completely\n  // populated and inUse.removed has been set if appropriate,\n  // populateTransitiveVars must be called after that information has been\n  // collected by the first traversal of the document.\n  const populateTransitiveVars = (inUse: InternalInUseInfo) => {\n    if (!inUse.transitiveVars) {\n      inUse.transitiveVars = new Set(inUse.variables);\n      if (!inUse.removed) {\n        inUse.fragmentSpreads.forEach((childFragmentName) => {\n          populateTransitiveVars(\n            getInUseByFragmentName(childFragmentName)\n          ).transitiveVars!.forEach((varName) => {\n            inUse.transitiveVars!.add(varName);\n          });\n        });\n      }\n    }\n    return inUse;\n  };\n\n  // Since we've been keeping track of fragment spreads used by particular\n  // operations and fragment definitions, we now need to compute the set of all\n  // spreads used (transitively) by any operations in the document.\n  const allFragmentNamesUsed = new Set<string>();\n  docWithoutDirectiveSubtrees.definitions.forEach((def) => {\n    if (def.kind === Kind.OPERATION_DEFINITION) {\n      populateTransitiveVars(\n        getInUseByOperationName(def.name && def.name.value)\n      ).fragmentSpreads.forEach((childFragmentName) => {\n        allFragmentNamesUsed.add(childFragmentName);\n      });\n    } else if (\n      def.kind === Kind.FRAGMENT_DEFINITION &&\n      // If there are no operations in the document, then all fragment\n      // definitions count as usages of their own fragment names. This heuristic\n      // prevents accidentally removing all fragment definitions from the\n      // document just because it contains no operations that use the fragments.\n      operationCount === 0 &&\n      !getInUseByFragmentName(def.name.value).removed\n    ) {\n      allFragmentNamesUsed.add(def.name.value);\n    }\n  });\n  // Now that we have added all fragment spreads used by operations to the\n  // allFragmentNamesUsed set, we can complete the set by transitively adding\n  // all fragment spreads used by those fragments, and so on.\n  allFragmentNamesUsed.forEach((fragmentName) => {\n    // Once all the childFragmentName strings added here have been seen already,\n    // the top-level allFragmentNamesUsed.forEach loop will terminate.\n    populateTransitiveVars(\n      getInUseByFragmentName(fragmentName)\n    ).fragmentSpreads.forEach((childFragmentName) => {\n      allFragmentNamesUsed.add(childFragmentName);\n    });\n  });\n\n  const fragmentWillBeRemoved = (fragmentName: string) =>\n    !!(\n      // A fragment definition will be removed if there are no spreads that refer\n      // to it, or the fragment was explicitly removed because it had no fields\n      // other than __typename.\n      (\n        !allFragmentNamesUsed.has(fragmentName) ||\n        getInUseByFragmentName(fragmentName).removed\n      )\n    );\n\n  const enterVisitor: EnterLeaveVisitor<\n    FragmentSpreadNode | FragmentDefinitionNode\n  > = {\n    enter(node) {\n      if (fragmentWillBeRemoved(node.name.value)) {\n        return null;\n      }\n    },\n  };\n\n  return nullIfDocIsEmpty(\n    visit(docWithoutDirectiveSubtrees, {\n      // If the fragment is going to be removed, then leaving any dangling\n      // FragmentSpread nodes with the same name would be a mistake.\n      FragmentSpread: enterVisitor,\n\n      // This is where the fragment definition is actually removed.\n      FragmentDefinition: enterVisitor,\n\n      OperationDefinition: {\n        leave(node) {\n          // Upon leaving each operation in the depth-first AST traversal, prune\n          // any variables that are declared by the operation but unused within.\n          if (node.variableDefinitions) {\n            const usedVariableNames = populateTransitiveVars(\n              // If an operation is anonymous, we use the empty string as its key.\n              getInUseByOperationName(node.name && node.name.value)\n            ).transitiveVars!;\n\n            // According to the GraphQL spec, all variables declared by an\n            // operation must either be used by that operation or used by some\n            // fragment included transitively into that operation:\n            // https://spec.graphql.org/draft/#sec-All-Variables-Used\n            //\n            // To stay on the right side of this validation rule, if/when we\n            // remove the last $var references from an operation or its fragments,\n            // we must also remove the corresponding $var declaration from the\n            // enclosing operation. This pruning applies only to operations and\n            // not fragment definitions, at the moment. Fragments may be able to\n            // declare variables eventually, but today they can only consume them.\n            if (usedVariableNames.size < node.variableDefinitions.length) {\n              return {\n                ...node,\n                variableDefinitions: node.variableDefinitions.filter((varDef) =>\n                  usedVariableNames.has(varDef.variable.name.value)\n                ),\n              };\n            }\n          }\n        },\n      },\n    })\n  );\n}\n\n// Helper interface and function used by removeDirectivesFromDocument to keep\n// track of variable references and fragments spreads found within a given\n// operation or fragment definition.\ninterface InternalInUseInfo {\n  variables: Set<string>;\n  fragmentSpreads: Set<string>;\n  // Set to true when we deliberately remove a fragment definition, so we can\n  // make sure also to remove dangling ...spreads that refer to it.\n  removed?: boolean;\n  // Populated by the populateTransitiveVars helper function below.\n  transitiveVars?: Set<string>;\n}\n\nfunction makeInUseGetterFunction<TKey>(defaultKey: TKey) {\n  const map = new Map<TKey, InternalInUseInfo>();\n\n  return function inUseGetterFunction(\n    key: TKey = defaultKey\n  ): InternalInUseInfo {\n    let inUse = map.get(key);\n    if (!inUse) {\n      map.set(\n        key,\n        (inUse = {\n          // Variable and fragment spread names used directly within this\n          // operation or fragment definition, as identified by key. These sets\n          // will be populated during the first traversal of the document in\n          // removeDirectivesFromDocument below.\n          variables: new Set(),\n          fragmentSpreads: new Set(),\n        })\n      );\n    }\n    return inUse;\n  };\n}\n\ntype GetDirectiveConfig = {\n  name?: string;\n  test?: (node: DirectiveNode) => boolean;\n};\n\nfunction getDirectiveMatcher(\n  configs: (RemoveDirectiveConfig | GetDirectiveConfig)[]\n) {\n  const names = new Map<string, RemoveDirectiveConfig | GetDirectiveConfig>();\n\n  const tests = new Map<\n    (directive: DirectiveNode) => boolean,\n    RemoveDirectiveConfig | GetDirectiveConfig\n  >();\n\n  configs.forEach((directive) => {\n    if (directive) {\n      if (directive.name) {\n        names.set(directive.name, directive);\n      } else if (directive.test) {\n        tests.set(directive.test, directive);\n      }\n    }\n  });\n\n  return (directive: DirectiveNode) => {\n    let config = names.get(directive.name.value);\n    if (!config && tests.size) {\n      tests.forEach((testConfig, test) => {\n        if (test(directive)) {\n          config = testConfig;\n        }\n      });\n    }\n    return config;\n  };\n}\n\nfunction isEmpty(\n  op: OperationDefinitionNode | FragmentDefinitionNode,\n  fragmentMap: FragmentMap\n): boolean {\n  return (\n    !op ||\n    op.selectionSet.selections.every(\n      (selection) =>\n        selection.kind === Kind.FRAGMENT_SPREAD &&\n        isEmpty(fragmentMap[selection.name.value], fragmentMap)\n    )\n  );\n}\n\nfunction nullIfDocIsEmpty(doc: DocumentNode) {\n  return (\n      isEmpty(\n        getOperationDefinition(doc) || getFragmentDefinition(doc),\n        createFragmentMap(getFragmentDefinitions(doc))\n      )\n    ) ?\n      null\n    : doc;\n}\n"
  },
  {
    "path": "src/utilities/internal/removeFragmentSpreads.ts",
    "content": "import type { DocumentNode } from \"graphql\";\nimport { visit } from \"graphql\";\n\nexport function removeMaskedFragmentSpreads(document: DocumentNode) {\n  return visit(document, {\n    FragmentSpread(node) {\n      if (!node.directives?.some(({ name }) => name.value === \"unmask\")) {\n        return null;\n      }\n    },\n  });\n}\n"
  },
  {
    "path": "src/utilities/internal/resultKeyNameFromField.ts",
    "content": "import type { FieldNode } from \"graphql\";\n\n/** @internal */\nexport function resultKeyNameFromField(field: FieldNode): string {\n  return field.alias ? field.alias.value : field.name.value;\n}\n"
  },
  {
    "path": "src/utilities/internal/shouldInclude.ts",
    "content": "import type {\n  ArgumentNode,\n  BooleanValueNode,\n  DirectiveNode,\n  SelectionNode,\n  ValueNode,\n  VariableNode,\n} from \"graphql\";\n\nimport { invariant } from \"@apollo/client/utilities/invariant\";\n\n/** @internal */\nexport function shouldInclude(\n  { directives }: SelectionNode,\n  variables?: Record<string, any>\n): boolean {\n  if (!directives || !directives.length) {\n    return true;\n  }\n  return getInclusionDirectives(directives).every(\n    ({ directive, ifArgument }) => {\n      let evaledValue: boolean = false;\n      if (ifArgument.value.kind === \"Variable\") {\n        evaledValue =\n          variables && variables[(ifArgument.value as VariableNode).name.value];\n        invariant(\n          evaledValue !== void 0,\n          `Invalid variable referenced in @%s directive.`,\n          directive.name.value\n        );\n      } else {\n        evaledValue = (ifArgument.value as BooleanValueNode).value;\n      }\n      return directive.name.value === \"skip\" ? !evaledValue : evaledValue;\n    }\n  );\n}\n\nfunction isInclusionDirective({ name: { value } }: DirectiveNode): boolean {\n  return value === \"skip\" || value === \"include\";\n}\n\ntype InclusionDirectives = Array<{\n  directive: DirectiveNode;\n  ifArgument: ArgumentNode;\n}>;\n\nfunction getInclusionDirectives(\n  directives: ReadonlyArray<DirectiveNode>\n): InclusionDirectives {\n  const result: InclusionDirectives = [];\n\n  if (directives && directives.length) {\n    directives.forEach((directive) => {\n      if (!isInclusionDirective(directive)) return;\n\n      const directiveArguments = directive.arguments;\n      const directiveName = directive.name.value;\n\n      invariant(\n        directiveArguments && directiveArguments.length === 1,\n        `Incorrect number of arguments for the @%s directive.`,\n        directiveName\n      );\n\n      const ifArgument = directiveArguments![0];\n      invariant(\n        ifArgument.name && ifArgument.name.value === \"if\",\n        `Invalid argument for the @%s directive.`,\n        directiveName\n      );\n\n      const ifValue: ValueNode = ifArgument.value;\n\n      // means it has to be a variable value if this is a valid @skip or @include directive\n      invariant(\n        ifValue &&\n          (ifValue.kind === \"Variable\" || ifValue.kind === \"BooleanValue\"),\n        `Argument for the @%s directive must be a variable or a boolean value.`,\n        directiveName\n      );\n\n      result.push({ directive, ifArgument });\n    });\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "src/utilities/internal/storeKeyNameFromField.ts",
    "content": "import type { FieldNode } from \"graphql\";\n\nimport { getStoreKeyName } from \"./getStoreKeyName.js\";\nimport { valueToObjectRepresentation } from \"./valueToObjectRepresentation.js\";\n\n/** @internal */\nexport function storeKeyNameFromField(\n  field: FieldNode,\n  variables?: Object\n): string {\n  let directivesObj: any = null;\n  if (field.directives) {\n    directivesObj = {};\n    field.directives.forEach((directive) => {\n      directivesObj[directive.name.value] = {};\n\n      if (directive.arguments) {\n        directive.arguments.forEach(({ name, value }) =>\n          valueToObjectRepresentation(\n            directivesObj[directive.name.value],\n            name,\n            value,\n            variables\n          )\n        );\n      }\n    });\n  }\n\n  let argObj: any = null;\n  if (field.arguments && field.arguments.length) {\n    argObj = {};\n    field.arguments.forEach(({ name, value }) =>\n      valueToObjectRepresentation(argObj, name, value, variables)\n    );\n  }\n\n  return getStoreKeyName(field.name.value, argObj, directivesObj);\n}\n"
  },
  {
    "path": "src/utilities/internal/stringifyForDisplay.ts",
    "content": "import { makeUniqueId } from \"./makeUniqueId.js\";\n\n/** @internal */\nexport function stringifyForDisplay(value: any, space = 0): string {\n  const undefId = makeUniqueId(\"stringifyForDisplay\");\n  return JSON.stringify(\n    value,\n    (_, value) => {\n      return value === void 0 ? undefId : value;\n    },\n    space\n  )\n    .split(JSON.stringify(undefId))\n    .join(\"<undefined>\");\n}\n"
  },
  {
    "path": "src/utilities/internal/toQueryResult.ts",
    "content": "import type { ApolloClient, ObservableQuery } from \"@apollo/client\";\n\n/** @internal */\nexport function toQueryResult<TData = unknown>(\n  value: ObservableQuery.Result<TData>\n) {\n  const result: ApolloClient.QueryResult<TData> = {\n    data: value.data as TData | undefined,\n  };\n\n  if (value.error) {\n    result.error = value.error;\n  }\n\n  return result;\n}\n"
  },
  {
    "path": "src/utilities/internal/types/ApplyHKT.ts",
    "content": "import type { HKT } from \"@apollo/client/utilities\";\n\n/**\n * @internal\n */\n\nexport type ApplyHKT<\n  fn extends HKT,\n  arg1,\n  arg2 = never,\n  arg3 = never,\n  arg4 = never,\n> = (fn & {\n  arg1: arg1;\n  arg2: arg2;\n  arg3: arg3;\n  arg4: arg4;\n})[\"return\"];\n"
  },
  {
    "path": "src/utilities/internal/types/ApplyHKTImplementationWithDefault.ts",
    "content": "import type { HKT } from \"@apollo/client/utilities\";\n\nimport type { ApplyHKT } from \"./ApplyHKT.js\";\n\n/**\n * @internal\n */\n\nexport type ApplyHKTImplementationWithDefault<\n  Implementation,\n  Name extends string,\n  DefaultImplementation extends Record<Name, HKT>,\n  arg1,\n  arg2 = never,\n  arg3 = never,\n  arg4 = never,\n> = ApplyHKT<\n  Implementation extends {\n    [name in Name]: infer Implementation extends HKT;\n  } ?\n    Implementation\n  : DefaultImplementation[Name],\n  arg1,\n  arg2,\n  arg3,\n  arg4\n>;\n"
  },
  {
    "path": "src/utilities/internal/types/DecoratedPromise.ts",
    "content": "import type { FulfilledPromise } from \"./FulfilledPromise.js\";\nimport type { PendingPromise } from \"./PendingPromise.js\";\nimport type { RejectedPromise } from \"./RejectedPromise.js\";\n\n/** @internal */\nexport type DecoratedPromise<TValue> =\n  | PendingPromise<TValue>\n  | FulfilledPromise<TValue>\n  | RejectedPromise<TValue>;\n"
  },
  {
    "path": "src/utilities/internal/types/DeepOmit.ts",
    "content": "import type { Primitive } from \"./Primitive.js\";\n\n// DeepOmit primitives include functions since these are unmodified.\ntype DeepOmitPrimitive = Primitive | Function;\n\ntype DeepOmitArray<T extends any[], K> = {\n  [P in keyof T]: DeepOmit<T[P], K>;\n};\n\n// Unfortunately there is one major flaw in this type: This will omit properties\n// from class instances in the return type even though our omitDeep helper\n// ignores class instances, therefore resulting in a type mismatch between\n// the return value and the runtime value.\n//\n// It is not currently possible with TypeScript to distinguish between plain\n// objects and class instances.\n// https://github.com/microsoft/TypeScript/issues/29063\n//\n// This should be fine as of the time of this writing until omitDeep gets\n// broader use since this utility is only used to strip __typename from\n// `variables`; a case in which class instances are invalid anyways.\n/** @internal */\nexport type DeepOmit<T, K> =\n  T extends DeepOmitPrimitive ? T\n  : {\n      [P in keyof T as P extends K ? never : P]: T[P] extends infer TP ?\n        TP extends DeepOmitPrimitive ? TP\n        : TP extends any[] ? DeepOmitArray<TP, K>\n        : DeepOmit<TP, K>\n      : never;\n    };\n"
  },
  {
    "path": "src/utilities/internal/types/DocumentationTypes.ts",
    "content": "import type {\n  Observable,\n  Observer,\n  OperatorFunction,\n  Subscription,\n} from \"rxjs\";\n\nimport type {\n  DataValue,\n  ErrorLike,\n  MaybeMasked,\n  NetworkStatus,\n  OperationVariables,\n} from \"@apollo/client\";\n\n/**\n * This namespace contains simplified interface versions of existing, complicated, types in Apollo Client.\n * These interfaces are used in the documentation to provide a more readable\n * and understandable API reference.\n */\nexport declare namespace DocumentationTypes {\n  export interface DataState<TData> {\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#data:member} */\n    data?:\n      | DataValue.Complete<TData>\n      | DataValue.Streaming<TData>\n      | DataValue.Partial<TData>\n      | undefined;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#dataState:member} */\n    dataState: \"complete\" | \"streaming\" | \"partial\" | \"empty\";\n  }\n\n  export interface VariableOptions<TVariables extends OperationVariables> {\n    /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n    variables?: TVariables;\n  }\n\n  export interface ApolloQueryResult<TData> extends DataState<TData> {\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#error:member} */\n    error?: ErrorLike;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#loading:member} */\n    loading: boolean;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#networkStatus:member} */\n    networkStatus: NetworkStatus;\n    /** {@inheritDoc @apollo/client!QueryResultDocumentation#partial:member} */\n    partial: boolean;\n  }\n\n  export interface RxjsObservable<TData> {\n    pipe<OperatorResult>(\n      ...operators:\n        | [\n            OperatorFunction<\n              Observable<ApolloQueryResult<TData>>,\n              OperatorResult\n            >,\n          ]\n        | [\n            OperatorFunction<Observable<ApolloQueryResult<TData>>, unknown>,\n            ...OperatorFunction<unknown, unknown>[],\n            OperatorFunction<unknown, OperatorResult>,\n          ]\n    ): Observable<OperatorResult>;\n\n    subscribe(\n      observer:\n        | Partial<Observer<ApolloQueryResult<MaybeMasked<TData>>>>\n        | ((value: ApolloQueryResult<MaybeMasked<TData>>) => void)\n    ): Subscription;\n  }\n}\n"
  },
  {
    "path": "src/utilities/internal/types/ExtensionsWithStreamDetails.ts",
    "content": "import type { streamInfoSymbol } from \"../constants.js\";\n\nimport type { StreamInfoTrie } from \"./StreamInfoTrie.js\";\n\n/**\n * For use in Cache implementations only.\n * This should not be used in userland code.\n */\nexport interface ExtensionsWithStreamInfo extends Record<string, unknown> {\n  [streamInfoSymbol]?: {\n    deref(): StreamInfoTrie | undefined;\n  };\n}\n"
  },
  {
    "path": "src/utilities/internal/types/FragmentMap.ts",
    "content": "import type { FragmentDefinitionNode } from \"graphql\";\n\n/**\n * Describes a map from fragment names to fragment definitions.\n *\n * @internal\n */\nexport interface FragmentMap {\n  [fragmentName: string]: FragmentDefinitionNode;\n}\n"
  },
  {
    "path": "src/utilities/internal/types/FragmentMapFunction.ts",
    "content": "import type { FragmentDefinitionNode } from \"graphql\";\n\n/** @internal */\nexport type FragmentMapFunction = (\n  fragmentName: string\n) => FragmentDefinitionNode | null;\n"
  },
  {
    "path": "src/utilities/internal/types/FulfilledPromise.ts",
    "content": "/** @internal */\nexport interface FulfilledPromise<TValue> extends Promise<TValue> {\n  status: \"fulfilled\";\n  value: TValue;\n}\n"
  },
  {
    "path": "src/utilities/internal/types/IsAny.ts",
    "content": "/** @internal */\nexport type IsAny<T> = 0 extends 1 & T ? true : false;\n"
  },
  {
    "path": "src/utilities/internal/types/NoInfer.ts",
    "content": "/**\n * Helper type that allows using a type in a way that cannot be \"widened\" by inference on the value it is used on.\n *\n * This type was first suggested [in this Github discussion](https://github.com/microsoft/TypeScript/issues/14829#issuecomment-504042546).\n *\n * Example usage:\n *\n * ```ts\n * export function useQuery<\n *   TData = unknown,\n *   TVariables extends OperationVariables = OperationVariables,\n * >(\n *   query: DocumentNode | TypedDocumentNode<TData, TVariables>,\n *   options: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> = {}\n * );\n * ```\n *\n * In this case, `TData` and `TVariables` should be inferred from `query`, but never widened from something in `options`.\n *\n * So, in this code example:\n *\n * ```ts\n * declare const typedNode: TypedDocumentNode<{ foo: string }, { bar: number }>;\n * const { variables } = useQuery(typedNode, {\n *   variables: { bar: 4, nonExistingVariable: \"string\" },\n * });\n * ```\n *\n * Without the use of `NoInfer`, `variables` would now be of the type `{ bar: number, nonExistingVariable: \"string\" }`.\n * With `NoInfer`, it will instead give an error on `nonExistingVariable`.\n *\n * @deprecated use the official `NoInfer` type instead.\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never];\n"
  },
  {
    "path": "src/utilities/internal/types/PendingPromise.ts",
    "content": "/** @internal */\nexport interface PendingPromise<TValue> extends Promise<TValue> {\n  status: \"pending\";\n}\n"
  },
  {
    "path": "src/utilities/internal/types/Prettify.ts",
    "content": "/** @internal */\nexport type Prettify<T> = { [K in keyof T]: T[K] } & {};\n"
  },
  {
    "path": "src/utilities/internal/types/Primitive.ts",
    "content": "// Matches any primitive value: https://developer.mozilla.org/en-US/docs/Glossary/Primitive.\n/** @internal */\nexport type Primitive =\n  | null\n  | undefined\n  | string\n  | number\n  | boolean\n  | symbol\n  | bigint;\n"
  },
  {
    "path": "src/utilities/internal/types/RejectedPromise.ts",
    "content": "/** @internal */\nexport interface RejectedPromise<TValue> extends Promise<TValue> {\n  status: \"rejected\";\n  reason: unknown;\n}\n"
  },
  {
    "path": "src/utilities/internal/types/RemoveIndexSignature.ts",
    "content": "/** @internal */\nexport type RemoveIndexSignature<T> = {\n  [K in keyof T as string extends K ? never\n  : number extends K ? never\n  : symbol extends K ? never\n  : K]: T[K];\n};\n"
  },
  {
    "path": "src/utilities/internal/types/StreamInfoTrie.ts",
    "content": "import type { Trie } from \"@wry/trie\";\n\nimport type { Incremental } from \"@apollo/client/incremental\";\n\n/** @internal */\nexport type StreamInfoTrie = Trie<{\n  current: Incremental.StreamFieldInfo;\n  previous?: {\n    incoming: unknown;\n    streamFieldInfo: Incremental.StreamFieldInfo;\n    result: unknown;\n  };\n}>;\n"
  },
  {
    "path": "src/utilities/internal/types/TupleToIntersection.ts",
    "content": "export type TupleToIntersection<T extends any[]> =\n  T extends [infer A] ? A\n  : T extends [infer A, infer B] ? A & B\n  : T extends [infer A, infer B, infer C] ? A & B & C\n  : T extends [infer A, infer B, infer C, infer D] ? A & B & C & D\n  : T extends [infer A, infer B, infer C, infer D, infer E] ? A & B & C & D & E\n  : T extends (infer U)[] ? U\n  : any;\n"
  },
  {
    "path": "src/utilities/internal/types/VariablesOption.ts",
    "content": "import type { OperationVariables } from \"@apollo/client\";\n\n/** @internal */\nexport type VariablesOption<TVariables extends OperationVariables> =\n  {} extends TVariables ?\n    {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n      variables?: TVariables;\n    }\n  : {\n      /** {@inheritDoc @apollo/client!QueryOptionsDocumentation#variables:member} */\n      variables: TVariables;\n    };\n"
  },
  {
    "path": "src/utilities/internal/types/__tests__/HTK.test.ts",
    "content": "import { expectTypeOf } from \"expect-type\";\n\nimport type { CustomHKT } from \"@apollo/client\";\nimport type { HKT } from \"@apollo/client/utilities\";\nimport type {\n  ApplyHKT,\n  ApplyHKTImplementationWithDefault,\n} from \"@apollo/client/utilities/internal\";\n\ndeclare module \"@apollo/client\" {\n  export interface CustomHKT {\n    Masked: CustomMaskedType;\n  }\n}\n\ninterface CustomMaskedType extends HKT {\n  arg1: unknown; // TData\n  return: CustomMaskedImplementation<this[\"arg1\"]>;\n}\n\ntype CustomMaskedImplementation<TData> = {\n  [K in keyof TData as K extends `_${string}` ? never : K]: TData[K];\n};\n\nit.skip(\"type tests\", () => {\n  type BaseType = {\n    _id: string;\n    name: string;\n    _description: string;\n    age: number;\n  };\n\n  type ExpectedResult = {\n    name: string;\n    age: number;\n  };\n\n  {\n    // base type does what we want\n    type Result = CustomMaskedImplementation<BaseType>;\n    expectTypeOf<Result>().toEqualTypeOf<ExpectedResult>();\n  }\n\n  {\n    // HKT/ApplyHKT type do what we want\n    type Result = ApplyHKT<CustomMaskedType, BaseType>;\n    expectTypeOf<Result>().toEqualTypeOf<ExpectedResult>();\n  }\n\n  {\n    // ApplyHKTImplementationWithDefault with a globally augmented interface\n    type Result = ApplyHKTImplementationWithDefault<\n      CustomHKT,\n      \"Masked\",\n      {\n        // this default implementation would return `unknown`\n        Masked: HKT;\n      },\n      BaseType\n    >;\n    expectTypeOf<Result>().toEqualTypeOf<ExpectedResult>();\n  }\n\n  {\n    interface Concat extends HKT {\n      arg1: string;\n      arg2: string;\n      return: `${this[\"arg1\"]}${this[\"arg2\"]}`;\n    }\n\n    type Result = ApplyHKT<Concat, \"Hello, \", \"world!\">;\n\n    expectTypeOf<Result>().toEqualTypeOf<\"Hello, world!\">();\n  }\n});\n"
  },
  {
    "path": "src/utilities/internal/valueToObjectRepresentation.ts",
    "content": "import type { EnumValueNode, NameNode, ValueNode } from \"graphql\";\nimport { Kind } from \"graphql\";\n\nimport { newInvariantError } from \"@apollo/client/utilities/invariant\";\n\n/** @internal */\nexport function valueToObjectRepresentation(\n  argObj: any,\n  name: NameNode,\n  value: ValueNode,\n  variables?: Object\n) {\n  if (value.kind === Kind.INT || value.kind === Kind.FLOAT) {\n    argObj[name.value] = Number(value.value);\n  } else if (value.kind === Kind.BOOLEAN || value.kind === Kind.STRING) {\n    argObj[name.value] = value.value;\n  } else if (value.kind === Kind.OBJECT) {\n    const nestedArgObj = {};\n    value.fields.map((obj) =>\n      valueToObjectRepresentation(nestedArgObj, obj.name, obj.value, variables)\n    );\n    argObj[name.value] = nestedArgObj;\n  } else if (value.kind === Kind.VARIABLE) {\n    const variableValue = (variables || ({} as any))[value.name.value];\n    argObj[name.value] = variableValue;\n  } else if (value.kind === Kind.LIST) {\n    argObj[name.value] = value.values.map((listValue) => {\n      const nestedArgArrayObj = {};\n      valueToObjectRepresentation(\n        nestedArgArrayObj,\n        name,\n        listValue,\n        variables\n      );\n      return (nestedArgArrayObj as any)[name.value];\n    });\n  } else if (value.kind === Kind.ENUM) {\n    argObj[name.value] = (value as EnumValueNode).value;\n  } else if (value.kind === Kind.NULL) {\n    argObj[name.value] = null;\n  } else {\n    throw newInvariantError(\n      `The inline argument \"%s\" of kind \"%s\"` +\n        \"is not supported. Use variables instead of inline arguments to \" +\n        \"overcome this limitation.\",\n      name.value,\n      (value as any).kind\n    );\n  }\n}\n"
  },
  {
    "path": "src/utilities/invariant/__tests__/invariant.test.ts",
    "content": "import { version } from \"@apollo/client\";\nimport { spyOnConsole } from \"@apollo/client/testing/internal\";\nimport {\n  ApolloErrorMessageHandler,\n  invariant,\n  InvariantError,\n} from \"@apollo/client/utilities/invariant\";\n\nfunction withDev(): typeof import(\"@apollo/client/dev\") & AsyncDisposable {\n  const originalErrorMessageHandler = window[ApolloErrorMessageHandler];\n  window[ApolloErrorMessageHandler] = undefined;\n  let dev: typeof import(\"@apollo/client/dev\");\n  let restore = () => {};\n  // we're running the test inside of `jest.isolateModulesAsync` to avoid\n  // the test overriding the module-level state of the `dev` module\n  const cleanupFinished = jest.isolateModulesAsync(\n    () =>\n      new Promise<void>((resolve) => {\n        dev = require(\"@apollo/client/dev\");\n        restore = resolve;\n      })\n  );\n  // replicate the code of `src/config/jest/setup.ts`\n  dev!.loadErrorMessageHandler();\n  return {\n    ...dev!,\n    async [Symbol.asyncDispose]() {\n      restore();\n      await cleanupFinished;\n      window[ApolloErrorMessageHandler] = originalErrorMessageHandler;\n    },\n  };\n}\n\nfunction disableErrorMessageHandler() {\n  const dev = withDev();\n  delete window[ApolloErrorMessageHandler];\n  return dev;\n}\n\nfunction mockErrorMessageHandler() {\n  const dev = withDev();\n  delete window[ApolloErrorMessageHandler];\n\n  dev.loadErrorMessageHandler({\n    5: { file: \"foo\", message: \"Replacing %s, %d, %f, %o\" },\n  });\n  return dev;\n}\n\ntest(\"base invariant(false, 5, ...), no handlers\", async () => {\n  await using _ = disableErrorMessageHandler();\n  expect(() => {\n    invariant(false, 5, \"string\", 1, 1.1, { a: 1 });\n  }).toThrow(\n    new InvariantError(\n      \"An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#\" +\n        encodeURIComponent(\n          JSON.stringify({\n            version,\n            message: 5,\n            args: [\n              \"string\",\n              \"1\",\n              \"1.1\",\n              JSON.stringify({ a: 1 }, undefined, 2),\n            ],\n          })\n        )\n    )\n  );\n});\n\ntest(\"base invariant(false, 5, ...), handlers in place\", async () => {\n  await using _ = mockErrorMessageHandler();\n  expect(() => {\n    invariant(false, 5, \"string\", 1, 1.1, { a: 1 });\n  }).toThrow(new InvariantError('Replacing string, 1, 1.1, {\\n  \"a\": 1\\n}'));\n});\n\ntest(\"base invariant(false, 5, ...), custom handler gets passed arguments\", async () => {\n  await using dev = disableErrorMessageHandler();\n\n  const handler = jest.fn(() => \"\");\n  dev.setErrorMessageHandler(handler);\n\n  try {\n    invariant(false, 5, \"string\", 1, 1.1, { a: 1 });\n  } catch {}\n\n  expect(handler).toHaveBeenCalledWith(5, [\n    \"string\",\n    \"1\",\n    \"1.1\",\n    '{\\n  \"a\": 1\\n}',\n  ]);\n});\n\ntest(\"base invariant(false, undefined), no handlers\", async () => {\n  await using _ = disableErrorMessageHandler();\n  expect(() => {\n    invariant(false);\n  }).toThrow(new InvariantError(\"Invariant Violation\"));\n});\n\ntest(\"base invariant(false, undefined), handlers in place\", async () => {\n  await using _ = mockErrorMessageHandler();\n  expect(() => {\n    invariant(false);\n  }).toThrow(new InvariantError(\"Invariant Violation\"));\n});\n\ntest(\"invariant.log(5, ...), no handlers\", async () => {\n  await using _ = disableErrorMessageHandler();\n  using consoleSpy = spyOnConsole(\"log\");\n  invariant.log(5, \"string\", 1, 1.1, { a: 1 });\n  expect(consoleSpy.log).toHaveBeenCalledWith(\n    \"An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#\" +\n      encodeURIComponent(\n        JSON.stringify({\n          version,\n          message: 5,\n          args: [\"string\", \"1\", \"1.1\", JSON.stringify({ a: 1 }, undefined, 2)],\n        })\n      )\n  );\n});\n\ntest(\"invariant.log(5, ...), with handlers\", async () => {\n  await using _ = mockErrorMessageHandler();\n  using consoleSpy = spyOnConsole(\"log\");\n  invariant.log(5, \"string\", 1, 1.1, { a: 1 });\n  expect(consoleSpy.log).toHaveBeenCalledWith(\n    \"Replacing %s, %d, %f, %o\",\n    \"string\",\n    1,\n    1.1,\n    { a: 1 }\n  );\n});\n\ntest(\"invariant.log(5, ...), custom handler does not get passed arguments\", async () => {\n  await using dev = disableErrorMessageHandler();\n  using _consoleSpy = spyOnConsole(\"log\");\n\n  const handler = jest.fn(() => \"\");\n  dev.setErrorMessageHandler(handler);\n\n  try {\n    invariant.log(5, \"string\", 1, 1.1, { a: 1 });\n  } catch {}\n\n  expect(handler).toHaveBeenCalledWith(5, []);\n});\n\ntest(\"base invariant(false, 6, ...), raises fallback\", async () => {\n  await using _ = mockErrorMessageHandler();\n  expect(() => {\n    invariant(false, 6, \"hello\");\n  }).toThrow(\n    new InvariantError(\n      \"An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#\" +\n        encodeURIComponent(\n          JSON.stringify({\n            version,\n            message: 6,\n            args: [\"hello\"],\n          })\n        )\n    )\n  );\n});\n\ntest(\"base invariant(false, 6, ...) with non-serializable param\", async () => {\n  await using _ = mockErrorMessageHandler();\n\n  const obj: any = {};\n  obj.self = obj;\n\n  expect(() => {\n    invariant(false, 6, obj);\n  }).toThrow(\n    new InvariantError(\n      \"An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#\" +\n        encodeURIComponent(\n          JSON.stringify({\n            version,\n            message: 6,\n            args: [\"<non-serializable>\"],\n          })\n        )\n    )\n  );\n});\n"
  },
  {
    "path": "src/utilities/invariant/index.development.ts",
    "content": "import { loadDevMessages, loadErrorMessages } from \"@apollo/client/dev\";\n\n// eslint-disable-next-line no-restricted-syntax\nexport * from \"./index.js\";\n// eslint-disable-next-line local-rules/import-from-export\nimport { invariant as origInvariant } from \"./index.js\";\nexport const invariant = (() => {\n  // side effects in an IIFE\n  loadDevMessages();\n  loadErrorMessages();\n  return origInvariant;\n})();\n"
  },
  {
    "path": "src/utilities/invariant/index.ts",
    "content": "import { __DEV__ } from \"@apollo/client/utilities/environment\";\nimport { global } from \"@apollo/client/utilities/internal/globals\";\n\nimport type { ErrorCodes } from \"../../invariantErrorCodes.js\";\nimport { version } from \"../../version.js\";\n// eslint-disable-next-line local-rules/import-from-inside-other-export\nimport { stringifyForDisplay } from \"../internal/stringifyForDisplay.js\";\n\nconst genericMessage = \"Invariant Violation\";\nexport class InvariantError extends Error {\n  constructor(message = genericMessage) {\n    super(message);\n    this.name = genericMessage;\n\n    Object.setPrototypeOf(this, InvariantError.prototype);\n  }\n}\n\nconst verbosityLevels = [\"debug\", \"log\", \"warn\", \"error\", \"silent\"] as const;\ntype VerbosityLevel = (typeof verbosityLevels)[number];\ntype ConsoleMethodName = Exclude<VerbosityLevel, \"silent\">;\nlet verbosityLevel = verbosityLevels.indexOf(__DEV__ ? \"log\" : \"silent\");\n\nexport function invariant(\n  condition: any,\n  ...args: [message?: string | number, ...any[]]\n): asserts condition {\n  if (!condition) {\n    throw newInvariantError(...args);\n  }\n}\n\nfunction wrapConsoleMethod<M extends ConsoleMethodName>(name: M) {\n  return function (message?: string | number, ...args: any[]) {\n    if (verbosityLevels.indexOf(name) >= verbosityLevel) {\n      // Default to console.log if this host environment happens not to provide\n      // all the console.* methods we need.\n      const method = console[name] || console.log;\n\n      if (typeof message === \"number\") {\n        const arg0 = message;\n        message = getHandledErrorMsg(arg0);\n        if (!message) {\n          message = getFallbackErrorMsg(arg0, args);\n          args = [];\n        }\n      }\n\n      method(message, ...args);\n    }\n  } as (typeof console)[M];\n}\n\ninvariant.debug = wrapConsoleMethod(\"debug\");\ninvariant.log = wrapConsoleMethod(\"log\");\ninvariant.warn = wrapConsoleMethod(\"warn\");\ninvariant.error = wrapConsoleMethod(\"error\");\n\nexport function setVerbosity(level: VerbosityLevel): VerbosityLevel {\n  const old = verbosityLevels[verbosityLevel];\n  verbosityLevel = Math.max(0, verbosityLevels.indexOf(level));\n  return old;\n}\n\n/**\n * Returns an InvariantError.\n *\n * `message` can only be a string, a concatenation of strings, or a ternary statement\n * that results in a string. This will be enforced on build, where the message will\n * be replaced with a message number.\n * String substitutions with %s are supported and will also return\n * pretty-stringified objects.\n * Excess `optionalParams` will be swallowed.\n */\nexport function newInvariantError(\n  message?: string | number,\n  ...optionalParams: unknown[]\n) {\n  return new InvariantError(\n    getHandledErrorMsg(message, optionalParams) ||\n      getFallbackErrorMsg(message, optionalParams)\n  );\n}\n\n// This is duplicated between `@apollo/client/dev` and `@apollo/client/utilities/invariant` to prevent circular references.\nexport const ApolloErrorMessageHandler = Symbol.for(\n  \"ApolloErrorMessageHandler_\" + version\n);\ndeclare global {\n  interface Window {\n    [ApolloErrorMessageHandler]?: {\n      (message: string | number, args: string[]): string | undefined;\n    } & ErrorCodes;\n  }\n}\n\nfunction stringify(arg: any) {\n  if (typeof arg == \"string\") {\n    return arg;\n  }\n\n  try {\n    return stringifyForDisplay(arg, 2).slice(0, 1000);\n  } catch {\n    return \"<non-serializable>\";\n  }\n}\n\nfunction getHandledErrorMsg(\n  message?: string | number,\n  messageArgs: unknown[] = []\n) {\n  if (!message) return;\n  return (\n    global[ApolloErrorMessageHandler] &&\n    global[ApolloErrorMessageHandler](message, messageArgs.map(stringify))\n  );\n}\n\nfunction getFallbackErrorMsg(\n  message?: string | number,\n  messageArgs: unknown[] = []\n) {\n  if (!message) return;\n  if (typeof message === \"string\") {\n    return messageArgs.reduce<string>(\n      (msg, arg) => msg.replace(/%[sdfo]/, stringify(arg)),\n      message\n    );\n  }\n  return `An error occurred! For more details, see the full error text at https://go.apollo.dev/c/err#${encodeURIComponent(\n    JSON.stringify({\n      version,\n      message,\n      args: messageArgs.map(stringify),\n    })\n  )}`;\n}\n"
  },
  {
    "path": "src/utilities/isNetworkRequestInFlight.ts",
    "content": "import type { NetworkStatus } from \"@apollo/client\";\n\nimport { isNetworkRequestSettled } from \"./isNetworkRequestSettled.js\";\n\n/**\n * Returns true if there is currently a network request in flight according to a given network\n * status.\n */\nexport function isNetworkRequestInFlight(\n  networkStatus?: NetworkStatus\n): boolean {\n  return !isNetworkRequestSettled(networkStatus);\n}\n"
  },
  {
    "path": "src/utilities/isNetworkRequestSettled.ts",
    "content": "import type { NetworkStatus } from \"@apollo/client\";\n\n/**\n * Returns true if the network request is in ready or error state according to a given network\n * status.\n */\nexport function isNetworkRequestSettled(\n  networkStatus?: NetworkStatus\n): boolean {\n  return networkStatus === 7 || networkStatus === 8;\n}\n"
  },
  {
    "path": "src/utilities/policies/__tests__/relayStylePagination.test.ts",
    "content": "import type { FieldFunctionOptions, StoreObject } from \"@apollo/client/cache\";\nimport { InMemoryCache, isReference } from \"@apollo/client/cache\";\nimport { relayStylePagination } from \"@apollo/client/utilities\";\nimport { makeReference } from \"@apollo/client/utilities/internal\";\n\nimport type { TRelayPageInfo } from \"../pagination.js\";\n\ndescribe(\"relayStylePagination\", () => {\n  const policy = relayStylePagination();\n\n  describe(\"read\", () => {\n    const fakeEdges = [\n      { node: { __ref: \"A\" }, cursor: \"cursorA\" },\n      { node: { __ref: \"B\" }, cursor: \"cursorB\" },\n      { node: { __ref: \"C\" }, cursor: \"cursorC\" },\n    ];\n\n    const fakeReadOptions = {\n      canRead() {\n        return true;\n      },\n      readField(key: string, obj: StoreObject) {\n        return obj && obj[key];\n      },\n    } as any as FieldFunctionOptions;\n\n    it(\"should prefer existing.pageInfo.startCursor\", () => {\n      const resultWithStartCursor = policy.read!(\n        {\n          edges: fakeEdges,\n          pageInfo: {\n            startCursor: \"preferredStartCursor\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          } as TRelayPageInfo,\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithStartCursor && resultWithStartCursor.pageInfo).toEqual({\n        startCursor: \"preferredStartCursor\",\n        endCursor: \"cursorC\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n\n    it(\"should prefer existing.pageInfo.endCursor\", () => {\n      const resultWithEndCursor = policy.read!(\n        {\n          edges: fakeEdges,\n          pageInfo: {\n            endCursor: \"preferredEndCursor\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          } as TRelayPageInfo,\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithEndCursor && resultWithEndCursor.pageInfo).toEqual({\n        startCursor: \"cursorA\",\n        endCursor: \"preferredEndCursor\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n\n    it(\"should prefer existing.pageInfo.{start,end}Cursor\", () => {\n      const resultWithEndCursor = policy.read!(\n        {\n          edges: fakeEdges,\n          pageInfo: {\n            startCursor: \"preferredStartCursor\",\n            endCursor: \"preferredEndCursor\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          },\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithEndCursor && resultWithEndCursor.pageInfo).toEqual({\n        startCursor: \"preferredStartCursor\",\n        endCursor: \"preferredEndCursor\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n\n    it(\"should override pageInfo.{start,end}Cursor if empty strings\", () => {\n      const resultWithEndCursor = policy.read!(\n        {\n          edges: [\n            { node: { __ref: \"A\" }, cursor: \"\" },\n            { node: { __ref: \"B\" }, cursor: \"cursorB\" },\n            { node: { __ref: \"C\" }, cursor: \"\" },\n            { node: { __ref: \"D\" }, cursor: \"cursorD\" },\n            { node: { __ref: \"E\" } },\n          ],\n          pageInfo: {\n            startCursor: \"\",\n            endCursor: \"\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          },\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithEndCursor && resultWithEndCursor.pageInfo).toEqual({\n        startCursor: \"cursorB\",\n        endCursor: \"cursorD\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n\n    it(\"should only override pageInfo.endCursor if empty strings with a single cursor\", () => {\n      const resultWithEndCursor = policy.read!(\n        {\n          edges: [\n            { node: { __ref: \"A\" }, cursor: \"\" },\n            { node: { __ref: \"B\" }, cursor: \"\" },\n            { node: { __ref: \"C\" }, cursor: \"\" },\n            { node: { __ref: \"D\" }, cursor: \"cursorD\" },\n            { node: { __ref: \"E\" } },\n          ],\n          pageInfo: {\n            startCursor: \"\",\n            endCursor: \"\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          },\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithEndCursor && resultWithEndCursor.pageInfo).toEqual({\n        startCursor: \"\",\n        endCursor: \"cursorD\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n\n    it(\"should only override both pageInfo.{start,end}Cursor if empty strings with a single cursor and single element\", () => {\n      const resultWithEndCursor = policy.read!(\n        {\n          edges: [{ node: { __ref: \"A\" }, cursor: \"cursorA\" }],\n          pageInfo: {\n            startCursor: \"\",\n            endCursor: \"\",\n            hasPreviousPage: false,\n            hasNextPage: true,\n          },\n        },\n        fakeReadOptions\n      );\n\n      expect(resultWithEndCursor && resultWithEndCursor.pageInfo).toEqual({\n        startCursor: \"cursorA\",\n        endCursor: \"cursorA\",\n        hasPreviousPage: false,\n        hasNextPage: true,\n      });\n    });\n  });\n\n  describe(\"merge\", () => {\n    const merge = policy.merge;\n    // The merge function should exist, make TS aware\n    if (typeof merge !== \"function\") {\n      throw new Error(\"Expecting merge function\");\n    }\n\n    const options: FieldFunctionOptions = {\n      args: null,\n      fieldName: \"fake\",\n      storeFieldName: \"fake\",\n      field: null,\n      isReference: isReference,\n      toReference: () => undefined,\n      storage: {},\n      cache: new InMemoryCache(),\n      readField: () => undefined,\n      canRead: () => false,\n      mergeObjects: (existing, _incoming) => existing,\n    };\n\n    it(\"should maintain endCursor and startCursor with empty edges\", () => {\n      const incoming: Parameters<typeof merge>[1] = {\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"abc\",\n          endCursor: \"xyz\",\n        },\n      };\n      const result = merge(undefined, incoming, {\n        ...options,\n        extensions: undefined,\n        existingData: undefined,\n      });\n      expect(result).toEqual({\n        edges: [],\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"abc\",\n          endCursor: \"xyz\",\n        },\n      });\n    });\n\n    it(\"should maintain existing PageInfo when adding a page\", () => {\n      const existingEdges = [\n        { cursor: \"alpha\", node: makeReference(\"fakeAlpha\") },\n      ];\n\n      const incomingEdges = [\n        { cursor: \"omega\", node: makeReference(\"fakeOmega\") },\n      ];\n\n      const existing = {\n        edges: existingEdges,\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"alpha\",\n        },\n      };\n\n      const result = merge(\n        existing,\n        {\n          edges: incomingEdges,\n          pageInfo: {\n            hasPreviousPage: true,\n            hasNextPage: true,\n            startCursor: incomingEdges[0].cursor,\n            endCursor: incomingEdges[incomingEdges.length - 1].cursor,\n          },\n        },\n        {\n          ...options,\n          args: {\n            after: \"alpha\",\n          },\n          extensions: undefined,\n          existingData: existing,\n        }\n      );\n\n      expect(result).toEqual({\n        edges: [...existingEdges, ...incomingEdges],\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"omega\",\n        },\n      });\n    });\n\n    it(\"should preserve existing if incoming is null\", () => {\n      const existingEdges = [\n        { cursor: \"alpha\", node: makeReference(\"fakeAlpha\") },\n      ];\n\n      const fakeExisting = {\n        edges: existingEdges,\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"alpha\",\n        },\n      };\n\n      const fakeIncoming = null;\n\n      const fakeOptions = {\n        ...options,\n        args: {\n          after: \"alpha\",\n        },\n        extensions: undefined,\n        existingData: fakeExisting,\n      };\n\n      const result = merge(fakeExisting, fakeIncoming, fakeOptions);\n\n      expect(result).toEqual(fakeExisting);\n    });\n\n    it(\"should replace existing null with incoming\", () => {\n      const incomingEdges = [\n        { cursor: \"alpha\", node: makeReference(\"fakeAlpha\") },\n      ];\n      const incoming = {\n        edges: incomingEdges,\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"alpha\",\n        },\n      };\n      const result = merge(null, incoming, {\n        ...options,\n        args: {\n          after: \"alpha\",\n        },\n        extensions: undefined,\n        existingData: null,\n      });\n\n      expect(result).toEqual(incoming);\n    });\n\n    it(\"should maintain extra PageInfo properties\", () => {\n      const existingEdges = [\n        { cursor: \"alpha\", node: makeReference(\"fakeAlpha\") },\n      ];\n\n      const incomingEdges = [\n        { cursor: \"omega\", node: makeReference(\"fakeOmega\") },\n      ];\n\n      const existing = {\n        edges: existingEdges,\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"alpha\",\n          extra: \"existing.pageInfo.extra\",\n        } as TRelayPageInfo,\n      };\n\n      const result = merge(\n        existing,\n        {\n          edges: incomingEdges,\n          pageInfo: {\n            hasPreviousPage: true,\n            hasNextPage: true,\n            startCursor: incomingEdges[0].cursor,\n            endCursor: incomingEdges[incomingEdges.length - 1].cursor,\n            extra: \"incoming.pageInfo.extra\",\n          } as TRelayPageInfo,\n        },\n        {\n          ...options,\n          args: {\n            after: \"alpha\",\n          },\n          extensions: undefined,\n          existingData: existing,\n        }\n      );\n\n      expect(result).toEqual({\n        edges: [...existingEdges, ...incomingEdges],\n        pageInfo: {\n          hasPreviousPage: false,\n          hasNextPage: true,\n          startCursor: \"alpha\",\n          endCursor: \"omega\",\n          // This is the most important line in this test, since it proves\n          // incoming.pageInfo.extra was not lost.\n          extra: \"incoming.pageInfo.extra\",\n        },\n      });\n    });\n  });\n});\n"
  },
  {
    "path": "src/utilities/policies/pagination.ts",
    "content": "import { __rest } from \"tslib\";\n\nimport type { FieldPolicy, Reference } from \"@apollo/client/cache\";\nimport { mergeDeep } from \"@apollo/client/utilities/internal\";\n\ntype KeyArgs = FieldPolicy<any>[\"keyArgs\"];\n\n/**\n * A basic pagination field policy that always concatenates new\n * results onto the existing array, without examining options.args.\n *\n * @param keyArgs - `keyArgs` that should be applied to the field policy\n * @returns The field policy that handles concatenating field results.\n */\nexport function concatPagination<T = Reference>(\n  keyArgs: KeyArgs = false\n): FieldPolicy<T[]> {\n  return {\n    keyArgs,\n    merge(existing, incoming) {\n      return existing ? [...existing, ...incoming] : incoming;\n    },\n  };\n}\n\n/**\n * A basic field policy that uses `options.args.{offset,limit}` to splice\n * the incoming data into the existing array. If your arguments are called\n * something different (like `args.{start,count}`), feel free to copy/paste\n * this implementation and make the appropriate changes.\n *\n * @param keyArgs - `keyArgs` that should be applied to the field policy\n * @returns The field policy that handles offset/limit pagination\n */\nexport function offsetLimitPagination<T = Reference>(\n  keyArgs: KeyArgs = false\n): FieldPolicy<T[]> {\n  return {\n    keyArgs,\n    merge(existing, incoming, { args }) {\n      const merged = existing ? existing.slice(0) : [];\n\n      if (incoming) {\n        if (args) {\n          // Assume an offset of 0 if args.offset omitted.\n          const { offset = 0 } = args;\n          for (let i = 0; i < incoming.length; ++i) {\n            merged[offset + i] = incoming[i];\n          }\n        } else {\n          // It's unusual (probably a mistake) for a paginated field not\n          // to receive any arguments, so you might prefer to throw an\n          // exception here, instead of recovering by appending incoming\n          // onto the existing array.\n          merged.push(...incoming);\n        }\n      }\n\n      return merged;\n    },\n  };\n}\n\n// Whether TRelayEdge<TNode> is a normalized Reference or a non-normalized\n// object, it needs a .cursor property where the relayStylePagination\n// merge function can store cursor strings taken from pageInfo. Storing an\n// extra reference.cursor property should be safe, and is easier than\n// attempting to update the cursor field of the normalized StoreObject\n// that the reference refers to, or managing edge wrapper objects\n// (something I attempted in #7023, but abandoned because of #7088).\ntype TRelayEdge<TNode> =\n  | {\n      cursor?: string;\n      node: TNode;\n    }\n  | (Reference & { cursor?: string });\n\nexport type TRelayPageInfo = {\n  hasPreviousPage: boolean;\n  hasNextPage: boolean;\n  startCursor: string;\n  endCursor: string;\n};\n\ntype TExistingRelay<TNode> = Readonly<{\n  edges: TRelayEdge<TNode>[];\n  pageInfo: TRelayPageInfo;\n}>;\n\ntype TIncomingRelay<TNode> = {\n  edges?: TRelayEdge<TNode>[];\n  pageInfo?: TRelayPageInfo;\n};\n\ntype RelayFieldPolicy<TNode> = FieldPolicy<\n  TExistingRelay<TNode> | null,\n  TIncomingRelay<TNode> | null,\n  TIncomingRelay<TNode> | null\n>;\n\n// As proof of the flexibility of field policies, this function generates\n// one that handles Relay-style pagination, without Apollo Client knowing\n// anything about connections, edges, cursors, or pageInfo objects.\n/**\n * A field policy that attempts to handle pagination for fields that adhere to\n * the [Relay Connections Spec](https://relay.dev/graphql/connections.htm).\n *\n * @param keyArgs - `keyArgs` that should be applied to the field policy\n * @returns The field policy that handles Relay pagination\n */\nexport function relayStylePagination<TNode extends Reference = Reference>(\n  keyArgs: KeyArgs = false\n): RelayFieldPolicy<TNode> {\n  return {\n    keyArgs,\n\n    read(existing, { canRead, readField }) {\n      if (!existing) return existing;\n\n      const edges: TRelayEdge<TNode>[] = [];\n      let firstEdgeCursor = \"\";\n      let lastEdgeCursor = \"\";\n      existing.edges.forEach((edge) => {\n        // Edges themselves could be Reference objects, so it's important\n        // to use readField to access the edge.edge.node property.\n        if (canRead(readField(\"node\", edge))) {\n          edges.push(edge);\n          if (edge.cursor) {\n            firstEdgeCursor = firstEdgeCursor || edge.cursor || \"\";\n            lastEdgeCursor = edge.cursor || lastEdgeCursor;\n          }\n        }\n      });\n\n      if (edges.length > 1 && firstEdgeCursor === lastEdgeCursor) {\n        firstEdgeCursor = \"\";\n      }\n\n      const { startCursor, endCursor } = existing.pageInfo || {};\n\n      return {\n        // Some implementations return additional Connection fields, such\n        // as existing.totalCount. These fields are saved by the merge\n        // function, so the read function should also preserve them.\n        ...getExtras(existing),\n        edges,\n        pageInfo: {\n          ...existing.pageInfo,\n          // If existing.pageInfo.{start,end}Cursor are undefined or \"\", default\n          // to firstEdgeCursor and/or lastEdgeCursor.\n          startCursor: startCursor || firstEdgeCursor,\n          endCursor: endCursor || lastEdgeCursor,\n        },\n      };\n    },\n\n    merge(existing, incoming, { args, isReference, readField }) {\n      if (!existing) {\n        existing = makeEmptyData();\n      }\n\n      if (!incoming) {\n        return existing;\n      }\n\n      const incomingEdges =\n        incoming.edges ?\n          incoming.edges.map((edge) => {\n            if (isReference((edge = { ...edge }))) {\n              // In case edge is a Reference, we read out its cursor field and\n              // store it as an extra property of the Reference object.\n              edge.cursor = readField<string>(\"cursor\", edge);\n            }\n            return edge;\n          })\n        : [];\n\n      if (incoming.pageInfo) {\n        const { pageInfo } = incoming;\n        const { startCursor, endCursor } = pageInfo;\n        const firstEdge = incomingEdges[0];\n        const lastEdge = incomingEdges[incomingEdges.length - 1];\n        // In case we did not request the cursor field for edges in this\n        // query, we can still infer cursors from pageInfo.\n        if (firstEdge && startCursor) {\n          firstEdge.cursor = startCursor;\n        }\n        if (lastEdge && endCursor) {\n          lastEdge.cursor = endCursor;\n        }\n        // Cursors can also come from edges, so we default\n        // pageInfo.{start,end}Cursor to {first,last}Edge.cursor.\n        const firstCursor = firstEdge && firstEdge.cursor;\n        if (firstCursor && !startCursor) {\n          incoming = mergeDeep(incoming, {\n            pageInfo: {\n              startCursor: firstCursor,\n            },\n          });\n        }\n        const lastCursor = lastEdge && lastEdge.cursor;\n        if (lastCursor && !endCursor) {\n          incoming = mergeDeep(incoming, {\n            pageInfo: {\n              endCursor: lastCursor,\n            },\n          });\n        }\n      }\n\n      let prefix = existing.edges;\n      let suffix: typeof prefix = [];\n\n      if (args && args.after) {\n        // This comparison does not need to use readField(\"cursor\", edge),\n        // because we stored the cursor field of any Reference edges as an\n        // extra property of the Reference object.\n        const index = prefix.findIndex((edge) => edge.cursor === args.after);\n        if (index >= 0) {\n          prefix = prefix.slice(0, index + 1);\n          // suffix = []; // already true\n        }\n      } else if (args && args.before) {\n        const index = prefix.findIndex((edge) => edge.cursor === args.before);\n        suffix = index < 0 ? prefix : prefix.slice(index);\n        prefix = [];\n      } else if (incoming.edges) {\n        // If we have neither args.after nor args.before, the incoming\n        // edges cannot be spliced into the existing edges, so they must\n        // replace the existing edges. See #6592 for a motivating example.\n        prefix = [];\n      }\n\n      const edges = [...prefix, ...incomingEdges, ...suffix];\n\n      const pageInfo: TRelayPageInfo = {\n        // The ordering of these two ...spreads may be surprising, but it\n        // makes sense because we want to combine PageInfo properties with a\n        // preference for existing values, *unless* the existing values are\n        // overridden by the logic below, which is permitted only when the\n        // incoming page falls at the beginning or end of the data.\n        ...incoming.pageInfo,\n        ...existing.pageInfo,\n      };\n\n      if (incoming.pageInfo) {\n        const {\n          hasPreviousPage,\n          hasNextPage,\n          startCursor,\n          endCursor,\n          ...extras\n        } = incoming.pageInfo;\n\n        // If incoming.pageInfo had any extra non-standard properties,\n        // assume they should take precedence over any existing properties\n        // of the same name, regardless of where this page falls with\n        // respect to the existing data.\n        Object.assign(pageInfo, extras);\n\n        // Keep existing.pageInfo.has{Previous,Next}Page unless the\n        // placement of the incoming edges means incoming.hasPreviousPage\n        // or incoming.hasNextPage should become the new values for those\n        // properties in existing.pageInfo. Note that these updates are\n        // only permitted when the beginning or end of the incoming page\n        // coincides with the beginning or end of the existing data, as\n        // determined using prefix.length and suffix.length.\n        if (!prefix.length) {\n          if (void 0 !== hasPreviousPage)\n            pageInfo.hasPreviousPage = hasPreviousPage;\n          if (void 0 !== startCursor) pageInfo.startCursor = startCursor;\n        }\n        if (!suffix.length) {\n          if (void 0 !== hasNextPage) pageInfo.hasNextPage = hasNextPage;\n          if (void 0 !== endCursor) pageInfo.endCursor = endCursor;\n        }\n      }\n\n      return {\n        ...getExtras(existing),\n        ...getExtras(incoming),\n        edges,\n        pageInfo,\n      };\n    },\n  };\n}\n\n// Returns any unrecognized properties of the given object.\nconst getExtras = (obj: Record<string, any>) => __rest(obj, notExtras);\nconst notExtras = [\"edges\", \"pageInfo\"];\n\nfunction makeEmptyData(): TExistingRelay<any> {\n  return {\n    edges: [],\n    pageInfo: {\n      hasPreviousPage: false,\n      hasNextPage: true,\n      startCursor: \"\",\n      endCursor: \"\",\n    },\n  };\n}\n"
  },
  {
    "path": "src/utilities/subscriptions/relay/__tests__/createFetchMultipartSubscription.test.ts",
    "content": "import type { RequestParameters } from \"relay-runtime\";\n\nimport { createFetchMultipartSubscription } from \"@apollo/client/utilities/subscriptions/relay\";\n\nconst mockRequestParameters: RequestParameters = {\n  cacheID: \"test-cache-id\",\n  id: null,\n  text: \"subscription { test }\",\n  name: \"TestSubscription\",\n  operationKind: \"subscription\",\n  metadata: {},\n} as const;\n\ndescribe(\"createFetchMultipartSubscription\", () => {\n  describe(\"abort controller support\", () => {\n    it(\"should pass an abort signal to fetch\", () => {\n      let receivedSignal: AbortSignal | undefined;\n\n      const mockFetch = jest.fn(\n        (_url: string, options: RequestInit) =>\n          new Promise<Response>(() => {\n            // Capture the signal for verification\n            receivedSignal = options.signal as AbortSignal;\n          })\n      );\n\n      const subscribe = createFetchMultipartSubscription(\"/graphql\", {\n        fetch: mockFetch as typeof fetch,\n      });\n\n      const observable = subscribe(mockRequestParameters, {});\n\n      observable.subscribe({\n        next: () => {},\n        error: () => {},\n        complete: () => {},\n      });\n\n      expect(mockFetch).toHaveBeenCalled();\n      expect(receivedSignal).toBeDefined();\n      expect(receivedSignal?.aborted).toBe(false);\n    });\n\n    it(\"should abort the fetch when unsubscribe is called\", () => {\n      let receivedSignal: AbortSignal | undefined;\n\n      const mockFetch = jest.fn(\n        (_url: string, options: RequestInit) =>\n          new Promise<Response>(() => {\n            receivedSignal = options.signal as AbortSignal;\n          })\n      );\n\n      const subscribe = createFetchMultipartSubscription(\"/graphql\", {\n        fetch: mockFetch as typeof fetch,\n      });\n\n      const observable = subscribe(mockRequestParameters, {});\n\n      const subscription = observable.subscribe({\n        next: () => {},\n        error: () => {},\n        complete: () => {},\n      });\n\n      expect(receivedSignal?.aborted).toBe(false);\n\n      subscription.unsubscribe();\n\n      expect(receivedSignal?.aborted).toBe(true);\n    });\n\n    it(\"should not call sink.error when fetch is aborted\", async () => {\n      const errorSpy = jest.fn();\n\n      const mockFetch = jest.fn((_url: string, options: RequestInit) => {\n        return new Promise<Response>((_resolve, reject) => {\n          options.signal?.addEventListener(\"abort\", () => {\n            const abortError = new Error(\"The operation was aborted.\");\n            abortError.name = \"AbortError\";\n            reject(abortError);\n          });\n        });\n      });\n\n      const subscribe = createFetchMultipartSubscription(\"/graphql\", {\n        fetch: mockFetch as typeof fetch,\n      });\n\n      const observable = subscribe(mockRequestParameters, {});\n\n      const subscription = observable.subscribe({\n        next: () => {},\n        error: errorSpy,\n        complete: () => {},\n      });\n\n      subscription.unsubscribe();\n\n      // Allow any pending promises to resolve\n      await new Promise((resolve) => setTimeout(resolve, 0));\n\n      expect(errorSpy).not.toHaveBeenCalled();\n    });\n\n    it(\"should still call sink.error for non-abort errors\", async () => {\n      const errorSpy = jest.fn();\n      const networkError = new Error(\"Network failure\");\n\n      const mockFetch = jest.fn(() => Promise.reject(networkError));\n\n      const subscribe = createFetchMultipartSubscription(\"/graphql\", {\n        fetch: mockFetch as typeof fetch,\n      });\n\n      const observable = subscribe(mockRequestParameters, {});\n\n      observable.subscribe({\n        next: () => {},\n        error: errorSpy,\n        complete: () => {},\n      });\n\n      // Allow any pending promises to resolve\n      await new Promise((resolve) => setTimeout(resolve, 0));\n\n      expect(errorSpy).toHaveBeenCalledWith(networkError);\n    });\n  });\n});\n"
  },
  {
    "path": "src/utilities/subscriptions/relay/index.ts",
    "content": "import type { GraphQLResponse, RequestParameters } from \"relay-runtime\";\nimport { Observable } from \"relay-runtime\";\n\nimport type { OperationVariables } from \"@apollo/client\";\nimport type { BaseHttpLink } from \"@apollo/client/link/http\";\nimport { maybe } from \"@apollo/client/utilities/internal/globals\";\n\n// eslint-disable-next-line local-rules/import-from-inside-other-export\nimport { readMultipartBody } from \"../../../link/http/parseAndCheckHttpResponse.js\";\n// eslint-disable-next-line local-rules/import-from-inside-other-export\nimport { fallbackHttpConfig } from \"../../../link/http/selectHttpOptionsAndBody.js\";\n\nconst backupFetch = maybe(() => fetch);\n\ntype CreateMultipartSubscriptionOptions = {\n  fetch?: WindowOrWorkerGlobalScope[\"fetch\"];\n  headers?: Record<string, string>;\n};\n\nexport function createFetchMultipartSubscription(\n  uri: string,\n  { fetch: preferredFetch, headers }: CreateMultipartSubscriptionOptions = {}\n) {\n  return function fetchMultipartSubscription(\n    operation: RequestParameters,\n    variables: OperationVariables\n  ): Observable<GraphQLResponse> {\n    const body: BaseHttpLink.Body = {\n      operationName: operation.name,\n      variables,\n      query: operation.text || \"\",\n    };\n    const options = generateOptionsForMultipartSubscription(headers || {});\n\n    return Observable.create((sink) => {\n      const controller = new AbortController();\n\n      try {\n        options.body = JSON.stringify(body);\n      } catch (parseError) {\n        sink.error(parseError as Error);\n      }\n\n      const currentFetch = preferredFetch || maybe(() => fetch) || backupFetch;\n      const observerNext = sink.next.bind(sink);\n\n      currentFetch!(uri, { ...options, signal: controller.signal })\n        .then((response) => {\n          const ctype = response.headers?.get(\"content-type\");\n\n          if (ctype !== null && /^multipart\\/mixed/i.test(ctype)) {\n            return readMultipartBody(response, observerNext);\n          }\n\n          sink.error(new Error(\"Expected multipart response\"));\n        })\n        .then(() => {\n          sink.complete();\n        })\n        .catch((err: any) => {\n          if (err.name !== \"AbortError\") {\n            sink.error(err);\n          }\n        });\n\n      return () => {\n        controller.abort();\n      };\n    });\n  };\n}\n\nfunction generateOptionsForMultipartSubscription(\n  headers: Record<string, string>\n) {\n  const options: { headers: Record<string, any>; body?: string } = {\n    ...fallbackHttpConfig.options,\n    headers: {\n      ...(headers || {}),\n      ...fallbackHttpConfig.headers,\n      accept:\n        \"multipart/mixed;boundary=graphql;subscriptionSpec=1.0,application/json\",\n    },\n  };\n  return options;\n}\n"
  },
  {
    "path": "src/v4-migration.ts",
    "content": "/**\n * This file documents exports that have been removed from Apollo Client in 4.0.\n *\n * Executing the `removals` codemod will point removed exports to this file, where\n * docblocks will explain the removal and suggest alternatives.\n */\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const ApolloConsumer: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"ApolloError\"} }\n */\nexport declare class ApolloError {}\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"Concast\"} }\n *\n * Instead of `Concast`, look into the `rxjs` [`BehaviorSubject`](https://rxjs.dev/api/index/class/BehaviorSubject) api.\n */\nexport declare class Concast {}\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"DataProxy\"} }\n *\n * You can find the types that were previously available in the `DataProxy` namespace either in the `ApolloClient` namespace or the `Cache` namespace.\n */\nexport declare const DataProxy: never;\n\n/**\n * @deprecated The `DocumentType` enum has been removed from Apollo Client 4.0, along with the `parser` API exported from `@apollo/client/react/parser`.\n *\n * This API was mostly an implementation detail and has been removed without replacement.\n */\nexport declare const DocumentType: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport declare const Mutation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"ObservableSubscription\"} }\n */\nexport declare const ObservableSubscription: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"Observer\"} }\n */\nexport declare const Observer: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"OperationBatcher\", \"of\": \"`BatchLink`\"} }\n */\nexport declare const OperationBatcher: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport declare const Query: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"RenderPromises\", \"of\": \"`getMarkupFromTree`\"} }\n */\nexport declare const RenderPromises: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"Subscription\"} }\n */\nexport declare const Subscription: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"addNonReactiveToNamedFragments\", \"of\": \"the internal `QueryManager` class\"} }\n */\nexport declare const addNonReactiveToNamedFragments: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"asyncMap\"} }\n *\n * Consider using the `rxjs` [`mergeMap`](https://rxjs.dev/api/operators/mergeMap) operator instead.\n */\nexport declare const asyncMap: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"buildQueryFromSelectionSet\"} }\n */\nexport declare const buildQueryFromSelectionSet: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"canUseAsyncIteratorSymbol\"} }\n */\nexport declare const canUseAsyncIteratorSymbol: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"canUseLayoutEffect\"} }\n */\nexport declare const canUseLayoutEffect: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"canUseSymbol\"} }\n */\nexport declare const canUseSymbol: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"canUseWeakMap\"} }\n */\nexport declare const canUseWeakMap: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"canUseWeakSet\"} }\n */\nexport declare const canUseWeakSet: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedValue:type {\"name\":\"createMockClient\"} }\n *\n * Please create an `ApolloClient` instance with a `MockLink` manually instead.\n */\nexport declare const createMockClient: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.testingLibrary:type {\"name\":\"createSchemaFetch\"} }\n */\nexport declare const createSchemaFetch: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.testingLibrary:type {\"name\":\"createTestSchema\"} }\n */\nexport declare const createTestSchema: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"defaultCacheSizes\"} }\n */\nexport declare const defaultCacheSizes: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"fixObservableSubclass\",\"of\":\"ObservableQuery\"} }\n */\nexport declare const fixObservableSubclass: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"fromError\"} }\n */\nexport declare const fromError: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"fromPromise\"} }\n */\nexport declare const fromPromise: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"getDirectiveNames\"} }\n */\nexport declare const getDirectiveNames: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"getFragmentMaskMode\",\"of\":\"data masking\"} }\n */\nexport declare const getFragmentMaskMode: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"getInclusionDirectives\",\"of\":\"local state\"} }\n */\nexport declare const getInclusionDirectives: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"getTypenameFromResult\",\"of\":\"`InMemoryCache`\"} }\n */\nexport declare const getTypenameFromResult: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const graphql: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"hasAllDirectives\"} }\n */\nexport declare const hasAllDirectives: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"hasAnyDirectives\"} }\n */\nexport declare const hasAnyDirectives: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"hasClientExports\"} }\n */\nexport declare const hasClientExports: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"isApolloError\"} }\n */\nexport declare const isApolloError: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"isApolloPayloadResult\",\"of\":\"HttpLink\"} }\n */\nexport declare const isApolloPayloadResult: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.defer:type {\"name\":\"isExecutionPatchIncrementalResult\"} }\n */\nexport declare const isExecutionPatchIncrementalResult: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.defer:type {\"name\":\"isExecutionPatchInitialResult\"} }\n */\nexport declare const isExecutionPatchInitialResult: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.defer:type {\"name\":\"isExecutionPatchResult\"} }\n */\nexport declare const isExecutionPatchResult: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"isFullyUnmaskedOperation\",\"of\":\"data masking\"} }\n */\nexport declare const isFullyUnmaskedOperation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"isInlineFragment\"} }\n */\nexport declare const isInlineFragment: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"isStatefulPromise\"} }\n */\nexport declare const isStatefulPromise: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"itAsync\"} }\n */\nexport declare const itAsync: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"iterateObserversSafely\"} }\n */\nexport declare const iterateObserversSafely: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.defer:type {\"name\":\"mergeIncrementalData\"} }\n */\nexport declare const mergeIncrementalData: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedValue:type {\"name\":\"mockObservableLink\"} }\n */\nexport declare const mockObservableLink: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedValue:type {\"name\":\"mockSingleLink\"} }\n *\n * This utility was a wrapper around `MockLink`.\n * Please call `new MockLink(mockedResponses)` directly.\n */\nexport declare const mockSingleLink: never;\n\n/**\n * @deprecated The `operationName` function has been removed from Apollo Client 4.0, along with the `parser` API exported from `@apollo/client/react/parser`.\n *\n * This API was mostly an implementation detail and has been removed without replacement.\n */\nexport declare const operationName: never;\n\n/**\n * @deprecated The `parser` function has been removed from Apollo Client 4.0, along with the whole `@apollo/client/react/parser` entry point.\n *\n * This API was mostly an implementation detail and has been removed without replacement.\n */\nexport declare const parser: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"removeArgumentsFromDocument\"} }\n */\nexport declare const removeArgumentsFromDocument: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"removeClientSetsFromDocument\"} }\n */\nexport declare const removeClientSetsFromDocument: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"removeConnectionDirectiveFromDocument\"} }\n */\nexport declare const removeConnectionDirectiveFromDocument: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"removeFragmentSpreadFromDocument\"} }\n */\nexport declare const removeFragmentSpreadFromDocument: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedValue:type {\"name\":\"resetApolloContext\"} }\n *\n * This function was deprecated and is no longer available.\n */\nexport declare const resetApolloContext: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"serializeFetchParameter\",\"of\":\"HttpLink\"} }\n *\n * Please use `JSON.stringify` instead.\n */\nexport declare const serializeFetchParameter: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"subscribeAndCount\"} }\n */\nexport declare const subscribeAndCount: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"throwServerError\",\"of\":\"HttpLink\"} }\n *\n * Please instantiate a `ServerError` directly instead.\n */\nexport declare const throwServerError: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"tick\"} }\n */\nexport declare const tick: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.rxjs:type {\"name\":\"toPromise\"} }\n *\n * Please use the `rxjs` [`firstValueFrom`](https://rxjs.dev/api/index/function/firstValueFrom) or [`lastValueFrom`](https://rxjs.dev/api/index/function/lastValueFrom) functions instead.\n */\nexport declare const toPromise: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"transformOperation\",\"of\":\"ApolloLink.execute\"} }\n */\nexport declare const transformOperation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"validateOperation\",\"of\":\"ApolloLink.execute\"} }\n */\nexport declare const validateOperation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"valueToObjectRepresentation\"} }\n */\nexport declare const valueToObjectRepresentation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"verifyDocumentType\"} }\n */\nexport declare const verifyDocumentType: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"wait\"} }\n */\nexport declare const wait: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const withApollo: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"withErrorSpy\"} }\n */\nexport declare const withErrorSpy: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"withLogSpy\"} }\n */\nexport declare const withLogSpy: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const withMutation: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const withQuery: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport declare const withSubscription: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"withWarningSpy\"} }\n */\nexport declare const withWarningSpy: never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport type ApolloConsumerProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"ApolloErrorOptions\"} }\n */\nexport type ApolloErrorOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"BaseMutationOptions\"} }\n *\n * Look into `ApolloClient.MutateOptions` or `useMutation.Options` instead.\n */\nexport type BaseMutationOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"BaseQueryOptions\"} }\n *\n * Look into `ApolloClient.QueryOptions` or `useQuery.Options` instead.\n */\nexport type BaseQueryOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"BatchableRequest\"} }\n */\nexport type BatchableRequest = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type ChildDataProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type ChildMutateProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type ChildProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"ClientParseError\"} }\n */\nexport type ClientParseError = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"Masked\"} }\n */\nexport type Masked = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"MaskedDocumentNode\"} }\n */\nexport type MaskedDocumentNode = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"CommonOptions\"} }\n */\nexport type CommonOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"ConcastSourcesArray\"} }\n */\nexport type ConcastSourcesArray = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"ConcastSourcesIterable\"} }\n */\nexport type ConcastSourcesIterable = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"DataProps\"} }\n */\nexport type DataProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type DataValue = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"DirectiveInfo\"} }\n */\nexport type DirectiveInfo = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"Directives\"} }\n */\nexport type Directives = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"FetchMoreQueryOptions\"} }\n *\n * Look into `ObservableQuery.FetchMoreOptions` instead.\n */\nexport type FetchMoreQueryOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"FragmentMatcher\"} }\n */\nexport type FragmentMatcher = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"GetDirectiveConfig\"} }\n */\nexport type GetDirectiveConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"GetFragmentSpreadConfig\"} }\n */\nexport type GetFragmentSpreadConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"GetNodeConfig\"} }\n */\nexport type GetNodeConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"GraphQLErrors\"} }\n */\nexport type GraphQLErrors = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"IDocumentDefinition\"} }\n */\nexport type IDocumentDefinition = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"InclusionDirectives\"} }\n */\nexport type InclusionDirectives = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internalTesting:type {\"name\":\"IsStrictlyAny\"} }\n */\nexport type IsStrictlyAny = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"MethodKeys\"} }\n */\nexport type MethodKeys = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type MutateProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport type MutationComponentOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"MutationDataOptions\"} }\n *\n * Look into `ApolloClient.MutateOptions` or `useMutation.Options` instead.\n */\nexport type MutationDataOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"MutationUpdaterFn\"} }\n */\nexport type MutationUpdaterFn = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.errors:type {\"name\":\"NetworkError\"} }\n */\nexport type NetworkError = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"ObservableQueryFields\"} }\n */\nexport type ObservableQueryFields = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"OnlyRequiredProperties\"} }\n */\nexport type OnlyRequiredProperties = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type OperationOption = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type OptionProps = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"PromiseWithState\"} }\n */\nexport type PromiseWithState = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"PureQueryOptions\"} }\n */\nexport type PureQueryOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport type QueryComponentOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type QueryControls = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"QueryDataOptions\",\"of\":\"`getMarkupFromTree`\"} }\n */\nexport type QueryDataOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"QueryLazyOptions\"} }\n */\nexport type QueryLazyOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.internal:type {\"name\":\"ReconcilerFunction\"} }\n */\nexport type ReconcilerFunction = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RefetchQueriesFunction\"} }\n *\n * Look into using `useMutation.Options['refetchQueries']` instead.\n */\nexport type RefetchQueriesFunction = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveArgumentsConfig\"} }\n */\nexport type RemoveArgumentsConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveDirectiveConfig\"} }\n */\nexport type RemoveDirectiveConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveFragmentDefinitionConfig\"} }\n */\nexport type RemoveFragmentDefinitionConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveFragmentSpreadConfig\"} }\n */\nexport type RemoveFragmentSpreadConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveNodeConfig\"} }\n */\nexport type RemoveNodeConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"RemoveVariableDefinitionConfig\"} }\n */\nexport type RemoveVariableDefinitionConfig = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"Resolver\",\"of\":\"local state\"} }\n */\nexport type Resolver = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.implementationDetail:type {\"name\":\"Resolvers\",\"of\":\"local state\"} }\n */\nexport type Resolvers = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.renderProp:type }\n */\nexport type SubscriptionComponentOptions = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"SubscriptionCurrentObservable\"} }\n */\nexport type SubscriptionCurrentObservable = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"TupleToIntersection\"} }\n */\nexport type TupleToIntersection = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.utility:type {\"name\":\"UnionToIntersection\"} }\n */\nexport type UnionToIntersection = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.removedType:type {\"name\":\"VariableValue\"} }\n */\nexport type VariableValue = never;\n\n/**\n * {@inheritDoc @apollo/client/v4-migration!Removals.HOC:type }\n */\nexport type WithApolloClient = never;\n\nexport declare namespace Removals {\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   */\n  export type removedValue = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   */\n  export type removedType = never;\n  /**\n   * @deprecated All higher-order components (HOCs) have been removed from Apollo Client 4.0 and are no longer available.\n   * Use the hooks exported from the `@apollo/client/react` package instead.\n   */\n  export type HOC = never;\n  /**\n   * @deprecated All render prop components have been removed from Apollo Client 4.0 and are no longer available.\n   * Use the hooks exported from the `@apollo/client/react` package instead.\n   */\n  export type renderProp = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * Error handling has been overhauled as a whole.\n   */\n  export type errors = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * The Observable implementation of Apollo Client has been moved from `zen-observable` to `rxjs`.\n   */\n  export type rxjs = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * This export was an implementation detail of \\{\\{of\\}\\} and is no longer available.\n   */\n  export type implementationDetail = never;\n  /**\n   * @deprecated The utility `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * It was an implementation detail that is no longer necessary and has been removed without replacement.\n   */\n  export type utility = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * The testing utilities have moved into their own package, [\\@apollo/graphql-testing-library](https://github.com/apollographql/graphql-testing-library).\n   */\n  export type testingLibrary = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * This export is considered internal and is no longer exposed.\n   */\n  export type internal = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * This was an internal testing utility that was not meant for public use.\n   * It has been removed without replacement.\n   */\n  export type internalTesting = never;\n  /**\n   * @deprecated The export `{{name}}` has been removed from Apollo Client 4.0.\n   *\n   * This export was part of a specific `\\@defer` protocol implementation.\n   * These implementations are now pluggable, so this export might not be relevant for all protocol specifications.\n   */\n  export type defer = never;\n}\n"
  },
  {
    "path": "src/version.ts",
    "content": "export const version = \"local\" as string;\nexport const build = \"source\" as \"source\" | \"esm\" | \"cjs\";\n"
  },
  {
    "path": "tests.codegen.ts",
    "content": "import type { CodegenConfig } from \"@graphql-codegen/cli\";\n\nconst config: CodegenConfig = {\n  hooks: {\n    afterAllFileWrite: [\"prettier --write\"],\n  },\n  generates: {\n    \"./src/local-state/__tests__/LocalState/fixtures/local-resolvers.ts\": {\n      schema: [\n        \"./src/local-state/__tests__/LocalState/fixtures/localSchema.graphql\",\n      ],\n      plugins: [\n        { add: { content: \"/* eslint-disable */\" } },\n        \"typescript\",\n        \"@apollo/client-graphql-codegen/local-state\",\n      ],\n      config: {\n        nonOptionalTypename: true,\n        contextType: \"./context-value.js#ContextValue\",\n        baseTypesPath: \"./base-types.js\",\n      },\n    },\n    \"./src/local-state/__tests__/LocalState/fixtures/local-resolvers-without-context-value.ts\":\n      {\n        schema: [\n          \"./src/local-state/__tests__/LocalState/fixtures/localSchema.graphql\",\n        ],\n        plugins: [\n          { add: { content: \"/* eslint-disable */\" } },\n          \"typescript\",\n          \"@apollo/client-graphql-codegen/local-state\",\n        ],\n        config: {\n          nonOptionalTypename: true,\n          baseTypesPath: \"./base-types.js\",\n        },\n      },\n  },\n};\n\nexport default config;\n"
  },
  {
    "path": "tsconfig.build.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noEmit\": false,\n    \"types\": [\n      // we don't want to include our types for `jest`, our custom matchers etc.\n      // if one of those is referenced in our production code, we want a\n      // build error, so we can fix it\n      // we also explicitly do not include `node` here as we don't want our build\n      // artefact to rely on those types (for now, at least)\n    ]\n  },\n  \"extends\": \"./tsconfig.json\",\n  \"files\": [\n    // during the `compileTs` build step, this will momentarily be populated\n    // with all entry points specified in the `package.json` file\n    // this way we don't bundle up any files that cannot be reached by an\n    // `import` statement\n  ],\n  \"include\": [],\n  \"exclude\": []\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"noEmit\": true,\n    \"noImplicitAny\": true,\n    \"strictNullChecks\": true,\n    \"noUnusedParameters\": false,\n    \"noUnusedLocals\": true,\n    \"skipLibCheck\": true,\n    \"moduleResolution\": \"NodeNext\",\n    \"importHelpers\": true,\n    \"sourceMap\": true,\n    \"inlineSources\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"target\": \"ESNext\",\n    \"module\": \"NodeNext\",\n    \"esModuleInterop\": true,\n    \"experimentalDecorators\": true,\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\",\n    \"lib\": [\"DOM\", \"dom.asyncIterable\", \"ES2023\"],\n    \"types\": [\n      \"jest\",\n      \"node\",\n      \"./src/testing/matchers/index.d.ts\",\n      \"./src/testing/internal/declarations.d.ts\",\n      \"@testing-library/react-render-stream/expect\"\n    ],\n    \"jsx\": \"react\",\n    \"strict\": true,\n    \"paths\": {\n      // This entry point is not part of our public API, so we point it directly to the source.\n      \"@apollo/client/testing/internal\": [\"./src/testing/internal/index.ts\"]\n    }\n  },\n  \"include\": [\"src/**/*.ts\", \"src/**/*.tsx\"],\n  \"references\": [\n    {\n      \"path\": \"./config/tsconfig.json\"\n    },\n    {\n      \"path\": \"./docs/tsconfig.json\"\n    }\n  ],\n  \"mdx\": {\n    // Enable strict type checking in MDX files.\n    \"checkMdx\": true\n  }\n}\n"
  },
  {
    "path": "tsconfig.tests.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"moduleResolution\": \"Node\",\n    \"module\": \"ES2015\",\n    \"allowJs\": true,\n    \"isolatedModules\": true,\n    \"types\": [\n      \"jest\",\n      \"node\",\n      \"./src/testing/matchers/index.d.ts\",\n      \"./src/testing/internal/declarations.d.ts\",\n      \"@testing-library/react-render-stream/expect\"\n    ]\n  }\n}\n"
  },
  {
    "path": "tsdoc.json",
    "content": "{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/tsdoc/v0/tsdoc.schema.json\",\n\n  // Inherit the TSDoc configuration for API Extractor\n  \"extends\": [\"@microsoft/api-extractor/extends/tsdoc-base.json\"],\n\n  \"tagDefinitions\": [\n    {\n      \"tagName\": \"@since\",\n      \"syntaxKind\": \"block\",\n      \"allowMultiple\": false\n    },\n    {\n      \"tagName\": \"@docGroup\",\n      \"syntaxKind\": \"block\",\n      \"allowMultiple\": false\n    },\n    {\n      \"tagName\": \"@template\",\n      \"syntaxKind\": \"block\",\n      \"allowMultiple\": false\n    }\n  ],\n\n  \"supportForTags\": {\n    \"@since\": true,\n    \"@docGroup\": true,\n    \"@template\": true\n  }\n}\n"
  }
]